title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Cryptography Introduction - GeeksforGeeks
|
13 Feb, 2020
Cryptography is the study and practice of techniques for secure communication in the presence of third parties called adversaries. It deals with developing and analyzing protocols which prevents malicious third parties from retrieving information being shared between two entities thereby following the various aspects of information security.
Secure Communication refers to the scenario where the message or data shared between two parties can’t be accessed by an adversary. In Cryptography, an Adversary is a malicious entity, which aims to retrieve precious information or data thereby undermining the principles of information security.
Data Confidentiality, Data Integrity, Authentication and Non-repudiation are core principles of modern-day cryptography.
Confidentiality refers to certain rules and guidelines usually executed under confidentiality agreements which ensure that the information is restricted to certain people or places.Data integrity refers to maintaining and making sure that the data stays accurate and consistent over its entire life cycle.Authentication is the process of making sure that the piece of data being claimed by the user belongs to it.Non-repudiation refers to ability to make sure that a person or a party associated with a contract or a communication cannot deny the authenticity of their signature over their document or the sending of a message.
Confidentiality refers to certain rules and guidelines usually executed under confidentiality agreements which ensure that the information is restricted to certain people or places.
Data integrity refers to maintaining and making sure that the data stays accurate and consistent over its entire life cycle.
Authentication is the process of making sure that the piece of data being claimed by the user belongs to it.
Non-repudiation refers to ability to make sure that a person or a party associated with a contract or a communication cannot deny the authenticity of their signature over their document or the sending of a message.
Consider two parties Alice and Bob. Now, Alice wants to send a message m to Bob over a secure channel.So, what happens is as follows.The sender’s message or sometimes called the Plaintext, is converted into an unreadable form using a Key k. The resultant text obtained is called the Ciphertext. This process is known as Encryption. At the time of receival, the Ciphertext is converted back into the plaintext using the same Key k, so that it can be read by the receiver. This process is known as Decryption.
Alice (Sender) Bob (Receiver)
C = E (m, k) ----> m = D (C, k)
Here, C refers to the Ciphertext while E and D are the Encryption and Decryption algorithms respectively.
Let’s consider the case of Caesar Cipher or Shift Cipher as an example.As the name suggests, in Caesar Cipher each character in a word is replaced by another character under some defined rules. Thus, if A is replaced by D, B by E and so on. Then, each character in the word would be shifted by a position of 3. For example:
Plaintext : Geeksforgeeks
Ciphertext : Jhhnvirujhhnv
Note that even if the adversary knows that the cipher is based on Caesar Cipher, it cannot predict the plaintext as it doesn’t have the key in this case which is to shift the characters back by three places.
Refer for Introduction to Crypto-terminologies.
cryptography
Computer Networks
GATE CS
cryptography
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Socket Programming in Python
Types of Network Topology
UDP Server-Client implementation in C
Types of Transmission Media
TCP 3-Way Handshake Process
ACID Properties in DBMS
Page Replacement Algorithms in Operating Systems
Types of Operating Systems
Normal Forms in DBMS
Semaphores in Process Synchronization
|
[
{
"code": null,
"e": 24456,
"s": 24428,
"text": "\n13 Feb, 2020"
},
{
"code": null,
"e": 24800,
"s": 24456,
"text": "Cryptography is the study and practice of techniques for secure communication in the presence of third parties called adversaries. It deals with developing and analyzing protocols which prevents malicious third parties from retrieving information being shared between two entities thereby following the various aspects of information security."
},
{
"code": null,
"e": 25097,
"s": 24800,
"text": "Secure Communication refers to the scenario where the message or data shared between two parties can’t be accessed by an adversary. In Cryptography, an Adversary is a malicious entity, which aims to retrieve precious information or data thereby undermining the principles of information security."
},
{
"code": null,
"e": 25218,
"s": 25097,
"text": "Data Confidentiality, Data Integrity, Authentication and Non-repudiation are core principles of modern-day cryptography."
},
{
"code": null,
"e": 25846,
"s": 25218,
"text": "Confidentiality refers to certain rules and guidelines usually executed under confidentiality agreements which ensure that the information is restricted to certain people or places.Data integrity refers to maintaining and making sure that the data stays accurate and consistent over its entire life cycle.Authentication is the process of making sure that the piece of data being claimed by the user belongs to it.Non-repudiation refers to ability to make sure that a person or a party associated with a contract or a communication cannot deny the authenticity of their signature over their document or the sending of a message."
},
{
"code": null,
"e": 26028,
"s": 25846,
"text": "Confidentiality refers to certain rules and guidelines usually executed under confidentiality agreements which ensure that the information is restricted to certain people or places."
},
{
"code": null,
"e": 26153,
"s": 26028,
"text": "Data integrity refers to maintaining and making sure that the data stays accurate and consistent over its entire life cycle."
},
{
"code": null,
"e": 26262,
"s": 26153,
"text": "Authentication is the process of making sure that the piece of data being claimed by the user belongs to it."
},
{
"code": null,
"e": 26477,
"s": 26262,
"text": "Non-repudiation refers to ability to make sure that a person or a party associated with a contract or a communication cannot deny the authenticity of their signature over their document or the sending of a message."
},
{
"code": null,
"e": 26985,
"s": 26477,
"text": "Consider two parties Alice and Bob. Now, Alice wants to send a message m to Bob over a secure channel.So, what happens is as follows.The sender’s message or sometimes called the Plaintext, is converted into an unreadable form using a Key k. The resultant text obtained is called the Ciphertext. This process is known as Encryption. At the time of receival, the Ciphertext is converted back into the plaintext using the same Key k, so that it can be read by the receiver. This process is known as Decryption."
},
{
"code": null,
"e": 27058,
"s": 26985,
"text": "Alice (Sender) Bob (Receiver)\nC = E (m, k) ----> m = D (C, k) "
},
{
"code": null,
"e": 27164,
"s": 27058,
"text": "Here, C refers to the Ciphertext while E and D are the Encryption and Decryption algorithms respectively."
},
{
"code": null,
"e": 27488,
"s": 27164,
"text": "Let’s consider the case of Caesar Cipher or Shift Cipher as an example.As the name suggests, in Caesar Cipher each character in a word is replaced by another character under some defined rules. Thus, if A is replaced by D, B by E and so on. Then, each character in the word would be shifted by a position of 3. For example:"
},
{
"code": null,
"e": 27542,
"s": 27488,
"text": "Plaintext : Geeksforgeeks\nCiphertext : Jhhnvirujhhnv "
},
{
"code": null,
"e": 27750,
"s": 27542,
"text": "Note that even if the adversary knows that the cipher is based on Caesar Cipher, it cannot predict the plaintext as it doesn’t have the key in this case which is to shift the characters back by three places."
},
{
"code": null,
"e": 27798,
"s": 27750,
"text": "Refer for Introduction to Crypto-terminologies."
},
{
"code": null,
"e": 27811,
"s": 27798,
"text": "cryptography"
},
{
"code": null,
"e": 27829,
"s": 27811,
"text": "Computer Networks"
},
{
"code": null,
"e": 27837,
"s": 27829,
"text": "GATE CS"
},
{
"code": null,
"e": 27850,
"s": 27837,
"text": "cryptography"
},
{
"code": null,
"e": 27868,
"s": 27850,
"text": "Computer Networks"
},
{
"code": null,
"e": 27966,
"s": 27868,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27995,
"s": 27966,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 28021,
"s": 27995,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 28059,
"s": 28021,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 28087,
"s": 28059,
"text": "Types of Transmission Media"
},
{
"code": null,
"e": 28115,
"s": 28087,
"text": "TCP 3-Way Handshake Process"
},
{
"code": null,
"e": 28139,
"s": 28115,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 28188,
"s": 28139,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 28215,
"s": 28188,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 28236,
"s": 28215,
"text": "Normal Forms in DBMS"
}
] |
C++ Program to Implement the Rabin-Miller Primality Test to Check if a Given Number is Prime
|
Rabin-Miller Primality Test is used to check if a given Number is Prime or not. It is similar to the format primality and the Solovay-Stressen test. this test first was discovered by Russian Mathematician M. M. Artjuhov.
Begin
ll mulmod(ll a, ll b, ll m)
ll x = 0,y = a mod m
while (b > 0)
if (b mod 2 == 1)
compute x = (x + y) mod m
y = (y * 2) mod m
b = b/ 2
return x mod m.
End
Begin
ll modulo(ll base, ll e, ll m)
Initialize:
ll x = 1
ll y = base
while (e > 0)
if (e mod 2 == 1)
x = (x * y) mod m
y = (y * y) mod m
e = e / 2;
return x mod m
End
Begin
bool Miller(ll p, int iteration)
if (p < 2)
return false
if (p != 2 and p mod 2==0)
return false;
Compute: ll s = p - 1
while (s mod 2 == 0)
s = s/ 2;
for i = 0 to iteration - 1
Do
ll a = rand() mod (p - 1) + 1, temp = s
ll mod = modulo(a, temp, p)
while (temp != p - 1 and mod != 1 and mod != p - 1)
mod = mulmod(mod, mod, p);
temp *= 2;
if (mod != p - 1 && temp % 2 == 0)
return false
else
return true
End
#include <iostream>
#include<stdlib.h>
#define ll long long
using namespace std;
ll mulmod(ll a, ll b, ll m)//It returns true if number is prime otherwise false {
ll x = 0,y = a % m;
while (b > 0) {
if (b % 2 == 1) {
x = (x + y) % m;
}
y = (y * 2) % m;
b /= 2;
}
return x % m;
}
ll modulo(ll base, ll e, ll m) {
ll x = 1;
ll y = base;
while (e > 0) {
if (e % 2 == 1)
x = (x * y) % m;
y = (y * y) % m;
e = e / 2;
}
return x % m;
}
bool Miller(ll p, int iteration) {
if (p < 2) {
return false;
}
if (p != 2 && p % 2==0) {
return false;
}
ll s = p - 1;
while (s % 2 == 0) {
s /= 2;
}
for (int i = 0; i < iteration; i++) {
ll a = rand() % (p - 1) + 1, temp = s;
ll mod = modulo(a, temp, p);
while (temp != p - 1 && mod != 1 && mod != p - 1) {
mod = mulmod(mod, mod, p);
temp *= 2;
}
if (mod != p - 1 && temp % 2 == 0) {
return false;
}
}
return true;
}
int main() {
int iteration = 10;
ll num;
cout<<"Enter integer to test primality: ";
cin>>num;
if (Miller(num, iteration))
cout<<num<<" is prime"<<endl;
else
cout<<num<<" is not prime"<<endl;
return 0;
}
Enter integer to test primality: 26
26 is not prime
|
[
{
"code": null,
"e": 1283,
"s": 1062,
"text": "Rabin-Miller Primality Test is used to check if a given Number is Prime or not. It is similar to the format primality and the Solovay-Stressen test. this test first was discovered by Russian Mathematician M. M. Artjuhov."
},
{
"code": null,
"e": 2294,
"s": 1283,
"text": "Begin\n ll mulmod(ll a, ll b, ll m)\n ll x = 0,y = a mod m\n while (b > 0)\n if (b mod 2 == 1)\n compute x = (x + y) mod m\n y = (y * 2) mod m\n b = b/ 2\n return x mod m.\nEnd\n\nBegin\n ll modulo(ll base, ll e, ll m)\n Initialize:\n ll x = 1\n ll y = base\n while (e > 0)\n if (e mod 2 == 1)\n x = (x * y) mod m\n y = (y * y) mod m\n e = e / 2;\n return x mod m\nEnd\n\nBegin\n bool Miller(ll p, int iteration)\n if (p < 2)\n return false\n if (p != 2 and p mod 2==0)\n return false;\n Compute: ll s = p - 1\n while (s mod 2 == 0)\n s = s/ 2;\n for i = 0 to iteration - 1\n Do\n ll a = rand() mod (p - 1) + 1, temp = s\n ll mod = modulo(a, temp, p)\n while (temp != p - 1 and mod != 1 and mod != p - 1)\n mod = mulmod(mod, mod, p);\n temp *= 2;\n if (mod != p - 1 && temp % 2 == 0)\n return false\n else\n return true\nEnd"
},
{
"code": null,
"e": 3586,
"s": 2294,
"text": "#include <iostream>\n#include<stdlib.h>\n#define ll long long\nusing namespace std;\nll mulmod(ll a, ll b, ll m)//It returns true if number is prime otherwise false {\n ll x = 0,y = a % m;\n while (b > 0) {\n if (b % 2 == 1) {\n x = (x + y) % m;\n }\n y = (y * 2) % m;\n b /= 2;\n }\n return x % m;\n}\n\nll modulo(ll base, ll e, ll m) {\n ll x = 1;\n ll y = base;\n while (e > 0) {\n if (e % 2 == 1)\n x = (x * y) % m;\n y = (y * y) % m;\n e = e / 2;\n }\n return x % m;\n}\n\nbool Miller(ll p, int iteration) {\n if (p < 2) {\n return false;\n }\n if (p != 2 && p % 2==0) {\n return false;\n }\n ll s = p - 1;\n while (s % 2 == 0) {\n s /= 2;\n }\n for (int i = 0; i < iteration; i++) {\n ll a = rand() % (p - 1) + 1, temp = s;\n ll mod = modulo(a, temp, p);\n while (temp != p - 1 && mod != 1 && mod != p - 1) {\n mod = mulmod(mod, mod, p);\n temp *= 2;\n }\n if (mod != p - 1 && temp % 2 == 0) {\n return false;\n }\n }\n return true;\n}\n\nint main() {\n int iteration = 10;\n ll num;\n cout<<\"Enter integer to test primality: \";\n cin>>num;\n if (Miller(num, iteration))\n cout<<num<<\" is prime\"<<endl;\n else\n cout<<num<<\" is not prime\"<<endl;\n return 0;\n}"
},
{
"code": null,
"e": 3638,
"s": 3586,
"text": "Enter integer to test primality: 26\n26 is not prime"
}
] |
Android | How to Change Toast font? - GeeksforGeeks
|
17 Sep, 2019
A Toast is a feedback message. It takes a very little space for displaying while overall activity is interactive and visible to the user. It disappears after a few seconds. It disappears automatically. If user wants permanent visible message, Notification can be used.
Toast disappears automatically based on the toast length defined by the developer. Steps to change the toast message font are as follow:
Step 1: Add a buttons in activity_main.xml file to show toast message with custom font.Open activity_main.xml file and create a button with id showToast.<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- To show the Toolbar--> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:background="@color/colorPrimary" app:title="GFG" app:titleTextColor="@android:color/white" android:layout_height="android:attr/actionBarSize"/> <!-- Button To show the toast message--> <Button android:id="@+id/showToast" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Toast" android:layout_marginTop="16dp" android:padding="8dp" android:layout_below="@id/toolbar" android:layout_centerHorizontal="true"/> </RelativeLayout>Step 2: Open styles.xml file and add new style for toast message.Open style.xml file and add the following code. Here sans-serif-black font is used.<!-- Toast Style --><style name="toastTextStyle" parent="TextAppearance.AppCompat"> <item name="android:fontFamily">sans-serif-black</item></style>Step 3: Open MainActivity.java and add function to show custom Toast.Create a new instance of Toast using makeText() method. Use getView() method to get the view of the Toast. Open MainActivity.java file and add function to show toast message.private void showMessage(Boolean b, String msg){ // Creating new instance of Toast Toast toast = Toast.makeText( MainActivity.this, " " + msg + " ", Toast.LENGTH_SHORT); // Getting the View View view = toast.getView(); // Finding the textview in Toast view TextView text = (TextView)view .findViewById( android.R.id.message); // Setting the Text Appearance if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { text.setTextAppearance( R.style.toastTextStyle); } // Showing the Toast Message toast.show();}Step 4: setOnClickListner to the button and show the toast message.To setOnclickListner() first create a new instance of Button class in Java file and find the button view using the id given in xml file and call the setOnClickListener() method on the button object.// Finding the buttonButton showToast = findViewById(R.id.showToast); // Setting the on click listenershowToast .setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Calling the function // to show toast message showMessage(); } });
Step 1: Add a buttons in activity_main.xml file to show toast message with custom font.Open activity_main.xml file and create a button with id showToast.<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- To show the Toolbar--> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:background="@color/colorPrimary" app:title="GFG" app:titleTextColor="@android:color/white" android:layout_height="android:attr/actionBarSize"/> <!-- Button To show the toast message--> <Button android:id="@+id/showToast" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Toast" android:layout_marginTop="16dp" android:padding="8dp" android:layout_below="@id/toolbar" android:layout_centerHorizontal="true"/> </RelativeLayout>
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- To show the Toolbar--> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:background="@color/colorPrimary" app:title="GFG" app:titleTextColor="@android:color/white" android:layout_height="android:attr/actionBarSize"/> <!-- Button To show the toast message--> <Button android:id="@+id/showToast" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Toast" android:layout_marginTop="16dp" android:padding="8dp" android:layout_below="@id/toolbar" android:layout_centerHorizontal="true"/> </RelativeLayout>
Step 2: Open styles.xml file and add new style for toast message.Open style.xml file and add the following code. Here sans-serif-black font is used.<!-- Toast Style --><style name="toastTextStyle" parent="TextAppearance.AppCompat"> <item name="android:fontFamily">sans-serif-black</item></style>
Open style.xml file and add the following code. Here sans-serif-black font is used.
<!-- Toast Style --><style name="toastTextStyle" parent="TextAppearance.AppCompat"> <item name="android:fontFamily">sans-serif-black</item></style>
Step 3: Open MainActivity.java and add function to show custom Toast.Create a new instance of Toast using makeText() method. Use getView() method to get the view of the Toast. Open MainActivity.java file and add function to show toast message.private void showMessage(Boolean b, String msg){ // Creating new instance of Toast Toast toast = Toast.makeText( MainActivity.this, " " + msg + " ", Toast.LENGTH_SHORT); // Getting the View View view = toast.getView(); // Finding the textview in Toast view TextView text = (TextView)view .findViewById( android.R.id.message); // Setting the Text Appearance if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { text.setTextAppearance( R.style.toastTextStyle); } // Showing the Toast Message toast.show();}
Create a new instance of Toast using makeText() method. Use getView() method to get the view of the Toast. Open MainActivity.java file and add function to show toast message.
private void showMessage(Boolean b, String msg){ // Creating new instance of Toast Toast toast = Toast.makeText( MainActivity.this, " " + msg + " ", Toast.LENGTH_SHORT); // Getting the View View view = toast.getView(); // Finding the textview in Toast view TextView text = (TextView)view .findViewById( android.R.id.message); // Setting the Text Appearance if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { text.setTextAppearance( R.style.toastTextStyle); } // Showing the Toast Message toast.show();}
Step 4: setOnClickListner to the button and show the toast message.To setOnclickListner() first create a new instance of Button class in Java file and find the button view using the id given in xml file and call the setOnClickListener() method on the button object.// Finding the buttonButton showToast = findViewById(R.id.showToast); // Setting the on click listenershowToast .setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Calling the function // to show toast message showMessage(); } });
To setOnclickListner() first create a new instance of Button class in Java file and find the button view using the id given in xml file and call the setOnClickListener() method on the button object.
// Finding the buttonButton showToast = findViewById(R.id.showToast); // Setting the on click listenershowToast .setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Calling the function // to show toast message showMessage(); } });
Finally files are
activity_main.xml
styles.xml
MainActivity.java
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- To show the Toolbar--> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:background="@color/colorPrimary" app:title="GFG" app:titleTextColor="@android:color/white" android:layout_height="android:attr/actionBarSize"/> <!-- Button To show the toast message--> <Button android:id="@+id/showToast" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Toast" android:layout_marginTop="16dp" android:padding="8dp" android:layout_below="@id/toolbar" android:layout_centerHorizontal="true"/> </RelativeLayout>
<resources > <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <!-- Toast Style --> <style name="toastTextStyle" parent="TextAppearance.AppCompat"> <item name="android:fontFamily">sans-serif-black</item> </style></resources>
package org.geeksforgeeks.customtoast; import android.os.Build;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Finding the button Button showToast = findViewById(R.id.showToast); // Setting the on click listener showToast.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showMessage(); } }); } private void showMessage() { // Creating new instance of Toast Toast toast = Toast.makeText( MainActivity.this, "GeeksForGeeks", Toast.LENGTH_SHORT); // Getting the View View view = toast.getView(); // Finding the textview in Toast view TextView text = (TextView)view.findViewById( android.R.id.message); // Setting the Text Appearance if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { text.setTextAppearance( R.style.toastTextStyle); } // Showing the Toast Message toast.show(); }}
Output:
android
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Stream In Java
Constructors in Java
Generics in Java
Exceptions in Java
Functional Interfaces in Java
Comparator Interface in Java with Examples
Commonly Asked Java Programming Interview Questions | Set 2
HashMap get() Method in Java
Strings in Java
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 24217,
"s": 23948,
"text": "A Toast is a feedback message. It takes a very little space for displaying while overall activity is interactive and visible to the user. It disappears after a few seconds. It disappears automatically. If user wants permanent visible message, Notification can be used."
},
{
"code": null,
"e": 24354,
"s": 24217,
"text": "Toast disappears automatically based on the toast length defined by the developer. Steps to change the toast message font are as follow:"
},
{
"code": null,
"e": 27400,
"s": 24354,
"text": "Step 1: Add a buttons in activity_main.xml file to show toast message with custom font.Open activity_main.xml file and create a button with id showToast.<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- To show the Toolbar--> <android.support.v7.widget.Toolbar android:id=\"@+id/toolbar\" android:layout_width=\"match_parent\" android:background=\"@color/colorPrimary\" app:title=\"GFG\" app:titleTextColor=\"@android:color/white\" android:layout_height=\"android:attr/actionBarSize\"/> <!-- Button To show the toast message--> <Button android:id=\"@+id/showToast\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Show Toast\" android:layout_marginTop=\"16dp\" android:padding=\"8dp\" android:layout_below=\"@id/toolbar\" android:layout_centerHorizontal=\"true\"/> </RelativeLayout>Step 2: Open styles.xml file and add new style for toast message.Open style.xml file and add the following code. Here sans-serif-black font is used.<!-- Toast Style --><style name=\"toastTextStyle\" parent=\"TextAppearance.AppCompat\"> <item name=\"android:fontFamily\">sans-serif-black</item></style>Step 3: Open MainActivity.java and add function to show custom Toast.Create a new instance of Toast using makeText() method. Use getView() method to get the view of the Toast. Open MainActivity.java file and add function to show toast message.private void showMessage(Boolean b, String msg){ // Creating new instance of Toast Toast toast = Toast.makeText( MainActivity.this, \" \" + msg + \" \", Toast.LENGTH_SHORT); // Getting the View View view = toast.getView(); // Finding the textview in Toast view TextView text = (TextView)view .findViewById( android.R.id.message); // Setting the Text Appearance if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { text.setTextAppearance( R.style.toastTextStyle); } // Showing the Toast Message toast.show();}Step 4: setOnClickListner to the button and show the toast message.To setOnclickListner() first create a new instance of Button class in Java file and find the button view using the id given in xml file and call the setOnClickListener() method on the button object.// Finding the buttonButton showToast = findViewById(R.id.showToast); // Setting the on click listenershowToast .setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Calling the function // to show toast message showMessage(); } });"
},
{
"code": null,
"e": 28607,
"s": 27400,
"text": "Step 1: Add a buttons in activity_main.xml file to show toast message with custom font.Open activity_main.xml file and create a button with id showToast.<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- To show the Toolbar--> <android.support.v7.widget.Toolbar android:id=\"@+id/toolbar\" android:layout_width=\"match_parent\" android:background=\"@color/colorPrimary\" app:title=\"GFG\" app:titleTextColor=\"@android:color/white\" android:layout_height=\"android:attr/actionBarSize\"/> <!-- Button To show the toast message--> <Button android:id=\"@+id/showToast\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Show Toast\" android:layout_marginTop=\"16dp\" android:padding=\"8dp\" android:layout_below=\"@id/toolbar\" android:layout_centerHorizontal=\"true\"/> </RelativeLayout>"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- To show the Toolbar--> <android.support.v7.widget.Toolbar android:id=\"@+id/toolbar\" android:layout_width=\"match_parent\" android:background=\"@color/colorPrimary\" app:title=\"GFG\" app:titleTextColor=\"@android:color/white\" android:layout_height=\"android:attr/actionBarSize\"/> <!-- Button To show the toast message--> <Button android:id=\"@+id/showToast\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Show Toast\" android:layout_marginTop=\"16dp\" android:padding=\"8dp\" android:layout_below=\"@id/toolbar\" android:layout_centerHorizontal=\"true\"/> </RelativeLayout>",
"e": 29661,
"s": 28607,
"text": null
},
{
"code": null,
"e": 29960,
"s": 29661,
"text": "Step 2: Open styles.xml file and add new style for toast message.Open style.xml file and add the following code. Here sans-serif-black font is used.<!-- Toast Style --><style name=\"toastTextStyle\" parent=\"TextAppearance.AppCompat\"> <item name=\"android:fontFamily\">sans-serif-black</item></style>"
},
{
"code": null,
"e": 30044,
"s": 29960,
"text": "Open style.xml file and add the following code. Here sans-serif-black font is used."
},
{
"code": "<!-- Toast Style --><style name=\"toastTextStyle\" parent=\"TextAppearance.AppCompat\"> <item name=\"android:fontFamily\">sans-serif-black</item></style>",
"e": 30195,
"s": 30044,
"text": null
},
{
"code": null,
"e": 31089,
"s": 30195,
"text": "Step 3: Open MainActivity.java and add function to show custom Toast.Create a new instance of Toast using makeText() method. Use getView() method to get the view of the Toast. Open MainActivity.java file and add function to show toast message.private void showMessage(Boolean b, String msg){ // Creating new instance of Toast Toast toast = Toast.makeText( MainActivity.this, \" \" + msg + \" \", Toast.LENGTH_SHORT); // Getting the View View view = toast.getView(); // Finding the textview in Toast view TextView text = (TextView)view .findViewById( android.R.id.message); // Setting the Text Appearance if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { text.setTextAppearance( R.style.toastTextStyle); } // Showing the Toast Message toast.show();}"
},
{
"code": null,
"e": 31264,
"s": 31089,
"text": "Create a new instance of Toast using makeText() method. Use getView() method to get the view of the Toast. Open MainActivity.java file and add function to show toast message."
},
{
"code": "private void showMessage(Boolean b, String msg){ // Creating new instance of Toast Toast toast = Toast.makeText( MainActivity.this, \" \" + msg + \" \", Toast.LENGTH_SHORT); // Getting the View View view = toast.getView(); // Finding the textview in Toast view TextView text = (TextView)view .findViewById( android.R.id.message); // Setting the Text Appearance if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { text.setTextAppearance( R.style.toastTextStyle); } // Showing the Toast Message toast.show();}",
"e": 31915,
"s": 31264,
"text": null
},
{
"code": null,
"e": 32564,
"s": 31915,
"text": "Step 4: setOnClickListner to the button and show the toast message.To setOnclickListner() first create a new instance of Button class in Java file and find the button view using the id given in xml file and call the setOnClickListener() method on the button object.// Finding the buttonButton showToast = findViewById(R.id.showToast); // Setting the on click listenershowToast .setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Calling the function // to show toast message showMessage(); } });"
},
{
"code": null,
"e": 32763,
"s": 32564,
"text": "To setOnclickListner() first create a new instance of Button class in Java file and find the button view using the id given in xml file and call the setOnClickListener() method on the button object."
},
{
"code": "// Finding the buttonButton showToast = findViewById(R.id.showToast); // Setting the on click listenershowToast .setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Calling the function // to show toast message showMessage(); } });",
"e": 33147,
"s": 32763,
"text": null
},
{
"code": null,
"e": 33165,
"s": 33147,
"text": "Finally files are"
},
{
"code": null,
"e": 33183,
"s": 33165,
"text": "activity_main.xml"
},
{
"code": null,
"e": 33194,
"s": 33183,
"text": "styles.xml"
},
{
"code": null,
"e": 33212,
"s": 33194,
"text": "MainActivity.java"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- To show the Toolbar--> <android.support.v7.widget.Toolbar android:id=\"@+id/toolbar\" android:layout_width=\"match_parent\" android:background=\"@color/colorPrimary\" app:title=\"GFG\" app:titleTextColor=\"@android:color/white\" android:layout_height=\"android:attr/actionBarSize\"/> <!-- Button To show the toast message--> <Button android:id=\"@+id/showToast\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Show Toast\" android:layout_marginTop=\"16dp\" android:padding=\"8dp\" android:layout_below=\"@id/toolbar\" android:layout_centerHorizontal=\"true\"/> </RelativeLayout>",
"e": 34268,
"s": 33212,
"text": null
},
{
"code": "<resources > <!-- Base application theme. --> <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.NoActionBar\"> <!-- Customize your theme here. --> <item name=\"colorPrimary\">@color/colorPrimary</item> <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item> <item name=\"colorAccent\">@color/colorAccent</item> </style> <!-- Toast Style --> <style name=\"toastTextStyle\" parent=\"TextAppearance.AppCompat\"> <item name=\"android:fontFamily\">sans-serif-black</item> </style></resources>",
"e": 34810,
"s": 34268,
"text": null
},
{
"code": "package org.geeksforgeeks.customtoast; import android.os.Build;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Finding the button Button showToast = findViewById(R.id.showToast); // Setting the on click listener showToast.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showMessage(); } }); } private void showMessage() { // Creating new instance of Toast Toast toast = Toast.makeText( MainActivity.this, \"GeeksForGeeks\", Toast.LENGTH_SHORT); // Getting the View View view = toast.getView(); // Finding the textview in Toast view TextView text = (TextView)view.findViewById( android.R.id.message); // Setting the Text Appearance if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { text.setTextAppearance( R.style.toastTextStyle); } // Showing the Toast Message toast.show(); }}",
"e": 36310,
"s": 34810,
"text": null
},
{
"code": null,
"e": 36318,
"s": 36310,
"text": "Output:"
},
{
"code": null,
"e": 36326,
"s": 36318,
"text": "android"
},
{
"code": null,
"e": 36331,
"s": 36326,
"text": "Java"
},
{
"code": null,
"e": 36336,
"s": 36331,
"text": "Java"
},
{
"code": null,
"e": 36434,
"s": 36336,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36443,
"s": 36434,
"text": "Comments"
},
{
"code": null,
"e": 36456,
"s": 36443,
"text": "Old Comments"
},
{
"code": null,
"e": 36502,
"s": 36456,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 36517,
"s": 36502,
"text": "Stream In Java"
},
{
"code": null,
"e": 36538,
"s": 36517,
"text": "Constructors in Java"
},
{
"code": null,
"e": 36555,
"s": 36538,
"text": "Generics in Java"
},
{
"code": null,
"e": 36574,
"s": 36555,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 36604,
"s": 36574,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 36647,
"s": 36604,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 36707,
"s": 36647,
"text": "Commonly Asked Java Programming Interview Questions | Set 2"
},
{
"code": null,
"e": 36736,
"s": 36707,
"text": "HashMap get() Method in Java"
}
] |
Node.js - NPM
|
Node Package Manager (NPM) provides two main functionalities −
Online repositories for node.js packages/modules which are searchable on search.nodejs.org
Online repositories for node.js packages/modules which are searchable on search.nodejs.org
Command line utility to install Node.js packages, do version management and dependency management of Node.js packages.
Command line utility to install Node.js packages, do version management and dependency management of Node.js packages.
NPM comes bundled with Node.js installables after v0.6.3 version. To verify the same, open console and type the following command and see the result −
$ npm --version
2.7.1
If you are running an old version of NPM then it is quite easy to update it to the latest version. Just use the following command from root −
$ sudo npm install npm -g
/usr/bin/npm -> /usr/lib/node_modules/npm/bin/npm-cli.js
npm@2.7.1 /usr/lib/node_modules/npm
There is a simple syntax to install any Node.js module −
$ npm install <Module Name>
For example, following is the command to install a famous Node.js web framework module called express −
$ npm install express
Now you can use this module in your js file as following −
var express = require('express');
By default, NPM installs any dependency in the local mode. Here local mode refers to the package installation in node_modules directory lying in the folder where Node application is present. Locally deployed packages are accessible via require() method. For example, when we installed express module, it created node_modules directory in the current directory where it installed the express module.
$ ls -l
total 0
drwxr-xr-x 3 root root 20 Mar 17 02:23 node_modules
Alternatively, you can use npm ls command to list down all the locally installed modules.
Globally installed packages/dependencies are stored in system directory. Such dependencies can be used in CLI (Command Line Interface) function of any node.js but cannot be imported using require() in Node application directly. Now let's try installing the express module using global installation.
$ npm install express -g
This will produce a similar result but the module will be installed globally. Here, the first line shows the module version and the location where it is getting installed.
express@4.12.2 /usr/lib/node_modules/express
├── merge-descriptors@1.0.0
├── utils-merge@1.0.0
├── cookie-signature@1.0.6
├── methods@1.1.1
├── fresh@0.2.4
├── cookie@0.1.2
├── escape-html@1.0.1
├── range-parser@1.0.2
├── content-type@1.0.1
├── finalhandler@0.3.3
├── vary@1.0.0
├── parseurl@1.3.0
├── content-disposition@0.5.0
├── path-to-regexp@0.1.3
├── depd@1.0.0
├── qs@2.3.3
├── on-finished@2.2.0 (ee-first@1.1.0)
├── etag@1.5.1 (crc@3.2.1)
├── debug@2.1.3 (ms@0.7.0)
├── proxy-addr@1.0.7 (forwarded@0.1.0, ipaddr.js@0.1.9)
├── send@0.12.1 (destroy@1.0.3, ms@0.7.0, mime@1.3.4)
├── serve-static@1.9.2 (send@0.12.2)
├── accepts@1.2.5 (negotiator@0.5.1, mime-types@2.0.10)
└── type-is@1.6.1 (media-typer@0.3.0, mime-types@2.0.10)
You can use the following command to check all the modules installed globally −
$ npm ls -g
package.json is present in the root directory of any Node application/module and is used to define the properties of a package. Let's open package.json of express package present in node_modules/express/
{
"name": "express",
"description": "Fast, unopinionated, minimalist web framework",
"version": "4.11.2",
"author": {
"name": "TJ Holowaychuk",
"email": "tj@vision-media.ca"
},
"contributors": [{
"name": "Aaron Heckmann",
"email": "aaron.heckmann+github@gmail.com"
},
{
"name": "Ciaran Jessup",
"email": "ciaranj@gmail.com"
},
{
"name": "Douglas Christopher Wilson",
"email": "doug@somethingdoug.com"
},
{
"name": "Guillermo Rauch",
"email": "rauchg@gmail.com"
},
{
"name": "Jonathan Ong",
"email": "me@jongleberry.com"
},
{
"name": "Roman Shtylman",
"email": "shtylman+expressjs@gmail.com"
},
{
"name": "Young Jae Sim",
"email": "hanul@hanul.me"
} ],
"license": "MIT", "repository": {
"type": "git",
"url": "https://github.com/strongloop/express"
},
"homepage": "https://expressjs.com/", "keywords": [
"express",
"framework",
"sinatra",
"web",
"rest",
"restful",
"router",
"app",
"api"
],
"dependencies": {
"accepts": "~1.2.3",
"content-disposition": "0.5.0",
"cookie-signature": "1.0.5",
"debug": "~2.1.1",
"depd": "~1.0.0",
"escape-html": "1.0.1",
"etag": "~1.5.1",
"finalhandler": "0.3.3",
"fresh": "0.2.4",
"media-typer": "0.3.0",
"methods": "~1.1.1",
"on-finished": "~2.2.0",
"parseurl": "~1.3.0",
"path-to-regexp": "0.1.3",
"proxy-addr": "~1.0.6",
"qs": "2.3.3",
"range-parser": "~1.0.2",
"send": "0.11.1",
"serve-static": "~1.8.1",
"type-is": "~1.5.6",
"vary": "~1.0.0",
"cookie": "0.1.2",
"merge-descriptors": "0.0.2",
"utils-merge": "1.0.0"
},
"devDependencies": {
"after": "0.8.1",
"ejs": "2.1.4",
"istanbul": "0.3.5",
"marked": "0.3.3",
"mocha": "~2.1.0",
"should": "~4.6.2",
"supertest": "~0.15.0",
"hjs": "~0.0.6",
"body-parser": "~1.11.0",
"connect-redis": "~2.2.0",
"cookie-parser": "~1.3.3",
"express-session": "~1.10.2",
"jade": "~1.9.1",
"method-override": "~2.3.1",
"morgan": "~1.5.1",
"multiparty": "~4.1.1",
"vhost": "~3.0.0"
},
"engines": {
"node": ">= 0.10.0"
},
"files": [
"LICENSE",
"History.md",
"Readme.md",
"index.js",
"lib/"
],
"scripts": {
"test": "mocha --require test/support/env
--reporter spec --bail --check-leaks test/ test/acceptance/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha
-- --require test/support/env --reporter dot --check-leaks test/ test/acceptance/",
"test-tap": "mocha --require test/support/env
--reporter tap --check-leaks test/ test/acceptance/",
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha
--report lcovonly -- --require test/support/env
--reporter spec --check-leaks test/ test/acceptance/"
},
"gitHead": "63ab25579bda70b4927a179b580a9c580b6c7ada",
"bugs": {
"url": "https://github.com/strongloop/express/issues"
},
"_id": "express@4.11.2",
"_shasum": "8df3d5a9ac848585f00a0777601823faecd3b148",
"_from": "express@*",
"_npmVersion": "1.4.28",
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
"maintainers": [{
"name": "tjholowaychuk",
"email": "tj@vision-media.ca"
},
{
"name": "jongleberry",
"email": "jonathanrichardong@gmail.com"
},
{
"name": "shtylman",
"email": "shtylman@gmail.com"
},
{
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
{
"name": "aredridel",
"email": "aredridel@nbtsc.org"
},
{
"name": "strongloop",
"email": "callback@strongloop.com"
},
{
"name": "rfeng",
"email": "enjoyjava@gmail.com"
}],
"dist": {
"shasum": "8df3d5a9ac848585f00a0777601823faecd3b148",
"tarball": "https://registry.npmjs.org/express/-/express-4.11.2.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/express/-/express-4.11.2.tgz",
"readme": "ERROR: No README data found!"
}
name − name of the package
name − name of the package
version − version of the package
version − version of the package
description − description of the package
description − description of the package
homepage − homepage of the package
homepage − homepage of the package
author − author of the package
author − author of the package
contributors − name of the contributors to the package
contributors − name of the contributors to the package
dependencies − list of dependencies. NPM automatically installs all the dependencies mentioned here in the node_module folder of the package.
dependencies − list of dependencies. NPM automatically installs all the dependencies mentioned here in the node_module folder of the package.
repository − repository type and URL of the package
repository − repository type and URL of the package
main − entry point of the package
main − entry point of the package
keywords − keywords
keywords − keywords
Use the following command to uninstall a Node.js module.
$ npm uninstall express
Once NPM uninstalls the package, you can verify it by looking at the content of /node_modules/ directory or type the following command −
$ npm ls
Update package.json and change the version of the dependency to be updated and run the following command.
$ npm update express
Search a package name using NPM.
$ npm search express
Creating a module requires package.json to be generated. Let's generate package.json using NPM, which will generate the basic skeleton of the package.json.
$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sane defaults.
See 'npm help json' for definitive documentation on these fields
and exactly what they do.
Use 'npm install <pkg> --save' afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
name: (webmaster)
You will need to provide all the required information about your module. You can take help from the above-mentioned package.json file to understand the meanings of various information demanded. Once package.json is generated, use the following command to register yourself with NPM repository site using a valid email address.
$ npm adduser
Username: mcmohd
Password:
Email: (this IS public) mcmohd@gmail.com
It is time now to publish your module −
$ npm publish
If everything is fine with your module, then it will be published in the repository and will be accessible to install using NPM like any other Node.js module.
44 Lectures
7.5 hours
Eduonix Learning Solutions
88 Lectures
17 hours
Eduonix Learning Solutions
32 Lectures
1.5 hours
Richard Wells
8 Lectures
33 mins
Anant Rungta
9 Lectures
2.5 hours
SHIVPRASAD KOIRALA
97 Lectures
6 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2081,
"s": 2018,
"text": "Node Package Manager (NPM) provides two main functionalities −"
},
{
"code": null,
"e": 2172,
"s": 2081,
"text": "Online repositories for node.js packages/modules which are searchable on search.nodejs.org"
},
{
"code": null,
"e": 2263,
"s": 2172,
"text": "Online repositories for node.js packages/modules which are searchable on search.nodejs.org"
},
{
"code": null,
"e": 2382,
"s": 2263,
"text": "Command line utility to install Node.js packages, do version management and dependency management of Node.js packages."
},
{
"code": null,
"e": 2501,
"s": 2382,
"text": "Command line utility to install Node.js packages, do version management and dependency management of Node.js packages."
},
{
"code": null,
"e": 2652,
"s": 2501,
"text": "NPM comes bundled with Node.js installables after v0.6.3 version. To verify the same, open console and type the following command and see the result −"
},
{
"code": null,
"e": 2675,
"s": 2652,
"text": "$ npm --version\n2.7.1\n"
},
{
"code": null,
"e": 2817,
"s": 2675,
"text": "If you are running an old version of NPM then it is quite easy to update it to the latest version. Just use the following command from root −"
},
{
"code": null,
"e": 2937,
"s": 2817,
"text": "$ sudo npm install npm -g\n/usr/bin/npm -> /usr/lib/node_modules/npm/bin/npm-cli.js\nnpm@2.7.1 /usr/lib/node_modules/npm\n"
},
{
"code": null,
"e": 2994,
"s": 2937,
"text": "There is a simple syntax to install any Node.js module −"
},
{
"code": null,
"e": 3023,
"s": 2994,
"text": "$ npm install <Module Name>\n"
},
{
"code": null,
"e": 3127,
"s": 3023,
"text": "For example, following is the command to install a famous Node.js web framework module called express −"
},
{
"code": null,
"e": 3150,
"s": 3127,
"text": "$ npm install express\n"
},
{
"code": null,
"e": 3209,
"s": 3150,
"text": "Now you can use this module in your js file as following −"
},
{
"code": null,
"e": 3244,
"s": 3209,
"text": "var express = require('express');\n"
},
{
"code": null,
"e": 3643,
"s": 3244,
"text": "By default, NPM installs any dependency in the local mode. Here local mode refers to the package installation in node_modules directory lying in the folder where Node application is present. Locally deployed packages are accessible via require() method. For example, when we installed express module, it created node_modules directory in the current directory where it installed the express module."
},
{
"code": null,
"e": 3712,
"s": 3643,
"text": "$ ls -l\ntotal 0\ndrwxr-xr-x 3 root root 20 Mar 17 02:23 node_modules\n"
},
{
"code": null,
"e": 3802,
"s": 3712,
"text": "Alternatively, you can use npm ls command to list down all the locally installed modules."
},
{
"code": null,
"e": 4101,
"s": 3802,
"text": "Globally installed packages/dependencies are stored in system directory. Such dependencies can be used in CLI (Command Line Interface) function of any node.js but cannot be imported using require() in Node application directly. Now let's try installing the express module using global installation."
},
{
"code": null,
"e": 4127,
"s": 4101,
"text": "$ npm install express -g\n"
},
{
"code": null,
"e": 4299,
"s": 4127,
"text": "This will produce a similar result but the module will be installed globally. Here, the first line shows the module version and the location where it is getting installed."
},
{
"code": null,
"e": 5034,
"s": 4299,
"text": "express@4.12.2 /usr/lib/node_modules/express\n├── merge-descriptors@1.0.0\n├── utils-merge@1.0.0\n├── cookie-signature@1.0.6\n├── methods@1.1.1\n├── fresh@0.2.4\n├── cookie@0.1.2\n├── escape-html@1.0.1\n├── range-parser@1.0.2\n├── content-type@1.0.1\n├── finalhandler@0.3.3\n├── vary@1.0.0\n├── parseurl@1.3.0\n├── content-disposition@0.5.0\n├── path-to-regexp@0.1.3\n├── depd@1.0.0\n├── qs@2.3.3\n├── on-finished@2.2.0 (ee-first@1.1.0)\n├── etag@1.5.1 (crc@3.2.1)\n├── debug@2.1.3 (ms@0.7.0)\n├── proxy-addr@1.0.7 (forwarded@0.1.0, ipaddr.js@0.1.9)\n├── send@0.12.1 (destroy@1.0.3, ms@0.7.0, mime@1.3.4)\n├── serve-static@1.9.2 (send@0.12.2)\n├── accepts@1.2.5 (negotiator@0.5.1, mime-types@2.0.10)\n└── type-is@1.6.1 (media-typer@0.3.0, mime-types@2.0.10)\n"
},
{
"code": null,
"e": 5114,
"s": 5034,
"text": "You can use the following command to check all the modules installed globally −"
},
{
"code": null,
"e": 5127,
"s": 5114,
"text": "$ npm ls -g\n"
},
{
"code": null,
"e": 5331,
"s": 5127,
"text": "package.json is present in the root directory of any Node application/module and is used to define the properties of a package. Let's open package.json of express package present in node_modules/express/"
},
{
"code": null,
"e": 9786,
"s": 5331,
"text": "{\n \"name\": \"express\",\n \"description\": \"Fast, unopinionated, minimalist web framework\",\n \"version\": \"4.11.2\",\n \"author\": {\n \n \"name\": \"TJ Holowaychuk\",\n \"email\": \"tj@vision-media.ca\"\n },\n \n \"contributors\": [{\n \"name\": \"Aaron Heckmann\",\n \"email\": \"aaron.heckmann+github@gmail.com\"\n }, \n \n {\n \"name\": \"Ciaran Jessup\",\n \"email\": \"ciaranj@gmail.com\"\n },\n \n {\n \"name\": \"Douglas Christopher Wilson\",\n \"email\": \"doug@somethingdoug.com\"\n },\n \n {\n \"name\": \"Guillermo Rauch\",\n \"email\": \"rauchg@gmail.com\"\n },\n \n {\n \"name\": \"Jonathan Ong\",\n \"email\": \"me@jongleberry.com\"\n },\n \n {\n \"name\": \"Roman Shtylman\",\n \"email\": \"shtylman+expressjs@gmail.com\"\n },\n \n {\n \"name\": \"Young Jae Sim\",\n \"email\": \"hanul@hanul.me\"\n } ],\n \n \"license\": \"MIT\", \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/strongloop/express\"\n },\n \n \"homepage\": \"https://expressjs.com/\", \"keywords\": [\n \"express\",\n \"framework\",\n \"sinatra\",\n \"web\",\n \"rest\",\n \"restful\",\n \"router\",\n \"app\",\n \"api\"\n ],\n \n \"dependencies\": {\n \"accepts\": \"~1.2.3\",\n \"content-disposition\": \"0.5.0\",\n \"cookie-signature\": \"1.0.5\",\n \"debug\": \"~2.1.1\",\n \"depd\": \"~1.0.0\",\n \"escape-html\": \"1.0.1\",\n \"etag\": \"~1.5.1\",\n \"finalhandler\": \"0.3.3\",\n \"fresh\": \"0.2.4\",\n \"media-typer\": \"0.3.0\",\n \"methods\": \"~1.1.1\",\n \"on-finished\": \"~2.2.0\",\n \"parseurl\": \"~1.3.0\",\n \"path-to-regexp\": \"0.1.3\",\n \"proxy-addr\": \"~1.0.6\",\n \"qs\": \"2.3.3\",\n \"range-parser\": \"~1.0.2\",\n \"send\": \"0.11.1\",\n \"serve-static\": \"~1.8.1\",\n \"type-is\": \"~1.5.6\",\n \"vary\": \"~1.0.0\",\n \"cookie\": \"0.1.2\",\n \"merge-descriptors\": \"0.0.2\",\n \"utils-merge\": \"1.0.0\"\n },\n \n \"devDependencies\": {\n \"after\": \"0.8.1\",\n \"ejs\": \"2.1.4\",\n \"istanbul\": \"0.3.5\",\n \"marked\": \"0.3.3\",\n \"mocha\": \"~2.1.0\",\n \"should\": \"~4.6.2\",\n \"supertest\": \"~0.15.0\",\n \"hjs\": \"~0.0.6\",\n \"body-parser\": \"~1.11.0\",\n \"connect-redis\": \"~2.2.0\",\n \"cookie-parser\": \"~1.3.3\",\n \"express-session\": \"~1.10.2\",\n \"jade\": \"~1.9.1\",\n \"method-override\": \"~2.3.1\",\n \"morgan\": \"~1.5.1\",\n \"multiparty\": \"~4.1.1\",\n \"vhost\": \"~3.0.0\"\n },\n \n \"engines\": {\n \"node\": \">= 0.10.0\"\n },\n \n \"files\": [\n \"LICENSE\",\n \"History.md\",\n \"Readme.md\",\n \"index.js\",\n \"lib/\"\n ],\n \n \"scripts\": {\n \"test\": \"mocha --require test/support/env \n --reporter spec --bail --check-leaks test/ test/acceptance/\",\n \"test-cov\": \"istanbul cover node_modules/mocha/bin/_mocha \n -- --require test/support/env --reporter dot --check-leaks test/ test/acceptance/\",\n \"test-tap\": \"mocha --require test/support/env \n --reporter tap --check-leaks test/ test/acceptance/\",\n \"test-travis\": \"istanbul cover node_modules/mocha/bin/_mocha \n --report lcovonly -- --require test/support/env \n --reporter spec --check-leaks test/ test/acceptance/\"\n },\n \n \"gitHead\": \"63ab25579bda70b4927a179b580a9c580b6c7ada\",\n \"bugs\": {\n \"url\": \"https://github.com/strongloop/express/issues\"\n },\n \n \"_id\": \"express@4.11.2\",\n \"_shasum\": \"8df3d5a9ac848585f00a0777601823faecd3b148\",\n \"_from\": \"express@*\",\n \"_npmVersion\": \"1.4.28\",\n \"_npmUser\": {\n \"name\": \"dougwilson\",\n \"email\": \"doug@somethingdoug.com\"\n },\n \n \"maintainers\": [{\n \"name\": \"tjholowaychuk\",\n \"email\": \"tj@vision-media.ca\"\n },\n \n {\n \"name\": \"jongleberry\",\n \"email\": \"jonathanrichardong@gmail.com\"\n },\n \n {\n \"name\": \"shtylman\",\n \"email\": \"shtylman@gmail.com\"\n },\n \n {\n \"name\": \"dougwilson\",\n \"email\": \"doug@somethingdoug.com\"\n },\n \n {\n \"name\": \"aredridel\",\n \"email\": \"aredridel@nbtsc.org\"\n },\n \n {\n \"name\": \"strongloop\",\n \"email\": \"callback@strongloop.com\"\n },\n \n {\n \"name\": \"rfeng\",\n \"email\": \"enjoyjava@gmail.com\"\n }],\n \n \"dist\": {\n \"shasum\": \"8df3d5a9ac848585f00a0777601823faecd3b148\",\n \"tarball\": \"https://registry.npmjs.org/express/-/express-4.11.2.tgz\"\n },\n \n \"directories\": {},\n \"_resolved\": \"https://registry.npmjs.org/express/-/express-4.11.2.tgz\",\n \"readme\": \"ERROR: No README data found!\"\n}"
},
{
"code": null,
"e": 9813,
"s": 9786,
"text": "name − name of the package"
},
{
"code": null,
"e": 9840,
"s": 9813,
"text": "name − name of the package"
},
{
"code": null,
"e": 9873,
"s": 9840,
"text": "version − version of the package"
},
{
"code": null,
"e": 9906,
"s": 9873,
"text": "version − version of the package"
},
{
"code": null,
"e": 9947,
"s": 9906,
"text": "description − description of the package"
},
{
"code": null,
"e": 9988,
"s": 9947,
"text": "description − description of the package"
},
{
"code": null,
"e": 10023,
"s": 9988,
"text": "homepage − homepage of the package"
},
{
"code": null,
"e": 10058,
"s": 10023,
"text": "homepage − homepage of the package"
},
{
"code": null,
"e": 10089,
"s": 10058,
"text": "author − author of the package"
},
{
"code": null,
"e": 10120,
"s": 10089,
"text": "author − author of the package"
},
{
"code": null,
"e": 10175,
"s": 10120,
"text": "contributors − name of the contributors to the package"
},
{
"code": null,
"e": 10230,
"s": 10175,
"text": "contributors − name of the contributors to the package"
},
{
"code": null,
"e": 10372,
"s": 10230,
"text": "dependencies − list of dependencies. NPM automatically installs all the dependencies mentioned here in the node_module folder of the package."
},
{
"code": null,
"e": 10514,
"s": 10372,
"text": "dependencies − list of dependencies. NPM automatically installs all the dependencies mentioned here in the node_module folder of the package."
},
{
"code": null,
"e": 10566,
"s": 10514,
"text": "repository − repository type and URL of the package"
},
{
"code": null,
"e": 10618,
"s": 10566,
"text": "repository − repository type and URL of the package"
},
{
"code": null,
"e": 10652,
"s": 10618,
"text": "main − entry point of the package"
},
{
"code": null,
"e": 10686,
"s": 10652,
"text": "main − entry point of the package"
},
{
"code": null,
"e": 10706,
"s": 10686,
"text": "keywords − keywords"
},
{
"code": null,
"e": 10726,
"s": 10706,
"text": "keywords − keywords"
},
{
"code": null,
"e": 10783,
"s": 10726,
"text": "Use the following command to uninstall a Node.js module."
},
{
"code": null,
"e": 10808,
"s": 10783,
"text": "$ npm uninstall express\n"
},
{
"code": null,
"e": 10945,
"s": 10808,
"text": "Once NPM uninstalls the package, you can verify it by looking at the content of /node_modules/ directory or type the following command −"
},
{
"code": null,
"e": 10955,
"s": 10945,
"text": "$ npm ls\n"
},
{
"code": null,
"e": 11061,
"s": 10955,
"text": "Update package.json and change the version of the dependency to be updated and run the following command."
},
{
"code": null,
"e": 11083,
"s": 11061,
"text": "$ npm update express\n"
},
{
"code": null,
"e": 11116,
"s": 11083,
"text": "Search a package name using NPM."
},
{
"code": null,
"e": 11138,
"s": 11116,
"text": "$ npm search express\n"
},
{
"code": null,
"e": 11294,
"s": 11138,
"text": "Creating a module requires package.json to be generated. Let's generate package.json using NPM, which will generate the basic skeleton of the package.json."
},
{
"code": null,
"e": 11702,
"s": 11294,
"text": "$ npm init\nThis utility will walk you through creating a package.json file.\nIt only covers the most common items, and tries to guess sane defaults.\n\nSee 'npm help json' for definitive documentation on these fields\nand exactly what they do.\n\nUse 'npm install <pkg> --save' afterwards to install a package and\nsave it as a dependency in the package.json file.\n\nPress ^C at any time to quit.\nname: (webmaster)\n"
},
{
"code": null,
"e": 12029,
"s": 11702,
"text": "You will need to provide all the required information about your module. You can take help from the above-mentioned package.json file to understand the meanings of various information demanded. Once package.json is generated, use the following command to register yourself with NPM repository site using a valid email address."
},
{
"code": null,
"e": 12112,
"s": 12029,
"text": "$ npm adduser\nUsername: mcmohd\nPassword:\nEmail: (this IS public) mcmohd@gmail.com\n"
},
{
"code": null,
"e": 12152,
"s": 12112,
"text": "It is time now to publish your module −"
},
{
"code": null,
"e": 12167,
"s": 12152,
"text": "$ npm publish\n"
},
{
"code": null,
"e": 12326,
"s": 12167,
"text": "If everything is fine with your module, then it will be published in the repository and will be accessible to install using NPM like any other Node.js module."
},
{
"code": null,
"e": 12361,
"s": 12326,
"text": "\n 44 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 12389,
"s": 12361,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12423,
"s": 12389,
"text": "\n 88 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 12451,
"s": 12423,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12486,
"s": 12451,
"text": "\n 32 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 12501,
"s": 12486,
"text": " Richard Wells"
},
{
"code": null,
"e": 12532,
"s": 12501,
"text": "\n 8 Lectures \n 33 mins\n"
},
{
"code": null,
"e": 12546,
"s": 12532,
"text": " Anant Rungta"
},
{
"code": null,
"e": 12580,
"s": 12546,
"text": "\n 9 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12600,
"s": 12580,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 12633,
"s": 12600,
"text": "\n 97 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 12653,
"s": 12633,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 12660,
"s": 12653,
"text": " Print"
},
{
"code": null,
"e": 12671,
"s": 12660,
"text": " Add Notes"
}
] |
PyQt5 – Digital StopWatch - GeeksforGeeks
|
22 Apr, 2020
In this article we will see how we can create a stop watch using Python GUI – PyQt5.A stopwatch is a handheld timepiece designed to measure the amount of time that elapses between its activation and deactivation. A large digital version of a stopwatch designed for viewing at a distance, as in a sports stadium, is called a Stopclock.
Steps to create a stop watch –
1. Create a counter which signify the seconds2. Create flag to know when to start and when to pause, set it to False3. Create label to show seconds4. Create three push button for starting the stop watch pausing the stop watch and for re-setting the stop watch5. Add action to each push button.6. Inside start push button action make flag to true7. Inside pause push button action make flag to false8. Inside reset push button action make flag to false and make the counter value to 09. Create QTimer object which calls a method after every 100 millisecond i.e 10th part of second10. Inside QTimer object method check for the flag status if it is true increment the counter11. Show the counter value through label using setText method.
Below is the implementation –
# 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 Stop watch") # setting geometry self.setGeometry(100, 100, 400, 500) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # counter self.count = 0 # creating flag self.flag = False # creating a label to show the time self.label = QLabel(self) # setting geometry of label self.label.setGeometry(75, 100, 250, 70) # adding border to the label self.label.setStyleSheet("border : 4px solid black;") # setting text to the label self.label.setText(str(self.count)) # setting font to the label self.label.setFont(QFont('Arial', 25)) # setting alignment to the text of label self.label.setAlignment(Qt.AlignCenter) # creating start button start = QPushButton("Start", self) # setting geometry to the button start.setGeometry(125, 250, 150, 40) # add action to the method start.pressed.connect(self.Start) # creating pause button pause = QPushButton("Pause", self) # setting geometry to the button pause.setGeometry(125, 300, 150, 40) # add action to the method pause.pressed.connect(self.Pause) # creating reset button re_set = QPushButton("Re-set", self) # setting geometry to the button re_set.setGeometry(125, 350, 150, 40) # add action to the method re_set.pressed.connect(self.Re_set) # creating a timer object timer = QTimer(self) # adding action to timer timer.timeout.connect(self.showTime) # update the timer every tenth second timer.start(100) # method called by timer def showTime(self): # checking if flag is true if self.flag: # incrementing the counter self.count+= 1 # getting text from count text = str(self.count / 10) # showing text self.label.setText(text) def Start(self): # making flag to true self.flag = True def Pause(self): # making flag to False self.flag = False def Re_set(self): # making flag to false self.flag = False # reseeting the count self.count = 0 # setting text to label self.label.setText(str(self.count)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24240,
"s": 24212,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 24575,
"s": 24240,
"text": "In this article we will see how we can create a stop watch using Python GUI – PyQt5.A stopwatch is a handheld timepiece designed to measure the amount of time that elapses between its activation and deactivation. A large digital version of a stopwatch designed for viewing at a distance, as in a sports stadium, is called a Stopclock."
},
{
"code": null,
"e": 24606,
"s": 24575,
"text": "Steps to create a stop watch –"
},
{
"code": null,
"e": 25341,
"s": 24606,
"text": "1. Create a counter which signify the seconds2. Create flag to know when to start and when to pause, set it to False3. Create label to show seconds4. Create three push button for starting the stop watch pausing the stop watch and for re-setting the stop watch5. Add action to each push button.6. Inside start push button action make flag to true7. Inside pause push button action make flag to false8. Inside reset push button action make flag to false and make the counter value to 09. Create QTimer object which calls a method after every 100 millisecond i.e 10th part of second10. Inside QTimer object method check for the flag status if it is true increment the counter11. Show the counter value through label using setText method."
},
{
"code": null,
"e": 25371,
"s": 25341,
"text": "Below is the implementation –"
},
{
"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 Stop watch\") # setting geometry self.setGeometry(100, 100, 400, 500) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # counter self.count = 0 # creating flag self.flag = False # creating a label to show the time self.label = QLabel(self) # setting geometry of label self.label.setGeometry(75, 100, 250, 70) # adding border to the label self.label.setStyleSheet(\"border : 4px solid black;\") # setting text to the label self.label.setText(str(self.count)) # setting font to the label self.label.setFont(QFont('Arial', 25)) # setting alignment to the text of label self.label.setAlignment(Qt.AlignCenter) # creating start button start = QPushButton(\"Start\", self) # setting geometry to the button start.setGeometry(125, 250, 150, 40) # add action to the method start.pressed.connect(self.Start) # creating pause button pause = QPushButton(\"Pause\", self) # setting geometry to the button pause.setGeometry(125, 300, 150, 40) # add action to the method pause.pressed.connect(self.Pause) # creating reset button re_set = QPushButton(\"Re-set\", self) # setting geometry to the button re_set.setGeometry(125, 350, 150, 40) # add action to the method re_set.pressed.connect(self.Re_set) # creating a timer object timer = QTimer(self) # adding action to timer timer.timeout.connect(self.showTime) # update the timer every tenth second timer.start(100) # method called by timer def showTime(self): # checking if flag is true if self.flag: # incrementing the counter self.count+= 1 # getting text from count text = str(self.count / 10) # showing text self.label.setText(text) def Start(self): # making flag to true self.flag = True def Pause(self): # making flag to False self.flag = False def Re_set(self): # making flag to false self.flag = False # reseeting the count self.count = 0 # setting text to label self.label.setText(str(self.count)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 28257,
"s": 25371,
"text": null
},
{
"code": null,
"e": 28266,
"s": 28257,
"text": "Output :"
},
{
"code": null,
"e": 28277,
"s": 28266,
"text": "Python-gui"
},
{
"code": null,
"e": 28289,
"s": 28277,
"text": "Python-PyQt"
},
{
"code": null,
"e": 28296,
"s": 28289,
"text": "Python"
},
{
"code": null,
"e": 28394,
"s": 28296,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28412,
"s": 28394,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28447,
"s": 28412,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28469,
"s": 28447,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28501,
"s": 28469,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28531,
"s": 28501,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28573,
"s": 28531,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28599,
"s": 28573,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28636,
"s": 28599,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28679,
"s": 28636,
"text": "Python program to convert a list to string"
}
] |
Highcharts - Ajax Loaded Data Chart
|
Here, we will discuss an example of an ajax loaded data chart. To begin with, we will make an ajax call to load a csv file from Highcharts.Com using the jQuery.getJSON() method and when the data gets retrieved, we will populate the chart with received data and draw the chart.
We have understood most of the configuration used to draw a chart in Highcharts Configuration Syntax chapter.
In order to work with ajax data, import the following script.
<script src = "https://code.highcharts.com/modules/data.js"></script>
Let us now understand additional configurations/step taken.
Configure the tick intervals to be based on weekly basis on the X-Axis.
var xAxis = {
tickInterval: 7 * 24 * 3600 * 1000, // one week
tickWidth: 0,
gridLineWidth: 1,
labels: {
align: 'left',
x: 3,
y: -3
}
};
Configure two axes on the y-Axis.
var yAxis = [
{ // left y axis
title: {
text: null
},
labels: {
align: 'left',
x: 3,
y: 16,
format: '{value:.,0f}'
},
showFirstLabel: false
},
{ // right y axis
linkedTo: 0,
gridLineWidth: 0,
opposite: true,
title: {
text: null
},
labels: {
align: 'right',
x: -3,
y: 16,
format: '{value:.,0f}'
},
showFirstLabel: false
}
];
plotOptions is used to control the formatting of various parts of chart like series, marker on series.
var plotOptions = {
series: {
cursor: 'pointer',
point: {
events: {
click: function (e) {
hs.htmlExpand(null, {
pageOrigin: {
x: e.pageX || e.clientX,
y: e.pageY || e.clientY
},
headingText: this.series.name,
maincontentText: Highcharts.dateFormat('%A, %b %e, %Y', this.x)
+ ':<br/> ' + this.y + ' visits', width: 200
});
}
}
},
marker: {
lineWidth: 1
}
}
}
highcharts_line_ajax.htm
<html>
<head>
<title>Highcharts Tutorial</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src = "https://code.highcharts.com/highcharts.js"></script>
<script src = "https://code.highcharts.com/highcharts-more.js"></script>
<script src = "https://code.highcharts.com/modules/data.js"></script>
</head>
<body>
<div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"></div>
<script language = "JavaScript">
$(document).ready(function() {
var title = {
text: 'Daily visits at www.highcharts.com'
};
var subtitle = {
text: 'Source: Google Analytics'
};
var xAxis = {
tickInterval: 7 * 24 * 3600 * 1000, // one week
tickWidth: 0,
gridLineWidth: 1,
labels: {
align: 'left',
x: 3,
y: -3
}
};
var yAxis = [
{ // left y axis
title: {
text: null
},
labels: {
align: 'left',
x: 3,
y: 16,
format: '{value:.,0f}'
},
showFirstLabel: false
},
{ // right y axis
linkedTo: 0,
gridLineWidth: 0,
opposite: true,
title: {
text: null
},
labels: {
align: 'right',
x: -3,
y: 16,
format: '{value:.,0f}'
},
showFirstLabel: false
}
];
var tooltip = {
shared: true,
crosshairs: true
}
var legend = {
align: 'left',
verticalAlign: 'top',
y: 20,
floating: true,
borderWidth: 0
};
var plotOptions = {
series: {
cursor: 'pointer',
point: {
events: {
click: function (e) {
hs.htmlExpand(null, {
pageOrigin: {
x: e.pageX || e.clientX,
y: e.pageY || e.clientY
},
headingText: this.series.name,
maincontentText: Highcharts.dateFormat(
'%A, %b %e, %Y', this.x) +
':<br/> ' + this.y +
' visits', width: 200
});
}
}
},
marker: {
lineWidth: 1
}
}
}
var series = [
{
name: 'All visits',
lineWidth: 4,
marker: {
radius: 4
}
},
{
name: 'New visitors'
}
]
var json = {};
json.title = title;
json.subtitle = subtitle;
json.xAxis = xAxis;
json.yAxis = yAxis;
json.tooltip = tooltip;
json.legend = legend;
json.series = series;
json.plotOptions = plotOptions;
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename =
analytics.csv&callback = ?', function (csv) {
var data = {
csv: csv
};
json.data = data;
$('#container').highcharts(json);
});
});
</script>
</body>
</html>
Verify the result.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2294,
"s": 2017,
"text": "Here, we will discuss an example of an ajax loaded data chart. To begin with, we will make an ajax call to load a csv file from Highcharts.Com using the jQuery.getJSON() method and when the data gets retrieved, we will populate the chart with received data and draw the chart."
},
{
"code": null,
"e": 2404,
"s": 2294,
"text": "We have understood most of the configuration used to draw a chart in Highcharts Configuration Syntax chapter."
},
{
"code": null,
"e": 2466,
"s": 2404,
"text": "In order to work with ajax data, import the following script."
},
{
"code": null,
"e": 2538,
"s": 2466,
"text": "<script src = \"https://code.highcharts.com/modules/data.js\"></script> \n"
},
{
"code": null,
"e": 2598,
"s": 2538,
"text": "Let us now understand additional configurations/step taken."
},
{
"code": null,
"e": 2670,
"s": 2598,
"text": "Configure the tick intervals to be based on weekly basis on the X-Axis."
},
{
"code": null,
"e": 2843,
"s": 2670,
"text": "var xAxis = {\n tickInterval: 7 * 24 * 3600 * 1000, // one week\n tickWidth: 0,\n gridLineWidth: 1,\n \n labels: {\n align: 'left',\n x: 3,\n y: -3\n }\n};"
},
{
"code": null,
"e": 2877,
"s": 2843,
"text": "Configure two axes on the y-Axis."
},
{
"code": null,
"e": 3391,
"s": 2877,
"text": "var yAxis = [\n { // left y axis\n title: {\n text: null\n },\n labels: {\n align: 'left',\n x: 3,\n y: 16,\n format: '{value:.,0f}'\n },\n showFirstLabel: false\n },\n { // right y axis\n linkedTo: 0,\n gridLineWidth: 0,\n opposite: true,\n \n title: {\n text: null\n },\n labels: {\n align: 'right',\n x: -3,\n y: 16,\n format: '{value:.,0f}'\n },\n showFirstLabel: false\n }\n]; "
},
{
"code": null,
"e": 3494,
"s": 3391,
"text": "plotOptions is used to control the formatting of various parts of chart like series, marker on series."
},
{
"code": null,
"e": 4105,
"s": 3494,
"text": "var plotOptions = {\n series: {\n cursor: 'pointer',\n point: {\n events: {\n click: function (e) {\n hs.htmlExpand(null, {\n pageOrigin: {\n x: e.pageX || e.clientX,\n y: e.pageY || e.clientY\n },\n headingText: this.series.name,\n maincontentText: Highcharts.dateFormat('%A, %b %e, %Y', this.x)\n + ':<br/> ' + this.y + ' visits', width: 200\n });\n } \n }\n },\n marker: {\n lineWidth: 1\n }\n }\n}"
},
{
"code": null,
"e": 4130,
"s": 4105,
"text": "highcharts_line_ajax.htm"
},
{
"code": null,
"e": 8426,
"s": 4130,
"text": "<html>\n <head>\n <title>Highcharts Tutorial</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n <script src = \"https://code.highcharts.com/highcharts.js\"></script> \n <script src = \"https://code.highcharts.com/highcharts-more.js\"></script> \n <script src = \"https://code.highcharts.com/modules/data.js\"></script> \n </head>\n \n <body>\n <div id = \"container\" style = \"width: 550px; height: 400px; margin: 0 auto\"></div>\n <script language = \"JavaScript\">\n $(document).ready(function() {\n var title = {\n text: 'Daily visits at www.highcharts.com' \n };\n \n var subtitle = {\n text: 'Source: Google Analytics'\n };\n \n var xAxis = {\n tickInterval: 7 * 24 * 3600 * 1000, // one week\n tickWidth: 0,\n gridLineWidth: 1,\n \n labels: {\n align: 'left',\n x: 3,\n y: -3\n }\n };\n \n var yAxis = [\n { // left y axis\n title: {\n text: null\n },\n labels: {\n align: 'left',\n x: 3,\n y: 16,\n format: '{value:.,0f}'\n },\n showFirstLabel: false\n }, \n { // right y axis\n linkedTo: 0,\n gridLineWidth: 0,\n opposite: true,\n \n title: {\n text: null\n },\n labels: {\n align: 'right',\n x: -3,\n y: 16,\n format: '{value:.,0f}'\n },\n showFirstLabel: false\n }\n ]; \n \n var tooltip = {\n shared: true,\n crosshairs: true\n }\n \n var legend = {\n align: 'left',\n verticalAlign: 'top',\n y: 20,\n floating: true,\n borderWidth: 0\n };\n \n var plotOptions = {\n series: {\n cursor: 'pointer',\n point: {\n events: {\n click: function (e) {\n hs.htmlExpand(null, {\n pageOrigin: {\n x: e.pageX || e.clientX,\n y: e.pageY || e.clientY\n },\n headingText: this.series.name,\n maincontentText: Highcharts.dateFormat(\n '%A, %b %e, %Y', this.x) +\n ':<br/> ' + this.y +\n ' visits', width: 200\n });\n }\n }\n },\n marker: {\n lineWidth: 1\n }\n }\n }\n \n var series = [\n {\n name: 'All visits',\n lineWidth: 4,\n marker: {\n radius: 4\n }\n }, \n {\n name: 'New visitors'\n }\n ]\n \n var json = {};\n json.title = title;\n json.subtitle = subtitle;\n json.xAxis = xAxis;\n json.yAxis = yAxis;\n json.tooltip = tooltip;\n json.legend = legend;\n json.series = series;\n json.plotOptions = plotOptions;\n \n $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename =\n analytics.csv&callback = ?', function (csv) {\n var data = {\n csv: csv\n };\n json.data = data;\n $('#container').highcharts(json);\n }); \n });\n </script>\n </body>\n \n</html>"
},
{
"code": null,
"e": 8445,
"s": 8426,
"text": "Verify the result."
},
{
"code": null,
"e": 8452,
"s": 8445,
"text": " Print"
},
{
"code": null,
"e": 8463,
"s": 8452,
"text": " Add Notes"
}
] |
How to remove an element from an array in JavaScript? - GeeksforGeeks
|
14 Mar, 2019
Array splice() method can be used to remove any particular element from an array in JavaScript. Moreover, this function can be used to add/remove more than one element from an array.
Syntax:
array.splice(index, howmany, item1, ....., itemX)
Parameters: This method requires 3 parameters :-
index: Required. It specifies the position to remove/add the elements.
howmany: Optional. It specifies how many elements to be removed.
item: Optional. It specifies new elements to be added.
Return Value: A new Array, containing the removed items (if any).
Example: This example uses splice() method to remove particular element from an array.
<!DOCTYPE html><html> <body> <h1>Welcome to GeeksforGeeks</h1> <p>Click the button to remove 3rd element from the array.</p> <button onclick="remove_ele()">Try it</button> <p id="display"></p> <p id="demo"></p> <!--Script to remove an element from an array using spice method--> <script> var Lang = ["C++ ", " Java ", " Python ", " Go ", " Prolog"]; document.getElementById("display").innerHTML = Lang; function remove_ele() { Lang.splice(2, 1); document.getElementById("display").innerHTML = Lang; } </script> </body></html>
Output:Before clicking try it button:After clicking try it button:Supported Browsers: The browser supported by Array splice() Method are listed below:
Google Chrome
Apple Safari
Firefox
Opera
Edge
javascript-array
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
How to create a link in JavaScript ?
How to Show Images on Click using HTML ?
Remove elements from a JavaScript Array
How to remove an HTML element using JavaScript ?
Express.js express.Router() Function
Installation of Node.js on Linux
How to set input type date in dd-mm-yyyy format using HTML ?
How to create footer to stay at the bottom of a Web page?
How to float three div side by side using CSS?
|
[
{
"code": null,
"e": 24909,
"s": 24881,
"text": "\n14 Mar, 2019"
},
{
"code": null,
"e": 25092,
"s": 24909,
"text": "Array splice() method can be used to remove any particular element from an array in JavaScript. Moreover, this function can be used to add/remove more than one element from an array."
},
{
"code": null,
"e": 25100,
"s": 25092,
"text": "Syntax:"
},
{
"code": null,
"e": 25150,
"s": 25100,
"text": "array.splice(index, howmany, item1, ....., itemX)"
},
{
"code": null,
"e": 25199,
"s": 25150,
"text": "Parameters: This method requires 3 parameters :-"
},
{
"code": null,
"e": 25270,
"s": 25199,
"text": "index: Required. It specifies the position to remove/add the elements."
},
{
"code": null,
"e": 25335,
"s": 25270,
"text": "howmany: Optional. It specifies how many elements to be removed."
},
{
"code": null,
"e": 25390,
"s": 25335,
"text": "item: Optional. It specifies new elements to be added."
},
{
"code": null,
"e": 25456,
"s": 25390,
"text": "Return Value: A new Array, containing the removed items (if any)."
},
{
"code": null,
"e": 25543,
"s": 25456,
"text": "Example: This example uses splice() method to remove particular element from an array."
},
{
"code": "<!DOCTYPE html><html> <body> <h1>Welcome to GeeksforGeeks</h1> <p>Click the button to remove 3rd element from the array.</p> <button onclick=\"remove_ele()\">Try it</button> <p id=\"display\"></p> <p id=\"demo\"></p> <!--Script to remove an element from an array using spice method--> <script> var Lang = [\"C++ \", \" Java \", \" Python \", \" Go \", \" Prolog\"]; document.getElementById(\"display\").innerHTML = Lang; function remove_ele() { Lang.splice(2, 1); document.getElementById(\"display\").innerHTML = Lang; } </script> </body></html>",
"e": 26220,
"s": 25543,
"text": null
},
{
"code": null,
"e": 26371,
"s": 26220,
"text": "Output:Before clicking try it button:After clicking try it button:Supported Browsers: The browser supported by Array splice() Method are listed below:"
},
{
"code": null,
"e": 26385,
"s": 26371,
"text": "Google Chrome"
},
{
"code": null,
"e": 26398,
"s": 26385,
"text": "Apple Safari"
},
{
"code": null,
"e": 26406,
"s": 26398,
"text": "Firefox"
},
{
"code": null,
"e": 26412,
"s": 26406,
"text": "Opera"
},
{
"code": null,
"e": 26417,
"s": 26412,
"text": "Edge"
},
{
"code": null,
"e": 26434,
"s": 26417,
"text": "javascript-array"
},
{
"code": null,
"e": 26441,
"s": 26434,
"text": "Picked"
},
{
"code": null,
"e": 26452,
"s": 26441,
"text": "JavaScript"
},
{
"code": null,
"e": 26469,
"s": 26452,
"text": "Web Technologies"
},
{
"code": null,
"e": 26567,
"s": 26469,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26576,
"s": 26567,
"text": "Comments"
},
{
"code": null,
"e": 26589,
"s": 26576,
"text": "Old Comments"
},
{
"code": null,
"e": 26650,
"s": 26589,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26687,
"s": 26650,
"text": "How to create a link in JavaScript ?"
},
{
"code": null,
"e": 26728,
"s": 26687,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 26768,
"s": 26728,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 26817,
"s": 26768,
"text": "How to remove an HTML element using JavaScript ?"
},
{
"code": null,
"e": 26854,
"s": 26817,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 26887,
"s": 26854,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26948,
"s": 26887,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 27006,
"s": 26948,
"text": "How to create footer to stay at the bottom of a Web page?"
}
] |
Queries to count Palindrome Numbers from a range whose sum of digits is a Prime Number
|
09 Jun, 2021
Given an array Q[][] consisting of N queries of the form {L, R}, the task for each query is to find the count of the numbers in the range [L, R] that are palindrome and the sum of their digits is a prime number.
Examples:
Input: Q[][] = {{5, 9}, {5, 22}}Output:23Explanation:Query 1: All palindrome numbers from the range [5, 9] having sum of their digits equal to a prime number are {5, 7}. Therefore, the count of elements is 2.Query 2: All palindrome numbers from the range [5, 20] having sum of their digits equal to a prime number are {5, 7, 11}. Therefore, the count of elements is 2.
Input: Q[] = {{1, 101}, {13, 15}}Output:60
Naive Approach: The simplest approach to solve the given problem is to iterate over the range [L, R] for each query and print the count of those numbers that are palindrome, and the sum of their digits is a prime number.
Time Complexity: O(N*(R – L))Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by using the Inclusion-Exclusion principle and the concepts of prefix sum. Follow the steps below to solve the given problem:
Initialize an array arr[] to store the count of numbers up to each index i that are palindrome and the sum of their digits is a prime number at every ith index.
Iterate over the range [1, 105], and for each element X, if the number X is palindromic and the sum of the digits is prime then update arr[i] to 1. Otherwise, set arr[i] = 0.
Find the prefix sum array of the array arr[].
Now, Traverse the array Q[] and for each query {L, R}, print the total count of the numbers in the range [L, R] that are palindrome and the sum of their digits is a prime number as (arr[R] – arr[L – 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 arr[100005]; // Function to check if the number N// is palindrome or notbool isPalindrome(int N){ // Store the value of N int temp = N; // Store the reverse of number N int res = 0; // Reverse temp and store in res while (temp != 0) { int rem = temp % 10; res = res * 10 + rem; temp /= 10; } // If N is the same as res, then // return true if (res == N) { return true; } else { return false; }} // Function to find the sum of the// digits of the number Nint sumOfDigits(int N){ // Stores the sum of the digits int sum = 0; while (N != 0) { // Add the last digit of the // number N to the sum sum += N % 10; // Remove the last digit // from N N /= 10; } // Return the resultant sum return sum;} // Function to check if N is prime or notbool isPrime(int n){ // If i is 1 or 0, then return false if (n <= 1) { return false; } // Check if i is divisible by any // number in the range [2, n/2] for (int i = 2; i <= n / 2; ++i) { // If n is divisible by i if (n % i == 0) return false; } return true;} // Function to precompute all the numbers// till 10^5 that are palindromic and// whose sum of digits is prime numbersvoid precompute(){ // Iterate over the range 1 to 10 ^ 5 for (int i = 1; i <= 100000; i++) { // If i is a palindrome number if (isPalindrome(i)) { // Stores the sum of // the digits in i int sum = sumOfDigits(i); // If the sum of digits // in i is a prime number if (isPrime(sum)) arr[i] = 1; else arr[i] = 0; } else arr[i] = 0; } // Find the prefix sum of arr[] for (int i = 1; i <= 100000; i++) { arr[i] = arr[i] + arr[i - 1]; }} // Function to count all the numbers in// the given ranges that are palindromic// and the sum of digits is prime numbersvoid countNumbers(int Q[][2], int N){ // Function Call to precompute // all the numbers till 10^5 precompute(); // Traverse the given queries Q[] for (int i = 0; i < N; i++) { // Print the result for // each query cout << (arr[Q[i][1]] - arr[Q[i][0] - 1]); cout << endl; }} // Driver Codeint main(){ int Q[][2] = { { 5, 9 }, { 1, 101 } }; int N = sizeof(Q) / sizeof(Q[0]); // Function Call countNumbers(Q, N);}
// Java program for the above approachclass GFG{ static int[] arr = new int[100005]; // Function to check if the number N// is palindrome or notstatic boolean isPalindrome(int N){ int temp = N; // Store the reverse of number N int res = 0; // Reverse temp and store in res while (temp != 0) { int rem = temp % 10; res = res * 10 + rem; temp /= 10; } // If N is the same as res, then // return true if (res == N) { return true; } else { return false; }} // Function to find the sum of the// digits of the number Nstatic int sumOfDigits(int N){ // Stores the sum of the digits int sum = 0; while (N != 0) { // Add the last digit of the // number N to the sum sum += N % 10; // Remove the last digit // from N N /= 10; } // Return the resultant sum return sum;} // Function to check if N is prime or notstatic boolean isPrime(int n){ // If i is 1 or 0, then return false if (n <= 1) { return false; } // Check if i is divisible by any // number in the range [2, n/2] for(int i = 2; i <= n / 2; ++i) { // If n is divisible by i if (n % i == 0) return false; } return true;} // Function to precompute all the numbers// till 10^5 that are palindromic and// whose sum of digits is prime numbersstatic void precompute(){ // Iterate over the range 1 to 10 ^ 5 for(int i = 1; i <= 100000; i++) { // If i is a palindrome number if (isPalindrome(i)) { // Stores the sum of // the digits in i int sum = sumOfDigits(i); // If the sum of digits // in i is a prime number if (isPrime(sum)) arr[i] = 1; else arr[i] = 0; } else arr[i] = 0; } // Find the prefix sum of arr[] for(int i = 1; i <= 100000; i++) { arr[i] = arr[i] + arr[i - 1]; }} // Function to count all the numbers in// the given ranges that are palindromic// and the sum of digits is prime numbersstatic void countNumbers(int[][] Q, int N){ // Function Call to precompute // all the numbers till 10^5 precompute(); // Traverse the given queries Q[] for(int i = 0; i < N; i++) { // Print the result for // each query System.out.println((arr[Q[i][1]] - arr[Q[i][0] - 1])); }} // Driver Codepublic static void main(String[] args){ int[][] Q = { { 5, 9 }, { 1, 101 } }; int N = Q.length; // Function Call countNumbers(Q, N);}} // This code is contributed by user_qa7r
# Python 3 program for the above approacharr = [0 for i in range(100005)] # Function to check if the number N# is palindrome or notdef isPalindrome(N): # Store the value of N temp = N # Store the reverse of number N res = 0 # Reverse temp and store in res while (temp != 0): rem = temp % 10 res = res * 10 + rem temp //= 10 # If N is the same as res, then # return true if (res == N): return True else: return False # Function to find the sum of the# digits of the number Ndef sumOfDigits(N): # Stores the sum of the digits sum = 0 while (N != 0): # Add the last digit of the # number N to the sum sum += N % 10 # Remove the last digit # from N N //= 10 # Return the resultant sum return sum # Function to check if N is prime or notdef isPrime(n): # If i is 1 or 0, then return false if (n <= 1): return False # Check if i is divisible by any # number in the range [2, n/2] for i in range(2, (n//2) + 1, 1): # If n is divisible by i if (n % i == 0): return False return True # Function to precompute all the numbers# till 10^5 that are palindromic and# whose sum of digits is prime numbersdef precompute(): # Iterate over the range 1 to 10 ^ 5 for i in range(1, 100001, 1): # If i is a palindrome number if (isPalindrome(i)): # Stores the sum of # the digits in i sum = sumOfDigits(i) # If the sum of digits # in i is a prime number if (isPrime(sum)): arr[i] = 1 else: arr[i] = 0 else: arr[i] = 0 # Find the prefix sum of arr[] for i in range(1,100001,1): arr[i] = arr[i] + arr[i - 1] # Function to count all the numbers in# the given ranges that are palindromic# and the sum of digits is prime numbersdef countNumbers(Q, N): # Function Call to precompute # all the numbers till 10^5 precompute() # Traverse the given queries Q[] for i in range(N): # Print the result for # each query print(arr[Q[i][1]] - arr[Q[i][0] - 1]) # Driver Codeif __name__ == '__main__': Q = [[5, 9], [1, 101]] N = len(Q) # Function Call countNumbers(Q, N) # This code is contributed by bgangwar59.
// C# program for the above approachusing System; class GFG{ static int[] arr = new int[100005]; // Function to check if the number N// is palindrome or notstatic bool isPalindrome(int N){ int temp = N; // Store the reverse of number N int res = 0; // Reverse temp and store in res while (temp != 0) { int rem = temp % 10; res = res * 10 + rem; temp /= 10; } // If N is the same as res, then // return true if (res == N) { return true; } else { return false; }} // Function to find the sum of the// digits of the number Nstatic int sumOfDigits(int N){ // Stores the sum of the digits int sum = 0; while (N != 0) { // Add the last digit of the // number N to the sum sum += N % 10; // Remove the last digit // from N N /= 10; } // Return the resultant sum return sum;} // Function to check if N is prime or notstatic bool isPrime(int n){ // If i is 1 or 0, then return false if (n <= 1) { return false; } // Check if i is divisible by any // number in the range [2, n/2] for(int i = 2; i <= n / 2; ++i) { // If n is divisible by i if (n % i == 0) return false; } return true;} // Function to precompute all the numbers// till 10^5 that are palindromic and// whose sum of digits is prime numbersstatic void precompute(){ // Iterate over the range 1 to 10 ^ 5 for(int i = 1; i <= 100000; i++) { // If i is a palindrome number if (isPalindrome(i)) { // Stores the sum of // the digits in i int sum = sumOfDigits(i); // If the sum of digits // in i is a prime number if (isPrime(sum)) arr[i] = 1; else arr[i] = 0; } else arr[i] = 0; } // Find the prefix sum of arr[] for(int i = 1; i <= 100000; i++) { arr[i] = arr[i] + arr[i - 1]; }} // Function to count all the numbers in// the given ranges that are palindromic// and the sum of digits is prime numbersstatic void countNumbers(int[, ] Q, int N){ // Function Call to precompute // all the numbers till 10^5 precompute(); // Traverse the given queries Q[] for(int i = 0; i < N; i++) { // Print the result for // each query Console.WriteLine((arr[Q[i, 1]] - arr[Q[i, 0] - 1])); }} // Driver Codestatic public void Main(){ int[,] Q = { { 5, 9 }, { 1, 101 } }; int N = Q.GetLength(0); // Function Call countNumbers(Q, N);}} // This code is contributed by Dharanendra L V.
<script>// JavaScript program for the above approach let arr = [];for(let m = 0; m < 100005; m++){ arr[m] = 0;} // Function to check if the number N// is palindrome or notfunction isPalindrome(N){ let temp = N; // Store the reverse of number N let res = 0; // Reverse temp and store in res while (temp != 0) { let rem = temp % 10; res = res * 10 + rem; temp = Math.floor( temp / 10); } // If N is the same as res, then // return true if (res == N) { return true; } else { return false; }} // Function to find the sum of the// digits of the number Nfunction sumOfDigits(N){ // Stores the sum of the digits let sum = 0; while (N != 0) { // Add the last digit of the // number N to the sum sum += N % 10; // Remove the last digit // from N N = Math.floor( N / 10); } // Return the resultant sum return sum;} // Function to check if N is prime or notfunction isPrime(n){ // If i is 1 or 0, then return false if (n <= 1) { return false; } // Check if i is divisible by any // number in the range [2, n/2] for(let i = 2; i <= Math.floor(n / 2); ++i) { // If n is divisible by i if (n % i == 0) return false; } return true;} // Function to precompute all the numbers// till 10^5 that are palindromic and// whose sum of digits is prime numbersfunction precompute(){ // Iterate over the range 1 to 10 ^ 5 for(let i = 1; i <= 100000; i++) { // If i is a palindrome number if (isPalindrome(i)) { // Stores the sum of // the digits in i let sum = sumOfDigits(i); // If the sum of digits // in i is a prime number if (isPrime(sum)) arr[i] = 1; else arr[i] = 0; } else arr[i] = 0; } // Find the prefix sum of arr[] for(let i = 1; i <= 100000; i++) { arr[i] = arr[i] + arr[i - 1]; }} // Function to count all the numbers in// the given ranges that are palindromic// and the sum of digits is prime numbersfunction countNumbers( Q, N){ // Function Call to precompute // all the numbers till 10^5 precompute(); // Traverse the given queries Q[] for(let i = 0; i < N; i++) { // Print the result for // each query document.write((arr[Q[i][1]] - arr[Q[i][0] - 1]) + "<br/>"); }} // Driver Code let Q = [[ 5, 9 ], [ 1, 101 ]]; let N = Q.length; // Function Call countNumbers(Q, N); </script>
2
6
Time Complexity: O(N*log N)Auxiliary Space: O(M), where M is the maximum element among each query.
hritikrommie
dharanendralv23
bgangwar59
chinmoy1997pal
ankita_saini
array-range-queries
palindrome
Prime Number
Technical Scripter 2020
Greedy
Mathematical
Technical Scripter
Greedy
Mathematical
Prime Number
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Huffman Coding | Greedy Algo-3
Coin Change | DP-7
Activity Selection Problem | Greedy Algo-1
Fractional Knapsack Problem
Job Sequencing Problem
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
C++ Data Types
Merge two sorted arrays
Coin Change | DP-7
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Jun, 2021"
},
{
"code": null,
"e": 266,
"s": 54,
"text": "Given an array Q[][] consisting of N queries of the form {L, R}, the task for each query is to find the count of the numbers in the range [L, R] that are palindrome and the sum of their digits is a prime number."
},
{
"code": null,
"e": 276,
"s": 266,
"text": "Examples:"
},
{
"code": null,
"e": 645,
"s": 276,
"text": "Input: Q[][] = {{5, 9}, {5, 22}}Output:23Explanation:Query 1: All palindrome numbers from the range [5, 9] having sum of their digits equal to a prime number are {5, 7}. Therefore, the count of elements is 2.Query 2: All palindrome numbers from the range [5, 20] having sum of their digits equal to a prime number are {5, 7, 11}. Therefore, the count of elements is 2."
},
{
"code": null,
"e": 688,
"s": 645,
"text": "Input: Q[] = {{1, 101}, {13, 15}}Output:60"
},
{
"code": null,
"e": 910,
"s": 688,
"text": "Naive Approach: The simplest approach to solve the given problem is to iterate over the range [L, R] for each query and print the count of those numbers that are palindrome, and the sum of their digits is a prime number. "
},
{
"code": null,
"e": 961,
"s": 910,
"text": "Time Complexity: O(N*(R – L))Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1143,
"s": 961,
"text": "Efficient Approach: The above approach can be optimized by using the Inclusion-Exclusion principle and the concepts of prefix sum. Follow the steps below to solve the given problem:"
},
{
"code": null,
"e": 1304,
"s": 1143,
"text": "Initialize an array arr[] to store the count of numbers up to each index i that are palindrome and the sum of their digits is a prime number at every ith index."
},
{
"code": null,
"e": 1479,
"s": 1304,
"text": "Iterate over the range [1, 105], and for each element X, if the number X is palindromic and the sum of the digits is prime then update arr[i] to 1. Otherwise, set arr[i] = 0."
},
{
"code": null,
"e": 1525,
"s": 1479,
"text": "Find the prefix sum array of the array arr[]."
},
{
"code": null,
"e": 1729,
"s": 1525,
"text": "Now, Traverse the array Q[] and for each query {L, R}, print the total count of the numbers in the range [L, R] that are palindrome and the sum of their digits is a prime number as (arr[R] – arr[L – 1])."
},
{
"code": null,
"e": 1780,
"s": 1729,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1784,
"s": 1780,
"text": "C++"
},
{
"code": null,
"e": 1789,
"s": 1784,
"text": "Java"
},
{
"code": null,
"e": 1797,
"s": 1789,
"text": "Python3"
},
{
"code": null,
"e": 1800,
"s": 1797,
"text": "C#"
},
{
"code": null,
"e": 1811,
"s": 1800,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; int arr[100005]; // Function to check if the number N// is palindrome or notbool isPalindrome(int N){ // Store the value of N int temp = N; // Store the reverse of number N int res = 0; // Reverse temp and store in res while (temp != 0) { int rem = temp % 10; res = res * 10 + rem; temp /= 10; } // If N is the same as res, then // return true if (res == N) { return true; } else { return false; }} // Function to find the sum of the// digits of the number Nint sumOfDigits(int N){ // Stores the sum of the digits int sum = 0; while (N != 0) { // Add the last digit of the // number N to the sum sum += N % 10; // Remove the last digit // from N N /= 10; } // Return the resultant sum return sum;} // Function to check if N is prime or notbool isPrime(int n){ // If i is 1 or 0, then return false if (n <= 1) { return false; } // Check if i is divisible by any // number in the range [2, n/2] for (int i = 2; i <= n / 2; ++i) { // If n is divisible by i if (n % i == 0) return false; } return true;} // Function to precompute all the numbers// till 10^5 that are palindromic and// whose sum of digits is prime numbersvoid precompute(){ // Iterate over the range 1 to 10 ^ 5 for (int i = 1; i <= 100000; i++) { // If i is a palindrome number if (isPalindrome(i)) { // Stores the sum of // the digits in i int sum = sumOfDigits(i); // If the sum of digits // in i is a prime number if (isPrime(sum)) arr[i] = 1; else arr[i] = 0; } else arr[i] = 0; } // Find the prefix sum of arr[] for (int i = 1; i <= 100000; i++) { arr[i] = arr[i] + arr[i - 1]; }} // Function to count all the numbers in// the given ranges that are palindromic// and the sum of digits is prime numbersvoid countNumbers(int Q[][2], int N){ // Function Call to precompute // all the numbers till 10^5 precompute(); // Traverse the given queries Q[] for (int i = 0; i < N; i++) { // Print the result for // each query cout << (arr[Q[i][1]] - arr[Q[i][0] - 1]); cout << endl; }} // Driver Codeint main(){ int Q[][2] = { { 5, 9 }, { 1, 101 } }; int N = sizeof(Q) / sizeof(Q[0]); // Function Call countNumbers(Q, N);}",
"e": 4425,
"s": 1811,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ static int[] arr = new int[100005]; // Function to check if the number N// is palindrome or notstatic boolean isPalindrome(int N){ int temp = N; // Store the reverse of number N int res = 0; // Reverse temp and store in res while (temp != 0) { int rem = temp % 10; res = res * 10 + rem; temp /= 10; } // If N is the same as res, then // return true if (res == N) { return true; } else { return false; }} // Function to find the sum of the// digits of the number Nstatic int sumOfDigits(int N){ // Stores the sum of the digits int sum = 0; while (N != 0) { // Add the last digit of the // number N to the sum sum += N % 10; // Remove the last digit // from N N /= 10; } // Return the resultant sum return sum;} // Function to check if N is prime or notstatic boolean isPrime(int n){ // If i is 1 or 0, then return false if (n <= 1) { return false; } // Check if i is divisible by any // number in the range [2, n/2] for(int i = 2; i <= n / 2; ++i) { // If n is divisible by i if (n % i == 0) return false; } return true;} // Function to precompute all the numbers// till 10^5 that are palindromic and// whose sum of digits is prime numbersstatic void precompute(){ // Iterate over the range 1 to 10 ^ 5 for(int i = 1; i <= 100000; i++) { // If i is a palindrome number if (isPalindrome(i)) { // Stores the sum of // the digits in i int sum = sumOfDigits(i); // If the sum of digits // in i is a prime number if (isPrime(sum)) arr[i] = 1; else arr[i] = 0; } else arr[i] = 0; } // Find the prefix sum of arr[] for(int i = 1; i <= 100000; i++) { arr[i] = arr[i] + arr[i - 1]; }} // Function to count all the numbers in// the given ranges that are palindromic// and the sum of digits is prime numbersstatic void countNumbers(int[][] Q, int N){ // Function Call to precompute // all the numbers till 10^5 precompute(); // Traverse the given queries Q[] for(int i = 0; i < N; i++) { // Print the result for // each query System.out.println((arr[Q[i][1]] - arr[Q[i][0] - 1])); }} // Driver Codepublic static void main(String[] args){ int[][] Q = { { 5, 9 }, { 1, 101 } }; int N = Q.length; // Function Call countNumbers(Q, N);}} // This code is contributed by user_qa7r",
"e": 7161,
"s": 4425,
"text": null
},
{
"code": "# Python 3 program for the above approacharr = [0 for i in range(100005)] # Function to check if the number N# is palindrome or notdef isPalindrome(N): # Store the value of N temp = N # Store the reverse of number N res = 0 # Reverse temp and store in res while (temp != 0): rem = temp % 10 res = res * 10 + rem temp //= 10 # If N is the same as res, then # return true if (res == N): return True else: return False # Function to find the sum of the# digits of the number Ndef sumOfDigits(N): # Stores the sum of the digits sum = 0 while (N != 0): # Add the last digit of the # number N to the sum sum += N % 10 # Remove the last digit # from N N //= 10 # Return the resultant sum return sum # Function to check if N is prime or notdef isPrime(n): # If i is 1 or 0, then return false if (n <= 1): return False # Check if i is divisible by any # number in the range [2, n/2] for i in range(2, (n//2) + 1, 1): # If n is divisible by i if (n % i == 0): return False return True # Function to precompute all the numbers# till 10^5 that are palindromic and# whose sum of digits is prime numbersdef precompute(): # Iterate over the range 1 to 10 ^ 5 for i in range(1, 100001, 1): # If i is a palindrome number if (isPalindrome(i)): # Stores the sum of # the digits in i sum = sumOfDigits(i) # If the sum of digits # in i is a prime number if (isPrime(sum)): arr[i] = 1 else: arr[i] = 0 else: arr[i] = 0 # Find the prefix sum of arr[] for i in range(1,100001,1): arr[i] = arr[i] + arr[i - 1] # Function to count all the numbers in# the given ranges that are palindromic# and the sum of digits is prime numbersdef countNumbers(Q, N): # Function Call to precompute # all the numbers till 10^5 precompute() # Traverse the given queries Q[] for i in range(N): # Print the result for # each query print(arr[Q[i][1]] - arr[Q[i][0] - 1]) # Driver Codeif __name__ == '__main__': Q = [[5, 9], [1, 101]] N = len(Q) # Function Call countNumbers(Q, N) # This code is contributed by bgangwar59.",
"e": 9584,
"s": 7161,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ static int[] arr = new int[100005]; // Function to check if the number N// is palindrome or notstatic bool isPalindrome(int N){ int temp = N; // Store the reverse of number N int res = 0; // Reverse temp and store in res while (temp != 0) { int rem = temp % 10; res = res * 10 + rem; temp /= 10; } // If N is the same as res, then // return true if (res == N) { return true; } else { return false; }} // Function to find the sum of the// digits of the number Nstatic int sumOfDigits(int N){ // Stores the sum of the digits int sum = 0; while (N != 0) { // Add the last digit of the // number N to the sum sum += N % 10; // Remove the last digit // from N N /= 10; } // Return the resultant sum return sum;} // Function to check if N is prime or notstatic bool isPrime(int n){ // If i is 1 or 0, then return false if (n <= 1) { return false; } // Check if i is divisible by any // number in the range [2, n/2] for(int i = 2; i <= n / 2; ++i) { // If n is divisible by i if (n % i == 0) return false; } return true;} // Function to precompute all the numbers// till 10^5 that are palindromic and// whose sum of digits is prime numbersstatic void precompute(){ // Iterate over the range 1 to 10 ^ 5 for(int i = 1; i <= 100000; i++) { // If i is a palindrome number if (isPalindrome(i)) { // Stores the sum of // the digits in i int sum = sumOfDigits(i); // If the sum of digits // in i is a prime number if (isPrime(sum)) arr[i] = 1; else arr[i] = 0; } else arr[i] = 0; } // Find the prefix sum of arr[] for(int i = 1; i <= 100000; i++) { arr[i] = arr[i] + arr[i - 1]; }} // Function to count all the numbers in// the given ranges that are palindromic// and the sum of digits is prime numbersstatic void countNumbers(int[, ] Q, int N){ // Function Call to precompute // all the numbers till 10^5 precompute(); // Traverse the given queries Q[] for(int i = 0; i < N; i++) { // Print the result for // each query Console.WriteLine((arr[Q[i, 1]] - arr[Q[i, 0] - 1])); }} // Driver Codestatic public void Main(){ int[,] Q = { { 5, 9 }, { 1, 101 } }; int N = Q.GetLength(0); // Function Call countNumbers(Q, N);}} // This code is contributed by Dharanendra L V.",
"e": 12337,
"s": 9584,
"text": null
},
{
"code": "<script>// JavaScript program for the above approach let arr = [];for(let m = 0; m < 100005; m++){ arr[m] = 0;} // Function to check if the number N// is palindrome or notfunction isPalindrome(N){ let temp = N; // Store the reverse of number N let res = 0; // Reverse temp and store in res while (temp != 0) { let rem = temp % 10; res = res * 10 + rem; temp = Math.floor( temp / 10); } // If N is the same as res, then // return true if (res == N) { return true; } else { return false; }} // Function to find the sum of the// digits of the number Nfunction sumOfDigits(N){ // Stores the sum of the digits let sum = 0; while (N != 0) { // Add the last digit of the // number N to the sum sum += N % 10; // Remove the last digit // from N N = Math.floor( N / 10); } // Return the resultant sum return sum;} // Function to check if N is prime or notfunction isPrime(n){ // If i is 1 or 0, then return false if (n <= 1) { return false; } // Check if i is divisible by any // number in the range [2, n/2] for(let i = 2; i <= Math.floor(n / 2); ++i) { // If n is divisible by i if (n % i == 0) return false; } return true;} // Function to precompute all the numbers// till 10^5 that are palindromic and// whose sum of digits is prime numbersfunction precompute(){ // Iterate over the range 1 to 10 ^ 5 for(let i = 1; i <= 100000; i++) { // If i is a palindrome number if (isPalindrome(i)) { // Stores the sum of // the digits in i let sum = sumOfDigits(i); // If the sum of digits // in i is a prime number if (isPrime(sum)) arr[i] = 1; else arr[i] = 0; } else arr[i] = 0; } // Find the prefix sum of arr[] for(let i = 1; i <= 100000; i++) { arr[i] = arr[i] + arr[i - 1]; }} // Function to count all the numbers in// the given ranges that are palindromic// and the sum of digits is prime numbersfunction countNumbers( Q, N){ // Function Call to precompute // all the numbers till 10^5 precompute(); // Traverse the given queries Q[] for(let i = 0; i < N; i++) { // Print the result for // each query document.write((arr[Q[i][1]] - arr[Q[i][0] - 1]) + \"<br/>\"); }} // Driver Code let Q = [[ 5, 9 ], [ 1, 101 ]]; let N = Q.length; // Function Call countNumbers(Q, N); </script>",
"e": 15060,
"s": 12337,
"text": null
},
{
"code": null,
"e": 15064,
"s": 15060,
"text": "2\n6"
},
{
"code": null,
"e": 15165,
"s": 15066,
"text": "Time Complexity: O(N*log N)Auxiliary Space: O(M), where M is the maximum element among each query."
},
{
"code": null,
"e": 15178,
"s": 15165,
"text": "hritikrommie"
},
{
"code": null,
"e": 15194,
"s": 15178,
"text": "dharanendralv23"
},
{
"code": null,
"e": 15205,
"s": 15194,
"text": "bgangwar59"
},
{
"code": null,
"e": 15220,
"s": 15205,
"text": "chinmoy1997pal"
},
{
"code": null,
"e": 15233,
"s": 15220,
"text": "ankita_saini"
},
{
"code": null,
"e": 15253,
"s": 15233,
"text": "array-range-queries"
},
{
"code": null,
"e": 15264,
"s": 15253,
"text": "palindrome"
},
{
"code": null,
"e": 15277,
"s": 15264,
"text": "Prime Number"
},
{
"code": null,
"e": 15301,
"s": 15277,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 15308,
"s": 15301,
"text": "Greedy"
},
{
"code": null,
"e": 15321,
"s": 15308,
"text": "Mathematical"
},
{
"code": null,
"e": 15340,
"s": 15321,
"text": "Technical Scripter"
},
{
"code": null,
"e": 15347,
"s": 15340,
"text": "Greedy"
},
{
"code": null,
"e": 15360,
"s": 15347,
"text": "Mathematical"
},
{
"code": null,
"e": 15373,
"s": 15360,
"text": "Prime Number"
},
{
"code": null,
"e": 15384,
"s": 15373,
"text": "palindrome"
},
{
"code": null,
"e": 15482,
"s": 15384,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15513,
"s": 15482,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 15532,
"s": 15513,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 15575,
"s": 15532,
"text": "Activity Selection Problem | Greedy Algo-1"
},
{
"code": null,
"e": 15603,
"s": 15575,
"text": "Fractional Knapsack Problem"
},
{
"code": null,
"e": 15626,
"s": 15603,
"text": "Job Sequencing Problem"
},
{
"code": null,
"e": 15656,
"s": 15626,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 15699,
"s": 15656,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 15714,
"s": 15699,
"text": "C++ Data Types"
},
{
"code": null,
"e": 15738,
"s": 15714,
"text": "Merge two sorted arrays"
}
] |
Longest Common Substring | DP-29
|
21 Jun, 2022
Given two strings ‘X’ and ‘Y’, find the length of the longest common substring.
Examples :
Input : X = “GeeksforGeeks”, y = “GeeksQuiz” Output : 5 Explanation:The longest common substring is “Geeks” and is of length 5.
Input : X = “abcdxyz”, y = “xyzabcd” Output : 4 Explanation:The longest common substring is “abcd” and is of length 4.
Input : X = “zxabcdezy”, y = “yzabcdezx” Output : 6 Explanation:The longest common substring is “abcdez” and is of length 6.
Approach:Let m and n be the lengths of the first and second strings respectively.
A simple solution is to one by one consider all substrings of the first string and for every substring check if it is a substring in the second string. Keep track of the maximum length substring. There will be O(m^2) substrings and we can find whether a string is substring on another string in O(n) time (See this). So overall time complexity of this method would be O(n * m2)
Dynamic Programming can be used to find the longest common substring in O(m*n) time. The idea is to find the length of the longest common suffix for all substrings of both strings and store these lengths in a table.
The longest common suffix has following optimal substructure property. If last characters match, then we reduce both lengths by 1 LCSuff(X, Y, m, n) = LCSuff(X, Y, m-1, n-1) + 1 if X[m-1] = Y[n-1] If last characters do not match, then result is 0, i.e., LCSuff(X, Y, m, n) = 0 if (X[m-1] != Y[n-1])Now we consider suffixes of different substrings ending at different indexes. The maximum length Longest Common Suffix is the longest common substring. LCSubStr(X, Y, m, n) = Max(LCSuff(X, Y, i, j)) where 1 <= i <= m and 1 <= j <= n
Following is the iterative implementation of the above solution.
C++
Java
Python3
C#
PHP
Javascript
/* Dynamic Programming solution to find length of the longest common substring */#include <iostream>#include <string.h>using namespace std; /* Returns length of longest common substring of X[0..m-1] and Y[0..n-1] */int LCSubStr(char* X, char* Y, int m, int n){ // Create a table to store // lengths of longest // common suffixes of substrings. // Note that LCSuff[i][j] contains // length of longest common suffix // of X[0..i-1] and Y[0..j-1]. int LCSuff[m + 1][n + 1]; int result = 0; // To store length of the // longest common substring /* Following steps build LCSuff[m+1][n+1] in bottom up fashion. */ for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { // The first row and first column // entries have no logical meaning, // they are used only for simplicity // of program if (i == 0 || j == 0) LCSuff[i][j] = 0; else if (X[i - 1] == Y[j - 1]) { LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1; result = max(result, LCSuff[i][j]); } else LCSuff[i][j] = 0; } } return result;} // Driver codeint main(){ char X[] = "OldSite:GeeksforGeeks.org"; char Y[] = "NewSite:GeeksQuiz.com"; int m = strlen(X); int n = strlen(Y); cout << "Length of Longest Common Substring is " << LCSubStr(X, Y, m, n); return 0;}
// Java implementation of// finding length of longest// Common substring using// Dynamic Programmingclass GFG { /* Returns length of longest common substring of X[0..m-1] and Y[0..n-1] */ static int LCSubStr(char X[], char Y[], int m, int n) { // Create a table to store // lengths of longest common // suffixes of substrings. // Note that LCSuff[i][j] // contains length of longest // common suffix of // X[0..i-1] and Y[0..j-1]. // The first row and first // column entries have no // logical meaning, they are // used only for simplicity of program int LCStuff[][] = new int[m + 1][n + 1]; // To store length of the longest // common substring int result = 0; // Following steps build // LCSuff[m+1][n+1] in bottom up fashion for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) LCStuff[i][j] = 0; else if (X[i - 1] == Y[j - 1]) { LCStuff[i][j] = LCStuff[i - 1][j - 1] + 1; result = Integer.max(result, LCStuff[i][j]); } else LCStuff[i][j] = 0; } } return result; } // Driver Code public static void main(String[] args) { String X = "OldSite:GeeksforGeeks.org"; String Y = "NewSite:GeeksQuiz.com"; int m = X.length(); int n = Y.length(); System.out.println(LCSubStr(X.toCharArray(), Y.toCharArray(), m, n)); }} // This code is contributed by Sumit Ghosh
# Python3 implementation of Finding# Length of Longest Common Substring # Returns length of longest common# substring of X[0..m-1] and Y[0..n-1] def LCSubStr(X, Y, m, n): # Create a table to store lengths of # longest common suffixes of substrings. # Note that LCSuff[i][j] contains the # length of longest common suffix of # X[0...i-1] and Y[0...j-1]. The first # row and first column entries have no # logical meaning, they are used only # for simplicity of the program. # LCSuff is the table with zero # value initially in each cell LCSuff = [[0 for k in range(n+1)] for l in range(m+1)] # To store the length of # longest common substring result = 0 # Following steps to build # LCSuff[m+1][n+1] in bottom up fashion for i in range(m + 1): for j in range(n + 1): if (i == 0 or j == 0): LCSuff[i][j] = 0 elif (X[i-1] == Y[j-1]): LCSuff[i][j] = LCSuff[i-1][j-1] + 1 result = max(result, LCSuff[i][j]) else: LCSuff[i][j] = 0 return result # Driver CodeX = 'OldSite:GeeksforGeeks.org'Y = 'NewSite:GeeksQuiz.com' m = len(X)n = len(Y) print('Length of Longest Common Substring is', LCSubStr(X, Y, m, n)) # This code is contributed by Soumen Ghosh
// C# implementation of finding length of longest// Common substring using Dynamic Programmingusing System; class GFG { // Returns length of longest common // substring of X[0..m-1] and Y[0..n-1] static int LCSubStr(string X, string Y, int m, int n) { // Create a table to store lengths of // longest common suffixes of substrings. // Note that LCSuff[i][j] contains length // of longest common suffix of X[0..i-1] // and Y[0..j-1]. The first row and first // column entries have no logical meaning, // they are used only for simplicity of // program int[, ] LCStuff = new int[m + 1, n + 1]; // To store length of the longest common // substring int result = 0; // Following steps build LCSuff[m+1][n+1] // in bottom up fashion for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) LCStuff[i, j] = 0; else if (X[i - 1] == Y[j - 1]) { LCStuff[i, j] = LCStuff[i - 1, j - 1] + 1; result = Math.Max(result, LCStuff[i, j]); } else LCStuff[i, j] = 0; } } return result; } // Driver Code public static void Main() { String X = "OldSite:GeeksforGeeks.org"; String Y = "NewSite:GeeksQuiz.com"; int m = X.Length; int n = Y.Length; Console.Write("Length of Longest Common" + " Substring is " + LCSubStr(X, Y, m, n)); }} // This code is contributed by Sam007.
<?php// Dynamic Programming solution to find// length of the longest common substring // Returns length of longest common// substring of X[0..m-1] and Y[0..n-1]function LCSubStr($X, $Y, $m, $n){ // Create a table to store lengths of // longest common suffixes of substrings. // Notethat LCSuff[i][j] contains length // of longest common suffix of X[0..i-1] // and Y[0..j-1]. The first row and // first column entries have no logical // meaning, they are used only for // simplicity of program $LCSuff = array_fill(0, $m + 1, array_fill(0, $n + 1, NULL)); $result = 0; // To store length of the // longest common substring // Following steps build LCSuff[m+1][n+1] // in bottom up fashion. for ($i = 0; $i <= $m; $i++) { for ($j = 0; $j <= $n; $j++) { if ($i == 0 || $j == 0) $LCSuff[$i][$j] = 0; else if ($X[$i - 1] == $Y[$j - 1]) { $LCSuff[$i][$j] = $LCSuff[$i - 1][$j - 1] + 1; $result = max($result, $LCSuff[$i][$j]); } else $LCSuff[$i][$j] = 0; } } return $result;} // Driver Code$X = "OldSite:GeeksforGeeks.org";$Y = "NewSite:GeeksQuiz.com"; $m = strlen($X);$n = strlen($Y); echo "Length of Longest Common Substring is " . LCSubStr($X, $Y, $m, $n); // This code is contributed by ita_c?>
<script> // JavaScript implementation of// finding length of longest// Common substring using// Dynamic Programming /* Returns length of longest common substring of X[0..m-1] and Y[0..n-1] */ function LCSubStr( X, Y , m , n) { // Create a table to store // lengths of longest common // suffixes of substrings. // Note that LCSuff[i][j] // contains length of longest // common suffix of // X[0..i-1] and Y[0..j-1]. // The first row and first // column entries have no // logical meaning, they are // used only for simplicity of program var LCStuff = Array(m + 1).fill().map(()=>Array(n + 1).fill(0)); // To store length of the longest // common substring var result = 0; // Following steps build // LCSuff[m+1][n+1] in bottom up fashion for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) LCStuff[i][j] = 0; else if (X[i - 1] == Y[j - 1]) { LCStuff[i][j] = LCStuff[i - 1][j - 1] + 1; result = Math.max(result, LCStuff[i][j]); } else LCStuff[i][j] = 0; } } return result; } // Driver Code var X = "OldSite:GeeksforGeeks.org"; var Y = "NewSite:GeeksQuiz.com"; var m = X.length; var n = Y.length; document.write("Length of Longest Common Substring is " + LCSubStr(X, Y, m, n)); // This code contributed by Rajput-Ji </script>
Length of Longest Common Substring is 10
Time Complexity: O(m*n) Auxiliary Space: O(m*n)
Another approach: (Space optimized approach).In the above approach, we are only using the last row of the 2-D array only, hence we can optimize the space by using a 2-D array of dimension 2*(min(n,m)).
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to find the length of the// longest LCSint LCSubStr(string s, string t, int n, int m){ // Create DP table int dp[2][m + 1]; int res = 0; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (s[i - 1] == t[j - 1]) { dp[i % 2][j] = dp[(i - 1) % 2][j - 1] + 1; if (dp[i % 2][j] > res) res = dp[i % 2][j]; } else dp[i % 2][j] = 0; } } return res;} // Driver Codeint main(){ string X = "OldSite:GeeksforGeeks.org"; string Y = "NewSite:GeeksQuiz.com"; int m = X.length(); int n = Y.length(); cout << LCSubStr(X, Y, m, n); return 0; cout << "GFG!"; return 0;} // This code is contributed by rajsanghavi9.
// Java implementation of the above approach class GFG{ // Function to find the length of the // longest LCS static int LCSubStr(String s,String t, int n,int m) { // Create DP table int dp[][]=new int[2][m+1]; int res=0; for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { if(s.charAt(i-1)==t.charAt(j-1)) { dp[i%2][j]=dp[(i-1)%2][j-1]+1; if(dp[i%2][j]>res) res=dp[i%2][j]; } else dp[i%2][j]=0; } } return res; } // Driver Code public static void main (String[] args) { String X="OldSite:GeeksforGeeks.org"; String Y="NewSite:GeeksQuiz.com"; int m=X.length(); int n=Y.length(); // Function call System.out.println(LCSubStr(X,Y,m,n)); }}
# Python implementation of the above approach # Function to find the length of the# longest LCSdef LCSubStr(s, t, n, m): # Create DP table dp = [[0 for i in range(m + 1)] for j in range(2)] res = 0 for i in range(1,n + 1): for j in range(1,m + 1): if(s[i - 1] == t[j - 1]): dp[i % 2][j] = dp[(i - 1) % 2][j - 1] + 1 if(dp[i % 2][j] > res): res = dp[i % 2][j] else: dp[i % 2][j] = 0 return res # Driver CodeX = "OldSite:GeeksforGeeks.org"Y = "NewSite:GeeksQuiz.com"m = len(X)n = len(Y) # Function callprint(LCSubStr(X,Y,m,n)) # This code is contributed by avanitrachhadiya2155
// C# implementation of the above approachusing System;public class GFG{ // Function to find the length of the // longest LCS static int LCSubStr(string s,string t, int n,int m) { // Create DP table int[,] dp = new int[2, m + 1]; int res = 0; for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { if(s[i - 1] == t[j - 1]) { dp[i % 2, j] = dp[(i - 1) % 2, j - 1] + 1; if(dp[i % 2, j] > res) res = dp[i % 2, j]; } else dp[i % 2, j] = 0; } } return res; } // Driver Code static public void Main (){ string X = "OldSite:GeeksforGeeks.org"; string Y = "NewSite:GeeksQuiz.com"; int m = X.Length; int n = Y.Length; // Function call Console.WriteLine(LCSubStr(X,Y,m,n)); }} // This code is contributed by rag2127
<script>// JavaScript implementation of the above approach // Function to find the length of the // longest LCS function LCSubStr(s, t, n, m) { // Create DP table var dp = Array(2).fill().map(()=>Array(m+ 1).fill(0)); var res = 0; for(var i = 1; i <= n; i++) { for(var j = 1; j <= m; j++) { if(s.charAt(i - 1) == t.charAt(j - 1)) { dp[i % 2][j] = dp[(i - 1) % 2][j - 1] + 1; if(dp[i % 2][j] > res) res = dp[i % 2][j]; } else dp[i % 2][j] = 0; } } return res; } // Driver Code var X = "OldSite:GeeksforGeeks.org"; var Y = "NewSite:GeeksQuiz.com"; var m = X.length; var n = Y.length; // Function call document.write(LCSubStr(X, Y, m, n)); // This code is contributed by shivanisinghss2110</script>
10
Time Complexity: O(n*m)Auxiliary Space: O(min(m,n))
Another approach: (Using recursion) Here is the recursive solution of the above approach.
C++
Java
Python3
C#
PHP
Javascript
// C++ program using to find length of the// longest common substring recursion#include <iostream> using namespace std; string X, Y; // Returns length of function f// or longest common substring// of X[0..m-1] and Y[0..n-1]int lcs(int i, int j, int count){ if (i == 0 || j == 0) return count; if (X[i - 1] == Y[j - 1]) { count = lcs(i - 1, j - 1, count + 1); } count = max(count, max(lcs(i, j - 1, 0), lcs(i - 1, j, 0))); return count;} // Driver codeint main(){ int n, m; X = "abcdxyz"; Y = "xyzabcd"; n = X.size(); m = Y.size(); cout << lcs(n, m, 0); return 0;}
// Java program using to find length of the// longest common substring recursion class GFG { static String X, Y; // Returns length of function // for longest common // substring of X[0..m-1] and Y[0..n-1] static int lcs(int i, int j, int count) { if (i == 0 || j == 0) { return count; } if (X.charAt(i - 1) == Y.charAt(j - 1)) { count = lcs(i - 1, j - 1, count + 1); } count = Math.max(count, Math.max(lcs(i, j - 1, 0), lcs(i - 1, j, 0))); return count; } // Driver code public static void main(String[] args) { int n, m; X = "abcdxyz"; Y = "xyzabcd"; n = X.length(); m = Y.length(); System.out.println(lcs(n, m, 0)); }}// This code is contributed by Rajput-JI
# Python3 program using to find length of# the longest common substring recursion # Returns length of function for longest# common substring of X[0..m-1] and Y[0..n-1] def lcs(i, j, count): if (i == 0 or j == 0): return count if (X[i - 1] == Y[j - 1]): count = lcs(i - 1, j - 1, count + 1) count = max(count, max(lcs(i, j - 1, 0), lcs(i - 1, j, 0))) return count # Driver codeif __name__ == "__main__": X = "abcdxyz" Y = "xyzabcd" n = len(X) m = len(Y) print(lcs(n, m, 0)) # This code is contributed by Ryuga
// C# program using to find length// of the longest common substring// recursionusing System; class GFG { static String X, Y; // Returns length of function for // longest common substring of // X[0..m-1] and Y[0..n-1] static int lcs(int i, int j, int count) { if (i == 0 || j == 0) { return count; } if (X[i - 1] == Y[j - 1]) { count = lcs(i - 1, j - 1, count + 1); } count = Math.Max(count, Math.Max(lcs(i, j - 1, 0), lcs(i - 1, j, 0))); return count; } // Driver code public static void Main() { int n, m; X = "abcdxyz"; Y = "xyzabcd"; n = X.Length; m = Y.Length; Console.Write(lcs(n, m, 0)); }} // This code is contributed by Rajput-JI
<?php// PHP program using to find length of the// longest common substring recursion // Returns length of function for// longest common substring of// X[0..m-1] and Y[0..n-1]function lcs($i, $j, $count, &$X, &$Y){ if ($i == 0 || $j == 0) return $count; if ($X[$i - 1] == $Y[$j - 1]) { $count = lcs($i - 1, $j - 1, $count + 1, $X, $Y); } $count = max($count, lcs($i, $j - 1, 0, $X, $Y), lcs($i - 1, $j, 0, $X, $Y)); return $count;} // Driver code$X = "abcdxyz";$Y = "xyzabcd"; $n = strlen($X);$m = strlen($Y); echo lcs($n, $m, 0, $X, $Y); // This code is contributed// by rathbhupendra?>
<script> // Javascript program using to find length of the // longest common substring recursion let X, Y; // Returns length of function f // or longest common substring // of X[0..m-1] and Y[0..n-1] function lcs(i, j, count) { if (i == 0 || j == 0) return count; if (X[i - 1] == Y[j - 1]) { count = lcs(i - 1, j - 1, count + 1); } count = Math.max(count, Math.max(lcs(i, j - 1, 0), lcs(i - 1, j, 0))); return count; } let n, m; X = "abcdxyz"; Y = "xyzabcd"; n = X.length; m = Y.length; document.write(lcs(n, m, 0)); // This code is contributed by divyeshrabadiya07.</script>
4
In this method, we will use recursion to find the longest prefix of all the possible substrings.Let gives the length of the longest common suffix starting from indices i, j of strings X, Y respectively.Then the function can be defined as :In this recursion we can see that the function has only one dependency, so that means we can get away with memorizing just the previous computation if we do our computation in a specific order.Consider the following table where we memorize the solutions:
In this method, we will use recursion to find the longest prefix of all the possible substrings.
Let gives the length of the longest common suffix starting from indices i, j of strings X, Y respectively.
Then the function can be defined as :
In this recursion we can see that the function has only one dependency, so that means we can get away with memorizing just the previous computation if we do our computation in a specific order.
Consider the following table where we memorize the solutions:
We need to find the solution diagonally upwards. In this particular example:
first diagonal(4, 0)
(4, 0)
second diagonal(4, 1)(3, 0)
(4, 1)
(3, 0)
third diagonal(4, 2)(3, 1)(2, 0)
(4, 2)
(3, 1)
(2, 0)
...
Like this, we need to remember only the previous computation.
Python3
# Python code for the above approachfrom functools import lru_cachefrom operator import itemgetter def longest_common_substring(x: str, y: str) -> (int, int, int): # function to find the longest common substring # Memorizing with maximum size of the memory as 1 @lru_cache(maxsize=1) # function to find the longest common prefix def longest_common_prefix(i: int, j: int) -> int: if 0 <= i < len(x) and 0 <= j < len(y) and x[i] == y[j]: return 1 + longest_common_prefix(i + 1, j + 1) else: return 0 # diagonally computing the subproblems # to decrease memory dependency def digonal_computation(): # upper right triangle of the 2D array for k in range(len(x)): yield from ((longest_common_prefix(i, j), i, j) for i, j in zip(range(k, -1, -1), range(len(y) - 1, -1, -1))) # lower left triangle of the 2D array for k in range(len(y)): yield from ((longest_common_prefix(i, j), i, j) for i, j in zip(range(k, -1, -1), range(len(x) - 1, -1, -1))) # returning the maximum of all the subproblems return max(digonal_computation(), key=itemgetter(0), default=(0, 0, 0)) # Driver Codeif __name__ == '__main__': x: str = 'GeeksforGeeks' y: str = 'GeeksQuiz' length, i, j = longest_common_substring(x, y) print(f'length: {length}, i: {i}, j: {j}') print(f'x substring: {x[i: i + length]}') print(f'y substring: {y[j: j + length]}')
length: 5, i: 0, j: 0
x substring: Geeks
y substring: Geeks
Time Complexity: Space Complexity:
Exercise: The above solution prints only the length of the longest common substring. Extend the solution to print the substring also.
Kushdeep_Mittal
Rajput-Ji
ankthon
ukasp
rathbhupendra
ankit_ak
rag2127
avanitrachhadiya2155
divyeshrabadiya07
harshaabs
srd2705
pkalyan264
varshagumber28
simmytarika5
ruhelaa48
rajsanghavi9
shivanisinghss2110
surinderdawra388
hardikkoriintern
Amazon
Microsoft
Morgan Stanley
Dynamic Programming
Strings
Morgan Stanley
Amazon
Microsoft
Strings
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Largest Sum Contiguous Subarray
Program for Fibonacci numbers
Longest Palindromic Substring | Set 1
Longest Increasing Subsequence | DP-3
Sieve of Eratosthenes
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 135,
"s": 54,
"text": "Given two strings ‘X’ and ‘Y’, find the length of the longest common substring. "
},
{
"code": null,
"e": 147,
"s": 135,
"text": "Examples : "
},
{
"code": null,
"e": 275,
"s": 147,
"text": "Input : X = “GeeksforGeeks”, y = “GeeksQuiz” Output : 5 Explanation:The longest common substring is “Geeks” and is of length 5."
},
{
"code": null,
"e": 394,
"s": 275,
"text": "Input : X = “abcdxyz”, y = “xyzabcd” Output : 4 Explanation:The longest common substring is “abcd” and is of length 4."
},
{
"code": null,
"e": 519,
"s": 394,
"text": "Input : X = “zxabcdezy”, y = “yzabcdezx” Output : 6 Explanation:The longest common substring is “abcdez” and is of length 6."
},
{
"code": null,
"e": 601,
"s": 519,
"text": "Approach:Let m and n be the lengths of the first and second strings respectively."
},
{
"code": null,
"e": 979,
"s": 601,
"text": "A simple solution is to one by one consider all substrings of the first string and for every substring check if it is a substring in the second string. Keep track of the maximum length substring. There will be O(m^2) substrings and we can find whether a string is substring on another string in O(n) time (See this). So overall time complexity of this method would be O(n * m2)"
},
{
"code": null,
"e": 1196,
"s": 979,
"text": "Dynamic Programming can be used to find the longest common substring in O(m*n) time. The idea is to find the length of the longest common suffix for all substrings of both strings and store these lengths in a table. "
},
{
"code": null,
"e": 1729,
"s": 1196,
"text": "The longest common suffix has following optimal substructure property. If last characters match, then we reduce both lengths by 1 LCSuff(X, Y, m, n) = LCSuff(X, Y, m-1, n-1) + 1 if X[m-1] = Y[n-1] If last characters do not match, then result is 0, i.e., LCSuff(X, Y, m, n) = 0 if (X[m-1] != Y[n-1])Now we consider suffixes of different substrings ending at different indexes. The maximum length Longest Common Suffix is the longest common substring. LCSubStr(X, Y, m, n) = Max(LCSuff(X, Y, i, j)) where 1 <= i <= m and 1 <= j <= n "
},
{
"code": null,
"e": 1796,
"s": 1729,
"text": "Following is the iterative implementation of the above solution. "
},
{
"code": null,
"e": 1800,
"s": 1796,
"text": "C++"
},
{
"code": null,
"e": 1805,
"s": 1800,
"text": "Java"
},
{
"code": null,
"e": 1813,
"s": 1805,
"text": "Python3"
},
{
"code": null,
"e": 1816,
"s": 1813,
"text": "C#"
},
{
"code": null,
"e": 1820,
"s": 1816,
"text": "PHP"
},
{
"code": null,
"e": 1831,
"s": 1820,
"text": "Javascript"
},
{
"code": "/* Dynamic Programming solution to find length of the longest common substring */#include <iostream>#include <string.h>using namespace std; /* Returns length of longest common substring of X[0..m-1] and Y[0..n-1] */int LCSubStr(char* X, char* Y, int m, int n){ // Create a table to store // lengths of longest // common suffixes of substrings. // Note that LCSuff[i][j] contains // length of longest common suffix // of X[0..i-1] and Y[0..j-1]. int LCSuff[m + 1][n + 1]; int result = 0; // To store length of the // longest common substring /* Following steps build LCSuff[m+1][n+1] in bottom up fashion. */ for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { // The first row and first column // entries have no logical meaning, // they are used only for simplicity // of program if (i == 0 || j == 0) LCSuff[i][j] = 0; else if (X[i - 1] == Y[j - 1]) { LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1; result = max(result, LCSuff[i][j]); } else LCSuff[i][j] = 0; } } return result;} // Driver codeint main(){ char X[] = \"OldSite:GeeksforGeeks.org\"; char Y[] = \"NewSite:GeeksQuiz.com\"; int m = strlen(X); int n = strlen(Y); cout << \"Length of Longest Common Substring is \" << LCSubStr(X, Y, m, n); return 0;}",
"e": 3317,
"s": 1831,
"text": null
},
{
"code": "// Java implementation of// finding length of longest// Common substring using// Dynamic Programmingclass GFG { /* Returns length of longest common substring of X[0..m-1] and Y[0..n-1] */ static int LCSubStr(char X[], char Y[], int m, int n) { // Create a table to store // lengths of longest common // suffixes of substrings. // Note that LCSuff[i][j] // contains length of longest // common suffix of // X[0..i-1] and Y[0..j-1]. // The first row and first // column entries have no // logical meaning, they are // used only for simplicity of program int LCStuff[][] = new int[m + 1][n + 1]; // To store length of the longest // common substring int result = 0; // Following steps build // LCSuff[m+1][n+1] in bottom up fashion for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) LCStuff[i][j] = 0; else if (X[i - 1] == Y[j - 1]) { LCStuff[i][j] = LCStuff[i - 1][j - 1] + 1; result = Integer.max(result, LCStuff[i][j]); } else LCStuff[i][j] = 0; } } return result; } // Driver Code public static void main(String[] args) { String X = \"OldSite:GeeksforGeeks.org\"; String Y = \"NewSite:GeeksQuiz.com\"; int m = X.length(); int n = Y.length(); System.out.println(LCSubStr(X.toCharArray(), Y.toCharArray(), m, n)); }} // This code is contributed by Sumit Ghosh",
"e": 5166,
"s": 3317,
"text": null
},
{
"code": "# Python3 implementation of Finding# Length of Longest Common Substring # Returns length of longest common# substring of X[0..m-1] and Y[0..n-1] def LCSubStr(X, Y, m, n): # Create a table to store lengths of # longest common suffixes of substrings. # Note that LCSuff[i][j] contains the # length of longest common suffix of # X[0...i-1] and Y[0...j-1]. The first # row and first column entries have no # logical meaning, they are used only # for simplicity of the program. # LCSuff is the table with zero # value initially in each cell LCSuff = [[0 for k in range(n+1)] for l in range(m+1)] # To store the length of # longest common substring result = 0 # Following steps to build # LCSuff[m+1][n+1] in bottom up fashion for i in range(m + 1): for j in range(n + 1): if (i == 0 or j == 0): LCSuff[i][j] = 0 elif (X[i-1] == Y[j-1]): LCSuff[i][j] = LCSuff[i-1][j-1] + 1 result = max(result, LCSuff[i][j]) else: LCSuff[i][j] = 0 return result # Driver CodeX = 'OldSite:GeeksforGeeks.org'Y = 'NewSite:GeeksQuiz.com' m = len(X)n = len(Y) print('Length of Longest Common Substring is', LCSubStr(X, Y, m, n)) # This code is contributed by Soumen Ghosh",
"e": 6476,
"s": 5166,
"text": null
},
{
"code": "// C# implementation of finding length of longest// Common substring using Dynamic Programmingusing System; class GFG { // Returns length of longest common // substring of X[0..m-1] and Y[0..n-1] static int LCSubStr(string X, string Y, int m, int n) { // Create a table to store lengths of // longest common suffixes of substrings. // Note that LCSuff[i][j] contains length // of longest common suffix of X[0..i-1] // and Y[0..j-1]. The first row and first // column entries have no logical meaning, // they are used only for simplicity of // program int[, ] LCStuff = new int[m + 1, n + 1]; // To store length of the longest common // substring int result = 0; // Following steps build LCSuff[m+1][n+1] // in bottom up fashion for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) LCStuff[i, j] = 0; else if (X[i - 1] == Y[j - 1]) { LCStuff[i, j] = LCStuff[i - 1, j - 1] + 1; result = Math.Max(result, LCStuff[i, j]); } else LCStuff[i, j] = 0; } } return result; } // Driver Code public static void Main() { String X = \"OldSite:GeeksforGeeks.org\"; String Y = \"NewSite:GeeksQuiz.com\"; int m = X.Length; int n = Y.Length; Console.Write(\"Length of Longest Common\" + \" Substring is \" + LCSubStr(X, Y, m, n)); }} // This code is contributed by Sam007.",
"e": 8223,
"s": 6476,
"text": null
},
{
"code": "<?php// Dynamic Programming solution to find// length of the longest common substring // Returns length of longest common// substring of X[0..m-1] and Y[0..n-1]function LCSubStr($X, $Y, $m, $n){ // Create a table to store lengths of // longest common suffixes of substrings. // Notethat LCSuff[i][j] contains length // of longest common suffix of X[0..i-1] // and Y[0..j-1]. The first row and // first column entries have no logical // meaning, they are used only for // simplicity of program $LCSuff = array_fill(0, $m + 1, array_fill(0, $n + 1, NULL)); $result = 0; // To store length of the // longest common substring // Following steps build LCSuff[m+1][n+1] // in bottom up fashion. for ($i = 0; $i <= $m; $i++) { for ($j = 0; $j <= $n; $j++) { if ($i == 0 || $j == 0) $LCSuff[$i][$j] = 0; else if ($X[$i - 1] == $Y[$j - 1]) { $LCSuff[$i][$j] = $LCSuff[$i - 1][$j - 1] + 1; $result = max($result, $LCSuff[$i][$j]); } else $LCSuff[$i][$j] = 0; } } return $result;} // Driver Code$X = \"OldSite:GeeksforGeeks.org\";$Y = \"NewSite:GeeksQuiz.com\"; $m = strlen($X);$n = strlen($Y); echo \"Length of Longest Common Substring is \" . LCSubStr($X, $Y, $m, $n); // This code is contributed by ita_c?>",
"e": 9688,
"s": 8223,
"text": null
},
{
"code": "<script> // JavaScript implementation of// finding length of longest// Common substring using// Dynamic Programming /* Returns length of longest common substring of X[0..m-1] and Y[0..n-1] */ function LCSubStr( X, Y , m , n) { // Create a table to store // lengths of longest common // suffixes of substrings. // Note that LCSuff[i][j] // contains length of longest // common suffix of // X[0..i-1] and Y[0..j-1]. // The first row and first // column entries have no // logical meaning, they are // used only for simplicity of program var LCStuff = Array(m + 1).fill().map(()=>Array(n + 1).fill(0)); // To store length of the longest // common substring var result = 0; // Following steps build // LCSuff[m+1][n+1] in bottom up fashion for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) LCStuff[i][j] = 0; else if (X[i - 1] == Y[j - 1]) { LCStuff[i][j] = LCStuff[i - 1][j - 1] + 1; result = Math.max(result, LCStuff[i][j]); } else LCStuff[i][j] = 0; } } return result; } // Driver Code var X = \"OldSite:GeeksforGeeks.org\"; var Y = \"NewSite:GeeksQuiz.com\"; var m = X.length; var n = Y.length; document.write(\"Length of Longest Common Substring is \" + LCSubStr(X, Y, m, n)); // This code contributed by Rajput-Ji </script>",
"e": 11311,
"s": 9688,
"text": null
},
{
"code": null,
"e": 11352,
"s": 11311,
"text": "Length of Longest Common Substring is 10"
},
{
"code": null,
"e": 11400,
"s": 11352,
"text": "Time Complexity: O(m*n) Auxiliary Space: O(m*n)"
},
{
"code": null,
"e": 11602,
"s": 11400,
"text": "Another approach: (Space optimized approach).In the above approach, we are only using the last row of the 2-D array only, hence we can optimize the space by using a 2-D array of dimension 2*(min(n,m))."
},
{
"code": null,
"e": 11653,
"s": 11602,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 11657,
"s": 11653,
"text": "C++"
},
{
"code": null,
"e": 11662,
"s": 11657,
"text": "Java"
},
{
"code": null,
"e": 11670,
"s": 11662,
"text": "Python3"
},
{
"code": null,
"e": 11673,
"s": 11670,
"text": "C#"
},
{
"code": null,
"e": 11684,
"s": 11673,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to find the length of the// longest LCSint LCSubStr(string s, string t, int n, int m){ // Create DP table int dp[2][m + 1]; int res = 0; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (s[i - 1] == t[j - 1]) { dp[i % 2][j] = dp[(i - 1) % 2][j - 1] + 1; if (dp[i % 2][j] > res) res = dp[i % 2][j]; } else dp[i % 2][j] = 0; } } return res;} // Driver Codeint main(){ string X = \"OldSite:GeeksforGeeks.org\"; string Y = \"NewSite:GeeksQuiz.com\"; int m = X.length(); int n = Y.length(); cout << LCSubStr(X, Y, m, n); return 0; cout << \"GFG!\"; return 0;} // This code is contributed by rajsanghavi9.",
"e": 12553,
"s": 11684,
"text": null
},
{
"code": "// Java implementation of the above approach class GFG{ // Function to find the length of the // longest LCS static int LCSubStr(String s,String t, int n,int m) { // Create DP table int dp[][]=new int[2][m+1]; int res=0; for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { if(s.charAt(i-1)==t.charAt(j-1)) { dp[i%2][j]=dp[(i-1)%2][j-1]+1; if(dp[i%2][j]>res) res=dp[i%2][j]; } else dp[i%2][j]=0; } } return res; } // Driver Code public static void main (String[] args) { String X=\"OldSite:GeeksforGeeks.org\"; String Y=\"NewSite:GeeksQuiz.com\"; int m=X.length(); int n=Y.length(); // Function call System.out.println(LCSubStr(X,Y,m,n)); }}",
"e": 13528,
"s": 12553,
"text": null
},
{
"code": "# Python implementation of the above approach # Function to find the length of the# longest LCSdef LCSubStr(s, t, n, m): # Create DP table dp = [[0 for i in range(m + 1)] for j in range(2)] res = 0 for i in range(1,n + 1): for j in range(1,m + 1): if(s[i - 1] == t[j - 1]): dp[i % 2][j] = dp[(i - 1) % 2][j - 1] + 1 if(dp[i % 2][j] > res): res = dp[i % 2][j] else: dp[i % 2][j] = 0 return res # Driver CodeX = \"OldSite:GeeksforGeeks.org\"Y = \"NewSite:GeeksQuiz.com\"m = len(X)n = len(Y) # Function callprint(LCSubStr(X,Y,m,n)) # This code is contributed by avanitrachhadiya2155",
"e": 14220,
"s": 13528,
"text": null
},
{
"code": "// C# implementation of the above approachusing System;public class GFG{ // Function to find the length of the // longest LCS static int LCSubStr(string s,string t, int n,int m) { // Create DP table int[,] dp = new int[2, m + 1]; int res = 0; for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { if(s[i - 1] == t[j - 1]) { dp[i % 2, j] = dp[(i - 1) % 2, j - 1] + 1; if(dp[i % 2, j] > res) res = dp[i % 2, j]; } else dp[i % 2, j] = 0; } } return res; } // Driver Code static public void Main (){ string X = \"OldSite:GeeksforGeeks.org\"; string Y = \"NewSite:GeeksQuiz.com\"; int m = X.Length; int n = Y.Length; // Function call Console.WriteLine(LCSubStr(X,Y,m,n)); }} // This code is contributed by rag2127",
"e": 15078,
"s": 14220,
"text": null
},
{
"code": "<script>// JavaScript implementation of the above approach // Function to find the length of the // longest LCS function LCSubStr(s, t, n, m) { // Create DP table var dp = Array(2).fill().map(()=>Array(m+ 1).fill(0)); var res = 0; for(var i = 1; i <= n; i++) { for(var j = 1; j <= m; j++) { if(s.charAt(i - 1) == t.charAt(j - 1)) { dp[i % 2][j] = dp[(i - 1) % 2][j - 1] + 1; if(dp[i % 2][j] > res) res = dp[i % 2][j]; } else dp[i % 2][j] = 0; } } return res; } // Driver Code var X = \"OldSite:GeeksforGeeks.org\"; var Y = \"NewSite:GeeksQuiz.com\"; var m = X.length; var n = Y.length; // Function call document.write(LCSubStr(X, Y, m, n)); // This code is contributed by shivanisinghss2110</script>",
"e": 16073,
"s": 15078,
"text": null
},
{
"code": null,
"e": 16076,
"s": 16073,
"text": "10"
},
{
"code": null,
"e": 16128,
"s": 16076,
"text": "Time Complexity: O(n*m)Auxiliary Space: O(min(m,n))"
},
{
"code": null,
"e": 16219,
"s": 16128,
"text": "Another approach: (Using recursion) Here is the recursive solution of the above approach. "
},
{
"code": null,
"e": 16223,
"s": 16219,
"text": "C++"
},
{
"code": null,
"e": 16228,
"s": 16223,
"text": "Java"
},
{
"code": null,
"e": 16236,
"s": 16228,
"text": "Python3"
},
{
"code": null,
"e": 16239,
"s": 16236,
"text": "C#"
},
{
"code": null,
"e": 16243,
"s": 16239,
"text": "PHP"
},
{
"code": null,
"e": 16254,
"s": 16243,
"text": "Javascript"
},
{
"code": "// C++ program using to find length of the// longest common substring recursion#include <iostream> using namespace std; string X, Y; // Returns length of function f// or longest common substring// of X[0..m-1] and Y[0..n-1]int lcs(int i, int j, int count){ if (i == 0 || j == 0) return count; if (X[i - 1] == Y[j - 1]) { count = lcs(i - 1, j - 1, count + 1); } count = max(count, max(lcs(i, j - 1, 0), lcs(i - 1, j, 0))); return count;} // Driver codeint main(){ int n, m; X = \"abcdxyz\"; Y = \"xyzabcd\"; n = X.size(); m = Y.size(); cout << lcs(n, m, 0); return 0;}",
"e": 16909,
"s": 16254,
"text": null
},
{
"code": "// Java program using to find length of the// longest common substring recursion class GFG { static String X, Y; // Returns length of function // for longest common // substring of X[0..m-1] and Y[0..n-1] static int lcs(int i, int j, int count) { if (i == 0 || j == 0) { return count; } if (X.charAt(i - 1) == Y.charAt(j - 1)) { count = lcs(i - 1, j - 1, count + 1); } count = Math.max(count, Math.max(lcs(i, j - 1, 0), lcs(i - 1, j, 0))); return count; } // Driver code public static void main(String[] args) { int n, m; X = \"abcdxyz\"; Y = \"xyzabcd\"; n = X.length(); m = Y.length(); System.out.println(lcs(n, m, 0)); }}// This code is contributed by Rajput-JI",
"e": 17801,
"s": 16909,
"text": null
},
{
"code": "# Python3 program using to find length of# the longest common substring recursion # Returns length of function for longest# common substring of X[0..m-1] and Y[0..n-1] def lcs(i, j, count): if (i == 0 or j == 0): return count if (X[i - 1] == Y[j - 1]): count = lcs(i - 1, j - 1, count + 1) count = max(count, max(lcs(i, j - 1, 0), lcs(i - 1, j, 0))) return count # Driver codeif __name__ == \"__main__\": X = \"abcdxyz\" Y = \"xyzabcd\" n = len(X) m = len(Y) print(lcs(n, m, 0)) # This code is contributed by Ryuga",
"e": 18386,
"s": 17801,
"text": null
},
{
"code": "// C# program using to find length// of the longest common substring// recursionusing System; class GFG { static String X, Y; // Returns length of function for // longest common substring of // X[0..m-1] and Y[0..n-1] static int lcs(int i, int j, int count) { if (i == 0 || j == 0) { return count; } if (X[i - 1] == Y[j - 1]) { count = lcs(i - 1, j - 1, count + 1); } count = Math.Max(count, Math.Max(lcs(i, j - 1, 0), lcs(i - 1, j, 0))); return count; } // Driver code public static void Main() { int n, m; X = \"abcdxyz\"; Y = \"xyzabcd\"; n = X.Length; m = Y.Length; Console.Write(lcs(n, m, 0)); }} // This code is contributed by Rajput-JI",
"e": 19210,
"s": 18386,
"text": null
},
{
"code": "<?php// PHP program using to find length of the// longest common substring recursion // Returns length of function for// longest common substring of// X[0..m-1] and Y[0..n-1]function lcs($i, $j, $count, &$X, &$Y){ if ($i == 0 || $j == 0) return $count; if ($X[$i - 1] == $Y[$j - 1]) { $count = lcs($i - 1, $j - 1, $count + 1, $X, $Y); } $count = max($count, lcs($i, $j - 1, 0, $X, $Y), lcs($i - 1, $j, 0, $X, $Y)); return $count;} // Driver code$X = \"abcdxyz\";$Y = \"xyzabcd\"; $n = strlen($X);$m = strlen($Y); echo lcs($n, $m, 0, $X, $Y); // This code is contributed// by rathbhupendra?>",
"e": 19890,
"s": 19210,
"text": null
},
{
"code": "<script> // Javascript program using to find length of the // longest common substring recursion let X, Y; // Returns length of function f // or longest common substring // of X[0..m-1] and Y[0..n-1] function lcs(i, j, count) { if (i == 0 || j == 0) return count; if (X[i - 1] == Y[j - 1]) { count = lcs(i - 1, j - 1, count + 1); } count = Math.max(count, Math.max(lcs(i, j - 1, 0), lcs(i - 1, j, 0))); return count; } let n, m; X = \"abcdxyz\"; Y = \"xyzabcd\"; n = X.length; m = Y.length; document.write(lcs(n, m, 0)); // This code is contributed by divyeshrabadiya07.</script>",
"e": 20644,
"s": 19890,
"text": null
},
{
"code": null,
"e": 20646,
"s": 20644,
"text": "4"
},
{
"code": null,
"e": 21141,
"s": 20646,
"text": "In this method, we will use recursion to find the longest prefix of all the possible substrings.Let gives the length of the longest common suffix starting from indices i, j of strings X, Y respectively.Then the function can be defined as :In this recursion we can see that the function has only one dependency, so that means we can get away with memorizing just the previous computation if we do our computation in a specific order.Consider the following table where we memorize the solutions:"
},
{
"code": null,
"e": 21238,
"s": 21141,
"text": "In this method, we will use recursion to find the longest prefix of all the possible substrings."
},
{
"code": null,
"e": 21346,
"s": 21238,
"text": "Let gives the length of the longest common suffix starting from indices i, j of strings X, Y respectively."
},
{
"code": null,
"e": 21384,
"s": 21346,
"text": "Then the function can be defined as :"
},
{
"code": null,
"e": 21578,
"s": 21384,
"text": "In this recursion we can see that the function has only one dependency, so that means we can get away with memorizing just the previous computation if we do our computation in a specific order."
},
{
"code": null,
"e": 21640,
"s": 21578,
"text": "Consider the following table where we memorize the solutions:"
},
{
"code": null,
"e": 21717,
"s": 21640,
"text": "We need to find the solution diagonally upwards. In this particular example:"
},
{
"code": null,
"e": 21738,
"s": 21717,
"text": "first diagonal(4, 0)"
},
{
"code": null,
"e": 21745,
"s": 21738,
"text": "(4, 0)"
},
{
"code": null,
"e": 21773,
"s": 21745,
"text": "second diagonal(4, 1)(3, 0)"
},
{
"code": null,
"e": 21780,
"s": 21773,
"text": "(4, 1)"
},
{
"code": null,
"e": 21787,
"s": 21780,
"text": "(3, 0)"
},
{
"code": null,
"e": 21820,
"s": 21787,
"text": "third diagonal(4, 2)(3, 1)(2, 0)"
},
{
"code": null,
"e": 21827,
"s": 21820,
"text": "(4, 2)"
},
{
"code": null,
"e": 21834,
"s": 21827,
"text": "(3, 1)"
},
{
"code": null,
"e": 21841,
"s": 21834,
"text": "(2, 0)"
},
{
"code": null,
"e": 21845,
"s": 21841,
"text": "..."
},
{
"code": null,
"e": 21907,
"s": 21845,
"text": "Like this, we need to remember only the previous computation."
},
{
"code": null,
"e": 21915,
"s": 21907,
"text": "Python3"
},
{
"code": "# Python code for the above approachfrom functools import lru_cachefrom operator import itemgetter def longest_common_substring(x: str, y: str) -> (int, int, int): # function to find the longest common substring # Memorizing with maximum size of the memory as 1 @lru_cache(maxsize=1) # function to find the longest common prefix def longest_common_prefix(i: int, j: int) -> int: if 0 <= i < len(x) and 0 <= j < len(y) and x[i] == y[j]: return 1 + longest_common_prefix(i + 1, j + 1) else: return 0 # diagonally computing the subproblems # to decrease memory dependency def digonal_computation(): # upper right triangle of the 2D array for k in range(len(x)): yield from ((longest_common_prefix(i, j), i, j) for i, j in zip(range(k, -1, -1), range(len(y) - 1, -1, -1))) # lower left triangle of the 2D array for k in range(len(y)): yield from ((longest_common_prefix(i, j), i, j) for i, j in zip(range(k, -1, -1), range(len(x) - 1, -1, -1))) # returning the maximum of all the subproblems return max(digonal_computation(), key=itemgetter(0), default=(0, 0, 0)) # Driver Codeif __name__ == '__main__': x: str = 'GeeksforGeeks' y: str = 'GeeksQuiz' length, i, j = longest_common_substring(x, y) print(f'length: {length}, i: {i}, j: {j}') print(f'x substring: {x[i: i + length]}') print(f'y substring: {y[j: j + length]}')",
"e": 23537,
"s": 21915,
"text": null
},
{
"code": null,
"e": 23597,
"s": 23537,
"text": "length: 5, i: 0, j: 0\nx substring: Geeks\ny substring: Geeks"
},
{
"code": null,
"e": 23633,
"s": 23597,
"text": "Time Complexity: Space Complexity: "
},
{
"code": null,
"e": 23767,
"s": 23633,
"text": "Exercise: The above solution prints only the length of the longest common substring. Extend the solution to print the substring also."
},
{
"code": null,
"e": 23783,
"s": 23767,
"text": "Kushdeep_Mittal"
},
{
"code": null,
"e": 23793,
"s": 23783,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 23801,
"s": 23793,
"text": "ankthon"
},
{
"code": null,
"e": 23807,
"s": 23801,
"text": "ukasp"
},
{
"code": null,
"e": 23821,
"s": 23807,
"text": "rathbhupendra"
},
{
"code": null,
"e": 23830,
"s": 23821,
"text": "ankit_ak"
},
{
"code": null,
"e": 23838,
"s": 23830,
"text": "rag2127"
},
{
"code": null,
"e": 23859,
"s": 23838,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 23877,
"s": 23859,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 23887,
"s": 23877,
"text": "harshaabs"
},
{
"code": null,
"e": 23895,
"s": 23887,
"text": "srd2705"
},
{
"code": null,
"e": 23906,
"s": 23895,
"text": "pkalyan264"
},
{
"code": null,
"e": 23921,
"s": 23906,
"text": "varshagumber28"
},
{
"code": null,
"e": 23934,
"s": 23921,
"text": "simmytarika5"
},
{
"code": null,
"e": 23944,
"s": 23934,
"text": "ruhelaa48"
},
{
"code": null,
"e": 23957,
"s": 23944,
"text": "rajsanghavi9"
},
{
"code": null,
"e": 23976,
"s": 23957,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 23993,
"s": 23976,
"text": "surinderdawra388"
},
{
"code": null,
"e": 24010,
"s": 23993,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 24017,
"s": 24010,
"text": "Amazon"
},
{
"code": null,
"e": 24027,
"s": 24017,
"text": "Microsoft"
},
{
"code": null,
"e": 24042,
"s": 24027,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 24062,
"s": 24042,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 24070,
"s": 24062,
"text": "Strings"
},
{
"code": null,
"e": 24085,
"s": 24070,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 24092,
"s": 24085,
"text": "Amazon"
},
{
"code": null,
"e": 24102,
"s": 24092,
"text": "Microsoft"
},
{
"code": null,
"e": 24110,
"s": 24102,
"text": "Strings"
},
{
"code": null,
"e": 24130,
"s": 24110,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 24228,
"s": 24130,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24260,
"s": 24228,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 24290,
"s": 24260,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 24328,
"s": 24290,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 24366,
"s": 24328,
"text": "Longest Increasing Subsequence | DP-3"
},
{
"code": null,
"e": 24388,
"s": 24366,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 24434,
"s": 24388,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 24459,
"s": 24434,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 24519,
"s": 24459,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 24534,
"s": 24519,
"text": "C++ Data Types"
}
] |
Material UI ToolBar
|
20 Jan, 2021
Material-UI is a user interface library that provides predefined and customizable React components for faster and easy web development, these Material-UI components are based on top of Material Design by Google. In this article let’s discuss the Toolbar component in the Material-UI library.
Toolbar:
ToolBar doesn’t work independently as that of other Material-UI components, it works with the AppBar. The Toolbar component sets the properties of the children to make them horizontally aligned. The Toolbar component simply applies the normal CSS flex(display: ‘flex’), with vertical centering via alignItems: ‘center’, some padding, and the minHeight: 56px provided by the theme.mixins.toolbar.
Syntax:
<AppBar>
<Toolbar>
<Typography variant="h6">
This Is ToolBar Example
</Typography>
</Toolbar>
</AppBar>
Installing React App:
Step1: Create a React app using the following command.
npx create-react-app toolbar-example
Step 2: Now get into the project directory
cd toolbar-example
Installing Material-UI:
Installing Material-UI’s source files via npm/yarn, and they take care of injecting the CSS needed.
npm install @material-ui/core
// OR
yarn add @material-ui/core
Importing AppBar and Toolbar:
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
Important Props:
children: It is Toolbar children, usually it can be a mixture of IconButton, Button, Typography, etc.
component: The component used for the root node. Either a string to use the HTML element or a component. eg: div.
disableGutters: It is used to enable or disable gutter padding. Example: true or false.
variant: It is used to choose the variant of the toolbar. Example: regular, dense.
CSS Rule Names:
root: This applies styles to the root element.
gutters: This applies styles to the root element if disableGutters={false}.
regular: This applies styles to the root element if variant=”regular”.
dense: This applies styles to the root element if variant=”dense”.
Example 1: In this example, we have implemented the toolbar as Top AppBar.
Javascript
import React from 'react';import {AppBar, Toolbar, IconButton, Typography, Button} from '@material-ui/core';import { fade, makeStyles } from '@material-ui/core/styles';import MenuIcon from '@material-ui/icons/Menu'; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, }, menuButton: { marginRight: theme.spacing(2), }, title: { flexGrow: 1, display: 'none', [ theme.breakpoints.up('sm')]: { display: 'block', }, },})); export default function ToolbarExample() { const classes = useStyles(); return ( <div className={classes.root}> <AppBar position="static"> <Toolbar> <IconButton className={classes.menuButton} color="inherit" > <MenuIcon /> </IconButton> <Typography className={classes.title} variant="h6" noWrap> Welcome To GFG </Typography> <Button color="inherit">Login</Button> </Toolbar> </AppBar> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
Example 2: As a Bottom AppBar
Javascript
import React from 'react';import { makeStyles } from '@material-ui/core/styles';import { AppBar, Toolbar, Typography, IconButton, Paper, Fab, List, ListItem, ListItemText} from '@material-ui/core';import MenuIcon from '@material-ui/icons/Menu';import AddIcon from '@material-ui/icons/Add'; const messages = [ { id: 1, primary: 'Welcome To GeeksForGeeks', secondary: "A Computer Science Portal For Geeks", }, { id: 2, primary: 'Welcome To GeeksForGeeks', secondary: "A Computer Science Portal For Geeks", }, { id: 3, primary: 'Welcome To GeeksForGeeks', secondary: "A Computer Science Portal For Geeks", }, { id: 4, primary: 'Welcome To GeeksForGeeks', secondary: "A Computer Science Portal For Geeks", }, { id: 5, primary: 'Welcome To GeeksForGeeks', secondary: "A Computer Science Portal For Geeks", }, { id: 6, primary: 'Welcome To GeeksForGeeks', secondary: "A Computer Science Portal For Geeks", }, { id: 7, primary: 'Welcome To GeeksForGeeks', secondary: "A Computer Science Portal For Geeks", }, { id: 8, primary: 'Welcome To GeeksForGeeks', secondary: "A Computer Science Portal For Geeks", }]; const useStyles = makeStyles((theme) => ({ text: { padding: theme.spacing(2, 2, 0), }, paper: { paddingBottom: 50, }, list: { marginBottom: theme.spacing(2), }, appBar: { top: 'auto', bottom: 0, }, fabButton: { position: 'absolute', zIndex: 1, top: -30, left: 0, right: 0, margin: '0 auto', },})); export default function BottomAppBar() { const classes = useStyles(); return ( <React.Fragment> <Paper square className={classes.paper}> <Typography className={classes.text} variant="h5" gutterBottom> List </Typography> <List className={classes.list}> {messages.map(({ id, primary, secondary, person }) => ( <React.Fragment key={id}> <ListItem button> <ListItemText primary={primary} secondary={secondary} /> </ListItem> </React.Fragment> ))} </List> </Paper> <AppBar position="fixed" color="primary" className={classes.appBar}> <Toolbar> <IconButton edge="start" color="inherit" aria-label="open drawer"> <MenuIcon /> </IconButton> <Fab color="secondary" aria-label="add" className={classes.fabButton}> <AddIcon /> </Fab> </Toolbar> </AppBar> </React.Fragment> );}
Output:
Material-UI
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
How to create footer to stay at the bottom of a Web page?
Roadmap to Learn JavaScript For Beginners
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jan, 2021"
},
{
"code": null,
"e": 320,
"s": 28,
"text": "Material-UI is a user interface library that provides predefined and customizable React components for faster and easy web development, these Material-UI components are based on top of Material Design by Google. In this article let’s discuss the Toolbar component in the Material-UI library."
},
{
"code": null,
"e": 329,
"s": 320,
"text": "Toolbar:"
},
{
"code": null,
"e": 725,
"s": 329,
"text": "ToolBar doesn’t work independently as that of other Material-UI components, it works with the AppBar. The Toolbar component sets the properties of the children to make them horizontally aligned. The Toolbar component simply applies the normal CSS flex(display: ‘flex’), with vertical centering via alignItems: ‘center’, some padding, and the minHeight: 56px provided by the theme.mixins.toolbar."
},
{
"code": null,
"e": 733,
"s": 725,
"text": "Syntax:"
},
{
"code": null,
"e": 845,
"s": 733,
"text": "<AppBar>\n<Toolbar>\n <Typography variant=\"h6\">\n This Is ToolBar Example\n </Typography>\n</Toolbar>\n</AppBar>"
},
{
"code": null,
"e": 867,
"s": 845,
"text": "Installing React App:"
},
{
"code": null,
"e": 922,
"s": 867,
"text": "Step1: Create a React app using the following command."
},
{
"code": null,
"e": 959,
"s": 922,
"text": "npx create-react-app toolbar-example"
},
{
"code": null,
"e": 1002,
"s": 959,
"text": "Step 2: Now get into the project directory"
},
{
"code": null,
"e": 1021,
"s": 1002,
"text": "cd toolbar-example"
},
{
"code": null,
"e": 1046,
"s": 1021,
"text": "Installing Material-UI: "
},
{
"code": null,
"e": 1146,
"s": 1046,
"text": "Installing Material-UI’s source files via npm/yarn, and they take care of injecting the CSS needed."
},
{
"code": null,
"e": 1209,
"s": 1146,
"text": "npm install @material-ui/core\n// OR\nyarn add @material-ui/core"
},
{
"code": null,
"e": 1239,
"s": 1209,
"text": "Importing AppBar and Toolbar:"
},
{
"code": null,
"e": 1335,
"s": 1239,
"text": "import AppBar from '@material-ui/core/AppBar';\nimport Toolbar from '@material-ui/core/Toolbar';"
},
{
"code": null,
"e": 1352,
"s": 1335,
"text": "Important Props:"
},
{
"code": null,
"e": 1454,
"s": 1352,
"text": "children: It is Toolbar children, usually it can be a mixture of IconButton, Button, Typography, etc."
},
{
"code": null,
"e": 1568,
"s": 1454,
"text": "component: The component used for the root node. Either a string to use the HTML element or a component. eg: div."
},
{
"code": null,
"e": 1656,
"s": 1568,
"text": "disableGutters: It is used to enable or disable gutter padding. Example: true or false."
},
{
"code": null,
"e": 1739,
"s": 1656,
"text": "variant: It is used to choose the variant of the toolbar. Example: regular, dense."
},
{
"code": null,
"e": 1755,
"s": 1739,
"text": "CSS Rule Names:"
},
{
"code": null,
"e": 1802,
"s": 1755,
"text": "root: This applies styles to the root element."
},
{
"code": null,
"e": 1878,
"s": 1802,
"text": "gutters: This applies styles to the root element if disableGutters={false}."
},
{
"code": null,
"e": 1949,
"s": 1878,
"text": "regular: This applies styles to the root element if variant=”regular”."
},
{
"code": null,
"e": 2016,
"s": 1949,
"text": "dense: This applies styles to the root element if variant=”dense”."
},
{
"code": null,
"e": 2091,
"s": 2016,
"text": "Example 1: In this example, we have implemented the toolbar as Top AppBar."
},
{
"code": null,
"e": 2102,
"s": 2091,
"text": "Javascript"
},
{
"code": "import React from 'react';import {AppBar, Toolbar, IconButton, Typography, Button} from '@material-ui/core';import { fade, makeStyles } from '@material-ui/core/styles';import MenuIcon from '@material-ui/icons/Menu'; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, }, menuButton: { marginRight: theme.spacing(2), }, title: { flexGrow: 1, display: 'none', [ theme.breakpoints.up('sm')]: { display: 'block', }, },})); export default function ToolbarExample() { const classes = useStyles(); return ( <div className={classes.root}> <AppBar position=\"static\"> <Toolbar> <IconButton className={classes.menuButton} color=\"inherit\" > <MenuIcon /> </IconButton> <Typography className={classes.title} variant=\"h6\" noWrap> Welcome To GFG </Typography> <Button color=\"inherit\">Login</Button> </Toolbar> </AppBar> </div> );}",
"e": 3104,
"s": 2102,
"text": null
},
{
"code": null,
"e": 3217,
"s": 3104,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 3227,
"s": 3217,
"text": "npm start"
},
{
"code": null,
"e": 3235,
"s": 3227,
"text": "Output:"
},
{
"code": null,
"e": 3265,
"s": 3235,
"text": "Example 2: As a Bottom AppBar"
},
{
"code": null,
"e": 3276,
"s": 3265,
"text": "Javascript"
},
{
"code": "import React from 'react';import { makeStyles } from '@material-ui/core/styles';import { AppBar, Toolbar, Typography, IconButton, Paper, Fab, List, ListItem, ListItemText} from '@material-ui/core';import MenuIcon from '@material-ui/icons/Menu';import AddIcon from '@material-ui/icons/Add'; const messages = [ { id: 1, primary: 'Welcome To GeeksForGeeks', secondary: \"A Computer Science Portal For Geeks\", }, { id: 2, primary: 'Welcome To GeeksForGeeks', secondary: \"A Computer Science Portal For Geeks\", }, { id: 3, primary: 'Welcome To GeeksForGeeks', secondary: \"A Computer Science Portal For Geeks\", }, { id: 4, primary: 'Welcome To GeeksForGeeks', secondary: \"A Computer Science Portal For Geeks\", }, { id: 5, primary: 'Welcome To GeeksForGeeks', secondary: \"A Computer Science Portal For Geeks\", }, { id: 6, primary: 'Welcome To GeeksForGeeks', secondary: \"A Computer Science Portal For Geeks\", }, { id: 7, primary: 'Welcome To GeeksForGeeks', secondary: \"A Computer Science Portal For Geeks\", }, { id: 8, primary: 'Welcome To GeeksForGeeks', secondary: \"A Computer Science Portal For Geeks\", }]; const useStyles = makeStyles((theme) => ({ text: { padding: theme.spacing(2, 2, 0), }, paper: { paddingBottom: 50, }, list: { marginBottom: theme.spacing(2), }, appBar: { top: 'auto', bottom: 0, }, fabButton: { position: 'absolute', zIndex: 1, top: -30, left: 0, right: 0, margin: '0 auto', },})); export default function BottomAppBar() { const classes = useStyles(); return ( <React.Fragment> <Paper square className={classes.paper}> <Typography className={classes.text} variant=\"h5\" gutterBottom> List </Typography> <List className={classes.list}> {messages.map(({ id, primary, secondary, person }) => ( <React.Fragment key={id}> <ListItem button> <ListItemText primary={primary} secondary={secondary} /> </ListItem> </React.Fragment> ))} </List> </Paper> <AppBar position=\"fixed\" color=\"primary\" className={classes.appBar}> <Toolbar> <IconButton edge=\"start\" color=\"inherit\" aria-label=\"open drawer\"> <MenuIcon /> </IconButton> <Fab color=\"secondary\" aria-label=\"add\" className={classes.fabButton}> <AddIcon /> </Fab> </Toolbar> </AppBar> </React.Fragment> );}",
"e": 5954,
"s": 3276,
"text": null
},
{
"code": null,
"e": 5962,
"s": 5954,
"text": "Output:"
},
{
"code": null,
"e": 5974,
"s": 5962,
"text": "Material-UI"
},
{
"code": null,
"e": 5981,
"s": 5974,
"text": "Picked"
},
{
"code": null,
"e": 5998,
"s": 5981,
"text": "Web Technologies"
},
{
"code": null,
"e": 6096,
"s": 5998,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6157,
"s": 6096,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 6200,
"s": 6157,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 6272,
"s": 6200,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 6312,
"s": 6272,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 6336,
"s": 6312,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 6369,
"s": 6336,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 6429,
"s": 6369,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 6487,
"s": 6429,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 6529,
"s": 6487,
"text": "Roadmap to Learn JavaScript For Beginners"
}
] |
How to Integrate Google Admob Rewarded Video Ads in Android?
|
01 Sep, 2020
In order to earn money from the Android app or game, there are many ways such as in-App Purchases, Sponsorship, Advertisements, and many more. But there is another popular method to earn money from the Android app is by integrating an advertisement e.g known as Google AdMob. Google AdMob is designed with developers in mind, AdMob helps to earn more app revenue, deliver better user experience, and surface actionable insights all with automated tools that do the hard work for you.
Minimum Payout is $100
Wide Range of Ad Formats
Maximum Fill Rates
High eCPM(Effective Cost Per Mille)
Quality Ads
Personalized Ads
There are mainly four types of flexible, high-performing format available in Google AdMob
Native: Ads that you design to fit the app, seamlessly
Interstitial: Full-screen ads that capture attention and become part of the experience.
Banner: Traditional formats in a variety of placements.
Rewarded Video: An immersive, user-initiated video ad that rewards users for watching.
In this article let’s integrate Google Admob SDK to show Rewarded Video Ad in the Android app.
Rewarded Video:
Rewarded Video ad is full-screen ads that cover the whole UI of the app. The eCPM (Effective Cost Per Mille) of Rewarded Video ads are relatively higher than banner and Interstitial ads and also leads to higher CTR(Click Through Rate) which results in more earning from your app.
The user gets an in-App reward when they watch the Rewarded Video from start to end. This type of ad is mostly used in games and also can be used in the app.
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that choose Java as language though we are going to implement this project in Java language.
Go to app -> res -> values -> colors.xml file and set the colors for the app.
colors.xml
<?xml version="1.0" encoding="utf-8"?><resources> <color name="colorPrimary">#0F9D58</color> <color name="colorPrimaryDark">#0F9D58</color> <color name="colorAccent">#05af9b</color></resources>
Go to Gradle Scripts -> build.gradle (Module: app) section and import following dependencies and click the “sync now” on the above pop up.
implementation ‘com.google.android.gms:play-services-ads:19.3.0’
Go to app -> manifests -> AndroidManifests.xml section and allow “Internet Permission“.
<uses-permission android:name=”android.permission.INTERNET”/>
Go to app->manifests->AndroidManifest.xml section and add meta-data tag inside <application> tag.
<meta-data
android:name=”com.google.android.gms.ads.APPLICATION_ID”
android:value=”ca-app-pub-3940256099942544~3347511713′′
/>
In the activity_main.xml add a Button so when the user will click the Button the Rewarded Video will be played on the screen.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- Button to Show Rewarded Video Ad By Clicking it --> <Button android:id="@+id/showVideoBtn" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_margin="8dp" android:background="@color/colorPrimary" android:padding="16dp" android:text="Show Rewarded Video Ad " android:textColor="#ffff" android:textSize="20dp" /> </RelativeLayout>
Open the MainActivity.java file there within the class, first of all, create the object of the Button class.
// Creating a object of Button class
Button showVideoAdBtn;
Now inside the onCreate() method, link those objects with their respective IDs that are given in activity_main.xml file.
// link those objects with their respective id’s that we have given in activity_main.xml file
showVideoAdBtn=(Button)findViewById(R.id.showVideoBtn);
Now inside onCreate() method, initialize the Google Admob SDK
// initializing the Google Admob SDK
MobileAds.initialize(this);
Create an object of RewardedVideoAd inside MainActivity.java class
// creating object of RewardedVideoAd
private RewardedVideoAd AdMobrewardedVideoAd;
Create AdMob Rewarded Video Ad Id inside MainActivity.java class
// AdMob Rewarded Video Ad Id
private String AdId=”ca-app-pub-3940256099942544/5224354917′′;
Next create a private void loadRewardedVideoAd() method outside onCreate() method and define it.
void loadRewardedVideoAd()
{
// initializing RewardedVideoAd Object
// RewardedVideoAd Constructor Takes Context as its Argument
AdMobrewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
// Loading Rewarded Video Ad
AdMobrewardedVideoAd.loadAd(AdId, new AdRequest.Builder().build());
}
Call the loadRewardedVideoAd() inside oncreate() method after initializing the SDK.
Note: Replace “AdId” with your own app ad id to show real ads.
Next create a void showRewardedVideoAd() method outside onCreate() method which we call later to show ad.
public void showRewardedVideoAd()
{
if(AdMobrewardedVideoAd.isLoaded())//Checking If Ad is Loaded or Not
{
// showing Video Ad
AdMobrewardedVideoAd.show();
}
else
{
// Loading Rewarded Video Ad
AdMobrewardedVideoAd.loadAd(AdId, new AdRequest.Builder().build());
}
}
So the next thing is to call the showRewardedVideoAd() method. Now in oncreate() method create a ClickListener for the button and call showRewardedVideoAd().
// click listener to show Rewarded Video Ad
showVideoAdBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showRewardedVideoAd();
}
});
Now add RewardedVideoAdListener for Rewarded Video Ad, so that user will know the status of the ads.
To add RewardedVideoAdListener open loadRewardedVideoAd() method and add the below code before AdMobrewardedVideoAd.loadAd(AdId, new AdRequest.Builder().build());
// Rewarded Video Ad Listener
AdMobrewardedVideoAd.setRewardedVideoAdListener(new RewardedVideoAdListener() {
@Override
public void onRewardedVideoAdLoaded() {
// Showing Toast Message
Toast.makeText(MainActivity.this, “onRewardedVideoAdLoaded”, Toast.LENGTH_SHORT).show();
}
@Override
public void onRewardedVideoAdOpened() {
// Showing Toast Message
Toast.makeText(MainActivity.this, “onRewardedVideoAdOpened”, Toast.LENGTH_SHORT).show();
}
@Override
public void onRewardedVideoStarted() {
// Showing Toast Message
Toast.makeText(MainActivity.this, “onRewardedVideoStarted”, Toast.LENGTH_SHORT).show();
}
@Override
public void onRewardedVideoAdClosed() {
// Showing Toast Message
Toast.makeText(MainActivity.this, “onRewardedVideoAdClosed”, Toast.LENGTH_SHORT).show();
}
@Override
public void onRewarded(RewardItem rewardItem) {
// Showing Toast Message
Toast.makeText(MainActivity.this, “onRewarded”, Toast.LENGTH_SHORT).show();
}
@Override
public void onRewardedVideoAdLeftApplication() {
// Showing Toast Message
Toast.makeText(MainActivity.this, “onRewardedVideoAdLeftApplication”, Toast.LENGTH_SHORT).show();
}
@Override
public void onRewardedVideoAdFailedToLoad(int i) {
// Showing Toast Message
Toast.makeText(MainActivity.this, “onRewardedVideoAdFailedToLoad”, Toast.LENGTH_SHORT).show();
}
@Override
public void onRewardedVideoCompleted() {
// Showing Toast Message
Toast.makeText(MainActivity.this, “onRewardedVideoCompleted”, Toast.LENGTH_SHORT).show();
}
});
And inside RewardedVideoAdListener Override methods show a toast message so that users know the status of the ad. Below is the complete code for the MainActivity.Java file.
MainActivity.Java
package org.geeksforgeeks.project; import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import com.google.android.gms.ads.AdRequest;import com.google.android.gms.ads.MobileAds;import com.google.android.gms.ads.reward.RewardItem;import com.google.android.gms.ads.reward.RewardedVideoAd;import com.google.android.gms.ads.reward.RewardedVideoAdListener; public class MainActivity extends AppCompatActivity { // Creating a object of Button class Button showVideoAdBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // link those objects with their respective id's // that we have given in activity_main.xml file showVideoAdBtn = (Button)findViewById(R.id.showVideoBtn); // initializing the Google Admob SDK MobileAds.initialize(this); // loading Video Ad loadRewardedVideoAd(); // click listener to show Rewarded Video Ad showVideoAdBtn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { // showing Ad showRewardedVideoAd(); } }); } // creating RewardedVideoAd object private RewardedVideoAd AdMobrewardedVideoAd; // AdMob Rewarded Video Ad Id private String AdId = "ca-app-pub-3940256099942544/5224354917"; void loadRewardedVideoAd() { // initializing RewardedVideoAd Object // RewardedVideoAd Constructor Takes Context as its // Argument AdMobrewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this); // Rewarded Video Ad Listener AdMobrewardedVideoAd.setRewardedVideoAdListener( new RewardedVideoAdListener() { @Override public void onRewardedVideoAdLoaded() { // Showing Toast Message Toast .makeText(MainActivity.this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT) .show(); } @Override public void onRewardedVideoAdOpened() { // Showing Toast Message Toast .makeText(MainActivity.this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT) .show(); } @Override public void onRewardedVideoStarted() { // Showing Toast Message Toast .makeText(MainActivity.this, "onRewardedVideoStarted", Toast.LENGTH_SHORT) .show(); } @Override public void onRewardedVideoAdClosed() { // Showing Toast Message Toast .makeText(MainActivity.this, "onRewardedVideoAdClosed", Toast.LENGTH_SHORT) .show(); } @Override public void onRewarded( RewardItem rewardItem) { // Showing Toast Message Toast .makeText(MainActivity.this, "onRewarded", Toast.LENGTH_SHORT) .show(); } @Override public void onRewardedVideoAdLeftApplication() { // Showing Toast Message Toast .makeText( MainActivity.this, "onRewardedVideoAdLeftApplication", Toast.LENGTH_SHORT) .show(); } @Override public void onRewardedVideoAdFailedToLoad( int i) { // Showing Toast Message Toast .makeText( MainActivity.this, "onRewardedVideoAdFailedToLoad", Toast.LENGTH_SHORT) .show(); } @Override public void onRewardedVideoCompleted() { // Showing Toast Message Toast .makeText( MainActivity.this, "onRewardedVideoCompleted", Toast.LENGTH_SHORT) .show(); } }); // Loading Rewarded Video Ad AdMobrewardedVideoAd.loadAd( AdId, new AdRequest.Builder().build()); } public void showRewardedVideoAd() { // Checking If Ad is Loaded or Not if (AdMobrewardedVideoAd.isLoaded()) { // showing Video Ad AdMobrewardedVideoAd.show(); } else { // Loading Rewarded Video Ad AdMobrewardedVideoAd.loadAd( AdId, new AdRequest.Builder().build()); } }}
Below is the complete code for AndroidManifest.xml file.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.geeksforgeeks.project"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- meta data tag for admob Note:replace below app id value to your own app id --> <meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="ca-app-pub-3940256099942544~3347511713"/> </application> </manifest>
android
Android
Java
Java
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 RecyclerView in Kotlin
Android SDK and it's Components
How to Communicate Between Fragments in Android?
Broadcast Receiver in Android With Example
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": 28,
"s": 0,
"text": "\n01 Sep, 2020"
},
{
"code": null,
"e": 512,
"s": 28,
"text": "In order to earn money from the Android app or game, there are many ways such as in-App Purchases, Sponsorship, Advertisements, and many more. But there is another popular method to earn money from the Android app is by integrating an advertisement e.g known as Google AdMob. Google AdMob is designed with developers in mind, AdMob helps to earn more app revenue, deliver better user experience, and surface actionable insights all with automated tools that do the hard work for you."
},
{
"code": null,
"e": 535,
"s": 512,
"text": "Minimum Payout is $100"
},
{
"code": null,
"e": 560,
"s": 535,
"text": "Wide Range of Ad Formats"
},
{
"code": null,
"e": 579,
"s": 560,
"text": "Maximum Fill Rates"
},
{
"code": null,
"e": 615,
"s": 579,
"text": "High eCPM(Effective Cost Per Mille)"
},
{
"code": null,
"e": 627,
"s": 615,
"text": "Quality Ads"
},
{
"code": null,
"e": 644,
"s": 627,
"text": "Personalized Ads"
},
{
"code": null,
"e": 734,
"s": 644,
"text": "There are mainly four types of flexible, high-performing format available in Google AdMob"
},
{
"code": null,
"e": 789,
"s": 734,
"text": "Native: Ads that you design to fit the app, seamlessly"
},
{
"code": null,
"e": 877,
"s": 789,
"text": "Interstitial: Full-screen ads that capture attention and become part of the experience."
},
{
"code": null,
"e": 933,
"s": 877,
"text": "Banner: Traditional formats in a variety of placements."
},
{
"code": null,
"e": 1020,
"s": 933,
"text": "Rewarded Video: An immersive, user-initiated video ad that rewards users for watching."
},
{
"code": null,
"e": 1115,
"s": 1020,
"text": "In this article let’s integrate Google Admob SDK to show Rewarded Video Ad in the Android app."
},
{
"code": null,
"e": 1131,
"s": 1115,
"text": "Rewarded Video:"
},
{
"code": null,
"e": 1412,
"s": 1131,
"text": " Rewarded Video ad is full-screen ads that cover the whole UI of the app. The eCPM (Effective Cost Per Mille) of Rewarded Video ads are relatively higher than banner and Interstitial ads and also leads to higher CTR(Click Through Rate) which results in more earning from your app."
},
{
"code": null,
"e": 1570,
"s": 1412,
"text": "The user gets an in-App reward when they watch the Rewarded Video from start to end. This type of ad is mostly used in games and also can be used in the app."
},
{
"code": null,
"e": 1779,
"s": 1570,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that choose Java as language though we are going to implement this project in Java language."
},
{
"code": null,
"e": 1857,
"s": 1779,
"text": "Go to app -> res -> values -> colors.xml file and set the colors for the app."
},
{
"code": null,
"e": 1868,
"s": 1857,
"text": "colors.xml"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"colorPrimary\">#0F9D58</color> <color name=\"colorPrimaryDark\">#0F9D58</color> <color name=\"colorAccent\">#05af9b</color></resources>",
"e": 2071,
"s": 1868,
"text": null
},
{
"code": null,
"e": 2210,
"s": 2071,
"text": "Go to Gradle Scripts -> build.gradle (Module: app) section and import following dependencies and click the “sync now” on the above pop up."
},
{
"code": null,
"e": 2275,
"s": 2210,
"text": "implementation ‘com.google.android.gms:play-services-ads:19.3.0’"
},
{
"code": null,
"e": 2363,
"s": 2275,
"text": "Go to app -> manifests -> AndroidManifests.xml section and allow “Internet Permission“."
},
{
"code": null,
"e": 2425,
"s": 2363,
"text": "<uses-permission android:name=”android.permission.INTERNET”/>"
},
{
"code": null,
"e": 2523,
"s": 2425,
"text": "Go to app->manifests->AndroidManifest.xml section and add meta-data tag inside <application> tag."
},
{
"code": null,
"e": 2534,
"s": 2523,
"text": "<meta-data"
},
{
"code": null,
"e": 2604,
"s": 2534,
"text": " android:name=”com.google.android.gms.ads.APPLICATION_ID” "
},
{
"code": null,
"e": 2672,
"s": 2604,
"text": " android:value=”ca-app-pub-3940256099942544~3347511713′′"
},
{
"code": null,
"e": 2675,
"s": 2672,
"text": "/>"
},
{
"code": null,
"e": 2801,
"s": 2675,
"text": "In the activity_main.xml add a Button so when the user will click the Button the Rewarded Video will be played on the screen."
},
{
"code": null,
"e": 2819,
"s": 2801,
"text": "activity_main.xml"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- Button to Show Rewarded Video Ad By Clicking it --> <Button android:id=\"@+id/showVideoBtn\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:layout_margin=\"8dp\" android:background=\"@color/colorPrimary\" android:padding=\"16dp\" android:text=\"Show Rewarded Video Ad \" android:textColor=\"#ffff\" android:textSize=\"20dp\" /> </RelativeLayout>",
"e": 3588,
"s": 2819,
"text": null
},
{
"code": null,
"e": 3697,
"s": 3588,
"text": "Open the MainActivity.java file there within the class, first of all, create the object of the Button class."
},
{
"code": null,
"e": 3734,
"s": 3697,
"text": "// Creating a object of Button class"
},
{
"code": null,
"e": 3757,
"s": 3734,
"text": "Button showVideoAdBtn;"
},
{
"code": null,
"e": 3878,
"s": 3757,
"text": "Now inside the onCreate() method, link those objects with their respective IDs that are given in activity_main.xml file."
},
{
"code": null,
"e": 3973,
"s": 3878,
"text": " // link those objects with their respective id’s that we have given in activity_main.xml file"
},
{
"code": null,
"e": 4030,
"s": 3973,
"text": " showVideoAdBtn=(Button)findViewById(R.id.showVideoBtn);"
},
{
"code": null,
"e": 4092,
"s": 4030,
"text": "Now inside onCreate() method, initialize the Google Admob SDK"
},
{
"code": null,
"e": 4131,
"s": 4092,
"text": " // initializing the Google Admob SDK"
},
{
"code": null,
"e": 4160,
"s": 4131,
"text": " MobileAds.initialize(this);"
},
{
"code": null,
"e": 4227,
"s": 4160,
"text": "Create an object of RewardedVideoAd inside MainActivity.java class"
},
{
"code": null,
"e": 4265,
"s": 4227,
"text": "// creating object of RewardedVideoAd"
},
{
"code": null,
"e": 4311,
"s": 4265,
"text": "private RewardedVideoAd AdMobrewardedVideoAd;"
},
{
"code": null,
"e": 4376,
"s": 4311,
"text": "Create AdMob Rewarded Video Ad Id inside MainActivity.java class"
},
{
"code": null,
"e": 4408,
"s": 4376,
"text": " // AdMob Rewarded Video Ad Id"
},
{
"code": null,
"e": 4473,
"s": 4408,
"text": " private String AdId=”ca-app-pub-3940256099942544/5224354917′′;"
},
{
"code": null,
"e": 4570,
"s": 4473,
"text": "Next create a private void loadRewardedVideoAd() method outside onCreate() method and define it."
},
{
"code": null,
"e": 4599,
"s": 4570,
"text": " void loadRewardedVideoAd()"
},
{
"code": null,
"e": 4604,
"s": 4599,
"text": " {"
},
{
"code": null,
"e": 4650,
"s": 4604,
"text": " // initializing RewardedVideoAd Object"
},
{
"code": null,
"e": 4718,
"s": 4650,
"text": " // RewardedVideoAd Constructor Takes Context as its Argument"
},
{
"code": null,
"e": 4790,
"s": 4718,
"text": " AdMobrewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);"
},
{
"code": null,
"e": 4824,
"s": 4790,
"text": " // Loading Rewarded Video Ad"
},
{
"code": null,
"e": 4897,
"s": 4824,
"text": " AdMobrewardedVideoAd.loadAd(AdId, new AdRequest.Builder().build());"
},
{
"code": null,
"e": 4899,
"s": 4897,
"text": "}"
},
{
"code": null,
"e": 4983,
"s": 4899,
"text": "Call the loadRewardedVideoAd() inside oncreate() method after initializing the SDK."
},
{
"code": null,
"e": 5046,
"s": 4983,
"text": "Note: Replace “AdId” with your own app ad id to show real ads."
},
{
"code": null,
"e": 5152,
"s": 5046,
"text": "Next create a void showRewardedVideoAd() method outside onCreate() method which we call later to show ad."
},
{
"code": null,
"e": 5188,
"s": 5152,
"text": " public void showRewardedVideoAd()"
},
{
"code": null,
"e": 5193,
"s": 5188,
"text": " {"
},
{
"code": null,
"e": 5269,
"s": 5193,
"text": " if(AdMobrewardedVideoAd.isLoaded())//Checking If Ad is Loaded or Not"
},
{
"code": null,
"e": 5278,
"s": 5269,
"text": " {"
},
{
"code": null,
"e": 5309,
"s": 5278,
"text": " // showing Video Ad"
},
{
"code": null,
"e": 5349,
"s": 5309,
"text": " AdMobrewardedVideoAd.show();"
},
{
"code": null,
"e": 5358,
"s": 5349,
"text": " }"
},
{
"code": null,
"e": 5370,
"s": 5358,
"text": " else"
},
{
"code": null,
"e": 5379,
"s": 5370,
"text": " {"
},
{
"code": null,
"e": 5419,
"s": 5379,
"text": " // Loading Rewarded Video Ad"
},
{
"code": null,
"e": 5498,
"s": 5419,
"text": " AdMobrewardedVideoAd.loadAd(AdId, new AdRequest.Builder().build());"
},
{
"code": null,
"e": 5507,
"s": 5498,
"text": " }"
},
{
"code": null,
"e": 5512,
"s": 5507,
"text": " }"
},
{
"code": null,
"e": 5670,
"s": 5512,
"text": "So the next thing is to call the showRewardedVideoAd() method. Now in oncreate() method create a ClickListener for the button and call showRewardedVideoAd()."
},
{
"code": null,
"e": 5715,
"s": 5670,
"text": "// click listener to show Rewarded Video Ad"
},
{
"code": null,
"e": 5778,
"s": 5715,
"text": "showVideoAdBtn.setOnClickListener(new View.OnClickListener() {"
},
{
"code": null,
"e": 5798,
"s": 5778,
"text": " @Override"
},
{
"code": null,
"e": 5841,
"s": 5798,
"text": " public void onClick(View view) {"
},
{
"code": null,
"e": 5878,
"s": 5841,
"text": " showRewardedVideoAd();"
},
{
"code": null,
"e": 5890,
"s": 5878,
"text": " }"
},
{
"code": null,
"e": 5895,
"s": 5890,
"text": " });"
},
{
"code": null,
"e": 5996,
"s": 5895,
"text": "Now add RewardedVideoAdListener for Rewarded Video Ad, so that user will know the status of the ads."
},
{
"code": null,
"e": 6159,
"s": 5996,
"text": "To add RewardedVideoAdListener open loadRewardedVideoAd() method and add the below code before AdMobrewardedVideoAd.loadAd(AdId, new AdRequest.Builder().build());"
},
{
"code": null,
"e": 6190,
"s": 6159,
"text": " // Rewarded Video Ad Listener"
},
{
"code": null,
"e": 6271,
"s": 6190,
"text": " AdMobrewardedVideoAd.setRewardedVideoAdListener(new RewardedVideoAdListener() {"
},
{
"code": null,
"e": 6292,
"s": 6271,
"text": " @Override"
},
{
"code": null,
"e": 6343,
"s": 6292,
"text": " public void onRewardedVideoAdLoaded() {"
},
{
"code": null,
"e": 6383,
"s": 6343,
"text": " // Showing Toast Message"
},
{
"code": null,
"e": 6486,
"s": 6383,
"text": " Toast.makeText(MainActivity.this, “onRewardedVideoAdLoaded”, Toast.LENGTH_SHORT).show();"
},
{
"code": null,
"e": 6499,
"s": 6486,
"text": " }"
},
{
"code": null,
"e": 6520,
"s": 6499,
"text": " @Override"
},
{
"code": null,
"e": 6571,
"s": 6520,
"text": " public void onRewardedVideoAdOpened() {"
},
{
"code": null,
"e": 6611,
"s": 6571,
"text": " // Showing Toast Message"
},
{
"code": null,
"e": 6714,
"s": 6611,
"text": " Toast.makeText(MainActivity.this, “onRewardedVideoAdOpened”, Toast.LENGTH_SHORT).show();"
},
{
"code": null,
"e": 6727,
"s": 6714,
"text": " }"
},
{
"code": null,
"e": 6748,
"s": 6727,
"text": " @Override"
},
{
"code": null,
"e": 6798,
"s": 6748,
"text": " public void onRewardedVideoStarted() {"
},
{
"code": null,
"e": 6837,
"s": 6798,
"text": " // Showing Toast Message"
},
{
"code": null,
"e": 6939,
"s": 6837,
"text": " Toast.makeText(MainActivity.this, “onRewardedVideoStarted”, Toast.LENGTH_SHORT).show();"
},
{
"code": null,
"e": 6952,
"s": 6939,
"text": " }"
},
{
"code": null,
"e": 6973,
"s": 6952,
"text": " @Override"
},
{
"code": null,
"e": 7024,
"s": 6973,
"text": " public void onRewardedVideoAdClosed() {"
},
{
"code": null,
"e": 7064,
"s": 7024,
"text": " // Showing Toast Message"
},
{
"code": null,
"e": 7168,
"s": 7064,
"text": " Toast.makeText(MainActivity.this, “onRewardedVideoAdClosed”, Toast.LENGTH_SHORT).show();"
},
{
"code": null,
"e": 7181,
"s": 7168,
"text": " }"
},
{
"code": null,
"e": 7202,
"s": 7181,
"text": " @Override"
},
{
"code": null,
"e": 7261,
"s": 7202,
"text": " public void onRewarded(RewardItem rewardItem) {"
},
{
"code": null,
"e": 7301,
"s": 7261,
"text": " // Showing Toast Message"
},
{
"code": null,
"e": 7392,
"s": 7301,
"text": " Toast.makeText(MainActivity.this, “onRewarded”, Toast.LENGTH_SHORT).show();"
},
{
"code": null,
"e": 7405,
"s": 7392,
"text": " }"
},
{
"code": null,
"e": 7426,
"s": 7405,
"text": " @Override"
},
{
"code": null,
"e": 7486,
"s": 7426,
"text": " public void onRewardedVideoAdLeftApplication() {"
},
{
"code": null,
"e": 7526,
"s": 7486,
"text": " // Showing Toast Message"
},
{
"code": null,
"e": 7639,
"s": 7526,
"text": " Toast.makeText(MainActivity.this, “onRewardedVideoAdLeftApplication”, Toast.LENGTH_SHORT).show();"
},
{
"code": null,
"e": 7652,
"s": 7639,
"text": " }"
},
{
"code": null,
"e": 7673,
"s": 7652,
"text": " @Override"
},
{
"code": null,
"e": 7735,
"s": 7673,
"text": " public void onRewardedVideoAdFailedToLoad(int i) {"
},
{
"code": null,
"e": 7775,
"s": 7735,
"text": " // Showing Toast Message"
},
{
"code": null,
"e": 7885,
"s": 7775,
"text": " Toast.makeText(MainActivity.this, “onRewardedVideoAdFailedToLoad”, Toast.LENGTH_SHORT).show();"
},
{
"code": null,
"e": 7898,
"s": 7885,
"text": " }"
},
{
"code": null,
"e": 7919,
"s": 7898,
"text": " @Override"
},
{
"code": null,
"e": 7971,
"s": 7919,
"text": " public void onRewardedVideoCompleted() {"
},
{
"code": null,
"e": 8011,
"s": 7971,
"text": " // Showing Toast Message"
},
{
"code": null,
"e": 8116,
"s": 8011,
"text": " Toast.makeText(MainActivity.this, “onRewardedVideoCompleted”, Toast.LENGTH_SHORT).show();"
},
{
"code": null,
"e": 8129,
"s": 8116,
"text": " }"
},
{
"code": null,
"e": 8133,
"s": 8129,
"text": "});"
},
{
"code": null,
"e": 8306,
"s": 8133,
"text": "And inside RewardedVideoAdListener Override methods show a toast message so that users know the status of the ad. Below is the complete code for the MainActivity.Java file."
},
{
"code": null,
"e": 8324,
"s": 8306,
"text": "MainActivity.Java"
},
{
"code": "package org.geeksforgeeks.project; import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import com.google.android.gms.ads.AdRequest;import com.google.android.gms.ads.MobileAds;import com.google.android.gms.ads.reward.RewardItem;import com.google.android.gms.ads.reward.RewardedVideoAd;import com.google.android.gms.ads.reward.RewardedVideoAdListener; public class MainActivity extends AppCompatActivity { // Creating a object of Button class Button showVideoAdBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // link those objects with their respective id's // that we have given in activity_main.xml file showVideoAdBtn = (Button)findViewById(R.id.showVideoBtn); // initializing the Google Admob SDK MobileAds.initialize(this); // loading Video Ad loadRewardedVideoAd(); // click listener to show Rewarded Video Ad showVideoAdBtn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { // showing Ad showRewardedVideoAd(); } }); } // creating RewardedVideoAd object private RewardedVideoAd AdMobrewardedVideoAd; // AdMob Rewarded Video Ad Id private String AdId = \"ca-app-pub-3940256099942544/5224354917\"; void loadRewardedVideoAd() { // initializing RewardedVideoAd Object // RewardedVideoAd Constructor Takes Context as its // Argument AdMobrewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this); // Rewarded Video Ad Listener AdMobrewardedVideoAd.setRewardedVideoAdListener( new RewardedVideoAdListener() { @Override public void onRewardedVideoAdLoaded() { // Showing Toast Message Toast .makeText(MainActivity.this, \"onRewardedVideoAdLoaded\", Toast.LENGTH_SHORT) .show(); } @Override public void onRewardedVideoAdOpened() { // Showing Toast Message Toast .makeText(MainActivity.this, \"onRewardedVideoAdOpened\", Toast.LENGTH_SHORT) .show(); } @Override public void onRewardedVideoStarted() { // Showing Toast Message Toast .makeText(MainActivity.this, \"onRewardedVideoStarted\", Toast.LENGTH_SHORT) .show(); } @Override public void onRewardedVideoAdClosed() { // Showing Toast Message Toast .makeText(MainActivity.this, \"onRewardedVideoAdClosed\", Toast.LENGTH_SHORT) .show(); } @Override public void onRewarded( RewardItem rewardItem) { // Showing Toast Message Toast .makeText(MainActivity.this, \"onRewarded\", Toast.LENGTH_SHORT) .show(); } @Override public void onRewardedVideoAdLeftApplication() { // Showing Toast Message Toast .makeText( MainActivity.this, \"onRewardedVideoAdLeftApplication\", Toast.LENGTH_SHORT) .show(); } @Override public void onRewardedVideoAdFailedToLoad( int i) { // Showing Toast Message Toast .makeText( MainActivity.this, \"onRewardedVideoAdFailedToLoad\", Toast.LENGTH_SHORT) .show(); } @Override public void onRewardedVideoCompleted() { // Showing Toast Message Toast .makeText( MainActivity.this, \"onRewardedVideoCompleted\", Toast.LENGTH_SHORT) .show(); } }); // Loading Rewarded Video Ad AdMobrewardedVideoAd.loadAd( AdId, new AdRequest.Builder().build()); } public void showRewardedVideoAd() { // Checking If Ad is Loaded or Not if (AdMobrewardedVideoAd.isLoaded()) { // showing Video Ad AdMobrewardedVideoAd.show(); } else { // Loading Rewarded Video Ad AdMobrewardedVideoAd.loadAd( AdId, new AdRequest.Builder().build()); } }}",
"e": 13991,
"s": 8324,
"text": null
},
{
"code": null,
"e": 14048,
"s": 13991,
"text": "Below is the complete code for AndroidManifest.xml file."
},
{
"code": null,
"e": 14068,
"s": 14048,
"text": "AndroidManifest.xml"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"org.geeksforgeeks.project\"> <uses-permission android:name=\"android.permission.INTERNET\"/> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> <!-- meta data tag for admob Note:replace below app id value to your own app id --> <meta-data android:name=\"com.google.android.gms.ads.APPLICATION_ID\" android:value=\"ca-app-pub-3940256099942544~3347511713\"/> </application> </manifest>",
"e": 15112,
"s": 14068,
"text": null
},
{
"code": null,
"e": 15120,
"s": 15112,
"text": "android"
},
{
"code": null,
"e": 15128,
"s": 15120,
"text": "Android"
},
{
"code": null,
"e": 15133,
"s": 15128,
"text": "Java"
},
{
"code": null,
"e": 15138,
"s": 15133,
"text": "Java"
},
{
"code": null,
"e": 15146,
"s": 15138,
"text": "Android"
},
{
"code": null,
"e": 15244,
"s": 15146,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15313,
"s": 15244,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 15344,
"s": 15313,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 15376,
"s": 15344,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 15425,
"s": 15376,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 15468,
"s": 15425,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 15483,
"s": 15468,
"text": "Arrays in Java"
},
{
"code": null,
"e": 15527,
"s": 15483,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 15563,
"s": 15527,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 15614,
"s": 15563,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Kotlin | apply vs with
|
09 Aug, 2019
In Kotlin, apply is an extension function on a particular type and sets its scope to object on which apply is invoked. Apply runs on the object reference into the expression and also returns the object reference on completion. It does not simply setting properties of course but do much more functionalities and capable of evaluating complex logic before returning. In the end, it returns the same object, with some modified changes.
apply is an extension function on a type.
It requires an object reference to run into an expression.
It also return an object reference on completion.
Definition of apply :
inline fun T.apply(block: T.() -> Unit): T
{
block()
return this
}
Example of apply
fun main(args: Array<String>){ data class GFG(var name1 : String, var name2 : String,var name3 : String) // instantiating object of class var gfg = GFG("Geeks","for","hi") // apply function invoked to change the name3 value gfg.apply { this.name3 = "Geeks" } println(gfg)}
Output :
GFG(name1=Geeks, name2=for, name3=Geeks)
Here the 3rd member of class GFG is changed from “hi” to “Geeks”.
Like apply, with is also used to change properties of an instance. But here we don’t require a object reference to run, i.e. : we don’t need a dot operator for reference.
Definition of with
inline fun with(receiver: T, block: T.() -> R): R
{
return receiver.block()
}
Example of with
fun main(args: Array<String>){ data class GFG(var name1: String, var name2 : String,var name3 : String) var gfg = GFG("hello", "for","hi") // applying with function with(gfg) { name1 = "Geeks" name3 = "Geeks" } println(gfg)}
Output :
GFG(name1=Geeks, name2=for, name3=Geeks)
Here we don’t require any dot operator, and we changed the values of first and third variables of an object of class GFG using with extension function.
with runs without an object whereas apply needs one object to run
apply runs on the object reference, but with simply passes it as the argument
Picked
Kotlin
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?
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
Suspend Function In Kotlin Coroutines
How to Get Current Location in Android?
Kotlin extension function
Dagger Hilt in Android with Example
Scopes in Kotlin Coroutines
Kotlin Sealed Classes
Singleton Class in Kotlin
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Aug, 2019"
},
{
"code": null,
"e": 462,
"s": 28,
"text": "In Kotlin, apply is an extension function on a particular type and sets its scope to object on which apply is invoked. Apply runs on the object reference into the expression and also returns the object reference on completion. It does not simply setting properties of course but do much more functionalities and capable of evaluating complex logic before returning. In the end, it returns the same object, with some modified changes."
},
{
"code": null,
"e": 504,
"s": 462,
"text": "apply is an extension function on a type."
},
{
"code": null,
"e": 563,
"s": 504,
"text": "It requires an object reference to run into an expression."
},
{
"code": null,
"e": 613,
"s": 563,
"text": "It also return an object reference on completion."
},
{
"code": null,
"e": 635,
"s": 613,
"text": "Definition of apply :"
},
{
"code": null,
"e": 713,
"s": 635,
"text": "inline fun T.apply(block: T.() -> Unit): T \n{\n block()\n return this\n}\n"
},
{
"code": null,
"e": 730,
"s": 713,
"text": "Example of apply"
},
{
"code": "fun main(args: Array<String>){ data class GFG(var name1 : String, var name2 : String,var name3 : String) // instantiating object of class var gfg = GFG(\"Geeks\",\"for\",\"hi\") // apply function invoked to change the name3 value gfg.apply { this.name3 = \"Geeks\" } println(gfg)}",
"e": 1021,
"s": 730,
"text": null
},
{
"code": null,
"e": 1030,
"s": 1021,
"text": "Output :"
},
{
"code": null,
"e": 1072,
"s": 1030,
"text": "GFG(name1=Geeks, name2=for, name3=Geeks)\n"
},
{
"code": null,
"e": 1138,
"s": 1072,
"text": "Here the 3rd member of class GFG is changed from “hi” to “Geeks”."
},
{
"code": null,
"e": 1309,
"s": 1138,
"text": "Like apply, with is also used to change properties of an instance. But here we don’t require a object reference to run, i.e. : we don’t need a dot operator for reference."
},
{
"code": null,
"e": 1328,
"s": 1309,
"text": "Definition of with"
},
{
"code": null,
"e": 1413,
"s": 1328,
"text": "inline fun with(receiver: T, block: T.() -> R): R \n{\n return receiver.block()\n}\n"
},
{
"code": null,
"e": 1429,
"s": 1413,
"text": "Example of with"
},
{
"code": "fun main(args: Array<String>){ data class GFG(var name1: String, var name2 : String,var name3 : String) var gfg = GFG(\"hello\", \"for\",\"hi\") // applying with function with(gfg) { name1 = \"Geeks\" name3 = \"Geeks\" } println(gfg)}",
"e": 1689,
"s": 1429,
"text": null
},
{
"code": null,
"e": 1698,
"s": 1689,
"text": "Output :"
},
{
"code": null,
"e": 1740,
"s": 1698,
"text": "GFG(name1=Geeks, name2=for, name3=Geeks)\n"
},
{
"code": null,
"e": 1892,
"s": 1740,
"text": "Here we don’t require any dot operator, and we changed the values of first and third variables of an object of class GFG using with extension function."
},
{
"code": null,
"e": 1958,
"s": 1892,
"text": "with runs without an object whereas apply needs one object to run"
},
{
"code": null,
"e": 2036,
"s": 1958,
"text": "apply runs on the object reference, but with simply passes it as the argument"
},
{
"code": null,
"e": 2043,
"s": 2036,
"text": "Picked"
},
{
"code": null,
"e": 2050,
"s": 2043,
"text": "Kotlin"
},
{
"code": null,
"e": 2148,
"s": 2050,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2217,
"s": 2148,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 2266,
"s": 2217,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 2308,
"s": 2266,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 2346,
"s": 2308,
"text": "Suspend Function In Kotlin Coroutines"
},
{
"code": null,
"e": 2386,
"s": 2346,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 2412,
"s": 2386,
"text": "Kotlin extension function"
},
{
"code": null,
"e": 2448,
"s": 2412,
"text": "Dagger Hilt in Android with Example"
},
{
"code": null,
"e": 2476,
"s": 2448,
"text": "Scopes in Kotlin Coroutines"
},
{
"code": null,
"e": 2498,
"s": 2476,
"text": "Kotlin Sealed Classes"
}
] |
Program for Employee Management System
|
06 Sep, 2021
A Employee’s Management System (EMS) is a software built to handle the primary housekeeping functions of a company. EMS help companies keep track of all the employees and their records. It is used to manage the company using computerized system.
Aim of Employee’s Management System:
Built The Employee Table.
Insert New Entries.
Delete The Entries.
Search A Record.
Data of the Employee’s:
Name
Employee ID
Designation
Experience
Age
Approach:
For storing the data of the employee, create a user define datatype which will store the information regarding Employee. Below is the declaration of the data type:struct employee {
string name;
long int code;
string designation;
int exp;
int age;
};
Building the Employee's table: For building the employee table the idea is to use the array of the above struct datatype which will use to store the information regarding employee. For storing information at index i the data is stored as:
struct employee emp[10];
emp[i].name = "GeeksforGeeks"
emp[i].code = "12345"
emp[i].designation = "Organisation"
emp[i].exp = 10
emp[i].age = 10
Deleting in the record: Since we are using array to store the data, therefore to delete the data at any index shift all the data at that index by 1 and delete the last data of the array by decreasing the size of array by 1.Searching in the record: For searching in the record based on any parameter, the idea is to traverse the data and if at any index the value parameters matches with the record stored, print all the information of that employee.
For storing the data of the employee, create a user define datatype which will store the information regarding Employee. Below is the declaration of the data type:struct employee {
string name;
long int code;
string designation;
int exp;
int age;
};
struct employee {
string name;
long int code;
string designation;
int exp;
int age;
};
Building the Employee's table: For building the employee table the idea is to use the array of the above struct datatype which will use to store the information regarding employee. For storing information at index i the data is stored as:
struct employee emp[10];
emp[i].name = "GeeksforGeeks"
emp[i].code = "12345"
emp[i].designation = "Organisation"
emp[i].exp = 10
emp[i].age = 10
struct employee emp[10];
emp[i].name = "GeeksforGeeks"
emp[i].code = "12345"
emp[i].designation = "Organisation"
emp[i].exp = 10
emp[i].age = 10
Deleting in the record: Since we are using array to store the data, therefore to delete the data at any index shift all the data at that index by 1 and delete the last data of the array by decreasing the size of array by 1.
Searching in the record: For searching in the record based on any parameter, the idea is to traverse the data and if at any index the value parameters matches with the record stored, print all the information of that employee.
Below is the implementation of Employee Management system in C:
C++
// C++ program for the above approach#include <bits/stdc++.h> #define max 20using namespace std; // Structure of Employeestruct employee { string name; long int code; string designation; int exp; int age;}; int num;void showMenu(); // Array of Employees to store the// data in the form of the Structure// of the Arrayemployee emp[max], tempemp[max], sortemp[max], sortemp1[max]; // Function to build the given datatypevoid build(){ cout << "Build The Table\n"; cout << "Maximum Entries can be " << max << "\n"; cout << "Enter the number of " << "Entries required"; cin >> num; if (num > 20) { cout << "Maximum number of " << "Entries are 20\n"; num = 20; } cout << "Enter the following data:\n"; for (int i = 0; i < num; i++) { cout << "Name "; cin >> emp[i].name; cout << "Employee ID "; cin >> emp[i].code; cout << "Designation "; cin >> emp[i].designation; cout << "Experience "; cin >> emp[i].exp; cout << "Age "; cin >> emp[i].age; } showMenu();} // Function to insert the data into// given data typevoid insert(){ if (num < max) { int i = num; num++; cout << "Enter the information " << "of the Employee\n"; cout << "Name "; cin >> emp[i].name; cout << "Employee ID "; cin >> emp[i].code; cout << "Designation "; cin >> emp[i].designation; cout << "Experience "; cin >> emp[i].exp; cout << "Age "; cin >> emp[i].age; } else { cout << "Employee Table Full\n"; } showMenu();} // Function to delete record at index ivoid deleteIndex(int i){ for (int j = i; j < num - 1; j++) { emp[j].name = emp[j + 1].name; emp[j].code = emp[j + 1].code; emp[j].designation = emp[j + 1].designation; emp[j].exp = emp[j + 1].exp; emp[j].age = emp[j + 1].age; } return;} // Function to delete recordvoid deleteRecord(){ cout << "Enter the Employee ID " << "to Delete Record"; int code; cin >> code; for (int i = 0; i < num; i++) { if (emp[i].code == code) { deleteIndex(i); num--; break; } } showMenu();} void searchRecord(){ cout << "Enter the Employee" << " ID to Search Record"; int code; cin >> code; for (int i = 0; i < num; i++) { // If the data is found if (emp[i].code == code) { cout << "Name " << emp[i].name << "\n"; cout << "Employee ID " << emp[i].code << "\n"; cout << "Designation " << emp[i].designation << "\n"; cout << "Experience " << emp[i].exp << "\n"; cout << "Age " << emp[i].age << "\n"; break; } } showMenu();} // Function to show menuvoid showMenu(){ cout << "-------------------------" << "GeeksforGeeks Employee" << " Management System" << "-------------------------\n\n"; cout << "Available Options:\n\n"; cout << "Build Table (1)\n"; cout << "Insert New Entry (2)\n"; cout << "Delete Entry (3)\n"; cout << "Search a Record (4)\n"; cout << "Exit (5)\n"; int option; // Input Options cin >> option; // Call function on the bases of the // above option if (option == 1) { build(); } else if (option == 2) { insert(); } else if (option == 3) { deleteRecord(); } else if (option == 4) { searchRecord(); } else if (option == 5) { return; } else { cout << "Expected Options" << " are 1/2/3/4/5"; showMenu(); }} // Driver Codeint main(){ showMenu(); return 0;}
akshaysingh98088
khushboogoyal499
Arrays
Project
School Programming
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Python | Using 2D arrays/lists the right way
SDE SHEET - A Complete Guide for SDE Preparation
Morse Code Translator In Python
Working with Images in Python
Simple Chat Room using Python
Working with zip files in Python
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 300,
"s": 54,
"text": "A Employee’s Management System (EMS) is a software built to handle the primary housekeeping functions of a company. EMS help companies keep track of all the employees and their records. It is used to manage the company using computerized system."
},
{
"code": null,
"e": 338,
"s": 300,
"text": "Aim of Employee’s Management System: "
},
{
"code": null,
"e": 364,
"s": 338,
"text": "Built The Employee Table."
},
{
"code": null,
"e": 384,
"s": 364,
"text": "Insert New Entries."
},
{
"code": null,
"e": 404,
"s": 384,
"text": "Delete The Entries."
},
{
"code": null,
"e": 421,
"s": 404,
"text": "Search A Record."
},
{
"code": null,
"e": 445,
"s": 421,
"text": "Data of the Employee’s:"
},
{
"code": null,
"e": 451,
"s": 445,
"text": "Name "
},
{
"code": null,
"e": 463,
"s": 451,
"text": "Employee ID"
},
{
"code": null,
"e": 475,
"s": 463,
"text": "Designation"
},
{
"code": null,
"e": 486,
"s": 475,
"text": "Experience"
},
{
"code": null,
"e": 490,
"s": 486,
"text": "Age"
},
{
"code": null,
"e": 500,
"s": 490,
"text": "Approach:"
},
{
"code": null,
"e": 1595,
"s": 500,
"text": "For storing the data of the employee, create a user define datatype which will store the information regarding Employee. Below is the declaration of the data type:struct employee {\n string name;\n long int code;\n string designation;\n int exp;\n int age;\n};\n\nBuilding the Employee's table: For building the employee table the idea is to use the array of the above struct datatype which will use to store the information regarding employee. For storing information at index i the data is stored as:\nstruct employee emp[10];\nemp[i].name = \"GeeksforGeeks\"\nemp[i].code = \"12345\"\nemp[i].designation = \"Organisation\"\nemp[i].exp = 10\nemp[i].age = 10\nDeleting in the record: Since we are using array to store the data, therefore to delete the data at any index shift all the data at that index by 1 and delete the last data of the array by decreasing the size of array by 1.Searching in the record: For searching in the record based on any parameter, the idea is to traverse the data and if at any index the value parameters matches with the record stored, print all the information of that employee."
},
{
"code": null,
"e": 1857,
"s": 1595,
"text": "For storing the data of the employee, create a user define datatype which will store the information regarding Employee. Below is the declaration of the data type:struct employee {\n string name;\n long int code;\n string designation;\n int exp;\n int age;\n};\n\n"
},
{
"code": null,
"e": 1955,
"s": 1857,
"text": "struct employee {\n string name;\n long int code;\n string designation;\n int exp;\n int age;\n};\n"
},
{
"code": null,
"e": 2340,
"s": 1955,
"text": "Building the Employee's table: For building the employee table the idea is to use the array of the above struct datatype which will use to store the information regarding employee. For storing information at index i the data is stored as:\nstruct employee emp[10];\nemp[i].name = \"GeeksforGeeks\"\nemp[i].code = \"12345\"\nemp[i].designation = \"Organisation\"\nemp[i].exp = 10\nemp[i].age = 10\n"
},
{
"code": null,
"e": 2486,
"s": 2340,
"text": "struct employee emp[10];\nemp[i].name = \"GeeksforGeeks\"\nemp[i].code = \"12345\"\nemp[i].designation = \"Organisation\"\nemp[i].exp = 10\nemp[i].age = 10\n"
},
{
"code": null,
"e": 2710,
"s": 2486,
"text": "Deleting in the record: Since we are using array to store the data, therefore to delete the data at any index shift all the data at that index by 1 and delete the last data of the array by decreasing the size of array by 1."
},
{
"code": null,
"e": 2937,
"s": 2710,
"text": "Searching in the record: For searching in the record based on any parameter, the idea is to traverse the data and if at any index the value parameters matches with the record stored, print all the information of that employee."
},
{
"code": null,
"e": 3001,
"s": 2937,
"text": "Below is the implementation of Employee Management system in C:"
},
{
"code": null,
"e": 3005,
"s": 3001,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h> #define max 20using namespace std; // Structure of Employeestruct employee { string name; long int code; string designation; int exp; int age;}; int num;void showMenu(); // Array of Employees to store the// data in the form of the Structure// of the Arrayemployee emp[max], tempemp[max], sortemp[max], sortemp1[max]; // Function to build the given datatypevoid build(){ cout << \"Build The Table\\n\"; cout << \"Maximum Entries can be \" << max << \"\\n\"; cout << \"Enter the number of \" << \"Entries required\"; cin >> num; if (num > 20) { cout << \"Maximum number of \" << \"Entries are 20\\n\"; num = 20; } cout << \"Enter the following data:\\n\"; for (int i = 0; i < num; i++) { cout << \"Name \"; cin >> emp[i].name; cout << \"Employee ID \"; cin >> emp[i].code; cout << \"Designation \"; cin >> emp[i].designation; cout << \"Experience \"; cin >> emp[i].exp; cout << \"Age \"; cin >> emp[i].age; } showMenu();} // Function to insert the data into// given data typevoid insert(){ if (num < max) { int i = num; num++; cout << \"Enter the information \" << \"of the Employee\\n\"; cout << \"Name \"; cin >> emp[i].name; cout << \"Employee ID \"; cin >> emp[i].code; cout << \"Designation \"; cin >> emp[i].designation; cout << \"Experience \"; cin >> emp[i].exp; cout << \"Age \"; cin >> emp[i].age; } else { cout << \"Employee Table Full\\n\"; } showMenu();} // Function to delete record at index ivoid deleteIndex(int i){ for (int j = i; j < num - 1; j++) { emp[j].name = emp[j + 1].name; emp[j].code = emp[j + 1].code; emp[j].designation = emp[j + 1].designation; emp[j].exp = emp[j + 1].exp; emp[j].age = emp[j + 1].age; } return;} // Function to delete recordvoid deleteRecord(){ cout << \"Enter the Employee ID \" << \"to Delete Record\"; int code; cin >> code; for (int i = 0; i < num; i++) { if (emp[i].code == code) { deleteIndex(i); num--; break; } } showMenu();} void searchRecord(){ cout << \"Enter the Employee\" << \" ID to Search Record\"; int code; cin >> code; for (int i = 0; i < num; i++) { // If the data is found if (emp[i].code == code) { cout << \"Name \" << emp[i].name << \"\\n\"; cout << \"Employee ID \" << emp[i].code << \"\\n\"; cout << \"Designation \" << emp[i].designation << \"\\n\"; cout << \"Experience \" << emp[i].exp << \"\\n\"; cout << \"Age \" << emp[i].age << \"\\n\"; break; } } showMenu();} // Function to show menuvoid showMenu(){ cout << \"-------------------------\" << \"GeeksforGeeks Employee\" << \" Management System\" << \"-------------------------\\n\\n\"; cout << \"Available Options:\\n\\n\"; cout << \"Build Table (1)\\n\"; cout << \"Insert New Entry (2)\\n\"; cout << \"Delete Entry (3)\\n\"; cout << \"Search a Record (4)\\n\"; cout << \"Exit (5)\\n\"; int option; // Input Options cin >> option; // Call function on the bases of the // above option if (option == 1) { build(); } else if (option == 2) { insert(); } else if (option == 3) { deleteRecord(); } else if (option == 4) { searchRecord(); } else if (option == 5) { return; } else { cout << \"Expected Options\" << \" are 1/2/3/4/5\"; showMenu(); }} // Driver Codeint main(){ showMenu(); return 0;}",
"e": 6950,
"s": 3005,
"text": null
},
{
"code": null,
"e": 6967,
"s": 6950,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 6984,
"s": 6967,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 6991,
"s": 6984,
"text": "Arrays"
},
{
"code": null,
"e": 6999,
"s": 6991,
"text": "Project"
},
{
"code": null,
"e": 7018,
"s": 6999,
"text": "School Programming"
},
{
"code": null,
"e": 7025,
"s": 7018,
"text": "Arrays"
},
{
"code": null,
"e": 7123,
"s": 7025,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7191,
"s": 7123,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 7223,
"s": 7191,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 7246,
"s": 7223,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 7260,
"s": 7246,
"text": "Linear Search"
},
{
"code": null,
"e": 7305,
"s": 7260,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 7354,
"s": 7305,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 7386,
"s": 7354,
"text": "Morse Code Translator In Python"
},
{
"code": null,
"e": 7416,
"s": 7386,
"text": "Working with Images in Python"
},
{
"code": null,
"e": 7446,
"s": 7416,
"text": "Simple Chat Room using Python"
}
] |
Sum of series 2/3 – 4/5 + 6/7 – 8/9 + ——- upto n terms
|
25 May, 2022
Given the value of n, find the sum of the series (2 / 3) – (4 / 5) + (6 / 7) – (8 / 9) + – – – – – – – upto n terms.Examples :
Input : n = 5
Output : 0.744012
Series : (2 / 3) - (4 / 5) + (6 / 7) - (8 / 9) + (10 / 11)
Input : n = 7
Output : 0.754268
Series : (2 / 3) - (4 / 5) + (6 / 7) - (8 / 9) +
(10 / 11) - (12 / 13) + (14 / 15)
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find// sum of given series#include <bits/stdc++.h>using namespace std; // Function to find sum of series// up-to n termsdouble seriesSum(int n){ // initializing counter by 1 int i = 1; // variable to calculate result double res = 0.0; bool sign = true; // while loop until nth term // is not reached while (n > 0) { n--; // boolean type variable // for checking validation if (sign) { sign = !sign; res = res + (double)++i / ++i; } else { sign = !sign; res = res - (double)++i / ++i; } } return res;} // Driver Codeint main(){ int n = 5; cout << seriesSum(n); return 0;}
// Java program to find// sum of given seriesimport java.io.*; class GFG { // Function to find sum of series // up-to n terms static double seriesSum(int n) { // initializing counter by 1 int i = 1; // variable to calculate result double res = 0.0; boolean sign = true; // while loop until nth term // is not reached while (n > 0) { n--; // boolean type variable // for checking validation if (sign) { sign = !sign; res = res + (double)++i / ++i; } else { sign = !sign; res = res - (double)++i / ++i; } } return res;} // Driver Code public static void main (String[] args) { int n = 5; System.out.print(seriesSum(n)); }} // This code is contributed by vt_m
# Python3 program to find# sum of given series # Function to find# sum of series# up-to n termsdef seriesSum(n): # initializing # counter by 1 i = 1; # variable to # calculate result res = 0.0; sign = True; # while loop until nth # term is not reached while (n > 0): n = n - 1; # boolean type variable # for checking validation if (sign): sign = False; res = res + (i + 1) / (i + 2); i = i + 2; else: sign = True; res = res - (i + 1) / (i + 2); i = i + 2; return res; # Driver Coden = 5;print(round(seriesSum(n), 6)); # This code is contributed# by mits
// C# program to find// sum of given seriesusing System; class GFG { // Function to find sum of // series up-to n terms static double seriesSum(int n) { // initializing counter by 1 int i = 1; // variable to calculate result double res = 0.0; bool sign = true; // while loop until nth term // is not reached while (n > 0) { n--; // boolean type variable // for checking validation if (sign) { sign = !sign; res = res + (double)++i / ++i; } else { sign = !sign; res = res - (double)++i / ++i; } } return res;} // Driver Code public static void Main () { int n = 5; Console.Write(seriesSum(n)); }} // This code is contributed by vt_m
<?php// PHP program to find// sum of given series // Function to find sum of series// up-to n termsfunction seriesSum($n){ // initializing counter by 1 $i = 1; // variable to calculate result $res = 0.0; $sign = true; // while loop until nth term // is not reached while ($n > 0) { $n--; // boolean type variable // for checking validation if ($sign) { $sign = !$sign; $res = $res + (double)++$i / ++$i; } else { $sign = !$sign; $res = $res - (double)++$i / ++$i; } } return $res;} // Driver Code$n = 5;echo(seriesSum($n)); // This code is contributed by Ajit.?>
<script> // javascript program to find// sum of given series // Function to find sum of series// up-to n termsfunction seriesSum( n){ // initializing counter by 1 let i = 1; // variable to calculate result let res = 0.0; let sign = true; // while loop until nth term // is not reached while (n > 0) { n--; // boolean type variable // for checking validation if (sign) { sign = !sign; res = res + ++i / ++i; } else { sign = !sign; res = res - ++i / ++i; } } return res;}// Driver Codelet n = 5 ; document.write(seriesSum(n).toFixed(6)) ; // This code contributed by aashish1995 </script>
Output :
0.744012
Time Complexity: O(n), where n represents the given integer.Auxiliary Space: O(1), no extra space is required, so it is a constant.
jit_t
Mithun Kumar
aashish1995
tamanna17122007
series
series-sum
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Find next greater number with same set of digits
Segment Tree | Set 1 (Sum of given range)
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 May, 2022"
},
{
"code": null,
"e": 157,
"s": 28,
"text": "Given the value of n, find the sum of the series (2 / 3) – (4 / 5) + (6 / 7) – (8 / 9) + – – – – – – – upto n terms.Examples : "
},
{
"code": null,
"e": 373,
"s": 157,
"text": "Input : n = 5\nOutput : 0.744012\nSeries : (2 / 3) - (4 / 5) + (6 / 7) - (8 / 9) + (10 / 11)\n\nInput : n = 7\nOutput : 0.754268\nSeries : (2 / 3) - (4 / 5) + (6 / 7) - (8 / 9) +\n (10 / 11) - (12 / 13) + (14 / 15)"
},
{
"code": null,
"e": 381,
"s": 377,
"text": "C++"
},
{
"code": null,
"e": 386,
"s": 381,
"text": "Java"
},
{
"code": null,
"e": 394,
"s": 386,
"text": "Python3"
},
{
"code": null,
"e": 397,
"s": 394,
"text": "C#"
},
{
"code": null,
"e": 401,
"s": 397,
"text": "PHP"
},
{
"code": null,
"e": 412,
"s": 401,
"text": "Javascript"
},
{
"code": "// C++ program to find// sum of given series#include <bits/stdc++.h>using namespace std; // Function to find sum of series// up-to n termsdouble seriesSum(int n){ // initializing counter by 1 int i = 1; // variable to calculate result double res = 0.0; bool sign = true; // while loop until nth term // is not reached while (n > 0) { n--; // boolean type variable // for checking validation if (sign) { sign = !sign; res = res + (double)++i / ++i; } else { sign = !sign; res = res - (double)++i / ++i; } } return res;} // Driver Codeint main(){ int n = 5; cout << seriesSum(n); return 0;}",
"e": 1163,
"s": 412,
"text": null
},
{
"code": "// Java program to find// sum of given seriesimport java.io.*; class GFG { // Function to find sum of series // up-to n terms static double seriesSum(int n) { // initializing counter by 1 int i = 1; // variable to calculate result double res = 0.0; boolean sign = true; // while loop until nth term // is not reached while (n > 0) { n--; // boolean type variable // for checking validation if (sign) { sign = !sign; res = res + (double)++i / ++i; } else { sign = !sign; res = res - (double)++i / ++i; } } return res;} // Driver Code public static void main (String[] args) { int n = 5; System.out.print(seriesSum(n)); }} // This code is contributed by vt_m",
"e": 2061,
"s": 1163,
"text": null
},
{
"code": "# Python3 program to find# sum of given series # Function to find# sum of series# up-to n termsdef seriesSum(n): # initializing # counter by 1 i = 1; # variable to # calculate result res = 0.0; sign = True; # while loop until nth # term is not reached while (n > 0): n = n - 1; # boolean type variable # for checking validation if (sign): sign = False; res = res + (i + 1) / (i + 2); i = i + 2; else: sign = True; res = res - (i + 1) / (i + 2); i = i + 2; return res; # Driver Coden = 5;print(round(seriesSum(n), 6)); # This code is contributed# by mits",
"e": 2778,
"s": 2061,
"text": null
},
{
"code": "// C# program to find// sum of given seriesusing System; class GFG { // Function to find sum of // series up-to n terms static double seriesSum(int n) { // initializing counter by 1 int i = 1; // variable to calculate result double res = 0.0; bool sign = true; // while loop until nth term // is not reached while (n > 0) { n--; // boolean type variable // for checking validation if (sign) { sign = !sign; res = res + (double)++i / ++i; } else { sign = !sign; res = res - (double)++i / ++i; } } return res;} // Driver Code public static void Main () { int n = 5; Console.Write(seriesSum(n)); }} // This code is contributed by vt_m",
"e": 3642,
"s": 2778,
"text": null
},
{
"code": "<?php// PHP program to find// sum of given series // Function to find sum of series// up-to n termsfunction seriesSum($n){ // initializing counter by 1 $i = 1; // variable to calculate result $res = 0.0; $sign = true; // while loop until nth term // is not reached while ($n > 0) { $n--; // boolean type variable // for checking validation if ($sign) { $sign = !$sign; $res = $res + (double)++$i / ++$i; } else { $sign = !$sign; $res = $res - (double)++$i / ++$i; } } return $res;} // Driver Code$n = 5;echo(seriesSum($n)); // This code is contributed by Ajit.?>",
"e": 4355,
"s": 3642,
"text": null
},
{
"code": "<script> // javascript program to find// sum of given series // Function to find sum of series// up-to n termsfunction seriesSum( n){ // initializing counter by 1 let i = 1; // variable to calculate result let res = 0.0; let sign = true; // while loop until nth term // is not reached while (n > 0) { n--; // boolean type variable // for checking validation if (sign) { sign = !sign; res = res + ++i / ++i; } else { sign = !sign; res = res - ++i / ++i; } } return res;}// Driver Codelet n = 5 ; document.write(seriesSum(n).toFixed(6)) ; // This code contributed by aashish1995 </script>",
"e": 5097,
"s": 4355,
"text": null
},
{
"code": null,
"e": 5107,
"s": 5097,
"text": "Output : "
},
{
"code": null,
"e": 5116,
"s": 5107,
"text": "0.744012"
},
{
"code": null,
"e": 5248,
"s": 5116,
"text": "Time Complexity: O(n), where n represents the given integer.Auxiliary Space: O(1), no extra space is required, so it is a constant."
},
{
"code": null,
"e": 5254,
"s": 5248,
"text": "jit_t"
},
{
"code": null,
"e": 5267,
"s": 5254,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 5279,
"s": 5267,
"text": "aashish1995"
},
{
"code": null,
"e": 5295,
"s": 5279,
"text": "tamanna17122007"
},
{
"code": null,
"e": 5302,
"s": 5295,
"text": "series"
},
{
"code": null,
"e": 5313,
"s": 5302,
"text": "series-sum"
},
{
"code": null,
"e": 5326,
"s": 5313,
"text": "Mathematical"
},
{
"code": null,
"e": 5345,
"s": 5326,
"text": "School Programming"
},
{
"code": null,
"e": 5358,
"s": 5345,
"text": "Mathematical"
},
{
"code": null,
"e": 5365,
"s": 5358,
"text": "series"
},
{
"code": null,
"e": 5463,
"s": 5365,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5495,
"s": 5463,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 5541,
"s": 5495,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 5585,
"s": 5541,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 5634,
"s": 5585,
"text": "Find next greater number with same set of digits"
},
{
"code": null,
"e": 5676,
"s": 5634,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 5694,
"s": 5676,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5719,
"s": 5694,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5735,
"s": 5719,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 5758,
"s": 5735,
"text": "Introduction To PYTHON"
}
] |
Python program to find the gcd of two numbers
|
26 Nov, 2020
Given two numbers. The task is to find the GCD of the two numbers.
Using STL :
In Python, the math module contains a number of mathematical operations, which can be performed with ease using the module. math.gcd() function compute the greatest common divisor of 2 numbers mentioned in its arguments.
Syntax: math.gcd(x, y)
Parameter:
x : Non-negative integer whose gcd has to be computed.
y : Non-negative integer whose gcd has to be computed.
Returns: An absolute/positive integer value after calculating the GCD of given parameters x and y.
Exceptions: When Both x and y are 0, function returns 0, If any number is a character, Type error is raised.
Python3
# Python code to demonstrate the working of gcd()# importing "math" for mathematical operationsimport math # prints 12print("The gcd of 60 and 48 is : ", end="")print(math.gcd(60, 48))
The gcd of 60 and 48 is : 12
Using Recursion :
Python3
# Python code to demonstrate naive# method to compute gcd ( recursion ) def hcf(a, b): if(b == 0): return a else: return hcf(b, a % b) a = 60b = 48 # prints 12print("The gcd of 60 and 48 is : ", end="")print(hcf(60, 48))
The gcd of 60 and 48 is : 12
Using Euclidean Algorithm :
The Euclid’s algorithm (or Euclidean Algorithm) is a method for efficiently finding the greatest common divisor (GCD) of two numbers. The GCD of two integers X and Y is the largest number that divides both of X and Y (without leaving a remainder).
Pseudo Code of the Algorithm-
Let a, b be the two numbersa mod b = RLet a = b and b = RRepeat Steps 2 and 3 until a mod b is greater than 0GCD = b Finish
Let a, b be the two numbers
a mod b = R
Let a = b and b = R
Repeat Steps 2 and 3 until a mod b is greater than 0
GCD = b
Finish
Python3
# Recursive function to return gcd of a and bdef gcd(a, b): # Everything divides 0 if (a == 0): return b if (b == 0): return a # base case if (a == b): return a # a is greater if (a > b): return gcd(a-b, b) return gcd(a, b-a) # Driver program to test above functiona = 98b = 56if(gcd(a, b)): print('GCD of', a, 'and', b, 'is', gcd(a, b))else: print('not found')
GCD of 98 and 56 is 14
GCD-LCM
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 119,
"s": 52,
"text": "Given two numbers. The task is to find the GCD of the two numbers."
},
{
"code": null,
"e": 131,
"s": 119,
"text": "Using STL :"
},
{
"code": null,
"e": 352,
"s": 131,
"text": "In Python, the math module contains a number of mathematical operations, which can be performed with ease using the module. math.gcd() function compute the greatest common divisor of 2 numbers mentioned in its arguments."
},
{
"code": null,
"e": 375,
"s": 352,
"text": "Syntax: math.gcd(x, y)"
},
{
"code": null,
"e": 386,
"s": 375,
"text": "Parameter:"
},
{
"code": null,
"e": 441,
"s": 386,
"text": "x : Non-negative integer whose gcd has to be computed."
},
{
"code": null,
"e": 496,
"s": 441,
"text": "y : Non-negative integer whose gcd has to be computed."
},
{
"code": null,
"e": 595,
"s": 496,
"text": "Returns: An absolute/positive integer value after calculating the GCD of given parameters x and y."
},
{
"code": null,
"e": 704,
"s": 595,
"text": "Exceptions: When Both x and y are 0, function returns 0, If any number is a character, Type error is raised."
},
{
"code": null,
"e": 712,
"s": 704,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of gcd()# importing \"math\" for mathematical operationsimport math # prints 12print(\"The gcd of 60 and 48 is : \", end=\"\")print(math.gcd(60, 48))",
"e": 898,
"s": 712,
"text": null
},
{
"code": null,
"e": 928,
"s": 898,
"text": "The gcd of 60 and 48 is : 12\n"
},
{
"code": null,
"e": 946,
"s": 928,
"text": "Using Recursion :"
},
{
"code": null,
"e": 954,
"s": 946,
"text": "Python3"
},
{
"code": "# Python code to demonstrate naive# method to compute gcd ( recursion ) def hcf(a, b): if(b == 0): return a else: return hcf(b, a % b) a = 60b = 48 # prints 12print(\"The gcd of 60 and 48 is : \", end=\"\")print(hcf(60, 48))",
"e": 1200,
"s": 954,
"text": null
},
{
"code": null,
"e": 1230,
"s": 1200,
"text": "The gcd of 60 and 48 is : 12\n"
},
{
"code": null,
"e": 1258,
"s": 1230,
"text": "Using Euclidean Algorithm :"
},
{
"code": null,
"e": 1506,
"s": 1258,
"text": "The Euclid’s algorithm (or Euclidean Algorithm) is a method for efficiently finding the greatest common divisor (GCD) of two numbers. The GCD of two integers X and Y is the largest number that divides both of X and Y (without leaving a remainder)."
},
{
"code": null,
"e": 1536,
"s": 1506,
"text": "Pseudo Code of the Algorithm-"
},
{
"code": null,
"e": 1667,
"s": 1536,
"text": "Let a, b be the two numbersa mod b = RLet a = b and b = RRepeat Steps 2 and 3 until a mod b is greater than 0GCD = b Finish"
},
{
"code": null,
"e": 1697,
"s": 1667,
"text": "Let a, b be the two numbers"
},
{
"code": null,
"e": 1709,
"s": 1697,
"text": "a mod b = R"
},
{
"code": null,
"e": 1732,
"s": 1709,
"text": "Let a = b and b = R"
},
{
"code": null,
"e": 1787,
"s": 1732,
"text": "Repeat Steps 2 and 3 until a mod b is greater than 0"
},
{
"code": null,
"e": 1795,
"s": 1787,
"text": "GCD = b"
},
{
"code": null,
"e": 1803,
"s": 1795,
"text": " Finish"
},
{
"code": null,
"e": 1811,
"s": 1803,
"text": "Python3"
},
{
"code": "# Recursive function to return gcd of a and bdef gcd(a, b): # Everything divides 0 if (a == 0): return b if (b == 0): return a # base case if (a == b): return a # a is greater if (a > b): return gcd(a-b, b) return gcd(a, b-a) # Driver program to test above functiona = 98b = 56if(gcd(a, b)): print('GCD of', a, 'and', b, 'is', gcd(a, b))else: print('not found')",
"e": 2238,
"s": 1811,
"text": null
},
{
"code": null,
"e": 2262,
"s": 2238,
"text": "GCD of 98 and 56 is 14\n"
},
{
"code": null,
"e": 2270,
"s": 2262,
"text": "GCD-LCM"
},
{
"code": null,
"e": 2277,
"s": 2270,
"text": "Python"
},
{
"code": null,
"e": 2293,
"s": 2277,
"text": "Python Programs"
}
] |
Perl | abs() function
|
25 Jun, 2019
This function returns the absolute value of its argument. If a pure integer value is passed then it will return it as it is, but if a string is passed then it will return zero. If VALUE is omitted then it uses $_
Syntax: abs(VALUE)
Parameter:VALUE: It is a required number which can be either positive or negative or a string.
Returns: Function returns the absolute value of the arguments passed.
Example 1:
#!/usr/bin/perl # Defining decimal value$var1 = 15.8; # Defining integer value$var2 = 7; # Defining negative value$var3 = "-15.2"; # Calling abs() function$res1 = abs($var1);$res2 = abs($var2);$res3 = abs($var3); # Printing these valuesprint "Abs value of var1 is $res1\n";print "Abs value of var2 is $res2\n";print "Abs value of var3 is $res3";
Output:
Abs value of var1 is 15.8
Abs value of var2 is 7
Abs value of var3 is 15.2
Example 2:
#!/usr/bin/perl # Defining string value$var1 = "Geeks"; # Defining Fractional value$var2 = 7/2; # Calling abs() function$res1 = abs($var1);$res2 = abs($var2); # Print these valuesprint "Abs value of var1 is $res1\n";print "Abs value of var2 is $res2";
Output:
Abs value of var1 is 0
Abs value of var2 is 3.5
Perl-function
Perl-Math-Functions
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl Tutorial - Learn Perl With Examples
Perl | Basic Syntax of a Perl Program
Perl | ne operator
Perl | Opening and Reading a File
Perl | Writing to a File
Perl | File Handling Introduction
Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)
Perl | Multidimensional Hashes
Perl | Data Types
Perl | qw Operator
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Jun, 2019"
},
{
"code": null,
"e": 241,
"s": 28,
"text": "This function returns the absolute value of its argument. If a pure integer value is passed then it will return it as it is, but if a string is passed then it will return zero. If VALUE is omitted then it uses $_"
},
{
"code": null,
"e": 260,
"s": 241,
"text": "Syntax: abs(VALUE)"
},
{
"code": null,
"e": 355,
"s": 260,
"text": "Parameter:VALUE: It is a required number which can be either positive or negative or a string."
},
{
"code": null,
"e": 425,
"s": 355,
"text": "Returns: Function returns the absolute value of the arguments passed."
},
{
"code": null,
"e": 436,
"s": 425,
"text": "Example 1:"
},
{
"code": "#!/usr/bin/perl # Defining decimal value$var1 = 15.8; # Defining integer value$var2 = 7; # Defining negative value$var3 = \"-15.2\"; # Calling abs() function$res1 = abs($var1);$res2 = abs($var2);$res3 = abs($var3); # Printing these valuesprint \"Abs value of var1 is $res1\\n\";print \"Abs value of var2 is $res2\\n\";print \"Abs value of var3 is $res3\";",
"e": 787,
"s": 436,
"text": null
},
{
"code": null,
"e": 795,
"s": 787,
"text": "Output:"
},
{
"code": null,
"e": 870,
"s": 795,
"text": "Abs value of var1 is 15.8\nAbs value of var2 is 7\nAbs value of var3 is 15.2"
},
{
"code": null,
"e": 881,
"s": 870,
"text": "Example 2:"
},
{
"code": "#!/usr/bin/perl # Defining string value$var1 = \"Geeks\"; # Defining Fractional value$var2 = 7/2; # Calling abs() function$res1 = abs($var1);$res2 = abs($var2); # Print these valuesprint \"Abs value of var1 is $res1\\n\";print \"Abs value of var2 is $res2\";",
"e": 1137,
"s": 881,
"text": null
},
{
"code": null,
"e": 1145,
"s": 1137,
"text": "Output:"
},
{
"code": null,
"e": 1193,
"s": 1145,
"text": "Abs value of var1 is 0\nAbs value of var2 is 3.5"
},
{
"code": null,
"e": 1207,
"s": 1193,
"text": "Perl-function"
},
{
"code": null,
"e": 1227,
"s": 1207,
"text": "Perl-Math-Functions"
},
{
"code": null,
"e": 1232,
"s": 1227,
"text": "Perl"
},
{
"code": null,
"e": 1237,
"s": 1232,
"text": "Perl"
},
{
"code": null,
"e": 1335,
"s": 1237,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1376,
"s": 1335,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 1414,
"s": 1376,
"text": "Perl | Basic Syntax of a Perl Program"
},
{
"code": null,
"e": 1433,
"s": 1414,
"text": "Perl | ne operator"
},
{
"code": null,
"e": 1467,
"s": 1433,
"text": "Perl | Opening and Reading a File"
},
{
"code": null,
"e": 1492,
"s": 1467,
"text": "Perl | Writing to a File"
},
{
"code": null,
"e": 1526,
"s": 1492,
"text": "Perl | File Handling Introduction"
},
{
"code": null,
"e": 1626,
"s": 1526,
"text": "Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)"
},
{
"code": null,
"e": 1657,
"s": 1626,
"text": "Perl | Multidimensional Hashes"
},
{
"code": null,
"e": 1675,
"s": 1657,
"text": "Perl | Data Types"
}
] |
Reduce the array by deleting elements which are greater than all elements to its left
|
09 Jun, 2021
Given an array arr[] of N integers, the task is to delete the element from the given array if element to it’s left is smaller than it. Keep on deleting the elements from the array until no element has a smaller adjacent left element. Print the resultant array after above operation.
Examples:
Input: arr[] = {2, 4, 1, 3, 4} Output: 2 1 Explanation: Since 4 is greater than 2 remove 4, and arr become {2, 1, 3, 4}. Now 3 is greater than 1 so remove 3 and arr become {2, 1, 4}. Now 4 is greater than 1 so remove 4 and arr become {2, 1}. Now no elements satisfy the removing criteria so the resultant array is {2, 1}.
Input: arr[] = {5, 4, 3, 2, 1} Output: 5 4 3 2 1
Approach: The idea is to use the concept of Merge Sort.
Divide the input array into sub-arrays till the size of each sub-array becomes 1.Start merging the element.While merging, delete elements from the left subarray till it’s rightmost element, which have a value greater than the leftmost element of the right subarray.Repeat the above steps in each merging step such all elements with value smaller to it’s left have been deleted.Finally print the resultant array.
Divide the input array into sub-arrays till the size of each sub-array becomes 1.
Start merging the element.
While merging, delete elements from the left subarray till it’s rightmost element, which have a value greater than the leftmost element of the right subarray.
Repeat the above steps in each merging step such all elements with value smaller to it’s left have been deleted.
Finally print the resultant array.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to implement merging of arr[]vector<int> merge(vector<int> x, vector<int> y){ for(auto i : y) { if (x[x.size() - 1] > i) x.push_back(i); } return x;} // Function to delete all elements which// satisfy the condition A[i] > A[i-1]vector<int> mergeDel(vector<int> l){ // Divide array into its subarray if (l.size() == 1) return l; int m = l.size() / 2; vector<int> temp1 = {l.begin() + 0, l.begin() + m}; vector<int> temp2 = {l.begin() + m, l.end()}; // Getting back merged array with all // its right element greater than // left one. return merge(mergeDel(temp1), mergeDel(temp2));} // Driver Codeint main(){ // Given array arr[] vector<int> arr({ 5, 4, 3, 2, 1 }); vector<int> ans = mergeDel(arr); cout << "[ "; for(auto x: ans) cout << x << ", "; cout << "]";} // This code is contributed by SURENDRA_GANGWAR
// Java program for the above approachimport java.util.ArrayList;import java.util.Arrays; class GFG{ // Function to implement merging of arr[]static ArrayList<Integer> merge(ArrayList<Integer> x, ArrayList<Integer> y){ for(Integer i : y) { if (x.get(x.size() - 1) > i) x.add(i); } return x;} // Function to delete all elements which// satisfy the condition A[i] > A[i-1]static ArrayList<Integer> mergeDel(ArrayList<Integer> l){ // Divide array into its subarray if (l.size() == 1) return l; int m = l.size() / 2; ArrayList<Integer> temp1 = new ArrayList<>( l.subList(0, m)); ArrayList<Integer> temp2 = new ArrayList<>( l.subList(m, l.size())); // Getting back merged array with all // its right element greater than // left one. return merge(mergeDel(temp1), mergeDel(temp2));} // Driver Codepublic static void main(String[] args){ // Given array arr[] Integer[] ar = { 5, 4, 3, 2, 1 }; ArrayList<Integer> arr = new ArrayList<>( Arrays.asList(ar)); ArrayList<Integer> ans = mergeDel(arr); System.out.print("[ "); for(Integer x : ans) System.out.print(x + ", "); System.out.println("]");}} // This code is contributed by sanjeev2552
# Python3 program for the above approach # Function to delete all elements which# satisfy the condition A[i] > A[i-1]def mergeDel(l): # Divide array into its subarray if len(l) == 1: return l m = int( len(l) / 2) # Getting back merged array with all # its right element greater than left one. return merge(mergeDel(l[ 0 : m ]), mergeDel(l[ m : len(l)]) ) # Function to implement merging of arr[]def merge(x, y): for i in y: if x[-1] > i : x = x + [i] return x # Driver Code # Function defination for main()def main(): # Given array arr[] arr = [5, 4, 3, 2, 1] print(mergeDel(arr)) main()
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to implement merging of arr[]static List<int> merge(List<int> x, List<int> y){ foreach(int i in y) { if (x[x.Count - 1] > i) x.Add(i); } return x;} // Function to delete all elements which// satisfy the condition A[i] > A[i-1]static List<int> mergeDel(List<int> l){ // Divide array into its subarray if (l.Count == 1) return l; int m = l.Count / 2; List<int> temp1 = l.GetRange(0, m); List<int> temp2 = l.GetRange(m, l.Count - m); // Getting back merged array with all // its right element greater than // left one. return merge(mergeDel(temp1), mergeDel(temp2));} // Driver Codepublic static void Main(string[] args){ // Given array arr[] List<int> arr = new List<int>{ 5, 4, 3, 2, 1 }; List<int> ans = mergeDel(arr); Console.Write("[ "); foreach(int x in ans) Console.Write(x + ", "); Console.Write("]");}} // This code is contributed by chitranayal
<script>// Javascript program for the above approach // Function to implement merging of arr[]function merge(x,y){ for(let i=0;i<y.length;i++) { if (x[x.length - 1] > y[i]) x.push(y[i]); } return x;} // Function to delete all elements which// satisfy the condition A[i] > A[i-1]function mergeDel(l){ // Divide array into its subarray if (l.length == 1) return l; let m = Math.floor(l.length / 2); let temp1 = l.slice(0, m); let temp2 = l.slice(m, l.length); // Getting back merged array with all // its right element greater than // left one. return merge(mergeDel(temp1), mergeDel(temp2));}// Driver Code // Given array arr[]let arr=[5, 4, 3, 2, 1];let ans = mergeDel(arr);document.write("[ ");document.write(ans.join(", "));document.write("]<br>"); // This code is contributed by avanitrachhadiya2155</script>
[5, 4, 3, 2, 1]
Time Complexity: O(N*log N) Auxiliary Space: O(1)
SURENDRA_GANGWAR
sanjeev2552
ukasp
avanitrachhadiya2155
Arrays
Competitive Programming
Divide and Conquer
Arrays
Divide and Conquer
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
Chocolate Distribution Problem
What is Data Structure: Types, Classifications and Applications
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Jun, 2021"
},
{
"code": null,
"e": 337,
"s": 54,
"text": "Given an array arr[] of N integers, the task is to delete the element from the given array if element to it’s left is smaller than it. Keep on deleting the elements from the array until no element has a smaller adjacent left element. Print the resultant array after above operation."
},
{
"code": null,
"e": 348,
"s": 337,
"text": "Examples: "
},
{
"code": null,
"e": 670,
"s": 348,
"text": "Input: arr[] = {2, 4, 1, 3, 4} Output: 2 1 Explanation: Since 4 is greater than 2 remove 4, and arr become {2, 1, 3, 4}. Now 3 is greater than 1 so remove 3 and arr become {2, 1, 4}. Now 4 is greater than 1 so remove 4 and arr become {2, 1}. Now no elements satisfy the removing criteria so the resultant array is {2, 1}."
},
{
"code": null,
"e": 720,
"s": 670,
"text": "Input: arr[] = {5, 4, 3, 2, 1} Output: 5 4 3 2 1 "
},
{
"code": null,
"e": 776,
"s": 720,
"text": "Approach: The idea is to use the concept of Merge Sort."
},
{
"code": null,
"e": 1188,
"s": 776,
"text": "Divide the input array into sub-arrays till the size of each sub-array becomes 1.Start merging the element.While merging, delete elements from the left subarray till it’s rightmost element, which have a value greater than the leftmost element of the right subarray.Repeat the above steps in each merging step such all elements with value smaller to it’s left have been deleted.Finally print the resultant array."
},
{
"code": null,
"e": 1270,
"s": 1188,
"text": "Divide the input array into sub-arrays till the size of each sub-array becomes 1."
},
{
"code": null,
"e": 1297,
"s": 1270,
"text": "Start merging the element."
},
{
"code": null,
"e": 1456,
"s": 1297,
"text": "While merging, delete elements from the left subarray till it’s rightmost element, which have a value greater than the leftmost element of the right subarray."
},
{
"code": null,
"e": 1569,
"s": 1456,
"text": "Repeat the above steps in each merging step such all elements with value smaller to it’s left have been deleted."
},
{
"code": null,
"e": 1604,
"s": 1569,
"text": "Finally print the resultant array."
},
{
"code": null,
"e": 1655,
"s": 1604,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1659,
"s": 1655,
"text": "C++"
},
{
"code": null,
"e": 1664,
"s": 1659,
"text": "Java"
},
{
"code": null,
"e": 1672,
"s": 1664,
"text": "Python3"
},
{
"code": null,
"e": 1675,
"s": 1672,
"text": "C#"
},
{
"code": null,
"e": 1686,
"s": 1675,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to implement merging of arr[]vector<int> merge(vector<int> x, vector<int> y){ for(auto i : y) { if (x[x.size() - 1] > i) x.push_back(i); } return x;} // Function to delete all elements which// satisfy the condition A[i] > A[i-1]vector<int> mergeDel(vector<int> l){ // Divide array into its subarray if (l.size() == 1) return l; int m = l.size() / 2; vector<int> temp1 = {l.begin() + 0, l.begin() + m}; vector<int> temp2 = {l.begin() + m, l.end()}; // Getting back merged array with all // its right element greater than // left one. return merge(mergeDel(temp1), mergeDel(temp2));} // Driver Codeint main(){ // Given array arr[] vector<int> arr({ 5, 4, 3, 2, 1 }); vector<int> ans = mergeDel(arr); cout << \"[ \"; for(auto x: ans) cout << x << \", \"; cout << \"]\";} // This code is contributed by SURENDRA_GANGWAR",
"e": 2778,
"s": 1686,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.ArrayList;import java.util.Arrays; class GFG{ // Function to implement merging of arr[]static ArrayList<Integer> merge(ArrayList<Integer> x, ArrayList<Integer> y){ for(Integer i : y) { if (x.get(x.size() - 1) > i) x.add(i); } return x;} // Function to delete all elements which// satisfy the condition A[i] > A[i-1]static ArrayList<Integer> mergeDel(ArrayList<Integer> l){ // Divide array into its subarray if (l.size() == 1) return l; int m = l.size() / 2; ArrayList<Integer> temp1 = new ArrayList<>( l.subList(0, m)); ArrayList<Integer> temp2 = new ArrayList<>( l.subList(m, l.size())); // Getting back merged array with all // its right element greater than // left one. return merge(mergeDel(temp1), mergeDel(temp2));} // Driver Codepublic static void main(String[] args){ // Given array arr[] Integer[] ar = { 5, 4, 3, 2, 1 }; ArrayList<Integer> arr = new ArrayList<>( Arrays.asList(ar)); ArrayList<Integer> ans = mergeDel(arr); System.out.print(\"[ \"); for(Integer x : ans) System.out.print(x + \", \"); System.out.println(\"]\");}} // This code is contributed by sanjeev2552",
"e": 4090,
"s": 2778,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to delete all elements which# satisfy the condition A[i] > A[i-1]def mergeDel(l): # Divide array into its subarray if len(l) == 1: return l m = int( len(l) / 2) # Getting back merged array with all # its right element greater than left one. return merge(mergeDel(l[ 0 : m ]), mergeDel(l[ m : len(l)]) ) # Function to implement merging of arr[]def merge(x, y): for i in y: if x[-1] > i : x = x + [i] return x # Driver Code # Function defination for main()def main(): # Given array arr[] arr = [5, 4, 3, 2, 1] print(mergeDel(arr)) main()",
"e": 4760,
"s": 4090,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to implement merging of arr[]static List<int> merge(List<int> x, List<int> y){ foreach(int i in y) { if (x[x.Count - 1] > i) x.Add(i); } return x;} // Function to delete all elements which// satisfy the condition A[i] > A[i-1]static List<int> mergeDel(List<int> l){ // Divide array into its subarray if (l.Count == 1) return l; int m = l.Count / 2; List<int> temp1 = l.GetRange(0, m); List<int> temp2 = l.GetRange(m, l.Count - m); // Getting back merged array with all // its right element greater than // left one. return merge(mergeDel(temp1), mergeDel(temp2));} // Driver Codepublic static void Main(string[] args){ // Given array arr[] List<int> arr = new List<int>{ 5, 4, 3, 2, 1 }; List<int> ans = mergeDel(arr); Console.Write(\"[ \"); foreach(int x in ans) Console.Write(x + \", \"); Console.Write(\"]\");}} // This code is contributed by chitranayal",
"e": 5839,
"s": 4760,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to implement merging of arr[]function merge(x,y){ for(let i=0;i<y.length;i++) { if (x[x.length - 1] > y[i]) x.push(y[i]); } return x;} // Function to delete all elements which// satisfy the condition A[i] > A[i-1]function mergeDel(l){ // Divide array into its subarray if (l.length == 1) return l; let m = Math.floor(l.length / 2); let temp1 = l.slice(0, m); let temp2 = l.slice(m, l.length); // Getting back merged array with all // its right element greater than // left one. return merge(mergeDel(temp1), mergeDel(temp2));}// Driver Code // Given array arr[]let arr=[5, 4, 3, 2, 1];let ans = mergeDel(arr);document.write(\"[ \");document.write(ans.join(\", \"));document.write(\"]<br>\"); // This code is contributed by avanitrachhadiya2155</script>",
"e": 6723,
"s": 5839,
"text": null
},
{
"code": null,
"e": 6739,
"s": 6723,
"text": "[5, 4, 3, 2, 1]"
},
{
"code": null,
"e": 6792,
"s": 6741,
"text": "Time Complexity: O(N*log N) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 6809,
"s": 6792,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 6821,
"s": 6809,
"text": "sanjeev2552"
},
{
"code": null,
"e": 6827,
"s": 6821,
"text": "ukasp"
},
{
"code": null,
"e": 6848,
"s": 6827,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 6855,
"s": 6848,
"text": "Arrays"
},
{
"code": null,
"e": 6879,
"s": 6855,
"text": "Competitive Programming"
},
{
"code": null,
"e": 6898,
"s": 6879,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 6905,
"s": 6898,
"text": "Arrays"
},
{
"code": null,
"e": 6924,
"s": 6905,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 7022,
"s": 6924,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7054,
"s": 7022,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 7079,
"s": 7054,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 7126,
"s": 7079,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 7157,
"s": 7126,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 7221,
"s": 7157,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 7264,
"s": 7221,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 7307,
"s": 7264,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 7348,
"s": 7307,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 7375,
"s": 7348,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
Python | Initializing dictionary with empty lists
|
11 May, 2020
In python one usually comes across situations in which one has to use dictionary for storing the lists. But in those cases, one usually checks for first element and then creates a list corresponding to key when it comes. But its always wanted a method to initialize the dict. keys with list. Let’s discuss certain ways to achieve this particular task.
Method #1 : Using Dictionary comprehensionThis is most sought of method to do this initialization. In this method, we create the no. of keys we require and then initialize the empty list as we keep on creating the keys, so as to facilitate the append operation afterwards without an error.
# Python3 code to demonstrate # to initialize dictionary with list # using dictionary comprehension # using dictionary comprehension to constructnew_dict = {new_list: [] for new_list in range(4)} # printing resultprint ("New dictionary with empty lists as keys : " + str(new_dict))
Output :
New dictionary with empty lists as keys : {0: [], 1: [], 2: [], 3: []}
Method #2 : Using fromkeys()fromkeys() can be used to perform this by specifying the additional empty list as argument and the range of elements which need to be the key of dictionary being made.
# Python3 code to demonstrate # to initialize dictionary with list # using fromkeys() # using fromkeys() to constructnew_dict = dict.fromkeys(range(4), []) # printing resultprint ("New dictionary with empty lists as keys : " + str(new_dict))
Output :
New dictionary with empty lists as keys : {0: [], 1: [], 2: [], 3: []}
Method #3 : Using defaultdictThis is most pythonic way and error free way to use any key without initialization of its value, it has to be told the type of default container of all its keys and then evaluates the operations and structures accordingly.
# Python3 code to demonstrate # to initialize dictionary with list # using defaultdictfrom collections import defaultdict # initializing dict with listsnew_dict = defaultdict(list) # performing append# shows no errornew_dict[0].append('GeeksforGeeks') # printing resultprint ("New dictionary created : " + str(dict(new_dict)))
Output :
New dictionary created : {0: ['GeeksforGeeks']}
Method #4 : Using setdefaultsetdefault() can be used to perform this by specifying key-value pairs within a comprehension. This method obviates the need to import a module as is required in Method #3.
# Python3 code to demonstrate # to initialize dictionary with list # using setdefault # initializing dict with listsnew_dict = {}[new_dict.setdefault(x, []) for x in range(4)] # performing append# shows no errornew_dict[0].append('GeeksforGeeks') # printing resultprint ("New dictionary created : " + str(dict(new_dict)))
Output :
New dictionary created : {0: ['GeeksforGeeks'], 1: [], 2: [], 3: []}
Method #5 : Using built-ins: dict and zipThe built-in functions dict, zip in conjunction with list comprehension can achieve the desired result.
# Python3 code to demonstrate # use of dict() and zip() built-ins to demonstrate# initializing dictionary with list keys = range(4)new_dict = dict(zip(keys, ([] for _ in keys))) print(new_dict)# performing append# shows no errornew_dict[0].append('GeeksforGeeks') # printing resultprint ("New dictionary created : " + str(dict(new_dict)))
Output :
New dictionary created : {0: ['GeeksforGeeks'], 1: [], 2: [], 3: []}
ashok bakthavathsala
Python dictionary-programs
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Python OOPs Concepts
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Python Classes and Objects
Introduction To PYTHON
Stack in Python
Queue in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 May, 2020"
},
{
"code": null,
"e": 380,
"s": 28,
"text": "In python one usually comes across situations in which one has to use dictionary for storing the lists. But in those cases, one usually checks for first element and then creates a list corresponding to key when it comes. But its always wanted a method to initialize the dict. keys with list. Let’s discuss certain ways to achieve this particular task."
},
{
"code": null,
"e": 670,
"s": 380,
"text": "Method #1 : Using Dictionary comprehensionThis is most sought of method to do this initialization. In this method, we create the no. of keys we require and then initialize the empty list as we keep on creating the keys, so as to facilitate the append operation afterwards without an error."
},
{
"code": "# Python3 code to demonstrate # to initialize dictionary with list # using dictionary comprehension # using dictionary comprehension to constructnew_dict = {new_list: [] for new_list in range(4)} # printing resultprint (\"New dictionary with empty lists as keys : \" + str(new_dict))",
"e": 958,
"s": 670,
"text": null
},
{
"code": null,
"e": 967,
"s": 958,
"text": "Output :"
},
{
"code": null,
"e": 1039,
"s": 967,
"text": "New dictionary with empty lists as keys : {0: [], 1: [], 2: [], 3: []}\n"
},
{
"code": null,
"e": 1235,
"s": 1039,
"text": "Method #2 : Using fromkeys()fromkeys() can be used to perform this by specifying the additional empty list as argument and the range of elements which need to be the key of dictionary being made."
},
{
"code": "# Python3 code to demonstrate # to initialize dictionary with list # using fromkeys() # using fromkeys() to constructnew_dict = dict.fromkeys(range(4), []) # printing resultprint (\"New dictionary with empty lists as keys : \" + str(new_dict))",
"e": 1483,
"s": 1235,
"text": null
},
{
"code": null,
"e": 1492,
"s": 1483,
"text": "Output :"
},
{
"code": null,
"e": 1564,
"s": 1492,
"text": "New dictionary with empty lists as keys : {0: [], 1: [], 2: [], 3: []}\n"
},
{
"code": null,
"e": 1816,
"s": 1564,
"text": "Method #3 : Using defaultdictThis is most pythonic way and error free way to use any key without initialization of its value, it has to be told the type of default container of all its keys and then evaluates the operations and structures accordingly."
},
{
"code": "# Python3 code to demonstrate # to initialize dictionary with list # using defaultdictfrom collections import defaultdict # initializing dict with listsnew_dict = defaultdict(list) # performing append# shows no errornew_dict[0].append('GeeksforGeeks') # printing resultprint (\"New dictionary created : \" + str(dict(new_dict)))",
"e": 2150,
"s": 1816,
"text": null
},
{
"code": null,
"e": 2159,
"s": 2150,
"text": "Output :"
},
{
"code": null,
"e": 2208,
"s": 2159,
"text": "New dictionary created : {0: ['GeeksforGeeks']}\n"
},
{
"code": null,
"e": 2409,
"s": 2208,
"text": "Method #4 : Using setdefaultsetdefault() can be used to perform this by specifying key-value pairs within a comprehension. This method obviates the need to import a module as is required in Method #3."
},
{
"code": "# Python3 code to demonstrate # to initialize dictionary with list # using setdefault # initializing dict with listsnew_dict = {}[new_dict.setdefault(x, []) for x in range(4)] # performing append# shows no errornew_dict[0].append('GeeksforGeeks') # printing resultprint (\"New dictionary created : \" + str(dict(new_dict)))",
"e": 2738,
"s": 2409,
"text": null
},
{
"code": null,
"e": 2747,
"s": 2738,
"text": "Output :"
},
{
"code": null,
"e": 2817,
"s": 2747,
"text": "New dictionary created : {0: ['GeeksforGeeks'], 1: [], 2: [], 3: []}\n"
},
{
"code": null,
"e": 2962,
"s": 2817,
"text": "Method #5 : Using built-ins: dict and zipThe built-in functions dict, zip in conjunction with list comprehension can achieve the desired result."
},
{
"code": "# Python3 code to demonstrate # use of dict() and zip() built-ins to demonstrate# initializing dictionary with list keys = range(4)new_dict = dict(zip(keys, ([] for _ in keys))) print(new_dict)# performing append# shows no errornew_dict[0].append('GeeksforGeeks') # printing resultprint (\"New dictionary created : \" + str(dict(new_dict)))",
"e": 3309,
"s": 2962,
"text": null
},
{
"code": null,
"e": 3318,
"s": 3309,
"text": "Output :"
},
{
"code": null,
"e": 3388,
"s": 3318,
"text": "New dictionary created : {0: ['GeeksforGeeks'], 1: [], 2: [], 3: []}\n"
},
{
"code": null,
"e": 3409,
"s": 3388,
"text": "ashok bakthavathsala"
},
{
"code": null,
"e": 3436,
"s": 3409,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 3448,
"s": 3436,
"text": "python-dict"
},
{
"code": null,
"e": 3455,
"s": 3448,
"text": "Python"
},
{
"code": null,
"e": 3467,
"s": 3455,
"text": "python-dict"
},
{
"code": null,
"e": 3565,
"s": 3467,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3595,
"s": 3565,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3640,
"s": 3595,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 3662,
"s": 3640,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3683,
"s": 3662,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3725,
"s": 3683,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3754,
"s": 3725,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3781,
"s": 3754,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3804,
"s": 3781,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3820,
"s": 3804,
"text": "Stack in Python"
}
] |
JSTL - Core <fmt:formatNumber> Tag
|
The <fmt:formatNumber> tag is used to format numbers, percentages, and currencies.
The <fmt:formatNumber> tag has the following attributes −
If the type attribute is percent or number, then you can use several number-formatting attributes. The maxIntegerDigits and minIntegerDigits attributes allow you to specify the size of the nonfractional portion of the number. If the actual number exceeds maxIntegerDigits, then the number is truncated.
If the type attribute is percent or number, then you can use several number-formatting attributes. The maxIntegerDigits and minIntegerDigits attributes allow you to specify the size of the nonfractional portion of the number. If the actual number exceeds maxIntegerDigits, then the number is truncated.
Attributes are also provided to allow you to determine how many decimal places should be used. The minFractionalDigits and maxFractionalDigits attributes allow you to specify the number of decimal places. If the number exceeds the maximum number of fractional digits, the number will be rounded.
Attributes are also provided to allow you to determine how many decimal places should be used. The minFractionalDigits and maxFractionalDigits attributes allow you to specify the number of decimal places. If the number exceeds the maximum number of fractional digits, the number will be rounded.
Grouping can be used to insert commas between thousands groups. Grouping is specified by setting the groupingIsUsed attribute to either true or false. When using grouping with minIntegerDigits, you must be careful to get your intended result.
Grouping can be used to insert commas between thousands groups. Grouping is specified by setting the groupingIsUsed attribute to either true or false. When using grouping with minIntegerDigits, you must be careful to get your intended result.
You may select to use the pattern attribute. This attribute lets you include special characters that specify how you would like your number encoded. Following table lists out the codes.
You may select to use the pattern attribute. This attribute lets you include special characters that specify how you would like your number encoded. Following table lists out the codes.
0
Represents a digit.
E
Represents in exponential form.
#
Represents a digit; displays 0 as absent.
.
Serves as a placeholder for a decimal separator.
,
Serves as a placeholder for a grouping separator.
;
Separates formats.
-
Used as the default negative prefix.
%
Multiplies by 100 and displays as a percentage.
?
Multiplies by 1000 and displays as per mille.
¤
Represents the currency sign; replaced by actional currency symbol.
X
Indicates that any other characters can be used in the prefix or suffix.
'
Used to quote special characters in a prefix or suffix.
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<title>JSTL fmt:formatNumber Tag</title>
</head>
<body>
<h3>Number Format:</h3>
<c:set var = "balance" value = "120000.2309" />
<p>Formatted Number (1): <fmt:formatNumber value = "${balance}"
type = "currency"/></p>
<p>Formatted Number (2): <fmt:formatNumber type = "number"
maxIntegerDigits = "3" value = "${balance}" /></p>
<p>Formatted Number (3): <fmt:formatNumber type = "number"
maxFractionDigits = "3" value = "${balance}" /></p>
<p>Formatted Number (4): <fmt:formatNumber type = "number"
groupingUsed = "false" value = "${balance}" /></p>
<p>Formatted Number (5): <fmt:formatNumber type = "percent"
maxIntegerDigits="3" value = "${balance}" /></p>
<p>Formatted Number (6): <fmt:formatNumber type = "percent"
minFractionDigits = "10" value = "${balance}" /></p>
<p>Formatted Number (7): <fmt:formatNumber type = "percent"
maxIntegerDigits = "3" value = "${balance}" /></p>
<p>Formatted Number (8): <fmt:formatNumber type = "number"
pattern = "###.###E0" value = "${balance}" /></p>
<p>Currency in USA :
<fmt:setLocale value = "en_US"/>
<fmt:formatNumber value = "${balance}" type = "currency"/>
</p>
</body>
</html>
The above code will generate the following result −
Number Format:
Formatted Number (1): £120,000.23
Formatted Number (2): 000.231
Formatted Number (3): 120,000.231
Formatted Number (4): 120000.231
Formatted Number (5): 023%
Formatted Number (6): 12,000,023.0900000000%
Formatted Number (7): 023%
Formatted Number (8): 120E3
Currency in USA : $120,000.23
Formatted Number (1): £120,000.23
Formatted Number (2): 000.231
Formatted Number (3): 120,000.231
Formatted Number (4): 120000.231
Formatted Number (5): 023%
Formatted Number (6): 12,000,023.0900000000%
Formatted Number (7): 023%
Formatted Number (8): 120E3
Currency in USA : $120,000.23
|
[
{
"code": null,
"e": 2457,
"s": 2373,
"text": "The <fmt:formatNumber> tag is used to format numbers, percentages, and currencies."
},
{
"code": null,
"e": 2515,
"s": 2457,
"text": "The <fmt:formatNumber> tag has the following attributes −"
},
{
"code": null,
"e": 2818,
"s": 2515,
"text": "If the type attribute is percent or number, then you can use several number-formatting attributes. The maxIntegerDigits and minIntegerDigits attributes allow you to specify the size of the nonfractional portion of the number. If the actual number exceeds maxIntegerDigits, then the number is truncated."
},
{
"code": null,
"e": 3121,
"s": 2818,
"text": "If the type attribute is percent or number, then you can use several number-formatting attributes. The maxIntegerDigits and minIntegerDigits attributes allow you to specify the size of the nonfractional portion of the number. If the actual number exceeds maxIntegerDigits, then the number is truncated."
},
{
"code": null,
"e": 3417,
"s": 3121,
"text": "Attributes are also provided to allow you to determine how many decimal places should be used. The minFractionalDigits and maxFractionalDigits attributes allow you to specify the number of decimal places. If the number exceeds the maximum number of fractional digits, the number will be rounded."
},
{
"code": null,
"e": 3713,
"s": 3417,
"text": "Attributes are also provided to allow you to determine how many decimal places should be used. The minFractionalDigits and maxFractionalDigits attributes allow you to specify the number of decimal places. If the number exceeds the maximum number of fractional digits, the number will be rounded."
},
{
"code": null,
"e": 3956,
"s": 3713,
"text": "Grouping can be used to insert commas between thousands groups. Grouping is specified by setting the groupingIsUsed attribute to either true or false. When using grouping with minIntegerDigits, you must be careful to get your intended result."
},
{
"code": null,
"e": 4199,
"s": 3956,
"text": "Grouping can be used to insert commas between thousands groups. Grouping is specified by setting the groupingIsUsed attribute to either true or false. When using grouping with minIntegerDigits, you must be careful to get your intended result."
},
{
"code": null,
"e": 4385,
"s": 4199,
"text": "You may select to use the pattern attribute. This attribute lets you include special characters that specify how you would like your number encoded. Following table lists out the codes."
},
{
"code": null,
"e": 4571,
"s": 4385,
"text": "You may select to use the pattern attribute. This attribute lets you include special characters that specify how you would like your number encoded. Following table lists out the codes."
},
{
"code": null,
"e": 4573,
"s": 4571,
"text": "0"
},
{
"code": null,
"e": 4593,
"s": 4573,
"text": "Represents a digit."
},
{
"code": null,
"e": 4595,
"s": 4593,
"text": "E"
},
{
"code": null,
"e": 4627,
"s": 4595,
"text": "Represents in exponential form."
},
{
"code": null,
"e": 4629,
"s": 4627,
"text": "#"
},
{
"code": null,
"e": 4671,
"s": 4629,
"text": "Represents a digit; displays 0 as absent."
},
{
"code": null,
"e": 4673,
"s": 4671,
"text": "."
},
{
"code": null,
"e": 4722,
"s": 4673,
"text": "Serves as a placeholder for a decimal separator."
},
{
"code": null,
"e": 4724,
"s": 4722,
"text": ","
},
{
"code": null,
"e": 4774,
"s": 4724,
"text": "Serves as a placeholder for a grouping separator."
},
{
"code": null,
"e": 4776,
"s": 4774,
"text": ";"
},
{
"code": null,
"e": 4795,
"s": 4776,
"text": "Separates formats."
},
{
"code": null,
"e": 4797,
"s": 4795,
"text": "-"
},
{
"code": null,
"e": 4834,
"s": 4797,
"text": "Used as the default negative prefix."
},
{
"code": null,
"e": 4836,
"s": 4834,
"text": "%"
},
{
"code": null,
"e": 4884,
"s": 4836,
"text": "Multiplies by 100 and displays as a percentage."
},
{
"code": null,
"e": 4886,
"s": 4884,
"text": "?"
},
{
"code": null,
"e": 4932,
"s": 4886,
"text": "Multiplies by 1000 and displays as per mille."
},
{
"code": null,
"e": 4934,
"s": 4932,
"text": "¤"
},
{
"code": null,
"e": 5002,
"s": 4934,
"text": "Represents the currency sign; replaced by actional currency symbol."
},
{
"code": null,
"e": 5004,
"s": 5002,
"text": "X"
},
{
"code": null,
"e": 5077,
"s": 5004,
"text": "Indicates that any other characters can be used in the prefix or suffix."
},
{
"code": null,
"e": 5079,
"s": 5077,
"text": "'"
},
{
"code": null,
"e": 5135,
"s": 5079,
"text": "Used to quote special characters in a prefix or suffix."
},
{
"code": null,
"e": 6695,
"s": 5135,
"text": "<%@ taglib prefix = \"c\" uri = \"http://java.sun.com/jsp/jstl/core\" %>\n<%@ taglib prefix = \"fmt\" uri = \"http://java.sun.com/jsp/jstl/fmt\" %>\n\n<html>\n <head>\n <title>JSTL fmt:formatNumber Tag</title>\n </head>\n\n <body>\n <h3>Number Format:</h3>\n <c:set var = \"balance\" value = \"120000.2309\" />\n \n <p>Formatted Number (1): <fmt:formatNumber value = \"${balance}\" \n type = \"currency\"/></p>\n \n <p>Formatted Number (2): <fmt:formatNumber type = \"number\" \n maxIntegerDigits = \"3\" value = \"${balance}\" /></p>\n \n <p>Formatted Number (3): <fmt:formatNumber type = \"number\" \n maxFractionDigits = \"3\" value = \"${balance}\" /></p>\n \n <p>Formatted Number (4): <fmt:formatNumber type = \"number\" \n groupingUsed = \"false\" value = \"${balance}\" /></p>\n \n <p>Formatted Number (5): <fmt:formatNumber type = \"percent\" \n maxIntegerDigits=\"3\" value = \"${balance}\" /></p>\n \n <p>Formatted Number (6): <fmt:formatNumber type = \"percent\" \n minFractionDigits = \"10\" value = \"${balance}\" /></p>\n \n <p>Formatted Number (7): <fmt:formatNumber type = \"percent\" \n maxIntegerDigits = \"3\" value = \"${balance}\" /></p>\n \n <p>Formatted Number (8): <fmt:formatNumber type = \"number\" \n pattern = \"###.###E0\" value = \"${balance}\" /></p>\n \n <p>Currency in USA :\n <fmt:setLocale value = \"en_US\"/>\n <fmt:formatNumber value = \"${balance}\" type = \"currency\"/>\n </p>\n \n </body>\n</html>"
},
{
"code": null,
"e": 6747,
"s": 6695,
"text": "The above code will generate the following result −"
},
{
"code": null,
"e": 7051,
"s": 6747,
"text": "Number Format:\nFormatted Number (1): £120,000.23\nFormatted Number (2): 000.231\nFormatted Number (3): 120,000.231\nFormatted Number (4): 120000.231\nFormatted Number (5): 023%\nFormatted Number (6): 12,000,023.0900000000%\nFormatted Number (7): 023%\nFormatted Number (8): 120E3\nCurrency in USA : $120,000.23\n"
},
{
"code": null,
"e": 7085,
"s": 7051,
"text": "Formatted Number (1): £120,000.23"
},
{
"code": null,
"e": 7115,
"s": 7085,
"text": "Formatted Number (2): 000.231"
},
{
"code": null,
"e": 7149,
"s": 7115,
"text": "Formatted Number (3): 120,000.231"
},
{
"code": null,
"e": 7182,
"s": 7149,
"text": "Formatted Number (4): 120000.231"
},
{
"code": null,
"e": 7209,
"s": 7182,
"text": "Formatted Number (5): 023%"
},
{
"code": null,
"e": 7254,
"s": 7209,
"text": "Formatted Number (6): 12,000,023.0900000000%"
},
{
"code": null,
"e": 7281,
"s": 7254,
"text": "Formatted Number (7): 023%"
},
{
"code": null,
"e": 7309,
"s": 7281,
"text": "Formatted Number (8): 120E3"
}
] |
Connect PHP to MySQL
|
03 Jun, 2022
What is MySQL?
MySQL is an open-source relational database management system (RDBMS). It is the most popular database system used with PHP.
Structured Query Language (SQL). The data in a MySQL database are stored in tables that consist of columns and rows.
MySQL is a database system that runs on a server. MySQL is ideal for both small and large applications. MySQL is a very fast, reliable, and easy-to-use database system. It uses standard SQL. MySQL compiles on a number of platforms.
How we can connect PHP to MySQL?
PHP 5 and later can work with a MySQL database using:
MySQLi extension (the ‘i’ is abbreviation for improved)
PDO (PHP Data Objects)
Which one should we use MySQLi or PDO?
Both MySQLi and PDO have their recompenses:
PDO will work with 12 different database systems, whereas MySQLi will only work with MySQL databases.
So, if you have to shift your project to use alternative database, PDO makes the process easy. You only have to change the connection string and a few queries. With MySQLi, you will need to rewrite the complete code — queries included.
Both are object-oriented, but MySQLi also offers a procedural API.
In short, you can choose whichever you want if you want to stick to MySQL otherwise you should go with PDO.
Connection to MySQL using MySQLi
PHP provides mysql_connect() function to open a database connection.
This function takes a single parameter, which is a connection returned by the mysql_connect() function.
You can disconnect from the MySQL database anytime using another PHP function mysql_close().
There is also a procedural approach of MySQLi to establish a connection to MySQL database from a PHP script.
It can be done in two ways:
MySQLi Object-Oriented
PHP
<?php$servername = "localhost";$username = "username";$password = "password"; // Connection$conn = new mysqli($servername, $username, $password); // For checking if connection is// successful or notif ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}echo "Connected successfully";?>
MySQLi Procedural
PHP
<?php $servername = "localhost";$username = "username";$password = "password"; // Connection$conn = mysqli_connect($servername, $username, $password); // Check if connection is// Successful or notif (!$conn) { die("Connection failed: " . mysqli_connect_error());}echo "Connected successfully";?>
Connection to MySQL using PDO
PHP
<?php $servername = "localhost";$username = "username";$password = "password"; try { $conn = new PDO( "mysql:host=$servername;dbname=myDB", $username, $password); // Set the PDO error mode // to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully";} catch(PDOException $e) { echo "Connection failed: " . $e->getMessage();}?>
saurabh1990aror
jyotsnarasam
PHP-Misc
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
How to call PHP function on the click of a Button ?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Jun, 2022"
},
{
"code": null,
"e": 67,
"s": 52,
"text": "What is MySQL?"
},
{
"code": null,
"e": 192,
"s": 67,
"text": "MySQL is an open-source relational database management system (RDBMS). It is the most popular database system used with PHP."
},
{
"code": null,
"e": 309,
"s": 192,
"text": "Structured Query Language (SQL). The data in a MySQL database are stored in tables that consist of columns and rows."
},
{
"code": null,
"e": 541,
"s": 309,
"text": "MySQL is a database system that runs on a server. MySQL is ideal for both small and large applications. MySQL is a very fast, reliable, and easy-to-use database system. It uses standard SQL. MySQL compiles on a number of platforms."
},
{
"code": null,
"e": 574,
"s": 541,
"text": "How we can connect PHP to MySQL?"
},
{
"code": null,
"e": 628,
"s": 574,
"text": "PHP 5 and later can work with a MySQL database using:"
},
{
"code": null,
"e": 684,
"s": 628,
"text": "MySQLi extension (the ‘i’ is abbreviation for improved)"
},
{
"code": null,
"e": 707,
"s": 684,
"text": "PDO (PHP Data Objects)"
},
{
"code": null,
"e": 747,
"s": 707,
"text": " Which one should we use MySQLi or PDO?"
},
{
"code": null,
"e": 791,
"s": 747,
"text": "Both MySQLi and PDO have their recompenses:"
},
{
"code": null,
"e": 893,
"s": 791,
"text": "PDO will work with 12 different database systems, whereas MySQLi will only work with MySQL databases."
},
{
"code": null,
"e": 1129,
"s": 893,
"text": "So, if you have to shift your project to use alternative database, PDO makes the process easy. You only have to change the connection string and a few queries. With MySQLi, you will need to rewrite the complete code — queries included."
},
{
"code": null,
"e": 1196,
"s": 1129,
"text": "Both are object-oriented, but MySQLi also offers a procedural API."
},
{
"code": null,
"e": 1304,
"s": 1196,
"text": "In short, you can choose whichever you want if you want to stick to MySQL otherwise you should go with PDO."
},
{
"code": null,
"e": 1337,
"s": 1304,
"text": "Connection to MySQL using MySQLi"
},
{
"code": null,
"e": 1406,
"s": 1337,
"text": "PHP provides mysql_connect() function to open a database connection."
},
{
"code": null,
"e": 1510,
"s": 1406,
"text": "This function takes a single parameter, which is a connection returned by the mysql_connect() function."
},
{
"code": null,
"e": 1603,
"s": 1510,
"text": "You can disconnect from the MySQL database anytime using another PHP function mysql_close()."
},
{
"code": null,
"e": 1712,
"s": 1603,
"text": "There is also a procedural approach of MySQLi to establish a connection to MySQL database from a PHP script."
},
{
"code": null,
"e": 1740,
"s": 1712,
"text": "It can be done in two ways:"
},
{
"code": null,
"e": 1763,
"s": 1740,
"text": "MySQLi Object-Oriented"
},
{
"code": null,
"e": 1776,
"s": 1772,
"text": "PHP"
},
{
"code": "<?php$servername = \"localhost\";$username = \"username\";$password = \"password\"; // Connection$conn = new mysqli($servername, $username, $password); // For checking if connection is// successful or notif ($conn->connect_error) { die(\"Connection failed: \" . $conn->connect_error);}echo \"Connected successfully\";?>",
"e": 2102,
"s": 1776,
"text": null
},
{
"code": null,
"e": 2120,
"s": 2102,
"text": "MySQLi Procedural"
},
{
"code": null,
"e": 2124,
"s": 2120,
"text": "PHP"
},
{
"code": "<?php $servername = \"localhost\";$username = \"username\";$password = \"password\"; // Connection$conn = mysqli_connect($servername, $username, $password); // Check if connection is// Successful or notif (!$conn) { die(\"Connection failed: \" . mysqli_connect_error());}echo \"Connected successfully\";?>",
"e": 2440,
"s": 2124,
"text": null
},
{
"code": null,
"e": 2470,
"s": 2440,
"text": "Connection to MySQL using PDO"
},
{
"code": null,
"e": 2474,
"s": 2470,
"text": "PHP"
},
{
"code": "<?php $servername = \"localhost\";$username = \"username\";$password = \"password\"; try { $conn = new PDO( \"mysql:host=$servername;dbname=myDB\", $username, $password); // Set the PDO error mode // to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo \"Connected successfully\";} catch(PDOException $e) { echo \"Connection failed: \" . $e->getMessage();}?>",
"e": 2924,
"s": 2474,
"text": null
},
{
"code": null,
"e": 2940,
"s": 2924,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 2953,
"s": 2940,
"text": "jyotsnarasam"
},
{
"code": null,
"e": 2962,
"s": 2953,
"text": "PHP-Misc"
},
{
"code": null,
"e": 2966,
"s": 2962,
"text": "PHP"
},
{
"code": null,
"e": 2979,
"s": 2966,
"text": "PHP Programs"
},
{
"code": null,
"e": 2996,
"s": 2979,
"text": "Web Technologies"
},
{
"code": null,
"e": 3000,
"s": 2996,
"text": "PHP"
},
{
"code": null,
"e": 3098,
"s": 3000,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3148,
"s": 3098,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 3188,
"s": 3148,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 3249,
"s": 3188,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 3299,
"s": 3249,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 3344,
"s": 3299,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 3394,
"s": 3344,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 3434,
"s": 3394,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 3495,
"s": 3434,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 3545,
"s": 3495,
"text": "How to check whether an array is empty using PHP?"
}
] |
hypot(), hypotf(), hypotl() in C++
|
24 Oct, 2019
The hypot() function in C++ returns the square root of sum of square of arguments passed. It finds the hypotenuse, hypotenuse is the longest side of a right angled triangle. It is calculated by the formula :
h = sqrt(x2+y2)
where x and y are the other two sides of the triangle.
Syntax:
double hypot(double x, double y);
float hypot(float x, float y);
long double hypot(long double x, long double y);
Examples:
Input : x=3, y=4
Output :5
Input :x=9, y=10
Output :13.4536
Explanation
Header File : cmathParameters : The hypot() takes either 2 or 3 parameters of integral or floating-point type.Returns :1. The hypotenuse of a right-angled triangle if two arguments are passed.2. Distance from the origin to the (x, y, x) if three arguments are passed
Exceptions or Errors1. hypot(x, y), hypot(y, x), and hypot(x, -y) are equivalent.2. If one of the arguments is 0, hypot(x, y) is equivalent to fabs called with the non-zero argument3. If one of the arguments is infinite or undefined, hypot(x, y) returns undefined.
Example Application : Finding the hypotenuse of a right angle triangle given 2 of its other sides.
// CPP program to illustrate// hypot() function#include <cmath>#include <iostream>using namespace std;// Driver Programint main(){ double x = 9, y = 10, res; res = hypot(x, y); // hypot() returns double in this case cout << res << endl; long double a, b, result; a = 4.525252; b = 5.767676; // hypot() returns long double in this case result = hypot(a, b); cout << result; return 0;}
Output:
13.4536
7.33103
hypotf() function
hypotf() function is same as the hypot function.The only difference is that the parameter and return type of the function is float type. The ‘f‘ character appended to ‘hypotf‘ stands for float and it signify the parameter type and return type of the function.
Syntax
float hypotf(float x);
C++ program implementation of hypotf()Here, variables are assigned float type otherwise type mismatch error occurs.
// CPP program to illustrate// hypotf() function#include <cmath>#include <iostream>using namespace std;// Driver Programint main(){ float x = 9.3425, y = 10.0987, res; // hypotf() takes float values and returns float res = hypotf(x, y); cout << res << endl; return 0;}
Output:
13.7574
hypotl() function
hypotl() function is same as the hypot function.The only difference is that the parameter and return type of the function is long double type.The ‘l‘ character appended to ‘hypotl‘ stands for long double and it signify the parameter type and return type of the function.
Syntax
long double hypotl(long double x);
C++ program implementation of hypotl()Here, variables are assigned long double type otherwise type mismatch error occurs.
// CPP program to illustrate// hypotl() function#include <cmath>#include <iostream>using namespace std;// Driver Programint main(){ long double x = 9.3425453435, y = 10.0987456456, res; // hypotl() takes long double values and returns long double res = hypotl(x, y); cout << res << endl; return 0;}
Output:
13.7575
Akanksha_Rai
CPP-Library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Templates in C++ with Examples
Operator Overloading in C++
Queue in C++ Standard Template Library (STL)
Virtual Function in C++
unordered_map in C++ STL
Polymorphism in C++
Socket Programming in C/C++
C++ Classes and Objects
vector erase() and clear() in C++
Copy Constructor in C++
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Oct, 2019"
},
{
"code": null,
"e": 261,
"s": 53,
"text": "The hypot() function in C++ returns the square root of sum of square of arguments passed. It finds the hypotenuse, hypotenuse is the longest side of a right angled triangle. It is calculated by the formula :"
},
{
"code": null,
"e": 278,
"s": 261,
"text": " h = sqrt(x2+y2)"
},
{
"code": null,
"e": 333,
"s": 278,
"text": "where x and y are the other two sides of the triangle."
},
{
"code": null,
"e": 456,
"s": 333,
"text": "Syntax:\ndouble hypot(double x, double y);\nfloat hypot(float x, float y);\nlong double hypot(long double x, long double y);\n"
},
{
"code": null,
"e": 466,
"s": 456,
"text": "Examples:"
},
{
"code": null,
"e": 528,
"s": 466,
"text": "Input : x=3, y=4\nOutput :5\n\nInput :x=9, y=10\nOutput :13.4536\n"
},
{
"code": null,
"e": 540,
"s": 528,
"text": "Explanation"
},
{
"code": null,
"e": 807,
"s": 540,
"text": "Header File : cmathParameters : The hypot() takes either 2 or 3 parameters of integral or floating-point type.Returns :1. The hypotenuse of a right-angled triangle if two arguments are passed.2. Distance from the origin to the (x, y, x) if three arguments are passed"
},
{
"code": null,
"e": 1072,
"s": 807,
"text": "Exceptions or Errors1. hypot(x, y), hypot(y, x), and hypot(x, -y) are equivalent.2. If one of the arguments is 0, hypot(x, y) is equivalent to fabs called with the non-zero argument3. If one of the arguments is infinite or undefined, hypot(x, y) returns undefined."
},
{
"code": null,
"e": 1171,
"s": 1072,
"text": "Example Application : Finding the hypotenuse of a right angle triangle given 2 of its other sides."
},
{
"code": "// CPP program to illustrate// hypot() function#include <cmath>#include <iostream>using namespace std;// Driver Programint main(){ double x = 9, y = 10, res; res = hypot(x, y); // hypot() returns double in this case cout << res << endl; long double a, b, result; a = 4.525252; b = 5.767676; // hypot() returns long double in this case result = hypot(a, b); cout << result; return 0;}",
"e": 1592,
"s": 1171,
"text": null
},
{
"code": null,
"e": 1600,
"s": 1592,
"text": "Output:"
},
{
"code": null,
"e": 1617,
"s": 1600,
"text": "13.4536\n7.33103\n"
},
{
"code": null,
"e": 1635,
"s": 1617,
"text": "hypotf() function"
},
{
"code": null,
"e": 1895,
"s": 1635,
"text": "hypotf() function is same as the hypot function.The only difference is that the parameter and return type of the function is float type. The ‘f‘ character appended to ‘hypotf‘ stands for float and it signify the parameter type and return type of the function."
},
{
"code": null,
"e": 1926,
"s": 1895,
"text": "Syntax\nfloat hypotf(float x);\n"
},
{
"code": null,
"e": 2042,
"s": 1926,
"text": "C++ program implementation of hypotf()Here, variables are assigned float type otherwise type mismatch error occurs."
},
{
"code": "// CPP program to illustrate// hypotf() function#include <cmath>#include <iostream>using namespace std;// Driver Programint main(){ float x = 9.3425, y = 10.0987, res; // hypotf() takes float values and returns float res = hypotf(x, y); cout << res << endl; return 0;}",
"e": 2328,
"s": 2042,
"text": null
},
{
"code": null,
"e": 2336,
"s": 2328,
"text": "Output:"
},
{
"code": null,
"e": 2345,
"s": 2336,
"text": "13.7574\n"
},
{
"code": null,
"e": 2363,
"s": 2345,
"text": "hypotl() function"
},
{
"code": null,
"e": 2634,
"s": 2363,
"text": "hypotl() function is same as the hypot function.The only difference is that the parameter and return type of the function is long double type.The ‘l‘ character appended to ‘hypotl‘ stands for long double and it signify the parameter type and return type of the function."
},
{
"code": null,
"e": 2677,
"s": 2634,
"text": "Syntax\nlong double hypotl(long double x);\n"
},
{
"code": null,
"e": 2799,
"s": 2677,
"text": "C++ program implementation of hypotl()Here, variables are assigned long double type otherwise type mismatch error occurs."
},
{
"code": "// CPP program to illustrate// hypotl() function#include <cmath>#include <iostream>using namespace std;// Driver Programint main(){ long double x = 9.3425453435, y = 10.0987456456, res; // hypotl() takes long double values and returns long double res = hypotl(x, y); cout << res << endl; return 0;}",
"e": 3115,
"s": 2799,
"text": null
},
{
"code": null,
"e": 3123,
"s": 3115,
"text": "Output:"
},
{
"code": null,
"e": 3132,
"s": 3123,
"text": "13.7575\n"
},
{
"code": null,
"e": 3145,
"s": 3132,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 3157,
"s": 3145,
"text": "CPP-Library"
},
{
"code": null,
"e": 3161,
"s": 3157,
"text": "C++"
},
{
"code": null,
"e": 3165,
"s": 3161,
"text": "CPP"
},
{
"code": null,
"e": 3263,
"s": 3165,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3294,
"s": 3263,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 3322,
"s": 3294,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 3367,
"s": 3322,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3391,
"s": 3367,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 3416,
"s": 3391,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 3436,
"s": 3416,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 3464,
"s": 3436,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 3488,
"s": 3464,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 3522,
"s": 3488,
"text": "vector erase() and clear() in C++"
}
] |
Program for Sudoku Generator
|
22 Jun, 2022
Background: Following are the rules of Sudoku for a player.
In all 9 sub matrices 3×3 the elements should be 1-9, without repetition.In all rows there should be elements between 1-9 , without repetition.In all columns there should be elements between 1-9 , without repetition.
In all 9 sub matrices 3×3 the elements should be 1-9, without repetition.
In all rows there should be elements between 1-9 , without repetition.
In all columns there should be elements between 1-9 , without repetition.
The task is to generate a 9 x 9 Sudoku grid that is valid, i.e., a player can fill the grid following above set of rules.
A simple naïve solution can be.
Randomly take any number 1-9.Check if it is safe to put in the cell.(row , column and box)If safe, place it and increment to next location and go to step 1.If not safe, then without incrementing go to step 1.Once matrix is fully filled, remove k no. of elements randomly to complete game.
Randomly take any number 1-9.
Check if it is safe to put in the cell.(row , column and box)
If safe, place it and increment to next location and go to step 1.
If not safe, then without incrementing go to step 1.
Once matrix is fully filled, remove k no. of elements randomly to complete game.
Improved Solution : We can improve the solution, if we understand a pattern in this game. We can observe that all 3 x 3 matrices, which are diagonally present are independent of other 3 x 3 adjacent matrices initially, as others are empty.
3 8 5 0 0 0 0 0 0
9 2 1 0 0 0 0 0 0
6 4 7 0 0 0 0 0 0
0 0 0 1 2 3 0 0 0
0 0 0 7 8 4 0 0 0
0 0 0 6 9 5 0 0 0
0 0 0 0 0 0 8 7 3
0 0 0 0 0 0 9 6 2
0 0 0 0 0 0 1 4 5
(We can observe that in above matrix, the diagonal matrices are independent of other empty matrices initially). So if we fill them first, then we will only have to do box check and thus column/row check not required.
Secondly, while we fill rest of the non-diagonal elements, we will not have to use random generator, but we can fill recursively by checking 1 to 9.
Following is the improved logic for the problem.
1. Fill all the diagonal 3x3 matrices.
2. Fill recursively rest of the non-diagonal matrices.
For every cell to be filled, we try all numbers until
we find a safe number to be placed.
3. Once matrix is fully filled, remove K elements
randomly to complete game.
C++
Java
C#
/* C++ program for Sudoku generator */#include <bits/stdc++.h>using namespace std; class Sudoku {public: int** mat; int N; // number of columns/rows. int SRN; // square root of N int K; // No. Of missing digits // Constructor Sudoku(int N, int K) { this->N = N; this->K = K; // Compute square root of N double SRNd = sqrt(N); SRN = (int)SRNd; mat = new int*[N]; // Create a row for every pointer for (int i = 0; i < N; i++) { // Note : Rows may not be contiguous mat[i] = new int[N]; // Initialize all entries as false to indicate // that there are no edges initially memset(mat[i], 0, N * sizeof(int)); } } // Sudoku Generator void fillValues() { // Fill the diagonal of SRN x SRN matrices fillDiagonal(); // Fill remaining blocks fillRemaining(0, SRN); // Remove Randomly K digits to make game removeKDigits(); } // Fill the diagonal SRN number of SRN x SRN matrices void fillDiagonal() { for (int i = 0; i < N; i = i + SRN) { // for diagonal box, start coordinates->i==j fillBox(i, i); } } // Returns false if given 3 x 3 block contains num. bool unUsedInBox(int rowStart, int colStart, int num) { for (int i = 0; i < SRN; i++) { for (int j = 0; j < SRN; j++) { if (mat[rowStart + i][colStart + j] == num) { return false; } } } return true; } // Fill a 3 x 3 matrix. void fillBox(int row, int col) { int num; for (int i = 0; i < SRN; i++) { for (int j = 0; j < SRN; j++) { do { num = randomGenerator(N); } while (!unUsedInBox(row, col, num)); mat[row + i][col + j] = num; } } } // Random generator int randomGenerator(int num) { return (int)floor( (float)(rand() / double(RAND_MAX) * num + 1)); } // Check if safe to put in cell bool CheckIfSafe(int i, int j, int num) { return ( unUsedInRow(i, num) && unUsedInCol(j, num) && unUsedInBox(i - i % SRN, j - j % SRN, num)); } // check in the row for existence bool unUsedInRow(int i, int num) { for (int j = 0; j < N; j++) { if (mat[i][j] == num) { return false; } } return true; } // check in the row for existence bool unUsedInCol(int j, int num) { for (int i = 0; i < N; i++) { if (mat[i][j] == num) { return false; } } return true; } // A recursive function to fill remaining // matrix bool fillRemaining(int i, int j) { // System.out.println(i+" "+j); if (j >= N && i < N - 1) { i = i + 1; j = 0; } if (i >= N && j >= N) { return true; } if (i < SRN) { if (j < SRN) { j = SRN; } } else if (i < N - SRN) { if (j == (int)(i / SRN) * SRN) { j = j + SRN; } } else { if (j == N - SRN) { i = i + 1; j = 0; if (i >= N) { return true; } } } for (int num = 1; num <= N; num++) { if (CheckIfSafe(i, j, num)) { mat[i][j] = num; if (fillRemaining(i, j + 1)) { return true; } mat[i][j] = 0; } } return false; } // Remove the K no. of digits to // complete game void removeKDigits() { int count = K; while (count != 0) { int cellId = randomGenerator(N * N) - 1; // System.out.println(cellId); // extract coordinates i and j int i = (cellId / N); int j = cellId % 9; if (j != 0) { j = j - 1; } // System.out.println(i+" "+j); if (mat[i][j] != 0) { count--; mat[i][j] = 0; } } } // Print sudoku void printSudoku() { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << to_string(mat[i][j]) + " "; } cout << endl; } cout << endl; }}; // Driver codeint main(){ int N = 9; int K = 20; Sudoku* sudoku = new Sudoku(N, K); sudoku->fillValues(); sudoku->printSudoku(); return 0;} // This code is contributed by Aarti_Rathi
/* Java program for Sudoku generator */import java.lang.*; public class Sudoku{ int[] mat[]; int N; // number of columns/rows. int SRN; // square root of N int K; // No. Of missing digits // Constructor Sudoku(int N, int K) { this.N = N; this.K = K; // Compute square root of N Double SRNd = Math.sqrt(N); SRN = SRNd.intValue(); mat = new int[N][N]; } // Sudoku Generator public void fillValues() { // Fill the diagonal of SRN x SRN matrices fillDiagonal(); // Fill remaining blocks fillRemaining(0, SRN); // Remove Randomly K digits to make game removeKDigits(); } // Fill the diagonal SRN number of SRN x SRN matrices void fillDiagonal() { for (int i = 0; i<N; i=i+SRN) // for diagonal box, start coordinates->i==j fillBox(i, i); } // Returns false if given 3 x 3 block contains num. boolean unUsedInBox(int rowStart, int colStart, int num) { for (int i = 0; i<SRN; i++) for (int j = 0; j<SRN; j++) if (mat[rowStart+i][colStart+j]==num) return false; return true; } // Fill a 3 x 3 matrix. void fillBox(int row,int col) { int num; for (int i=0; i<SRN; i++) { for (int j=0; j<SRN; j++) { do { num = randomGenerator(N); } while (!unUsedInBox(row, col, num)); mat[row+i][col+j] = num; } } } // Random generator int randomGenerator(int num) { return (int) Math.floor((Math.random()*num+1)); } // Check if safe to put in cell boolean CheckIfSafe(int i,int j,int num) { return (unUsedInRow(i, num) && unUsedInCol(j, num) && unUsedInBox(i-i%SRN, j-j%SRN, num)); } // check in the row for existence boolean unUsedInRow(int i,int num) { for (int j = 0; j<N; j++) if (mat[i][j] == num) return false; return true; } // check in the row for existence boolean unUsedInCol(int j,int num) { for (int i = 0; i<N; i++) if (mat[i][j] == num) return false; return true; } // A recursive function to fill remaining // matrix boolean fillRemaining(int i, int j) { // System.out.println(i+" "+j); if (j>=N && i<N-1) { i = i + 1; j = 0; } if (i>=N && j>=N) return true; if (i < SRN) { if (j < SRN) j = SRN; } else if (i < N-SRN) { if (j==(int)(i/SRN)*SRN) j = j + SRN; } else { if (j == N-SRN) { i = i + 1; j = 0; if (i>=N) return true; } } for (int num = 1; num<=N; num++) { if (CheckIfSafe(i, j, num)) { mat[i][j] = num; if (fillRemaining(i, j+1)) return true; mat[i][j] = 0; } } return false; } // Remove the K no. of digits to // complete game public void removeKDigits() { int count = K; while (count != 0) { int cellId = randomGenerator(N*N)-1; // System.out.println(cellId); // extract coordinates i and j int i = (cellId/N); int j = cellId%9; if (j != 0) j = j - 1; // System.out.println(i+" "+j); if (mat[i][j] != 0) { count--; mat[i][j] = 0; } } } // Print sudoku public void printSudoku() { for (int i = 0; i<N; i++) { for (int j = 0; j<N; j++) System.out.print(mat[i][j] + " "); System.out.println(); } System.out.println(); } // Driver code public static void main(String[] args) { int N = 9, K = 20; Sudoku sudoku = new Sudoku(N, K); sudoku.fillValues(); sudoku.printSudoku(); }}
/* C# program for Sudoku generator */using System; public class Sudoku{ int[,] mat; int N; // number of columns/rows. int SRN; // square root of N int K; // No. Of missing digits // Constructor public Sudoku(int N, int K) { this.N = N; this.K = K; // Compute square root of N double SRNd = Math.Sqrt(N); SRN = (int)SRNd; mat = new int[N,N]; } // Sudoku Generator public void fillValues() { // Fill the diagonal of SRN x SRN matrices fillDiagonal(); // Fill remaining blocks fillRemaining(0, SRN); // Remove Randomly K digits to make game removeKDigits(); } // Fill the diagonal SRN number of SRN x SRN matrices void fillDiagonal() { for (int i = 0; i<N; i=i+SRN) // for diagonal box, start coordinates->i==j fillBox(i, i); } // Returns false if given 3 x 3 block contains num. bool unUsedInBox(int rowStart, int colStart, int num) { for (int i = 0; i<SRN; i++) for (int j = 0; j<SRN; j++) if (mat[rowStart+i,colStart+j]==num) return false; return true; } // Fill a 3 x 3 matrix. void fillBox(int row,int col) { int num; for (int i=0; i<SRN; i++) { for (int j=0; j<SRN; j++) { do { num = randomGenerator(N); } while (!unUsedInBox(row, col, num)); mat[row+i,col+j] = num; } } } // Random generator int randomGenerator(int num) { Random rand = new Random(); return (int) Math.Floor((double)(rand.NextDouble()*num+1)); } // Check if safe to put in cell bool CheckIfSafe(int i,int j,int num) { return (unUsedInRow(i, num) && unUsedInCol(j, num) && unUsedInBox(i-i%SRN, j-j%SRN, num)); } // check in the row for existence bool unUsedInRow(int i,int num) { for (int j = 0; j<N; j++) if (mat[i,j] == num) return false; return true; } // check in the row for existence bool unUsedInCol(int j,int num) { for (int i = 0; i<N; i++) if (mat[i,j] == num) return false; return true; } // A recursive function to fill remaining // matrix bool fillRemaining(int i, int j) { // System.out.println(i+" "+j); if (j>=N && i<N-1) { i = i + 1; j = 0; } if (i>=N && j>=N) return true; if (i < SRN) { if (j < SRN) j = SRN; } else if (i < N-SRN) { if (j==(int)(i/SRN)*SRN) j = j + SRN; } else { if (j == N-SRN) { i = i + 1; j = 0; if (i>=N) return true; } } for (int num = 1; num<=N; num++) { if (CheckIfSafe(i, j, num)) { mat[i,j] = num; if (fillRemaining(i, j+1)) return true; mat[i,j] = 0; } } return false; } // Remove the K no. of digits to // complete game public void removeKDigits() { int count = K; while (count != 0) { int cellId = randomGenerator(N*N)-1; // System.out.println(cellId); // extract coordinates i and j int i = (cellId/N); int j = cellId%9; if (j != 0) j = j - 1; // System.out.println(i+" "+j); if (mat[i,j] != 0) { count--; mat[i,j] = 0; } } } // Print sudoku public void printSudoku() { for (int i = 0; i<N; i++) { for (int j = 0; j<N; j++) Console.Write(mat[i,j] + " "); Console.WriteLine(); } Console.WriteLine(); } // Driver code public static void Main(string[] args) { int N = 9, K = 20; Sudoku sudoku = new Sudoku(N, K); sudoku.fillValues(); sudoku.printSudoku(); }} // This code is contributed by rrrtnx.
Output: [0 means not filled]
2 3 0 4 1 5 0 6 8
0 8 0 2 3 6 5 1 9
1 6 0 9 8 7 2 3 4
3 1 7 0 9 4 0 2 5
4 5 8 1 2 0 6 9 7
9 2 6 0 5 8 3 0 1
0 0 0 5 0 0 1 0 2
0 0 0 8 4 2 9 0 3
5 9 2 3 7 1 4 8 6
Time Complexity: O(N2) Auxiliary Space: O(N2)
This article is contributed by Aarti_Rathi and Ankur Trisal (ankur.trisal@gmail.com). 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.
menonkartikeya
clintra
rrrtnx
codewithshinchan
adi1212
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find largest element in an array
Matrix Chain Multiplication | DP-8
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
Find the number of islands | Set 1 (Using DFS)
Rotate a matrix by 90 degree in clockwise direction without using any extra space
The Celebrity Problem
Unique paths in a Grid with Obstacles
Count all possible paths from top left to bottom right of a mXn matrix
Printing all solutions in N-Queen Problem
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 113,
"s": 52,
"text": "Background: Following are the rules of Sudoku for a player. "
},
{
"code": null,
"e": 330,
"s": 113,
"text": "In all 9 sub matrices 3×3 the elements should be 1-9, without repetition.In all rows there should be elements between 1-9 , without repetition.In all columns there should be elements between 1-9 , without repetition."
},
{
"code": null,
"e": 404,
"s": 330,
"text": "In all 9 sub matrices 3×3 the elements should be 1-9, without repetition."
},
{
"code": null,
"e": 475,
"s": 404,
"text": "In all rows there should be elements between 1-9 , without repetition."
},
{
"code": null,
"e": 549,
"s": 475,
"text": "In all columns there should be elements between 1-9 , without repetition."
},
{
"code": null,
"e": 671,
"s": 549,
"text": "The task is to generate a 9 x 9 Sudoku grid that is valid, i.e., a player can fill the grid following above set of rules."
},
{
"code": null,
"e": 705,
"s": 671,
"text": "A simple naïve solution can be. "
},
{
"code": null,
"e": 994,
"s": 705,
"text": "Randomly take any number 1-9.Check if it is safe to put in the cell.(row , column and box)If safe, place it and increment to next location and go to step 1.If not safe, then without incrementing go to step 1.Once matrix is fully filled, remove k no. of elements randomly to complete game."
},
{
"code": null,
"e": 1024,
"s": 994,
"text": "Randomly take any number 1-9."
},
{
"code": null,
"e": 1086,
"s": 1024,
"text": "Check if it is safe to put in the cell.(row , column and box)"
},
{
"code": null,
"e": 1153,
"s": 1086,
"text": "If safe, place it and increment to next location and go to step 1."
},
{
"code": null,
"e": 1206,
"s": 1153,
"text": "If not safe, then without incrementing go to step 1."
},
{
"code": null,
"e": 1287,
"s": 1206,
"text": "Once matrix is fully filled, remove k no. of elements randomly to complete game."
},
{
"code": null,
"e": 1528,
"s": 1287,
"text": "Improved Solution : We can improve the solution, if we understand a pattern in this game. We can observe that all 3 x 3 matrices, which are diagonally present are independent of other 3 x 3 adjacent matrices initially, as others are empty. "
},
{
"code": null,
"e": 1726,
"s": 1528,
"text": " 3 8 5 0 0 0 0 0 0 \n 9 2 1 0 0 0 0 0 0 \n 6 4 7 0 0 0 0 0 0 \n 0 0 0 1 2 3 0 0 0 \n 0 0 0 7 8 4 0 0 0 \n 0 0 0 6 9 5 0 0 0 \n 0 0 0 0 0 0 8 7 3 \n 0 0 0 0 0 0 9 6 2 \n 0 0 0 0 0 0 1 4 5 "
},
{
"code": null,
"e": 1943,
"s": 1726,
"text": "(We can observe that in above matrix, the diagonal matrices are independent of other empty matrices initially). So if we fill them first, then we will only have to do box check and thus column/row check not required."
},
{
"code": null,
"e": 2093,
"s": 1943,
"text": "Secondly, while we fill rest of the non-diagonal elements, we will not have to use random generator, but we can fill recursively by checking 1 to 9. "
},
{
"code": null,
"e": 2414,
"s": 2093,
"text": "Following is the improved logic for the problem.\n1. Fill all the diagonal 3x3 matrices.\n2. Fill recursively rest of the non-diagonal matrices.\n For every cell to be filled, we try all numbers until\n we find a safe number to be placed. \n3. Once matrix is fully filled, remove K elements\n randomly to complete game."
},
{
"code": null,
"e": 2418,
"s": 2414,
"text": "C++"
},
{
"code": null,
"e": 2423,
"s": 2418,
"text": "Java"
},
{
"code": null,
"e": 2426,
"s": 2423,
"text": "C#"
},
{
"code": "/* C++ program for Sudoku generator */#include <bits/stdc++.h>using namespace std; class Sudoku {public: int** mat; int N; // number of columns/rows. int SRN; // square root of N int K; // No. Of missing digits // Constructor Sudoku(int N, int K) { this->N = N; this->K = K; // Compute square root of N double SRNd = sqrt(N); SRN = (int)SRNd; mat = new int*[N]; // Create a row for every pointer for (int i = 0; i < N; i++) { // Note : Rows may not be contiguous mat[i] = new int[N]; // Initialize all entries as false to indicate // that there are no edges initially memset(mat[i], 0, N * sizeof(int)); } } // Sudoku Generator void fillValues() { // Fill the diagonal of SRN x SRN matrices fillDiagonal(); // Fill remaining blocks fillRemaining(0, SRN); // Remove Randomly K digits to make game removeKDigits(); } // Fill the diagonal SRN number of SRN x SRN matrices void fillDiagonal() { for (int i = 0; i < N; i = i + SRN) { // for diagonal box, start coordinates->i==j fillBox(i, i); } } // Returns false if given 3 x 3 block contains num. bool unUsedInBox(int rowStart, int colStart, int num) { for (int i = 0; i < SRN; i++) { for (int j = 0; j < SRN; j++) { if (mat[rowStart + i][colStart + j] == num) { return false; } } } return true; } // Fill a 3 x 3 matrix. void fillBox(int row, int col) { int num; for (int i = 0; i < SRN; i++) { for (int j = 0; j < SRN; j++) { do { num = randomGenerator(N); } while (!unUsedInBox(row, col, num)); mat[row + i][col + j] = num; } } } // Random generator int randomGenerator(int num) { return (int)floor( (float)(rand() / double(RAND_MAX) * num + 1)); } // Check if safe to put in cell bool CheckIfSafe(int i, int j, int num) { return ( unUsedInRow(i, num) && unUsedInCol(j, num) && unUsedInBox(i - i % SRN, j - j % SRN, num)); } // check in the row for existence bool unUsedInRow(int i, int num) { for (int j = 0; j < N; j++) { if (mat[i][j] == num) { return false; } } return true; } // check in the row for existence bool unUsedInCol(int j, int num) { for (int i = 0; i < N; i++) { if (mat[i][j] == num) { return false; } } return true; } // A recursive function to fill remaining // matrix bool fillRemaining(int i, int j) { // System.out.println(i+\" \"+j); if (j >= N && i < N - 1) { i = i + 1; j = 0; } if (i >= N && j >= N) { return true; } if (i < SRN) { if (j < SRN) { j = SRN; } } else if (i < N - SRN) { if (j == (int)(i / SRN) * SRN) { j = j + SRN; } } else { if (j == N - SRN) { i = i + 1; j = 0; if (i >= N) { return true; } } } for (int num = 1; num <= N; num++) { if (CheckIfSafe(i, j, num)) { mat[i][j] = num; if (fillRemaining(i, j + 1)) { return true; } mat[i][j] = 0; } } return false; } // Remove the K no. of digits to // complete game void removeKDigits() { int count = K; while (count != 0) { int cellId = randomGenerator(N * N) - 1; // System.out.println(cellId); // extract coordinates i and j int i = (cellId / N); int j = cellId % 9; if (j != 0) { j = j - 1; } // System.out.println(i+\" \"+j); if (mat[i][j] != 0) { count--; mat[i][j] = 0; } } } // Print sudoku void printSudoku() { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << to_string(mat[i][j]) + \" \"; } cout << endl; } cout << endl; }}; // Driver codeint main(){ int N = 9; int K = 20; Sudoku* sudoku = new Sudoku(N, K); sudoku->fillValues(); sudoku->printSudoku(); return 0;} // This code is contributed by Aarti_Rathi",
"e": 7294,
"s": 2426,
"text": null
},
{
"code": "/* Java program for Sudoku generator */import java.lang.*; public class Sudoku{ int[] mat[]; int N; // number of columns/rows. int SRN; // square root of N int K; // No. Of missing digits // Constructor Sudoku(int N, int K) { this.N = N; this.K = K; // Compute square root of N Double SRNd = Math.sqrt(N); SRN = SRNd.intValue(); mat = new int[N][N]; } // Sudoku Generator public void fillValues() { // Fill the diagonal of SRN x SRN matrices fillDiagonal(); // Fill remaining blocks fillRemaining(0, SRN); // Remove Randomly K digits to make game removeKDigits(); } // Fill the diagonal SRN number of SRN x SRN matrices void fillDiagonal() { for (int i = 0; i<N; i=i+SRN) // for diagonal box, start coordinates->i==j fillBox(i, i); } // Returns false if given 3 x 3 block contains num. boolean unUsedInBox(int rowStart, int colStart, int num) { for (int i = 0; i<SRN; i++) for (int j = 0; j<SRN; j++) if (mat[rowStart+i][colStart+j]==num) return false; return true; } // Fill a 3 x 3 matrix. void fillBox(int row,int col) { int num; for (int i=0; i<SRN; i++) { for (int j=0; j<SRN; j++) { do { num = randomGenerator(N); } while (!unUsedInBox(row, col, num)); mat[row+i][col+j] = num; } } } // Random generator int randomGenerator(int num) { return (int) Math.floor((Math.random()*num+1)); } // Check if safe to put in cell boolean CheckIfSafe(int i,int j,int num) { return (unUsedInRow(i, num) && unUsedInCol(j, num) && unUsedInBox(i-i%SRN, j-j%SRN, num)); } // check in the row for existence boolean unUsedInRow(int i,int num) { for (int j = 0; j<N; j++) if (mat[i][j] == num) return false; return true; } // check in the row for existence boolean unUsedInCol(int j,int num) { for (int i = 0; i<N; i++) if (mat[i][j] == num) return false; return true; } // A recursive function to fill remaining // matrix boolean fillRemaining(int i, int j) { // System.out.println(i+\" \"+j); if (j>=N && i<N-1) { i = i + 1; j = 0; } if (i>=N && j>=N) return true; if (i < SRN) { if (j < SRN) j = SRN; } else if (i < N-SRN) { if (j==(int)(i/SRN)*SRN) j = j + SRN; } else { if (j == N-SRN) { i = i + 1; j = 0; if (i>=N) return true; } } for (int num = 1; num<=N; num++) { if (CheckIfSafe(i, j, num)) { mat[i][j] = num; if (fillRemaining(i, j+1)) return true; mat[i][j] = 0; } } return false; } // Remove the K no. of digits to // complete game public void removeKDigits() { int count = K; while (count != 0) { int cellId = randomGenerator(N*N)-1; // System.out.println(cellId); // extract coordinates i and j int i = (cellId/N); int j = cellId%9; if (j != 0) j = j - 1; // System.out.println(i+\" \"+j); if (mat[i][j] != 0) { count--; mat[i][j] = 0; } } } // Print sudoku public void printSudoku() { for (int i = 0; i<N; i++) { for (int j = 0; j<N; j++) System.out.print(mat[i][j] + \" \"); System.out.println(); } System.out.println(); } // Driver code public static void main(String[] args) { int N = 9, K = 20; Sudoku sudoku = new Sudoku(N, K); sudoku.fillValues(); sudoku.printSudoku(); }}",
"e": 11602,
"s": 7294,
"text": null
},
{
"code": "/* C# program for Sudoku generator */using System; public class Sudoku{ int[,] mat; int N; // number of columns/rows. int SRN; // square root of N int K; // No. Of missing digits // Constructor public Sudoku(int N, int K) { this.N = N; this.K = K; // Compute square root of N double SRNd = Math.Sqrt(N); SRN = (int)SRNd; mat = new int[N,N]; } // Sudoku Generator public void fillValues() { // Fill the diagonal of SRN x SRN matrices fillDiagonal(); // Fill remaining blocks fillRemaining(0, SRN); // Remove Randomly K digits to make game removeKDigits(); } // Fill the diagonal SRN number of SRN x SRN matrices void fillDiagonal() { for (int i = 0; i<N; i=i+SRN) // for diagonal box, start coordinates->i==j fillBox(i, i); } // Returns false if given 3 x 3 block contains num. bool unUsedInBox(int rowStart, int colStart, int num) { for (int i = 0; i<SRN; i++) for (int j = 0; j<SRN; j++) if (mat[rowStart+i,colStart+j]==num) return false; return true; } // Fill a 3 x 3 matrix. void fillBox(int row,int col) { int num; for (int i=0; i<SRN; i++) { for (int j=0; j<SRN; j++) { do { num = randomGenerator(N); } while (!unUsedInBox(row, col, num)); mat[row+i,col+j] = num; } } } // Random generator int randomGenerator(int num) { Random rand = new Random(); return (int) Math.Floor((double)(rand.NextDouble()*num+1)); } // Check if safe to put in cell bool CheckIfSafe(int i,int j,int num) { return (unUsedInRow(i, num) && unUsedInCol(j, num) && unUsedInBox(i-i%SRN, j-j%SRN, num)); } // check in the row for existence bool unUsedInRow(int i,int num) { for (int j = 0; j<N; j++) if (mat[i,j] == num) return false; return true; } // check in the row for existence bool unUsedInCol(int j,int num) { for (int i = 0; i<N; i++) if (mat[i,j] == num) return false; return true; } // A recursive function to fill remaining // matrix bool fillRemaining(int i, int j) { // System.out.println(i+\" \"+j); if (j>=N && i<N-1) { i = i + 1; j = 0; } if (i>=N && j>=N) return true; if (i < SRN) { if (j < SRN) j = SRN; } else if (i < N-SRN) { if (j==(int)(i/SRN)*SRN) j = j + SRN; } else { if (j == N-SRN) { i = i + 1; j = 0; if (i>=N) return true; } } for (int num = 1; num<=N; num++) { if (CheckIfSafe(i, j, num)) { mat[i,j] = num; if (fillRemaining(i, j+1)) return true; mat[i,j] = 0; } } return false; } // Remove the K no. of digits to // complete game public void removeKDigits() { int count = K; while (count != 0) { int cellId = randomGenerator(N*N)-1; // System.out.println(cellId); // extract coordinates i and j int i = (cellId/N); int j = cellId%9; if (j != 0) j = j - 1; // System.out.println(i+\" \"+j); if (mat[i,j] != 0) { count--; mat[i,j] = 0; } } } // Print sudoku public void printSudoku() { for (int i = 0; i<N; i++) { for (int j = 0; j<N; j++) Console.Write(mat[i,j] + \" \"); Console.WriteLine(); } Console.WriteLine(); } // Driver code public static void Main(string[] args) { int N = 9, K = 20; Sudoku sudoku = new Sudoku(N, K); sudoku.fillValues(); sudoku.printSudoku(); }} // This code is contributed by rrrtnx.",
"e": 15958,
"s": 11602,
"text": null
},
{
"code": null,
"e": 15988,
"s": 15958,
"text": "Output: [0 means not filled] "
},
{
"code": null,
"e": 16159,
"s": 15988,
"text": "2 3 0 4 1 5 0 6 8 \n0 8 0 2 3 6 5 1 9 \n1 6 0 9 8 7 2 3 4 \n3 1 7 0 9 4 0 2 5 \n4 5 8 1 2 0 6 9 7 \n9 2 6 0 5 8 3 0 1 \n0 0 0 5 0 0 1 0 2 \n0 0 0 8 4 2 9 0 3 \n5 9 2 3 7 1 4 8 6 "
},
{
"code": null,
"e": 16205,
"s": 16159,
"text": "Time Complexity: O(N2) Auxiliary Space: O(N2)"
},
{
"code": null,
"e": 16667,
"s": 16205,
"text": "This article is contributed by Aarti_Rathi and Ankur Trisal (ankur.trisal@gmail.com). 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": 16682,
"s": 16667,
"text": "menonkartikeya"
},
{
"code": null,
"e": 16690,
"s": 16682,
"text": "clintra"
},
{
"code": null,
"e": 16697,
"s": 16690,
"text": "rrrtnx"
},
{
"code": null,
"e": 16714,
"s": 16697,
"text": "codewithshinchan"
},
{
"code": null,
"e": 16722,
"s": 16714,
"text": "adi1212"
},
{
"code": null,
"e": 16729,
"s": 16722,
"text": "Matrix"
},
{
"code": null,
"e": 16736,
"s": 16729,
"text": "Matrix"
},
{
"code": null,
"e": 16834,
"s": 16736,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16878,
"s": 16834,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 16913,
"s": 16878,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 16944,
"s": 16913,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 16968,
"s": 16944,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 17015,
"s": 16968,
"text": "Find the number of islands | Set 1 (Using DFS)"
},
{
"code": null,
"e": 17097,
"s": 17015,
"text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space"
},
{
"code": null,
"e": 17119,
"s": 17097,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 17157,
"s": 17119,
"text": "Unique paths in a Grid with Obstacles"
},
{
"code": null,
"e": 17228,
"s": 17157,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
}
] |
Random number generator in arbitrary probability distribution fashion
|
21 Oct, 2021
Given n numbers, each with some frequency of occurrence. Return a random number with probability proportional to its frequency of occurrence.
Example:
Let following be the given numbers.
arr[] = {10, 30, 20, 40}
Let following be the frequencies of given numbers.
freq[] = {1, 6, 2, 1}
The output should be
10 with probability 1/10
30 with probability 6/10
20 with probability 2/10
40 with probability 1/10
It is quite clear that the simple random number generator won’t work here as it doesn’t keep track of the frequency of occurrence.
We need to somehow transform the problem into a problem whose solution is known to us.
One simple method is to take an auxiliary array (say aux[]) and duplicate the numbers according to their frequency of occurrence. Generate a random number(say r) between 0 to Sum-1(including both), where Sum represents summation of frequency array (freq[] in above example). Return the random number aux[r] (Implementation of this method is left as an exercise to the readers).
The limitation of the above method discussed above is huge memory consumption when frequency of occurrence is high. If the input is 997, 8761 and 1, this method is clearly not efficient.
How can we reduce the memory consumption? Following is detailed algorithm that uses O(n) extra space where n is number of elements in input arrays.1. Take an auxiliary array (say prefix[]) of size n. 2. Populate it with prefix sum, such that prefix[i] represents sum of numbers from 0 to i. 3. Generate a random number(say r) between 1 to Sum(including both), where Sum represents summation of input frequency array. 4. Find index of Ceil of random number generated in step #3 in the prefix array. Let the index be indexc. 5. Return the random number arr[indexc], where arr[] contains the input n numbers. Before we go to the implementation part, let us have quick look at the algorithm with an example: arr[]: {10, 20, 30} freq[]: {2, 3, 1} Prefix[]: {2, 5, 6} Since last entry in prefix is 6, all possible values of r are [1, 2, 3, 4, 5, 6] 1: Ceil is 2. Random number generated is 10. 2: Ceil is 2. Random number generated is 10. 3: Ceil is 5. Random number generated is 20. 4: Ceil is 5. Random number generated is 20. 5: Ceil is 5. Random number generated is 20. 6. Ceil is 6. Random number generated is 30. In the above example 10 is generated with probability 2/6. 20 is generated with probability 3/6. 30 is generated with probability 1/6.
How does this work? Any number input[i] is generated as many times as its frequency of occurrence because there exists count of integers in range(prefix[i – 1], prefix[i]] is input[i]. Like in the above example 3 is generated thrice, as there exists 3 integers 3, 4 and 5 whose ceil is 5.
C++
C
Java
Python3
C#
Javascript
// C++ program to generate random numbers// according to given frequency distribution#include <bits/stdc++.h>using namespace std; // Utility function to find ceiling of r in arr[l..h]int findCeil(int arr[], int r, int l, int h){ int mid; while (l < h) { mid = l + ((h - l) >> 1); // Same as mid = (l+h)/2 (r > arr[mid]) ? (l = mid + 1) : (h = mid); } return (arr[l] >= r) ? l : -1;} // The main function that returns a random number// from arr[] according to distribution array// defined by freq[]. n is size of arrays.int myRand(int arr[], int freq[], int n){ // Create and fill prefix array int prefix[n], i; prefix[0] = freq[0]; for (i = 1; i < n; ++i) prefix[i] = prefix[i - 1] + freq[i]; // prefix[n-1] is sum of all frequencies. // Generate a random number with // value from 1 to this sum int r = (rand() % prefix[n - 1]) + 1; // Find index of ceiling of r in prefix array int indexc = findCeil(prefix, r, 0, n - 1); return arr[indexc];} // Driver codeint main(){ int arr[] = {1, 2, 3, 4}; int freq[] = {10, 5, 20, 100}; int i, n = sizeof(arr) / sizeof(arr[0]); // Use a different seed value for every run. srand(time(NULL)); // Let us generate 10 random numbers according to // given distribution for (i = 0; i < 5; i++) cout << myRand(arr, freq, n) << endl; return 0;} // This is code is contributed by rathbhupendra
//C program to generate random numbers according to given frequency distribution#include <stdio.h>#include <stdlib.h> // Utility function to find ceiling of r in arr[l..h]int findCeil(int arr[], int r, int l, int h){ int mid; while (l < h) { mid = l + ((h - l) >> 1); // Same as mid = (l+h)/2 (r > arr[mid]) ? (l = mid + 1) : (h = mid); } return (arr[l] >= r) ? l : -1;} // The main function that returns a random number from arr[] according to// distribution array defined by freq[]. n is size of arrays.int myRand(int arr[], int freq[], int n){ // Create and fill prefix array int prefix[n], i; prefix[0] = freq[0]; for (i = 1; i < n; ++i) prefix[i] = prefix[i - 1] + freq[i]; // prefix[n-1] is sum of all frequencies. Generate a random number // with value from 1 to this sum int r = (rand() % prefix[n - 1]) + 1; // Find index of ceiling of r in prefix array int indexc = findCeil(prefix, r, 0, n - 1); return arr[indexc];} // Driver program to test above functionsint main(){ int arr[] = {1, 2, 3, 4}; int freq[] = {10, 5, 20, 100}; int i, n = sizeof(arr) / sizeof(arr[0]); // Use a different seed value for every run. srand(time(NULL)); // Let us generate 10 random numbers according to // given distribution for (i = 0; i < 5; i++) printf("%d\n", myRand(arr, freq, n)); return 0;}
// Java program to generate random numbers// according to given frequency distributionclass GFG{ // Utility function to find ceiling of r in arr[l..h]static int findCeil(int arr[], int r, int l, int h){ int mid; while (l < h) { mid = l + ((h - l) >> 1); // Same as mid = (l+h)/2 if(r > arr[mid]) l = mid + 1; else h = mid; } return (arr[l] >= r) ? l : -1;} // The main function that returns a random number// from arr[] according to distribution array// defined by freq[]. n is size of arrays.static int myRand(int arr[], int freq[], int n){ // Create and fill prefix array int prefix[] = new int[n], i; prefix[0] = freq[0]; for (i = 1; i < n; ++i) prefix[i] = prefix[i - 1] + freq[i]; // prefix[n-1] is sum of all frequencies. // Generate a random number with // value from 1 to this sum int r = ((int)(Math.random()*(323567)) % prefix[n - 1]) + 1; // Find index of ceiling of r in prefix array int indexc = findCeil(prefix, r, 0, n - 1); return arr[indexc];} // Driver codepublic static void main(String args[]){ int arr[] = {1, 2, 3, 4}; int freq[] = {10, 5, 20, 100}; int i, n = arr.length; // Let us generate 10 random numbers according to // given distribution for (i = 0; i < 5; i++) System.out.println( myRand(arr, freq, n) );}} // This code is contributed by Arnab Kundu
# Python3 program to generate random numbers# according to given frequency distributionimport random # Utility function to find ceiling of r in arr[l..h]def findCeil(arr, r, l, h) : while (l < h) : mid = l + ((h - l) >> 1); # Same as mid = (l+h)/2 if r > arr[mid] : l = mid + 1 else : h = mid if arr[l] >= r : return l else : return -1 # The main function that returns a random number# from arr[] according to distribution array# defined by freq[]. n is size of arrays.def myRand(arr, freq, n) : # Create and fill prefix array prefix = [0] * n prefix[0] = freq[0] for i in range(n) : prefix[i] = prefix[i - 1] + freq[i] # prefix[n-1] is sum of all frequencies. # Generate a random number with # value from 1 to this sum r = random.randint(0, prefix[n - 1]) + 1 # Find index of ceiling of r in prefix array indexc = findCeil(prefix, r, 0, n - 1) return arr[indexc] # Driver codearr = [1, 2, 3, 4]freq = [10, 5, 20, 100]n = len(arr) # Let us generate 10 random numbers according to# given distributionfor i in range(5) : print(myRand(arr, freq, n)) # This code is contributed by divyesh072019
// C# program to generate random numbers// according to given frequency distributionusing System; class GFG{ // Utility function to find ceiling// of r in arr[l..h] static int findCeil(int[] arr, int r, int l, int h) { int mid; while (l < h) { // Same as mid = (l+h)/2 mid = l + ((h - l) >> 1); if (r > arr[mid]) l = mid + 1; else h = mid; } return (arr[l] >= r) ? l : -1; } // The main function that returns a random number// from arr[] according to distribution array // defined by freq[]. n is size of arrays. static int myRand(int[] arr, int[] freq, int n) { // Create and fill prefix array int[] prefix = new int[n]; int i; prefix[0] = freq[0]; for(i = 1; i < n; ++i) prefix[i] = prefix[i - 1] + freq[i]; // prefix[n-1] is sum of all frequencies. // Generate a random number with // value from 1 to this sum Random rand = new Random(); int r = ((int)(rand.Next() * (323567)) % prefix[n - 1]) + 1; // Find index of ceiling of r in prefix array int indexc = findCeil(prefix, r, 0, n - 1); return arr[indexc]; } // Driver Codestatic void Main(){ int[] arr = { 1, 2, 3, 4 }; int[] freq = { 10, 5, 20, 100 }; int i, n = arr.Length; // Let us generate 10 random numbers // according to given distribution for(i = 0; i < 5; i++) Console.WriteLine(myRand(arr, freq, n)); }} // This code is contributed by divyeshrabadiya07
<script> // JavaScript program to generate random numbers// according to given frequency distribution // Utility function to find ceiling of r in arr[l..h] function findCeil(arr, r, l, h) { let mid; while (l < h) { mid = l + ((h - l) >> 1); // Same as mid = (l+h)/2 (r > arr[mid]) ? (l = mid + 1) : (h = mid); } return (arr[l] >= r) ? l : -1; } // The main function that returns a random number // from arr[] according to distribution array // defined by freq[]. n is size of arrays. function myRand(arr, freq, n) { // Create and fill prefix array let prefix= []; let i; prefix[0] = freq[0]; for (i = 1; i < n; ++i) prefix[i] = prefix[i - 1] + freq[i]; // prefix[n-1] is sum of all frequencies. // Generate a random number with // value from 1 to this sum let r = Math.floor((Math.random()* prefix[n - 1])) + 1; // Find index of ceiling of r in prefix array let indexc = findCeil(prefix, r, 0, n - 1); return arr[indexc]; } // Driver code let arr = [1, 2, 3, 4]; let freq = [10, 5, 20, 100]; let i; let n = arr.length; // Use a different seed value for every run. // Let us generate 10 random numbers according to // given distribution for (i = 0; i < 5; i++) document.write(myRand(arr, freq, n)); // This code is contributed by rohitsingh07052.</script>
Output: May be different for different runs
4
3
4
4
4
Time Complexity: O(n)
This article is compiled by Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
rathbhupendra
pankaj182
andrew1234
divyeshrabadiya07
divyesh072019
rohitsingh07052
abhishek0719kadiyan
surindertarika1234
subhammahato348
prefix-sum
Mathematical
Randomized
prefix-sum
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Sieve of Eratosthenes
Prime Numbers
Program to find GCD or HCF of two numbers
K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
Shuffle a given array using Fisher–Yates shuffle Algorithm
QuickSort using Random Pivoting
Shuffle or Randomize a list in Java
Generating Random String Using PHP
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 194,
"s": 52,
"text": "Given n numbers, each with some frequency of occurrence. Return a random number with probability proportional to its frequency of occurrence."
},
{
"code": null,
"e": 204,
"s": 194,
"text": "Example: "
},
{
"code": null,
"e": 477,
"s": 204,
"text": "Let following be the given numbers.\n arr[] = {10, 30, 20, 40} \n\nLet following be the frequencies of given numbers.\n freq[] = {1, 6, 2, 1} \n\nThe output should be\n 10 with probability 1/10\n 30 with probability 6/10\n 20 with probability 2/10\n 40 with probability 1/10"
},
{
"code": null,
"e": 609,
"s": 477,
"text": "It is quite clear that the simple random number generator won’t work here as it doesn’t keep track of the frequency of occurrence. "
},
{
"code": null,
"e": 696,
"s": 609,
"text": "We need to somehow transform the problem into a problem whose solution is known to us."
},
{
"code": null,
"e": 1074,
"s": 696,
"text": "One simple method is to take an auxiliary array (say aux[]) and duplicate the numbers according to their frequency of occurrence. Generate a random number(say r) between 0 to Sum-1(including both), where Sum represents summation of frequency array (freq[] in above example). Return the random number aux[r] (Implementation of this method is left as an exercise to the readers)."
},
{
"code": null,
"e": 1261,
"s": 1074,
"text": "The limitation of the above method discussed above is huge memory consumption when frequency of occurrence is high. If the input is 997, 8761 and 1, this method is clearly not efficient."
},
{
"code": null,
"e": 2604,
"s": 1261,
"text": "How can we reduce the memory consumption? Following is detailed algorithm that uses O(n) extra space where n is number of elements in input arrays.1. Take an auxiliary array (say prefix[]) of size n. 2. Populate it with prefix sum, such that prefix[i] represents sum of numbers from 0 to i. 3. Generate a random number(say r) between 1 to Sum(including both), where Sum represents summation of input frequency array. 4. Find index of Ceil of random number generated in step #3 in the prefix array. Let the index be indexc. 5. Return the random number arr[indexc], where arr[] contains the input n numbers. Before we go to the implementation part, let us have quick look at the algorithm with an example: arr[]: {10, 20, 30} freq[]: {2, 3, 1} Prefix[]: {2, 5, 6} Since last entry in prefix is 6, all possible values of r are [1, 2, 3, 4, 5, 6] 1: Ceil is 2. Random number generated is 10. 2: Ceil is 2. Random number generated is 10. 3: Ceil is 5. Random number generated is 20. 4: Ceil is 5. Random number generated is 20. 5: Ceil is 5. Random number generated is 20. 6. Ceil is 6. Random number generated is 30. In the above example 10 is generated with probability 2/6. 20 is generated with probability 3/6. 30 is generated with probability 1/6."
},
{
"code": null,
"e": 2894,
"s": 2604,
"text": "How does this work? Any number input[i] is generated as many times as its frequency of occurrence because there exists count of integers in range(prefix[i – 1], prefix[i]] is input[i]. Like in the above example 3 is generated thrice, as there exists 3 integers 3, 4 and 5 whose ceil is 5. "
},
{
"code": null,
"e": 2898,
"s": 2894,
"text": "C++"
},
{
"code": null,
"e": 2900,
"s": 2898,
"text": "C"
},
{
"code": null,
"e": 2905,
"s": 2900,
"text": "Java"
},
{
"code": null,
"e": 2913,
"s": 2905,
"text": "Python3"
},
{
"code": null,
"e": 2916,
"s": 2913,
"text": "C#"
},
{
"code": null,
"e": 2927,
"s": 2916,
"text": "Javascript"
},
{
"code": "// C++ program to generate random numbers// according to given frequency distribution#include <bits/stdc++.h>using namespace std; // Utility function to find ceiling of r in arr[l..h]int findCeil(int arr[], int r, int l, int h){ int mid; while (l < h) { mid = l + ((h - l) >> 1); // Same as mid = (l+h)/2 (r > arr[mid]) ? (l = mid + 1) : (h = mid); } return (arr[l] >= r) ? l : -1;} // The main function that returns a random number// from arr[] according to distribution array// defined by freq[]. n is size of arrays.int myRand(int arr[], int freq[], int n){ // Create and fill prefix array int prefix[n], i; prefix[0] = freq[0]; for (i = 1; i < n; ++i) prefix[i] = prefix[i - 1] + freq[i]; // prefix[n-1] is sum of all frequencies. // Generate a random number with // value from 1 to this sum int r = (rand() % prefix[n - 1]) + 1; // Find index of ceiling of r in prefix array int indexc = findCeil(prefix, r, 0, n - 1); return arr[indexc];} // Driver codeint main(){ int arr[] = {1, 2, 3, 4}; int freq[] = {10, 5, 20, 100}; int i, n = sizeof(arr) / sizeof(arr[0]); // Use a different seed value for every run. srand(time(NULL)); // Let us generate 10 random numbers according to // given distribution for (i = 0; i < 5; i++) cout << myRand(arr, freq, n) << endl; return 0;} // This is code is contributed by rathbhupendra",
"e": 4357,
"s": 2927,
"text": null
},
{
"code": "//C program to generate random numbers according to given frequency distribution#include <stdio.h>#include <stdlib.h> // Utility function to find ceiling of r in arr[l..h]int findCeil(int arr[], int r, int l, int h){ int mid; while (l < h) { mid = l + ((h - l) >> 1); // Same as mid = (l+h)/2 (r > arr[mid]) ? (l = mid + 1) : (h = mid); } return (arr[l] >= r) ? l : -1;} // The main function that returns a random number from arr[] according to// distribution array defined by freq[]. n is size of arrays.int myRand(int arr[], int freq[], int n){ // Create and fill prefix array int prefix[n], i; prefix[0] = freq[0]; for (i = 1; i < n; ++i) prefix[i] = prefix[i - 1] + freq[i]; // prefix[n-1] is sum of all frequencies. Generate a random number // with value from 1 to this sum int r = (rand() % prefix[n - 1]) + 1; // Find index of ceiling of r in prefix array int indexc = findCeil(prefix, r, 0, n - 1); return arr[indexc];} // Driver program to test above functionsint main(){ int arr[] = {1, 2, 3, 4}; int freq[] = {10, 5, 20, 100}; int i, n = sizeof(arr) / sizeof(arr[0]); // Use a different seed value for every run. srand(time(NULL)); // Let us generate 10 random numbers according to // given distribution for (i = 0; i < 5; i++) printf(\"%d\\n\", myRand(arr, freq, n)); return 0;}",
"e": 5751,
"s": 4357,
"text": null
},
{
"code": "// Java program to generate random numbers// according to given frequency distributionclass GFG{ // Utility function to find ceiling of r in arr[l..h]static int findCeil(int arr[], int r, int l, int h){ int mid; while (l < h) { mid = l + ((h - l) >> 1); // Same as mid = (l+h)/2 if(r > arr[mid]) l = mid + 1; else h = mid; } return (arr[l] >= r) ? l : -1;} // The main function that returns a random number// from arr[] according to distribution array// defined by freq[]. n is size of arrays.static int myRand(int arr[], int freq[], int n){ // Create and fill prefix array int prefix[] = new int[n], i; prefix[0] = freq[0]; for (i = 1; i < n; ++i) prefix[i] = prefix[i - 1] + freq[i]; // prefix[n-1] is sum of all frequencies. // Generate a random number with // value from 1 to this sum int r = ((int)(Math.random()*(323567)) % prefix[n - 1]) + 1; // Find index of ceiling of r in prefix array int indexc = findCeil(prefix, r, 0, n - 1); return arr[indexc];} // Driver codepublic static void main(String args[]){ int arr[] = {1, 2, 3, 4}; int freq[] = {10, 5, 20, 100}; int i, n = arr.length; // Let us generate 10 random numbers according to // given distribution for (i = 0; i < 5; i++) System.out.println( myRand(arr, freq, n) );}} // This code is contributed by Arnab Kundu",
"e": 7153,
"s": 5751,
"text": null
},
{
"code": "# Python3 program to generate random numbers# according to given frequency distributionimport random # Utility function to find ceiling of r in arr[l..h]def findCeil(arr, r, l, h) : while (l < h) : mid = l + ((h - l) >> 1); # Same as mid = (l+h)/2 if r > arr[mid] : l = mid + 1 else : h = mid if arr[l] >= r : return l else : return -1 # The main function that returns a random number# from arr[] according to distribution array# defined by freq[]. n is size of arrays.def myRand(arr, freq, n) : # Create and fill prefix array prefix = [0] * n prefix[0] = freq[0] for i in range(n) : prefix[i] = prefix[i - 1] + freq[i] # prefix[n-1] is sum of all frequencies. # Generate a random number with # value from 1 to this sum r = random.randint(0, prefix[n - 1]) + 1 # Find index of ceiling of r in prefix array indexc = findCeil(prefix, r, 0, n - 1) return arr[indexc] # Driver codearr = [1, 2, 3, 4]freq = [10, 5, 20, 100]n = len(arr) # Let us generate 10 random numbers according to# given distributionfor i in range(5) : print(myRand(arr, freq, n)) # This code is contributed by divyesh072019",
"e": 8369,
"s": 7153,
"text": null
},
{
"code": "// C# program to generate random numbers// according to given frequency distributionusing System; class GFG{ // Utility function to find ceiling// of r in arr[l..h] static int findCeil(int[] arr, int r, int l, int h) { int mid; while (l < h) { // Same as mid = (l+h)/2 mid = l + ((h - l) >> 1); if (r > arr[mid]) l = mid + 1; else h = mid; } return (arr[l] >= r) ? l : -1; } // The main function that returns a random number// from arr[] according to distribution array // defined by freq[]. n is size of arrays. static int myRand(int[] arr, int[] freq, int n) { // Create and fill prefix array int[] prefix = new int[n]; int i; prefix[0] = freq[0]; for(i = 1; i < n; ++i) prefix[i] = prefix[i - 1] + freq[i]; // prefix[n-1] is sum of all frequencies. // Generate a random number with // value from 1 to this sum Random rand = new Random(); int r = ((int)(rand.Next() * (323567)) % prefix[n - 1]) + 1; // Find index of ceiling of r in prefix array int indexc = findCeil(prefix, r, 0, n - 1); return arr[indexc]; } // Driver Codestatic void Main(){ int[] arr = { 1, 2, 3, 4 }; int[] freq = { 10, 5, 20, 100 }; int i, n = arr.Length; // Let us generate 10 random numbers // according to given distribution for(i = 0; i < 5; i++) Console.WriteLine(myRand(arr, freq, n)); }} // This code is contributed by divyeshrabadiya07",
"e": 9930,
"s": 8369,
"text": null
},
{
"code": "<script> // JavaScript program to generate random numbers// according to given frequency distribution // Utility function to find ceiling of r in arr[l..h] function findCeil(arr, r, l, h) { let mid; while (l < h) { mid = l + ((h - l) >> 1); // Same as mid = (l+h)/2 (r > arr[mid]) ? (l = mid + 1) : (h = mid); } return (arr[l] >= r) ? l : -1; } // The main function that returns a random number // from arr[] according to distribution array // defined by freq[]. n is size of arrays. function myRand(arr, freq, n) { // Create and fill prefix array let prefix= []; let i; prefix[0] = freq[0]; for (i = 1; i < n; ++i) prefix[i] = prefix[i - 1] + freq[i]; // prefix[n-1] is sum of all frequencies. // Generate a random number with // value from 1 to this sum let r = Math.floor((Math.random()* prefix[n - 1])) + 1; // Find index of ceiling of r in prefix array let indexc = findCeil(prefix, r, 0, n - 1); return arr[indexc]; } // Driver code let arr = [1, 2, 3, 4]; let freq = [10, 5, 20, 100]; let i; let n = arr.length; // Use a different seed value for every run. // Let us generate 10 random numbers according to // given distribution for (i = 0; i < 5; i++) document.write(myRand(arr, freq, n)); // This code is contributed by rohitsingh07052.</script>",
"e": 11416,
"s": 9930,
"text": null
},
{
"code": null,
"e": 11461,
"s": 11416,
"text": "Output: May be different for different runs "
},
{
"code": null,
"e": 11471,
"s": 11461,
"text": "4\n3\n4\n4\n4"
},
{
"code": null,
"e": 11493,
"s": 11471,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 11664,
"s": 11493,
"text": "This article is compiled by Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 11678,
"s": 11664,
"text": "rathbhupendra"
},
{
"code": null,
"e": 11688,
"s": 11678,
"text": "pankaj182"
},
{
"code": null,
"e": 11699,
"s": 11688,
"text": "andrew1234"
},
{
"code": null,
"e": 11717,
"s": 11699,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 11731,
"s": 11717,
"text": "divyesh072019"
},
{
"code": null,
"e": 11747,
"s": 11731,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 11767,
"s": 11747,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 11786,
"s": 11767,
"text": "surindertarika1234"
},
{
"code": null,
"e": 11802,
"s": 11786,
"text": "subhammahato348"
},
{
"code": null,
"e": 11813,
"s": 11802,
"text": "prefix-sum"
},
{
"code": null,
"e": 11826,
"s": 11813,
"text": "Mathematical"
},
{
"code": null,
"e": 11837,
"s": 11826,
"text": "Randomized"
},
{
"code": null,
"e": 11848,
"s": 11837,
"text": "prefix-sum"
},
{
"code": null,
"e": 11861,
"s": 11848,
"text": "Mathematical"
},
{
"code": null,
"e": 11959,
"s": 11861,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11983,
"s": 11959,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 12004,
"s": 11983,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 12026,
"s": 12004,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 12040,
"s": 12026,
"text": "Prime Numbers"
},
{
"code": null,
"e": 12082,
"s": 12040,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 12161,
"s": 12082,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)"
},
{
"code": null,
"e": 12220,
"s": 12161,
"text": "Shuffle a given array using Fisher–Yates shuffle Algorithm"
},
{
"code": null,
"e": 12252,
"s": 12220,
"text": "QuickSort using Random Pivoting"
},
{
"code": null,
"e": 12288,
"s": 12252,
"text": "Shuffle or Randomize a list in Java"
}
] |
priority_queue::push() and priority_queue::pop() in C++ STL
|
14 Jun, 2022
Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. However, in C++ STL (by default) the largest element is at the top. We can also create a priority queue having the smallest element at the top by simply passing an extra parameter while creating the priority queue.
push() function is used to insert an element in the priority queue. The element is added to the priority queue container and the size of the queue is increased by 1. Firstly, the element is added at the back and at the same time the elements of the priority queue reorder themselves according to priority.
Syntax :
pqueuename.push(value)
Parameters :
The value of the element to be inserted is passed as the parameter.
Result :
Adds an element of value same as that of
the parameter passed in the priority queue.
Examples:
Input : pqueue
pqueue.push(6);
Output : 6
Input : pqueue = 5, 2, 1
pqueue.push(3);
Output : 5, 3, 2, 1
Errors and Exceptions 1. Shows error if the value passed doesn’t match the priority queue type. 2. Shows no exception throw guarantee if the parameter doesn’t throw any exception.
CPP
// CPP program to illustrate// Implementation of push() function#include <iostream>#include <queue>using namespace std; int main(){ // Empty Queue priority_queue<int> pqueue; pqueue.push(3); pqueue.push(5); pqueue.push(1); pqueue.push(2); // Priority queue becomes 5, 3, 2, 1 // Printing content of queue while (!pqueue.empty()) { cout << ' ' << pqueue.top(); pqueue.pop(); }}
Output:
5 3 2 1
pop() function is used to remove the top element of the priority queue.
Syntax :
pqueuename.pop()
Parameters :
No parameters are passed.
Result :
The top element of the priority
queue is removed.
Examples:
Input : pqueue = 3, 2, 1
myqueue.pop();
Output : 2, 1
Input : pqueue = 5, 3, 2, 1
pqueue.pop();
Output : 3, 2, 1
Errors and Exceptions 1. Shows error if a parameter is passed. 2. Shows no exception throw guarantee if the parameter doesn’t throw any exception.
CPP
// CPP program to illustrate// Implementation of pop() function#include <iostream>#include <queue>using namespace std; int main(){ // Empty Priority Queue priority_queue<int> pqueue; pqueue.push(0); pqueue.push(1); pqueue.push(2); // queue becomes 2, 1, 0 pqueue.pop(); pqueue.pop(); // queue becomes 0 // Printing content of priority queue while (!pqueue.empty()) { cout << ' ' << pqueue.top(); pqueue.pop(); }}
Output:
0
Application : push() and pop() Given a number of integers, add them to the priority queue and find the size of the priority queue without using size function.
Input : 5, 13, 0, 9, 4
Output: 5
Algorithm 1. Push the given elements to the priority queue container one by one. 2. Keep popping the elements of priority queue until it becomes empty, and increment the counter variable. 3. Print the counter variable.
CPP
// CPP program to illustrate// Application of push() and pop() function#include <iostream>#include <queue>using namespace std; int main(){ int c = 0; // Empty Priority Queue priority_queue<int> pqueue; pqueue.push(5); pqueue.push(13); pqueue.push(0); pqueue.push(9); pqueue.push(4); // Priority queue becomes 13, 9, 5, 4, 0 // Counting number of elements in queue while (!pqueue.empty()) { pqueue.pop(); c++; } cout << c;}
Output:
5
yasharth234
divyanshmishra101010
CPP-Library
cpp-priority-queue
cpp-queue
STL
C++
STL
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": 52,
"s": 24,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 449,
"s": 52,
"text": "Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. However, in C++ STL (by default) the largest element is at the top. We can also create a priority queue having the smallest element at the top by simply passing an extra parameter while creating the priority queue."
},
{
"code": null,
"e": 756,
"s": 449,
"text": "push() function is used to insert an element in the priority queue. The element is added to the priority queue container and the size of the queue is increased by 1. Firstly, the element is added at the back and at the same time the elements of the priority queue reorder themselves according to priority. "
},
{
"code": null,
"e": 765,
"s": 756,
"text": "Syntax :"
},
{
"code": null,
"e": 964,
"s": 765,
"text": "pqueuename.push(value)\nParameters :\nThe value of the element to be inserted is passed as the parameter.\nResult :\nAdds an element of value same as that of \nthe parameter passed in the priority queue."
},
{
"code": null,
"e": 974,
"s": 964,
"text": "Examples:"
},
{
"code": null,
"e": 1098,
"s": 974,
"text": "Input : pqueue\n pqueue.push(6);\nOutput : 6\n\nInput : pqueue = 5, 2, 1\n pqueue.push(3);\nOutput : 5, 3, 2, 1"
},
{
"code": null,
"e": 1279,
"s": 1098,
"text": "Errors and Exceptions 1. Shows error if the value passed doesn’t match the priority queue type. 2. Shows no exception throw guarantee if the parameter doesn’t throw any exception. "
},
{
"code": null,
"e": 1283,
"s": 1279,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// Implementation of push() function#include <iostream>#include <queue>using namespace std; int main(){ // Empty Queue priority_queue<int> pqueue; pqueue.push(3); pqueue.push(5); pqueue.push(1); pqueue.push(2); // Priority queue becomes 5, 3, 2, 1 // Printing content of queue while (!pqueue.empty()) { cout << ' ' << pqueue.top(); pqueue.pop(); }}",
"e": 1705,
"s": 1283,
"text": null
},
{
"code": null,
"e": 1713,
"s": 1705,
"text": "Output:"
},
{
"code": null,
"e": 1721,
"s": 1713,
"text": "5 3 2 1"
},
{
"code": null,
"e": 1794,
"s": 1721,
"text": "pop() function is used to remove the top element of the priority queue. "
},
{
"code": null,
"e": 1803,
"s": 1794,
"text": "Syntax :"
},
{
"code": null,
"e": 1918,
"s": 1803,
"text": "pqueuename.pop()\nParameters :\nNo parameters are passed.\nResult :\nThe top element of the priority\nqueue is removed."
},
{
"code": null,
"e": 1928,
"s": 1918,
"text": "Examples:"
},
{
"code": null,
"e": 2062,
"s": 1928,
"text": "Input : pqueue = 3, 2, 1\n myqueue.pop();\nOutput : 2, 1\n\nInput : pqueue = 5, 3, 2, 1\n pqueue.pop();\nOutput : 3, 2, 1"
},
{
"code": null,
"e": 2210,
"s": 2062,
"text": "Errors and Exceptions 1. Shows error if a parameter is passed. 2. Shows no exception throw guarantee if the parameter doesn’t throw any exception. "
},
{
"code": null,
"e": 2214,
"s": 2210,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// Implementation of pop() function#include <iostream>#include <queue>using namespace std; int main(){ // Empty Priority Queue priority_queue<int> pqueue; pqueue.push(0); pqueue.push(1); pqueue.push(2); // queue becomes 2, 1, 0 pqueue.pop(); pqueue.pop(); // queue becomes 0 // Printing content of priority queue while (!pqueue.empty()) { cout << ' ' << pqueue.top(); pqueue.pop(); }}",
"e": 2679,
"s": 2214,
"text": null
},
{
"code": null,
"e": 2687,
"s": 2679,
"text": "Output:"
},
{
"code": null,
"e": 2689,
"s": 2687,
"text": "0"
},
{
"code": null,
"e": 2848,
"s": 2689,
"text": "Application : push() and pop() Given a number of integers, add them to the priority queue and find the size of the priority queue without using size function."
},
{
"code": null,
"e": 2881,
"s": 2848,
"text": "Input : 5, 13, 0, 9, 4\nOutput: 5"
},
{
"code": null,
"e": 3101,
"s": 2881,
"text": "Algorithm 1. Push the given elements to the priority queue container one by one. 2. Keep popping the elements of priority queue until it becomes empty, and increment the counter variable. 3. Print the counter variable. "
},
{
"code": null,
"e": 3105,
"s": 3101,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// Application of push() and pop() function#include <iostream>#include <queue>using namespace std; int main(){ int c = 0; // Empty Priority Queue priority_queue<int> pqueue; pqueue.push(5); pqueue.push(13); pqueue.push(0); pqueue.push(9); pqueue.push(4); // Priority queue becomes 13, 9, 5, 4, 0 // Counting number of elements in queue while (!pqueue.empty()) { pqueue.pop(); c++; } cout << c;}",
"e": 3582,
"s": 3105,
"text": null
},
{
"code": null,
"e": 3590,
"s": 3582,
"text": "Output:"
},
{
"code": null,
"e": 3592,
"s": 3590,
"text": "5"
},
{
"code": null,
"e": 3604,
"s": 3592,
"text": "yasharth234"
},
{
"code": null,
"e": 3625,
"s": 3604,
"text": "divyanshmishra101010"
},
{
"code": null,
"e": 3637,
"s": 3625,
"text": "CPP-Library"
},
{
"code": null,
"e": 3656,
"s": 3637,
"text": "cpp-priority-queue"
},
{
"code": null,
"e": 3666,
"s": 3656,
"text": "cpp-queue"
},
{
"code": null,
"e": 3670,
"s": 3666,
"text": "STL"
},
{
"code": null,
"e": 3674,
"s": 3670,
"text": "C++"
},
{
"code": null,
"e": 3678,
"s": 3674,
"text": "STL"
},
{
"code": null,
"e": 3682,
"s": 3678,
"text": "CPP"
},
{
"code": null,
"e": 3780,
"s": 3682,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3804,
"s": 3780,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 3824,
"s": 3804,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 3857,
"s": 3824,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 3901,
"s": 3857,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3926,
"s": 3901,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3971,
"s": 3926,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4019,
"s": 3971,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 4036,
"s": 4019,
"text": "std::find in C++"
},
{
"code": null,
"e": 4080,
"s": 4036,
"text": "List in C++ Standard Template Library (STL)"
}
] |
How to Install python-nmap Library on Linux?
|
05 Oct, 2021
Python-Nmap is a network mapper that is exceptionally vital in handling security auditing and discovering the network. It exists as an open-source project; thus it is available for free.
All the core operating systems support Python-Nmap. However, the binary packages are only available for Windows, Linux, and Mac OS X. Nmap is essential in port scanning tasks by manipulating Nmap scanning results programmatically. Here we are going to see how to install python-nmap Library in Linux.
Os Detection – This involves identifying the host Operating System as well as the network device’s hardware characteristics
Port Scanning – Nmap can count and list the entire target and open ports
Scriptable interaction with the target – In Nmap, we can write scripts that carry out operations on the networking devices with Nmap Scripting Engine combined with Lua programming languages.
Version Detection – We can establish the application version number and application name by interrogating the network services located on the remote devices.
Host Discovery – This is the concept when we want to find out the hosts in a particular network. For instance, when we want to find out if specific ports are open. Or when they make ICMP requests. Besides, Nmap can also list hosts responding to TCP.
There are two varied ways to test the Nmap methods:
Method 1: The first approach is writing scripts in python and running them on the terminal using the following command.
root@gfg:~# python script_name.py
# script_name.py
import nmap
nmap =nmap.PortScanner()
host = '127.0.0.1'
nmap.scan(host, '1-10')
print(nmap.command_line())
testing Nmap methods using a script
Method 2: The second approach involves testing the Nmap methods over a command-line interface. To achieve this, open the terminal and run the command “python” so that you get an interface like the one below.
Run the following command
root@gfg:~# sudo apt-get install nmap
We also need the python module called python-nmap. It is responsible for host and service discovery within the computers’ network. It does so by analyzing responses from identified hosts after initializing sending specific packets to these hosts.
There are two ways to install python-nmap. The first involves installation on the terminal while the second one involves downloading the python-nmap library and doing a manual installation.
So we will run the following command:
root@gfg:~# pip install python-nmap
In this second approach, we will list all the steps necessary to download the python-nmap library till it is ready for use.
Step 1: Download python-nmap library using wget as follows.
root@gfg:~# wget http://xael.org/norman/python/python-nmap/python-nmap-0.1.4.tar.gz
Download python-nmap library using wget
Step 2: Use tar to extract the contents
root@gfg:~# tar xf python-nmap-0.1.4.tar.gz
Use tar to extract the contents
Step 3: Change directory to the extracted contents
root@gfg:~# cd python-nmap-0.1.4
Change directory to the extracted contents
Step 4: Installation of Python-Nmap
root@gfg:~# python setup.py install
Installation of Python-Nmap
Step 5: Confirm that Python-Nmap is successfully installed and ready for use.
root@gfg:~# python
Confirm that Python-Nmap is successfully installed and ready for use
We also need a virtual environment to separate concerns between the different modules and to differentiate the other projects. This is important if you decide to write python scripts and run them instead of the command-line interface.
The following command will aid in the creation of a virtual environment
python -m venv my_virtual_environment_name
Open the terminal by pressing Ctrl + Alt + T on the keyboard. Then, type the word python and press enter on your keyboard
root@gfg:~# python
To test the various Nmap commands, we will first import the Nmap module using the following command.
>>> import nmap
Next, we need to instantiate the Nmap’s port scanner as follows
>>> nmap =nmap.PortScanner()
>>> host = '127.0.0.1'
What’s next is setting both the port and host range to scan as below:
>>> nmap.scan(host, '1-10')
Next, we can print the command_line command used for the scan as shown
>>> print(nmap.command_line())
Using Nmap to get the hostname of 127.0.0.1
>>> nmap['127.0.0.1'].hostname()
'localhost'
>>>
If we want to get scan information on the Nmap, do as follows:
>>> print nmap.scaninfo()
The results will be like:
{'tcp': {'services': '1-10', 'method': 'connect'}}
To scan every host, we need to run the following commands
>>> for host in nmap.all_hosts():
... print('Host : %s (%s)' % (host, nmap[host].hostname()))
... print('State : %s' % nmap[host].state())
Similarly, we can also scan for all the protocols. It returns the protocol for the specific network being scanned.
>>> nmap['127.0.0.1'].all_protocols()
The result in our case was:
[tcp]
Get the state of a specific host as follows
>>> nmap['127.0.0.1'].state()
It will be indicated if the host is up or down. In our case,
'up'
Keys() method is responsible for displaying information on all the active ports while providing the range. The following is how to use the keys() method.
>>> nmap['127.0.0.1']['tcp'].keys()
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>
Validate port information of a given port. For instance, for 20 on the given host is as follows
>>> nmap['127.0.0.1'].has_tcp(20)
False
>>>
how-to-install
Picked
How To
Installation Guide
Linux-Unix
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Install Git in VS Code?
Installation of Node.js on Linux
Installation of Node.js on Windows
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Pygame on Windows ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 217,
"s": 28,
"text": "Python-Nmap is a network mapper that is exceptionally vital in handling security auditing and discovering the network. It exists as an open-source project; thus it is available for free. "
},
{
"code": null,
"e": 518,
"s": 217,
"text": "All the core operating systems support Python-Nmap. However, the binary packages are only available for Windows, Linux, and Mac OS X. Nmap is essential in port scanning tasks by manipulating Nmap scanning results programmatically. Here we are going to see how to install python-nmap Library in Linux."
},
{
"code": null,
"e": 642,
"s": 518,
"text": "Os Detection – This involves identifying the host Operating System as well as the network device’s hardware characteristics"
},
{
"code": null,
"e": 715,
"s": 642,
"text": "Port Scanning – Nmap can count and list the entire target and open ports"
},
{
"code": null,
"e": 906,
"s": 715,
"text": "Scriptable interaction with the target – In Nmap, we can write scripts that carry out operations on the networking devices with Nmap Scripting Engine combined with Lua programming languages."
},
{
"code": null,
"e": 1064,
"s": 906,
"text": "Version Detection – We can establish the application version number and application name by interrogating the network services located on the remote devices."
},
{
"code": null,
"e": 1315,
"s": 1064,
"text": "Host Discovery – This is the concept when we want to find out the hosts in a particular network. For instance, when we want to find out if specific ports are open. Or when they make ICMP requests. Besides, Nmap can also list hosts responding to TCP."
},
{
"code": null,
"e": 1367,
"s": 1315,
"text": "There are two varied ways to test the Nmap methods:"
},
{
"code": null,
"e": 1487,
"s": 1367,
"text": "Method 1: The first approach is writing scripts in python and running them on the terminal using the following command."
},
{
"code": null,
"e": 1521,
"s": 1487,
"text": "root@gfg:~# python script_name.py"
},
{
"code": null,
"e": 1646,
"s": 1521,
"text": "# script_name.py\n\nimport nmap\nnmap =nmap.PortScanner()\nhost = '127.0.0.1'\nnmap.scan(host, '1-10')\nprint(nmap.command_line())"
},
{
"code": null,
"e": 1682,
"s": 1646,
"text": "testing Nmap methods using a script"
},
{
"code": null,
"e": 1890,
"s": 1682,
"text": "Method 2: The second approach involves testing the Nmap methods over a command-line interface. To achieve this, open the terminal and run the command “python” so that you get an interface like the one below."
},
{
"code": null,
"e": 1916,
"s": 1890,
"text": "Run the following command"
},
{
"code": null,
"e": 1954,
"s": 1916,
"text": "root@gfg:~# sudo apt-get install nmap"
},
{
"code": null,
"e": 2201,
"s": 1954,
"text": "We also need the python module called python-nmap. It is responsible for host and service discovery within the computers’ network. It does so by analyzing responses from identified hosts after initializing sending specific packets to these hosts."
},
{
"code": null,
"e": 2391,
"s": 2201,
"text": "There are two ways to install python-nmap. The first involves installation on the terminal while the second one involves downloading the python-nmap library and doing a manual installation."
},
{
"code": null,
"e": 2429,
"s": 2391,
"text": "So we will run the following command:"
},
{
"code": null,
"e": 2465,
"s": 2429,
"text": "root@gfg:~# pip install python-nmap"
},
{
"code": null,
"e": 2589,
"s": 2465,
"text": "In this second approach, we will list all the steps necessary to download the python-nmap library till it is ready for use."
},
{
"code": null,
"e": 2649,
"s": 2589,
"text": "Step 1: Download python-nmap library using wget as follows."
},
{
"code": null,
"e": 2733,
"s": 2649,
"text": "root@gfg:~# wget http://xael.org/norman/python/python-nmap/python-nmap-0.1.4.tar.gz"
},
{
"code": null,
"e": 2773,
"s": 2733,
"text": "Download python-nmap library using wget"
},
{
"code": null,
"e": 2813,
"s": 2773,
"text": "Step 2: Use tar to extract the contents"
},
{
"code": null,
"e": 2858,
"s": 2813,
"text": "root@gfg:~# tar xf python-nmap-0.1.4.tar.gz "
},
{
"code": null,
"e": 2890,
"s": 2858,
"text": "Use tar to extract the contents"
},
{
"code": null,
"e": 2941,
"s": 2890,
"text": "Step 3: Change directory to the extracted contents"
},
{
"code": null,
"e": 2975,
"s": 2941,
"text": "root@gfg:~# cd python-nmap-0.1.4"
},
{
"code": null,
"e": 3018,
"s": 2975,
"text": "Change directory to the extracted contents"
},
{
"code": null,
"e": 3054,
"s": 3018,
"text": "Step 4: Installation of Python-Nmap"
},
{
"code": null,
"e": 3091,
"s": 3054,
"text": "root@gfg:~# python setup.py install"
},
{
"code": null,
"e": 3119,
"s": 3091,
"text": "Installation of Python-Nmap"
},
{
"code": null,
"e": 3197,
"s": 3119,
"text": "Step 5: Confirm that Python-Nmap is successfully installed and ready for use."
},
{
"code": null,
"e": 3216,
"s": 3197,
"text": "root@gfg:~# python"
},
{
"code": null,
"e": 3285,
"s": 3216,
"text": "Confirm that Python-Nmap is successfully installed and ready for use"
},
{
"code": null,
"e": 3520,
"s": 3285,
"text": "We also need a virtual environment to separate concerns between the different modules and to differentiate the other projects. This is important if you decide to write python scripts and run them instead of the command-line interface."
},
{
"code": null,
"e": 3592,
"s": 3520,
"text": "The following command will aid in the creation of a virtual environment"
},
{
"code": null,
"e": 3635,
"s": 3592,
"text": "python -m venv my_virtual_environment_name"
},
{
"code": null,
"e": 3757,
"s": 3635,
"text": "Open the terminal by pressing Ctrl + Alt + T on the keyboard. Then, type the word python and press enter on your keyboard"
},
{
"code": null,
"e": 3776,
"s": 3757,
"text": "root@gfg:~# python"
},
{
"code": null,
"e": 3877,
"s": 3776,
"text": "To test the various Nmap commands, we will first import the Nmap module using the following command."
},
{
"code": null,
"e": 3893,
"s": 3877,
"text": ">>> import nmap"
},
{
"code": null,
"e": 3957,
"s": 3893,
"text": "Next, we need to instantiate the Nmap’s port scanner as follows"
},
{
"code": null,
"e": 4009,
"s": 3957,
"text": ">>> nmap =nmap.PortScanner()\n>>> host = '127.0.0.1'"
},
{
"code": null,
"e": 4079,
"s": 4009,
"text": "What’s next is setting both the port and host range to scan as below:"
},
{
"code": null,
"e": 4107,
"s": 4079,
"text": ">>> nmap.scan(host, '1-10')"
},
{
"code": null,
"e": 4178,
"s": 4107,
"text": "Next, we can print the command_line command used for the scan as shown"
},
{
"code": null,
"e": 4209,
"s": 4178,
"text": ">>> print(nmap.command_line())"
},
{
"code": null,
"e": 4253,
"s": 4209,
"text": "Using Nmap to get the hostname of 127.0.0.1"
},
{
"code": null,
"e": 4302,
"s": 4253,
"text": ">>> nmap['127.0.0.1'].hostname()\n'localhost'\n>>>"
},
{
"code": null,
"e": 4365,
"s": 4302,
"text": "If we want to get scan information on the Nmap, do as follows:"
},
{
"code": null,
"e": 4391,
"s": 4365,
"text": ">>> print nmap.scaninfo()"
},
{
"code": null,
"e": 4417,
"s": 4391,
"text": "The results will be like:"
},
{
"code": null,
"e": 4468,
"s": 4417,
"text": "{'tcp': {'services': '1-10', 'method': 'connect'}}"
},
{
"code": null,
"e": 4526,
"s": 4468,
"text": "To scan every host, we need to run the following commands"
},
{
"code": null,
"e": 4673,
"s": 4526,
"text": ">>> for host in nmap.all_hosts():\n... print('Host : %s (%s)' % (host, nmap[host].hostname()))\n... print('State : %s' % nmap[host].state())"
},
{
"code": null,
"e": 4788,
"s": 4673,
"text": "Similarly, we can also scan for all the protocols. It returns the protocol for the specific network being scanned."
},
{
"code": null,
"e": 4826,
"s": 4788,
"text": ">>> nmap['127.0.0.1'].all_protocols()"
},
{
"code": null,
"e": 4854,
"s": 4826,
"text": "The result in our case was:"
},
{
"code": null,
"e": 4860,
"s": 4854,
"text": "[tcp]"
},
{
"code": null,
"e": 4904,
"s": 4860,
"text": "Get the state of a specific host as follows"
},
{
"code": null,
"e": 4934,
"s": 4904,
"text": ">>> nmap['127.0.0.1'].state()"
},
{
"code": null,
"e": 4995,
"s": 4934,
"text": "It will be indicated if the host is up or down. In our case,"
},
{
"code": null,
"e": 5000,
"s": 4995,
"text": "'up'"
},
{
"code": null,
"e": 5154,
"s": 5000,
"text": "Keys() method is responsible for displaying information on all the active ports while providing the range. The following is how to use the keys() method."
},
{
"code": null,
"e": 5226,
"s": 5154,
"text": ">>> nmap['127.0.0.1']['tcp'].keys()\n[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n>>>"
},
{
"code": null,
"e": 5322,
"s": 5226,
"text": "Validate port information of a given port. For instance, for 20 on the given host is as follows"
},
{
"code": null,
"e": 5366,
"s": 5322,
"text": ">>> nmap['127.0.0.1'].has_tcp(20)\nFalse\n>>>"
},
{
"code": null,
"e": 5381,
"s": 5366,
"text": "how-to-install"
},
{
"code": null,
"e": 5388,
"s": 5381,
"text": "Picked"
},
{
"code": null,
"e": 5395,
"s": 5388,
"text": "How To"
},
{
"code": null,
"e": 5414,
"s": 5395,
"text": "Installation Guide"
},
{
"code": null,
"e": 5425,
"s": 5414,
"text": "Linux-Unix"
},
{
"code": null,
"e": 5432,
"s": 5425,
"text": "Python"
},
{
"code": null,
"e": 5530,
"s": 5432,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5579,
"s": 5530,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 5621,
"s": 5579,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 5660,
"s": 5621,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 5714,
"s": 5660,
"text": "How to Install Python Packages for AWS Lambda Layers?"
},
{
"code": null,
"e": 5745,
"s": 5714,
"text": "How to Install Git in VS Code?"
},
{
"code": null,
"e": 5778,
"s": 5745,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5813,
"s": 5778,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 5855,
"s": 5813,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 5894,
"s": 5855,
"text": "How to Install and Use NVM on Windows?"
}
] |
Sorting Vector of Pairs by 1st element in ascending and 2nd element in descending
|
12 Jun, 2022
A pair is a container that stores two values mapped to each other, and a vector containing multiple numbers of such pairs is called a vector of pairs.
While solving problems there come many instances where there is a need to sort the elements of vector on the basis of both the first and second elements of the pair. In that instance we have to pass an additional argument to the sort() function i, e a call to a user-defined explicit function in the sort() function.This article focuses on discussing the sorting vector of pairs on the basis of the first element of pairs in ascending order and if the first element if equal then according to the second element in descending order.
Below is the C++ program to demonstrate the sorting of vectors of pairs.
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to sort the vector elements// ascending for first element// and if first element equal// then descending for second elementbool sortbyCond(const pair<int, int>& a, const pair<int, int>& b){ if (a.first != b.first) return (a.first < b.first); else return (a.second > b.second);} // Driver codeint main(){ // Declaring vector of pairs vector<pair<int, int> > vect; // Initialising 1st and 2nd element // of pairs with array values int arr[] = { 10, 10, 5, 5, 15, 15 }; int arr1[] = { 40, 60, 20, 50, 12, 24 }; int n = sizeof(arr) / sizeof(arr[0]); // Entering values in vector of pairs for (int i = 0; i < n; i++) vect.push_back(make_pair(arr[i], arr1[i])); // The original vector(before sort()) cout << "The vector before sort operation is:\n"; for (int i = 0; i < n; i++) { // "first" and "second" are used to // access 1st and 2nd element of pair // respectively cout << vect[i].first << " " << vect[i].second << endl; } // Using sort() function to sort by // 1st element of pair and if first // element equal then by descending // order of second element sort(vect.begin(), vect.end(), sortbyCond); // Printing the sorted vector(after // using sort()) cout << "The vector after sort operation is:\n"; for (int i = 0; i < n; i++) { // "first" and "second" are used to // access 1st and 2nd element of pair // respectively cout << vect[i].first << " " << vect[i].second << endl; } return 0;}
// Java program to implement// the above approachimport java.util.*; class GFG{ static class pair implements Comparable<pair> { int first,second; pair(int s, int e) { first = s; second = e; } // Function to sort the vector elements // ascending for first element // and if first element equal // then descending for second element public int compareTo(pair b) { if (this.first != b.first) return (this.first < b.first)?-1:1; else return this.second > b.second?-1:1; } } // Driver code public static void main(String[] args) { // Declaring vector of pairs List<pair > vect = new ArrayList<pair > (); // Initialising 1st and 2nd element // of pairs with array values int arr[] = { 10, 10, 5, 5, 15, 15 }; int arr1[] = { 40, 60, 20, 50, 12, 24 }; int n = arr.length; // Entering values in vector of pairs for (int i = 0; i < n; i++) vect.add(new pair(arr[i], arr1[i])); // The original vector(before sort()) System.out.print("The vector before sort operation is:\n"); for (int i = 0; i < n; i++) { // "first" and "second" are used to // access 1st and 2nd element of pair // respectively System.out.print(vect.get(i).first+ " " + vect.get(i).second +"\n"); } // Using sort() function to sort by // 1st element of pair and if first // element equal then by descending // order of second element Collections.sort(vect); // Printing the sorted vector(after // using sort()) System.out.print("The vector after sort operation is:\n"); for (int i = 0; i < n; i++) { // "first" and "second" are used to // access 1st and 2nd element of pair // respectively System.out.print(vect.get(i).first+ " " + vect.get(i).second +"\n"); } }} // This code is contributed by 29AjayKumar
# Python program to implement# the above approach # Function to sort the vector elements# ascending for first element# and if first element equal# then descending for second elementfrom functools import cmp_to_key def sortbyCond(a, b): if (a[0] != b[0]): return (a[0] - b[0]) else: return b[1] - a[1] # Driver code # Declaring vector of pairsvect = [] # Initialising 1st and 2nd element# of pairs with array valuesarr = [ 10, 10, 5, 5, 15, 15 ]arr1 = [ 40, 60, 20, 50, 12, 24 ]n = len(arr) # Entering values in vector of pairsfor i in range(n): vect.append([arr[i],arr1[i]]) # The original vector(before sort())print("The vector before sort operation is: ")for i in range(n): # "first" and "second" are used to # access 1st and 2nd element of pair # respectively print(f"{vect[i][0]} {vect[i][1]}") # Using sort() function to sort by# 1st element of pair and if first# element equal then by descending# order of second elementvect.sort(key = cmp_to_key(sortbyCond)) # Printing the sorted vector(after# using sort())print("The vector after sort operation is: ")for i in range(n): # "first" and "second" are used to # access 1st and 2nd element of pair # respectively print(f"{vect[i][0]} {vect[i][1]}") # This code is contributed by shinjanpatra
// C# program to implement// the above approachusing System;using System.Collections.Generic; public class GFG{ class pair : IComparable<pair> { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } public int CompareTo(pair b) { if (this.first != b.first) return (this.first < b.first)?-1:1; else return this.second > b.second?-1:1; } } // Driver code public static void Main(String[] args) { // Declaring vector of pairs List<pair > vect = new List<pair > (); // Initialising 1st and 2nd element // of pairs with array values int []arr = { 10, 10, 5, 5, 15, 15 }; int []arr1 = { 40, 60, 20, 50, 12, 24 }; int n = arr.Length; // Entering values in vector of pairs for (int i = 0; i < n; i++) vect.Add(new pair(arr[i], arr1[i])); // The original vector(before sort()) Console.Write("The vector before sort operation is:\n"); for (int i = 0; i < n; i++) { // "first" and "second" are used to // access 1st and 2nd element of pair // respectively Console.Write(vect[i].first+ " " + vect[i].second +"\n"); } // Using sort() function to sort by // 1st element of pair and if first // element equal then by descending // order of second element vect.Sort(); // Printing the sorted vector(after // using sort()) Console.Write("The vector after sort operation is:\n"); for (int i = 0; i < n; i++) { // "first" and "second" are used to // access 1st and 2nd element of pair // respectively Console.Write(vect[i].first+ " " + vect[i].second +"\n"); } }} // This code is contributed by shikhasingrajput
<script> // JavaScript program to implement// the above approach // Function to sort the vector elements// ascending for first element// and if first element equal// then descending for second elementfunction sortbyCond(a,b){ if (a[0] != b[0]) return (a[0] - b[0]); else return b[1] - a[1];} // Driver code // Declaring vector of pairslet vect = []; // Initialising 1st and 2nd element// of pairs with array valueslet arr = [ 10, 10, 5, 5, 15, 15 ]let arr1 = [ 40, 60, 20, 50, 12, 24 ]let n = arr.length // Entering values in vector of pairsfor (let i = 0; i < n; i++) vect.push([arr[i],arr1[i]]); // The original vector(before sort())document.write("The vector before sort operation is: ");for (let i = 0; i < n; i++){ // "first" and "second" are used to // access 1st and 2nd element of pair // respectively document.write(vect[i][0] + " " + vect[i][1]);} // Using sort() function to sort by// 1st element of pair and if first// element equal then by descending// order of second elementvect.sort(sortbyCond); // Printing the sorted vector(after// using sort())document.write("The vector after sort operation is: ");for (let i = 0; i < n; i++){ // "first" and "second" are used to // access 1st and 2nd element of pair // respectively document.write(vect[i][0] + " " +vect[i][1]);} // This code is contributed by shinjanpatra </script>
The vector before sort operation is:
10 40
10 60
5 20
5 50
15 12
15 24
The vector after sort operation is:
5 50
5 20
10 60
10 40
15 24
15 12
29AjayKumar
shikhasingrajput
germanshephered48
shinjanpatra
vedanshsrivastava6
cpp-pair
cpp-vector
C++
Sorting
Sorting
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Jun, 2022"
},
{
"code": null,
"e": 203,
"s": 52,
"text": "A pair is a container that stores two values mapped to each other, and a vector containing multiple numbers of such pairs is called a vector of pairs."
},
{
"code": null,
"e": 736,
"s": 203,
"text": "While solving problems there come many instances where there is a need to sort the elements of vector on the basis of both the first and second elements of the pair. In that instance we have to pass an additional argument to the sort() function i, e a call to a user-defined explicit function in the sort() function.This article focuses on discussing the sorting vector of pairs on the basis of the first element of pairs in ascending order and if the first element if equal then according to the second element in descending order."
},
{
"code": null,
"e": 809,
"s": 736,
"text": "Below is the C++ program to demonstrate the sorting of vectors of pairs."
},
{
"code": null,
"e": 813,
"s": 809,
"text": "C++"
},
{
"code": null,
"e": 818,
"s": 813,
"text": "Java"
},
{
"code": null,
"e": 826,
"s": 818,
"text": "Python3"
},
{
"code": null,
"e": 829,
"s": 826,
"text": "C#"
},
{
"code": null,
"e": 840,
"s": 829,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to sort the vector elements// ascending for first element// and if first element equal// then descending for second elementbool sortbyCond(const pair<int, int>& a, const pair<int, int>& b){ if (a.first != b.first) return (a.first < b.first); else return (a.second > b.second);} // Driver codeint main(){ // Declaring vector of pairs vector<pair<int, int> > vect; // Initialising 1st and 2nd element // of pairs with array values int arr[] = { 10, 10, 5, 5, 15, 15 }; int arr1[] = { 40, 60, 20, 50, 12, 24 }; int n = sizeof(arr) / sizeof(arr[0]); // Entering values in vector of pairs for (int i = 0; i < n; i++) vect.push_back(make_pair(arr[i], arr1[i])); // The original vector(before sort()) cout << \"The vector before sort operation is:\\n\"; for (int i = 0; i < n; i++) { // \"first\" and \"second\" are used to // access 1st and 2nd element of pair // respectively cout << vect[i].first << \" \" << vect[i].second << endl; } // Using sort() function to sort by // 1st element of pair and if first // element equal then by descending // order of second element sort(vect.begin(), vect.end(), sortbyCond); // Printing the sorted vector(after // using sort()) cout << \"The vector after sort operation is:\\n\"; for (int i = 0; i < n; i++) { // \"first\" and \"second\" are used to // access 1st and 2nd element of pair // respectively cout << vect[i].first << \" \" << vect[i].second << endl; } return 0;}",
"e": 2567,
"s": 840,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*; class GFG{ static class pair implements Comparable<pair> { int first,second; pair(int s, int e) { first = s; second = e; } // Function to sort the vector elements // ascending for first element // and if first element equal // then descending for second element public int compareTo(pair b) { if (this.first != b.first) return (this.first < b.first)?-1:1; else return this.second > b.second?-1:1; } } // Driver code public static void main(String[] args) { // Declaring vector of pairs List<pair > vect = new ArrayList<pair > (); // Initialising 1st and 2nd element // of pairs with array values int arr[] = { 10, 10, 5, 5, 15, 15 }; int arr1[] = { 40, 60, 20, 50, 12, 24 }; int n = arr.length; // Entering values in vector of pairs for (int i = 0; i < n; i++) vect.add(new pair(arr[i], arr1[i])); // The original vector(before sort()) System.out.print(\"The vector before sort operation is:\\n\"); for (int i = 0; i < n; i++) { // \"first\" and \"second\" are used to // access 1st and 2nd element of pair // respectively System.out.print(vect.get(i).first+ \" \" + vect.get(i).second +\"\\n\"); } // Using sort() function to sort by // 1st element of pair and if first // element equal then by descending // order of second element Collections.sort(vect); // Printing the sorted vector(after // using sort()) System.out.print(\"The vector after sort operation is:\\n\"); for (int i = 0; i < n; i++) { // \"first\" and \"second\" are used to // access 1st and 2nd element of pair // respectively System.out.print(vect.get(i).first+ \" \" + vect.get(i).second +\"\\n\"); } }} // This code is contributed by 29AjayKumar",
"e": 4520,
"s": 2567,
"text": null
},
{
"code": "# Python program to implement# the above approach # Function to sort the vector elements# ascending for first element# and if first element equal# then descending for second elementfrom functools import cmp_to_key def sortbyCond(a, b): if (a[0] != b[0]): return (a[0] - b[0]) else: return b[1] - a[1] # Driver code # Declaring vector of pairsvect = [] # Initialising 1st and 2nd element# of pairs with array valuesarr = [ 10, 10, 5, 5, 15, 15 ]arr1 = [ 40, 60, 20, 50, 12, 24 ]n = len(arr) # Entering values in vector of pairsfor i in range(n): vect.append([arr[i],arr1[i]]) # The original vector(before sort())print(\"The vector before sort operation is: \")for i in range(n): # \"first\" and \"second\" are used to # access 1st and 2nd element of pair # respectively print(f\"{vect[i][0]} {vect[i][1]}\") # Using sort() function to sort by# 1st element of pair and if first# element equal then by descending# order of second elementvect.sort(key = cmp_to_key(sortbyCond)) # Printing the sorted vector(after# using sort())print(\"The vector after sort operation is: \")for i in range(n): # \"first\" and \"second\" are used to # access 1st and 2nd element of pair # respectively print(f\"{vect[i][0]} {vect[i][1]}\") # This code is contributed by shinjanpatra",
"e": 5815,
"s": 4520,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections.Generic; public class GFG{ class pair : IComparable<pair> { public int first, second; public pair(int first, int second) { this.first = first; this.second = second; } public int CompareTo(pair b) { if (this.first != b.first) return (this.first < b.first)?-1:1; else return this.second > b.second?-1:1; } } // Driver code public static void Main(String[] args) { // Declaring vector of pairs List<pair > vect = new List<pair > (); // Initialising 1st and 2nd element // of pairs with array values int []arr = { 10, 10, 5, 5, 15, 15 }; int []arr1 = { 40, 60, 20, 50, 12, 24 }; int n = arr.Length; // Entering values in vector of pairs for (int i = 0; i < n; i++) vect.Add(new pair(arr[i], arr1[i])); // The original vector(before sort()) Console.Write(\"The vector before sort operation is:\\n\"); for (int i = 0; i < n; i++) { // \"first\" and \"second\" are used to // access 1st and 2nd element of pair // respectively Console.Write(vect[i].first+ \" \" + vect[i].second +\"\\n\"); } // Using sort() function to sort by // 1st element of pair and if first // element equal then by descending // order of second element vect.Sort(); // Printing the sorted vector(after // using sort()) Console.Write(\"The vector after sort operation is:\\n\"); for (int i = 0; i < n; i++) { // \"first\" and \"second\" are used to // access 1st and 2nd element of pair // respectively Console.Write(vect[i].first+ \" \" + vect[i].second +\"\\n\"); } }} // This code is contributed by shikhasingrajput",
"e": 7717,
"s": 5815,
"text": null
},
{
"code": "<script> // JavaScript program to implement// the above approach // Function to sort the vector elements// ascending for first element// and if first element equal// then descending for second elementfunction sortbyCond(a,b){ if (a[0] != b[0]) return (a[0] - b[0]); else return b[1] - a[1];} // Driver code // Declaring vector of pairslet vect = []; // Initialising 1st and 2nd element// of pairs with array valueslet arr = [ 10, 10, 5, 5, 15, 15 ]let arr1 = [ 40, 60, 20, 50, 12, 24 ]let n = arr.length // Entering values in vector of pairsfor (let i = 0; i < n; i++) vect.push([arr[i],arr1[i]]); // The original vector(before sort())document.write(\"The vector before sort operation is: \");for (let i = 0; i < n; i++){ // \"first\" and \"second\" are used to // access 1st and 2nd element of pair // respectively document.write(vect[i][0] + \" \" + vect[i][1]);} // Using sort() function to sort by// 1st element of pair and if first// element equal then by descending// order of second elementvect.sort(sortbyCond); // Printing the sorted vector(after// using sort())document.write(\"The vector after sort operation is: \");for (let i = 0; i < n; i++){ // \"first\" and \"second\" are used to // access 1st and 2nd element of pair // respectively document.write(vect[i][0] + \" \" +vect[i][1]);} // This code is contributed by shinjanpatra </script>",
"e": 9119,
"s": 7717,
"text": null
},
{
"code": null,
"e": 9263,
"s": 9122,
"text": "The vector before sort operation is:\n10 40\n10 60\n5 20\n5 50\n15 12\n15 24\nThe vector after sort operation is:\n5 50\n5 20\n10 60\n10 40\n15 24\n15 12"
},
{
"code": null,
"e": 9277,
"s": 9265,
"text": "29AjayKumar"
},
{
"code": null,
"e": 9294,
"s": 9277,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 9312,
"s": 9294,
"text": "germanshephered48"
},
{
"code": null,
"e": 9325,
"s": 9312,
"text": "shinjanpatra"
},
{
"code": null,
"e": 9344,
"s": 9325,
"text": "vedanshsrivastava6"
},
{
"code": null,
"e": 9353,
"s": 9344,
"text": "cpp-pair"
},
{
"code": null,
"e": 9364,
"s": 9353,
"text": "cpp-vector"
},
{
"code": null,
"e": 9368,
"s": 9364,
"text": "C++"
},
{
"code": null,
"e": 9376,
"s": 9368,
"text": "Sorting"
},
{
"code": null,
"e": 9384,
"s": 9376,
"text": "Sorting"
},
{
"code": null,
"e": 9388,
"s": 9384,
"text": "CPP"
}
] |
How to parse a JSON File in PHP ?
|
26 May, 2021
In this article, we are going to parse the JSON file by displaying JSON data using PHP. PHP is a server-side scripting language used to process the data. JSON stands for JavaScript object notation. JSON data is written as name/value pairs.
Syntax:
{“Data”:[{“key”:”value”,“key”:value,“key n “:”value”},. . .. . .{“key”:”value”,“key”:value,“key n “:”value”}]}
Example: The JSON notation for student details is as follows.
{“Student”:[{“Name”:”Sravan”,“Roll”:7058,“subject”:”java”},{“Name”:”Jyothika”,“Roll”:7059,“subject”:”SAP”}]}
Advantages:
JSON does not use an end tag.
JSON is a shorter format.
JSON is quicker to read and write.
JSON can use arrays.
Approach: Create a JSON file and save it as my_data.json. We have taken student data in the file. The contents are as follows.
{“Student”:[{“Name”:”Sravan”,“Roll”:7058,“subject”:”java”},{“Name”:”Jyothika”,“Roll”:7059,“subject”:”SAP”}]}
Use file_get_contents() function to read JSON file into PHP. This function is used to read the file into PHP code.
Syntax:
file_get_contents(path, file_name)
file_name is the name of the file and path is the location to be checked.
Use json_decode() function to decode to JSON file into array to display it.
It is used to convert the JSON into an array.
Syntax:
json_decode($json_object, true)
$json_object is the file object to be read.
PHP code: The following is the PHP code to parse JSON file.
PHP
<?php // Read the JSON file $json = file_get_contents('my_data.json'); // Decode the JSON file$json_data = json_decode($json,true); // Display dataprint_r($json_data); ?>
Output:
Array (
[Student] => Array (
[0] => Array (
[Name] => Sravan
[Roll] => 7058
[subject] => java
)
[1] => Array (
[Name] => Jyothika
[Roll] => 7059
[subject] => SAP
)
)
)
PHP-function
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 268,
"s": 28,
"text": "In this article, we are going to parse the JSON file by displaying JSON data using PHP. PHP is a server-side scripting language used to process the data. JSON stands for JavaScript object notation. JSON data is written as name/value pairs."
},
{
"code": null,
"e": 276,
"s": 268,
"text": "Syntax:"
},
{
"code": null,
"e": 387,
"s": 276,
"text": "{“Data”:[{“key”:”value”,“key”:value,“key n “:”value”},. . .. . .{“key”:”value”,“key”:value,“key n “:”value”}]}"
},
{
"code": null,
"e": 449,
"s": 387,
"text": "Example: The JSON notation for student details is as follows."
},
{
"code": null,
"e": 558,
"s": 449,
"text": "{“Student”:[{“Name”:”Sravan”,“Roll”:7058,“subject”:”java”},{“Name”:”Jyothika”,“Roll”:7059,“subject”:”SAP”}]}"
},
{
"code": null,
"e": 570,
"s": 558,
"text": "Advantages:"
},
{
"code": null,
"e": 600,
"s": 570,
"text": "JSON does not use an end tag."
},
{
"code": null,
"e": 626,
"s": 600,
"text": "JSON is a shorter format."
},
{
"code": null,
"e": 661,
"s": 626,
"text": "JSON is quicker to read and write."
},
{
"code": null,
"e": 682,
"s": 661,
"text": "JSON can use arrays."
},
{
"code": null,
"e": 809,
"s": 682,
"text": "Approach: Create a JSON file and save it as my_data.json. We have taken student data in the file. The contents are as follows."
},
{
"code": null,
"e": 918,
"s": 809,
"text": "{“Student”:[{“Name”:”Sravan”,“Roll”:7058,“subject”:”java”},{“Name”:”Jyothika”,“Roll”:7059,“subject”:”SAP”}]}"
},
{
"code": null,
"e": 1033,
"s": 918,
"text": "Use file_get_contents() function to read JSON file into PHP. This function is used to read the file into PHP code."
},
{
"code": null,
"e": 1041,
"s": 1033,
"text": "Syntax:"
},
{
"code": null,
"e": 1076,
"s": 1041,
"text": "file_get_contents(path, file_name)"
},
{
"code": null,
"e": 1150,
"s": 1076,
"text": "file_name is the name of the file and path is the location to be checked."
},
{
"code": null,
"e": 1226,
"s": 1150,
"text": "Use json_decode() function to decode to JSON file into array to display it."
},
{
"code": null,
"e": 1272,
"s": 1226,
"text": "It is used to convert the JSON into an array."
},
{
"code": null,
"e": 1280,
"s": 1272,
"text": "Syntax:"
},
{
"code": null,
"e": 1312,
"s": 1280,
"text": "json_decode($json_object, true)"
},
{
"code": null,
"e": 1356,
"s": 1312,
"text": "$json_object is the file object to be read."
},
{
"code": null,
"e": 1416,
"s": 1356,
"text": "PHP code: The following is the PHP code to parse JSON file."
},
{
"code": null,
"e": 1420,
"s": 1416,
"text": "PHP"
},
{
"code": "<?php // Read the JSON file $json = file_get_contents('my_data.json'); // Decode the JSON file$json_data = json_decode($json,true); // Display dataprint_r($json_data); ?>",
"e": 1595,
"s": 1420,
"text": null
},
{
"code": null,
"e": 1603,
"s": 1595,
"text": "Output:"
},
{
"code": null,
"e": 1897,
"s": 1603,
"text": "Array ( \n [Student] => Array ( \n [0] => Array ( \n [Name] => Sravan \n [Roll] => 7058 \n [subject] => java \n ) \n [1] => Array ( \n [Name] => Jyothika \n [Roll] => 7059 \n [subject] => SAP \n ) \n ) \n)\n"
},
{
"code": null,
"e": 1910,
"s": 1897,
"text": "PHP-function"
},
{
"code": null,
"e": 1924,
"s": 1910,
"text": "PHP-Questions"
},
{
"code": null,
"e": 1931,
"s": 1924,
"text": "Picked"
},
{
"code": null,
"e": 1935,
"s": 1931,
"text": "PHP"
},
{
"code": null,
"e": 1952,
"s": 1935,
"text": "Web Technologies"
},
{
"code": null,
"e": 1956,
"s": 1952,
"text": "PHP"
}
] |
Print all 3 digit repeating numbers in a very large number
|
11 May, 2021
Given a very large number, print all the 3 digit repeating numbers with their frequency. If a 3 digit number appears more then once, print the number and its frequency. Example:
Input: 123412345123456
Output: 123 - 3 times
234 - 3 times
345 - 2 times
Input: 43243243
Output: 432 - 2 times
324 - 2 times
243 - 2 times
Approach: Since the number is very large, it is stored in a string. Initially, the first three-digit number will be the first three characters from the left. Iterate in the string from the 3rd index from the left in the string and do %100 to remove the first character and append the ith index number at the end to get the new number. Increase the frequency of the number in the hash map. In the end, when all the 3-digit numbers are generated, print all the numbers which have a frequency of more than 1. Below is the implementation of the above idea:
C++
Java
Python3
C#
Javascript
// CPP program to print 3 digit repeating numbers#include <bits/stdc++.h>using namespace std; // function to print 3// digit repeating numbersvoid printNum(string s){ int i = 0, j = 0, val = 0; // Hashmap to store the // frequency of a 3 digit number map <int, int> mp; // first three digit number val = (s[0] - '0') * 100 + (s[1] - '0') * 10 + (s[2] - '0'); mp[val] = 1; for (i = 3; i < s.length(); i++) { val = (val % 100) * 10 + s[i] - '0'; // if key already exists // increase value by 1 if (mp.find(val) != mp.end()) { mp[val] = mp[val] + 1; } else { mp[val] = 1; } } // Output the three digit numbers with frequency>1 for (auto m : mp) { int key = m.first; int value = m.second; if (value > 1) cout << key << " - " << value << " times" << endl; }} // Driver Codeint main(){ // Input string string input = "123412345123456"; // Calling Function printNum(input);}// This code is contributed by Nishant Tanwar
// Java program to print 3 digit repeating numbersimport java.util.*;import java.lang.*; public class GFG { // function to print 3 // digit repeating numbers static void printNum(String s) { int i = 0, j = 0, val = 0; // Hashmap to store the // frequency of a 3 digit number LinkedHashMap<Integer, Integer> hm = new LinkedHashMap<>(); // first three digit number val = (s.charAt(0) - '0') * 100 + (s.charAt(1) - '0') * 10 + (s.charAt(2) - '0'); hm.put(val, 1); for (i = 3; i < s.length(); i++) { val = (val % 100) * 10 + s.charAt(i) - '0'; // if key already exists // increase value by 1 if (hm.containsKey(val)) { hm.put(val, hm.get(val) + 1); } else { hm.put(val, 1); } } // Output the three digit numbers with frequency>1 for (Map.Entry<Integer, Integer> en : hm.entrySet()) { int key = en.getKey(); int value = en.getValue(); if (value > 1) System.out.println(key + " - " + value + " times"); } } // Driver Code public static void main(String args[]) { // Input string String input = "123412345123456"; // Calling Function printNum(input); }}
# Python3 program to print# 3 digit repeating numbers # Function to print 3# digit repeating numbersdef printNum(s): i, j, val = 0, 0, 0 # Hashmap to store the # frequency of a 3 digit number mp = {} # first three digit number val = ((ord(s[0]) - ord('0')) * 100 + (ord(s[1]) - ord('0')) * 10 + (ord(s[2]) - ord('0'))) mp[val] = 1 for i in range (3, len(s)): val = (val % 100) * 10 + ord(s[i]) - ord('0') # if key already exists # increase value by 1 if (val in mp): mp[val] = mp[val] + 1 else: mp[val] = 1 # Output the three digit # numbers with frequency>1 for m in mp: key = m value = mp[m] if (value > 1): print (key, " - ", value, " times") # Driver Codeif __name__ == "__main__": # Input string input = "123412345123456" # Calling Function printNum(input) # This code is contributed by Chitranayal
// C# program to print 3 digit repeating numbersusing System;using System.Collections.Generic; class GFG{ // function to print 3 // digit repeating numbers static void printNum(String s) { int i = 0, val = 0; // Hashmap to store the // frequency of a 3 digit number Dictionary<int, int> hm = new Dictionary<int, int>(); // first three digit number val = (s[0] - '0') * 100 + (s[1] - '0') * 10 + (s[2] - '0'); hm.Add(val, 1); for (i = 3; i < s.Length; i++) { val = (val % 100) * 10 + s[i] - '0'; // if key already exists // increase value by 1 if (hm.ContainsKey(val)) { hm[val] = hm[val] + 1; } else { hm.Add(val, 1); } } // Output the three digit numbers with frequency>1 foreach(KeyValuePair<int, int> en in hm) { int key = en.Key; int value = en.Value; if (value > 1) Console.WriteLine(key + " - " + value + " times"); } } // Driver Code public static void Main(String []args) { // Input string String input = "123412345123456"; // Calling Function printNum(input); }} // This code is contributed by PrinciRaj1992
<script> // Javascript program to print 3 digit repeating numbers // function to print 3 // digit repeating numbers function printNum(s) { let i = 0, j = 0, val = 0; // Hashmap to store the // frequency of a 3 digit number let hm = new Map(); // first three digit number val = (s[0].charCodeAt(0) - '0'.charCodeAt(0)) * 100 + (s[1].charCodeAt(0) - '0'.charCodeAt(0)) * 10 + (s[2].charCodeAt(0) - '0'.charCodeAt(0)); hm.set(val, 1); for (i = 3; i < s.length; i++) { val = (val % 100) * 10 + s[i].charCodeAt(0) - '0'.charCodeAt(0); // if key already exists // increase value by 1 if (hm.has(val)) { hm.set(val, hm.get(val) + 1); } else { hm.set(val, 1); } } // Output the three digit numbers with frequency>1 for (let [Key, Value] of hm.entries()) { let key = Key; let value = Value; if (value > 1) document.write(key + " - " + value + " times<br>"); } } // Driver Code // Input string let input = "123412345123456"; // Calling Function printNum(input); // This code is contributed by avanitrachhadiya2155</script>
123 - 3 times
234 - 3 times
345 - 2 times
Nishant Tanwar
princiraj1992
ukasp
avanitrachhadiya2155
frequency-counting
Java-HashMap
Searching Quiz
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 May, 2021"
},
{
"code": null,
"e": 233,
"s": 54,
"text": "Given a very large number, print all the 3 digit repeating numbers with their frequency. If a 3 digit number appears more then once, print the number and its frequency. Example: "
},
{
"code": null,
"e": 408,
"s": 233,
"text": "Input: 123412345123456\nOutput: 123 - 3 times\n 234 - 3 times\n 345 - 2 times \n\nInput: 43243243\nOutput: 432 - 2 times\n 324 - 2 times\n 243 - 2 times"
},
{
"code": null,
"e": 963,
"s": 408,
"text": "Approach: Since the number is very large, it is stored in a string. Initially, the first three-digit number will be the first three characters from the left. Iterate in the string from the 3rd index from the left in the string and do %100 to remove the first character and append the ith index number at the end to get the new number. Increase the frequency of the number in the hash map. In the end, when all the 3-digit numbers are generated, print all the numbers which have a frequency of more than 1. Below is the implementation of the above idea: "
},
{
"code": null,
"e": 967,
"s": 963,
"text": "C++"
},
{
"code": null,
"e": 972,
"s": 967,
"text": "Java"
},
{
"code": null,
"e": 980,
"s": 972,
"text": "Python3"
},
{
"code": null,
"e": 983,
"s": 980,
"text": "C#"
},
{
"code": null,
"e": 994,
"s": 983,
"text": "Javascript"
},
{
"code": "// CPP program to print 3 digit repeating numbers#include <bits/stdc++.h>using namespace std; // function to print 3// digit repeating numbersvoid printNum(string s){ int i = 0, j = 0, val = 0; // Hashmap to store the // frequency of a 3 digit number map <int, int> mp; // first three digit number val = (s[0] - '0') * 100 + (s[1] - '0') * 10 + (s[2] - '0'); mp[val] = 1; for (i = 3; i < s.length(); i++) { val = (val % 100) * 10 + s[i] - '0'; // if key already exists // increase value by 1 if (mp.find(val) != mp.end()) { mp[val] = mp[val] + 1; } else { mp[val] = 1; } } // Output the three digit numbers with frequency>1 for (auto m : mp) { int key = m.first; int value = m.second; if (value > 1) cout << key << \" - \" << value << \" times\" << endl; }} // Driver Codeint main(){ // Input string string input = \"123412345123456\"; // Calling Function printNum(input);}// This code is contributed by Nishant Tanwar",
"e": 2088,
"s": 994,
"text": null
},
{
"code": "// Java program to print 3 digit repeating numbersimport java.util.*;import java.lang.*; public class GFG { // function to print 3 // digit repeating numbers static void printNum(String s) { int i = 0, j = 0, val = 0; // Hashmap to store the // frequency of a 3 digit number LinkedHashMap<Integer, Integer> hm = new LinkedHashMap<>(); // first three digit number val = (s.charAt(0) - '0') * 100 + (s.charAt(1) - '0') * 10 + (s.charAt(2) - '0'); hm.put(val, 1); for (i = 3; i < s.length(); i++) { val = (val % 100) * 10 + s.charAt(i) - '0'; // if key already exists // increase value by 1 if (hm.containsKey(val)) { hm.put(val, hm.get(val) + 1); } else { hm.put(val, 1); } } // Output the three digit numbers with frequency>1 for (Map.Entry<Integer, Integer> en : hm.entrySet()) { int key = en.getKey(); int value = en.getValue(); if (value > 1) System.out.println(key + \" - \" + value + \" times\"); } } // Driver Code public static void main(String args[]) { // Input string String input = \"123412345123456\"; // Calling Function printNum(input); }}",
"e": 3475,
"s": 2088,
"text": null
},
{
"code": "# Python3 program to print# 3 digit repeating numbers # Function to print 3# digit repeating numbersdef printNum(s): i, j, val = 0, 0, 0 # Hashmap to store the # frequency of a 3 digit number mp = {} # first three digit number val = ((ord(s[0]) - ord('0')) * 100 + (ord(s[1]) - ord('0')) * 10 + (ord(s[2]) - ord('0'))) mp[val] = 1 for i in range (3, len(s)): val = (val % 100) * 10 + ord(s[i]) - ord('0') # if key already exists # increase value by 1 if (val in mp): mp[val] = mp[val] + 1 else: mp[val] = 1 # Output the three digit # numbers with frequency>1 for m in mp: key = m value = mp[m] if (value > 1): print (key, \" - \", value, \" times\") # Driver Codeif __name__ == \"__main__\": # Input string input = \"123412345123456\" # Calling Function printNum(input) # This code is contributed by Chitranayal",
"e": 4460,
"s": 3475,
"text": null
},
{
"code": "// C# program to print 3 digit repeating numbersusing System;using System.Collections.Generic; class GFG{ // function to print 3 // digit repeating numbers static void printNum(String s) { int i = 0, val = 0; // Hashmap to store the // frequency of a 3 digit number Dictionary<int, int> hm = new Dictionary<int, int>(); // first three digit number val = (s[0] - '0') * 100 + (s[1] - '0') * 10 + (s[2] - '0'); hm.Add(val, 1); for (i = 3; i < s.Length; i++) { val = (val % 100) * 10 + s[i] - '0'; // if key already exists // increase value by 1 if (hm.ContainsKey(val)) { hm[val] = hm[val] + 1; } else { hm.Add(val, 1); } } // Output the three digit numbers with frequency>1 foreach(KeyValuePair<int, int> en in hm) { int key = en.Key; int value = en.Value; if (value > 1) Console.WriteLine(key + \" - \" + value + \" times\"); } } // Driver Code public static void Main(String []args) { // Input string String input = \"123412345123456\"; // Calling Function printNum(input); }} // This code is contributed by PrinciRaj1992",
"e": 5948,
"s": 4460,
"text": null
},
{
"code": "<script> // Javascript program to print 3 digit repeating numbers // function to print 3 // digit repeating numbers function printNum(s) { let i = 0, j = 0, val = 0; // Hashmap to store the // frequency of a 3 digit number let hm = new Map(); // first three digit number val = (s[0].charCodeAt(0) - '0'.charCodeAt(0)) * 100 + (s[1].charCodeAt(0) - '0'.charCodeAt(0)) * 10 + (s[2].charCodeAt(0) - '0'.charCodeAt(0)); hm.set(val, 1); for (i = 3; i < s.length; i++) { val = (val % 100) * 10 + s[i].charCodeAt(0) - '0'.charCodeAt(0); // if key already exists // increase value by 1 if (hm.has(val)) { hm.set(val, hm.get(val) + 1); } else { hm.set(val, 1); } } // Output the three digit numbers with frequency>1 for (let [Key, Value] of hm.entries()) { let key = Key; let value = Value; if (value > 1) document.write(key + \" - \" + value + \" times<br>\"); } } // Driver Code // Input string let input = \"123412345123456\"; // Calling Function printNum(input); // This code is contributed by avanitrachhadiya2155</script>",
"e": 7286,
"s": 5948,
"text": null
},
{
"code": null,
"e": 7328,
"s": 7286,
"text": "123 - 3 times\n234 - 3 times\n345 - 2 times"
},
{
"code": null,
"e": 7345,
"s": 7330,
"text": "Nishant Tanwar"
},
{
"code": null,
"e": 7359,
"s": 7345,
"text": "princiraj1992"
},
{
"code": null,
"e": 7365,
"s": 7359,
"text": "ukasp"
},
{
"code": null,
"e": 7386,
"s": 7365,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 7405,
"s": 7386,
"text": "frequency-counting"
},
{
"code": null,
"e": 7418,
"s": 7405,
"text": "Java-HashMap"
},
{
"code": null,
"e": 7433,
"s": 7418,
"text": "Searching Quiz"
},
{
"code": null,
"e": 7441,
"s": 7433,
"text": "Strings"
},
{
"code": null,
"e": 7449,
"s": 7441,
"text": "Strings"
}
] |
How to install bootstrap in React.js ?
|
20 Nov, 2021
Bootstrap is one of the most popular front-end open-source toolkit for developing responsive, mobile-first front-end projects on the web. It contains various types of design templates based on CSS and JavaScript. It has various prebuilt components such as Accordion, Alerts, Carousel, Button, Card, Breadcrumb, etc. Instead of writing code from scratch, one can use bootstrap templates to make the work a lot easier. There are multiple ways to use Bootstrap in your local project such as by using Bootstrap CDN or installing bootstrap in React JS.
However, using Bootstrap CDN is an easier way to add Bootstrap to the project. There is no need to install or download any package. One can add simply by putting a <link> into the <head> section of the file or react app. But today we are going to discuss how one can install Bootstrap in React JS.
Following are some steps to install Bootstrap:-
Create React App
Open terminal and change directory to the path of your current project
Run npm (node package manager) install command followed by the name of package and version(optional).
After installing one can use Bootstrap by simply importing the bootstrap dependency in your React JS file. After importing Bootstrap minified CSS as the dependency we can use built-in bootstrap classes in our React App Components. But in order to use Bootstrap’s JavaScript components in our React App we have to install jquery and popper.js similarly using npm install.
Creating react application:
Step 1: Create a React App using the following command. Write the following command inside terminal and hit enter. (Instead of gfg you can use foldername of your choice. )
npx create-react-app gfg
Step 2: Change directory to the project folder by entering the following command.
cd gfg
Project Structure: Now we are in our project directory. As we created the ReactJS successfully so let’s install the required package. After creating React app our project structure would look similar to the following.
Project_Structure
Step 3: Run the following command in the terminal. Do check whether you are in React App directory or not. For the sake of convenience I have taken F:\gfg as my current working directory, the directory of my React App(gfg).
npm install bootstrap
If you observe in the above command I have not mentioned the version of bootstrap. By default, it will install the latest version of bootstrap. But if you are following some tutorials, courses or wanted to build your React JS app in a particular bootstrap version, you can do so by passing ‘@version’ just after bootstrap that is npm install bootstrap@4.1 where 4.1 is name of version.
Our current working directory is F:/gfg. Bootstrap is now successfully installed you can verify by searching the bootstrap folder inside node_modules folder.
Bootstrap folder inside node_modules
You can also observe some changes in your package.json file is after installing bootstrap an entry is added inside the dependencies part of package.json similar to “bootstrap”: “version”.
package.json
Bootstrap inside dependencies after installation
Step 4: As of now bootstrap is successfully installed in React app but to use it we must import it inside React file. I am importing Bootstrap minified CSS file and Bootstrap JavaScript minified bundle file inside index.js which is in F:\gfg\src.
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.bundle.min';
The above to two statements are required in our index.js to import dependencies inside React file in order to use bootstrap classes in our React app components.
Filename: index.js
Javascript
import 'bootstrap/dist/css/bootstrap.min.css';import 'bootstrap/dist/js/bootstrap.bundle.min';import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import reportWebVitals from './reportWebVitals'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root'));
Explanation: The above code would probably look like index.js except line 1 and 2 they bootstrap is not imported as dependencies inside index.js by default on creating React App. In line 1 and 2 we have imported bootstrap minified css and bootstrap javascript minified bundle. Now we can use bootstrap classes inside our React app components.
Step 5: We are all set to use built-in Bootstrap classes but to use Bootstrap’s JavaScript components in our react app we have to install popper.js and jquery. In case they are not installed already. To install both jquery and popper.js write the following line in terminal and hit enter.
npm install jquery popper.js
After installing this similarly import these two dependencies in your React JS file in this case index.js Following are the statements to import these two dependencies.
import $ from 'jquery';
import Popper from 'popper.js';
After making all these additional changes your index.js file should look like the following
Filename: index.js
Javascript
import 'bootstrap/dist/css/bootstrap.min.css';import 'bootstrap/dist/js/bootstrap.bundle.min';import $ from 'jquery';import Popper from 'popper.js';import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import reportWebVitals from './reportWebVitals'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root')); // If you want to start measuring performance// in your app, pass a function to log results// (for example: reportWebVitals(console.log))// or send to an analytics endpoint.reportWebVitals();
Step 6: Let’s use simple bootstrap button in our React App. For that we have to import bootstrap minified css and bootstrap javascript minified bundle as a dependency in our index.js file. And add a button in our default index.js file. As we did already. After that, we have to add a button inside our App to that add the following code inside App.js.
Filename: App.js
Javascript
import logo from './logo.svg';import './App.css'; function App() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> <a className="btn btn-primary" data-bs-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample"> Bootstrap button </a> </header> </div> );} export default App;
Step to run the application: Save your file and run npm server by entering following command in the terminal.
npm start
Output: After running the server, your output would look like this
OUTPUT
avgaur22
kashishsoda
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS setState()
How to pass data from one component to other component in ReactJS ?
Re-rendering Components in ReactJS
ReactJS defaultProps
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Nov, 2021"
},
{
"code": null,
"e": 576,
"s": 28,
"text": "Bootstrap is one of the most popular front-end open-source toolkit for developing responsive, mobile-first front-end projects on the web. It contains various types of design templates based on CSS and JavaScript. It has various prebuilt components such as Accordion, Alerts, Carousel, Button, Card, Breadcrumb, etc. Instead of writing code from scratch, one can use bootstrap templates to make the work a lot easier. There are multiple ways to use Bootstrap in your local project such as by using Bootstrap CDN or installing bootstrap in React JS."
},
{
"code": null,
"e": 874,
"s": 576,
"text": "However, using Bootstrap CDN is an easier way to add Bootstrap to the project. There is no need to install or download any package. One can add simply by putting a <link> into the <head> section of the file or react app. But today we are going to discuss how one can install Bootstrap in React JS."
},
{
"code": null,
"e": 922,
"s": 874,
"text": "Following are some steps to install Bootstrap:-"
},
{
"code": null,
"e": 939,
"s": 922,
"text": "Create React App"
},
{
"code": null,
"e": 1010,
"s": 939,
"text": "Open terminal and change directory to the path of your current project"
},
{
"code": null,
"e": 1112,
"s": 1010,
"text": "Run npm (node package manager) install command followed by the name of package and version(optional)."
},
{
"code": null,
"e": 1483,
"s": 1112,
"text": "After installing one can use Bootstrap by simply importing the bootstrap dependency in your React JS file. After importing Bootstrap minified CSS as the dependency we can use built-in bootstrap classes in our React App Components. But in order to use Bootstrap’s JavaScript components in our React App we have to install jquery and popper.js similarly using npm install."
},
{
"code": null,
"e": 1511,
"s": 1483,
"text": "Creating react application:"
},
{
"code": null,
"e": 1683,
"s": 1511,
"text": "Step 1: Create a React App using the following command. Write the following command inside terminal and hit enter. (Instead of gfg you can use foldername of your choice. )"
},
{
"code": null,
"e": 1708,
"s": 1683,
"text": "npx create-react-app gfg"
},
{
"code": null,
"e": 1790,
"s": 1708,
"text": "Step 2: Change directory to the project folder by entering the following command."
},
{
"code": null,
"e": 1797,
"s": 1790,
"text": "cd gfg"
},
{
"code": null,
"e": 2015,
"s": 1797,
"text": "Project Structure: Now we are in our project directory. As we created the ReactJS successfully so let’s install the required package. After creating React app our project structure would look similar to the following."
},
{
"code": null,
"e": 2033,
"s": 2015,
"text": "Project_Structure"
},
{
"code": null,
"e": 2259,
"s": 2033,
"text": "Step 3: Run the following command in the terminal. Do check whether you are in React App directory or not. For the sake of convenience I have taken F:\\gfg as my current working directory, the directory of my React App(gfg). "
},
{
"code": null,
"e": 2281,
"s": 2259,
"text": "npm install bootstrap"
},
{
"code": null,
"e": 2668,
"s": 2281,
"text": "If you observe in the above command I have not mentioned the version of bootstrap. By default, it will install the latest version of bootstrap. But if you are following some tutorials, courses or wanted to build your React JS app in a particular bootstrap version, you can do so by passing ‘@version’ just after bootstrap that is npm install bootstrap@4.1 where 4.1 is name of version."
},
{
"code": null,
"e": 2827,
"s": 2668,
"text": "Our current working directory is F:/gfg. Bootstrap is now successfully installed you can verify by searching the bootstrap folder inside node_modules folder."
},
{
"code": null,
"e": 2864,
"s": 2827,
"text": "Bootstrap folder inside node_modules"
},
{
"code": null,
"e": 3052,
"s": 2864,
"text": "You can also observe some changes in your package.json file is after installing bootstrap an entry is added inside the dependencies part of package.json similar to “bootstrap”: “version”."
},
{
"code": null,
"e": 3065,
"s": 3052,
"text": "package.json"
},
{
"code": null,
"e": 3114,
"s": 3065,
"text": "Bootstrap inside dependencies after installation"
},
{
"code": null,
"e": 3362,
"s": 3114,
"text": "Step 4: As of now bootstrap is successfully installed in React app but to use it we must import it inside React file. I am importing Bootstrap minified CSS file and Bootstrap JavaScript minified bundle file inside index.js which is in F:\\gfg\\src. "
},
{
"code": null,
"e": 3458,
"s": 3362,
"text": "import 'bootstrap/dist/css/bootstrap.min.css';\nimport 'bootstrap/dist/js/bootstrap.bundle.min';"
},
{
"code": null,
"e": 3619,
"s": 3458,
"text": "The above to two statements are required in our index.js to import dependencies inside React file in order to use bootstrap classes in our React app components."
},
{
"code": null,
"e": 3638,
"s": 3619,
"text": "Filename: index.js"
},
{
"code": null,
"e": 3649,
"s": 3638,
"text": "Javascript"
},
{
"code": "import 'bootstrap/dist/css/bootstrap.min.css';import 'bootstrap/dist/js/bootstrap.bundle.min';import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import reportWebVitals from './reportWebVitals'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root'));",
"e": 4001,
"s": 3649,
"text": null
},
{
"code": null,
"e": 4346,
"s": 4001,
"text": "Explanation: The above code would probably look like index.js except line 1 and 2 they bootstrap is not imported as dependencies inside index.js by default on creating React App. In line 1 and 2 we have imported bootstrap minified css and bootstrap javascript minified bundle. Now we can use bootstrap classes inside our React app components. "
},
{
"code": null,
"e": 4636,
"s": 4346,
"text": "Step 5: We are all set to use built-in Bootstrap classes but to use Bootstrap’s JavaScript components in our react app we have to install popper.js and jquery. In case they are not installed already. To install both jquery and popper.js write the following line in terminal and hit enter."
},
{
"code": null,
"e": 4665,
"s": 4636,
"text": "npm install jquery popper.js"
},
{
"code": null,
"e": 4834,
"s": 4665,
"text": "After installing this similarly import these two dependencies in your React JS file in this case index.js Following are the statements to import these two dependencies."
},
{
"code": null,
"e": 4890,
"s": 4834,
"text": "import $ from 'jquery';\nimport Popper from 'popper.js';"
},
{
"code": null,
"e": 4982,
"s": 4890,
"text": "After making all these additional changes your index.js file should look like the following"
},
{
"code": null,
"e": 5001,
"s": 4982,
"text": "Filename: index.js"
},
{
"code": null,
"e": 5012,
"s": 5001,
"text": "Javascript"
},
{
"code": "import 'bootstrap/dist/css/bootstrap.min.css';import 'bootstrap/dist/js/bootstrap.bundle.min';import $ from 'jquery';import Popper from 'popper.js';import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import reportWebVitals from './reportWebVitals'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root')); // If you want to start measuring performance// in your app, pass a function to log results// (for example: reportWebVitals(console.log))// or send to an analytics endpoint.reportWebVitals();",
"e": 5610,
"s": 5012,
"text": null
},
{
"code": null,
"e": 5964,
"s": 5610,
"text": "Step 6: Let’s use simple bootstrap button in our React App. For that we have to import bootstrap minified css and bootstrap javascript minified bundle as a dependency in our index.js file. And add a button in our default index.js file. As we did already. After that, we have to add a button inside our App to that add the following code inside App.js. "
},
{
"code": null,
"e": 5981,
"s": 5964,
"text": "Filename: App.js"
},
{
"code": null,
"e": 5992,
"s": 5981,
"text": "Javascript"
},
{
"code": "import logo from './logo.svg';import './App.css'; function App() { return ( <div className=\"App\"> <header className=\"App-header\"> <img src={logo} className=\"App-logo\" alt=\"logo\" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className=\"App-link\" href=\"https://reactjs.org\" target=\"_blank\" rel=\"noopener noreferrer\" > Learn React </a> <a className=\"btn btn-primary\" data-bs-toggle=\"collapse\" href=\"#collapseExample\" role=\"button\" aria-expanded=\"false\" aria-controls=\"collapseExample\"> Bootstrap button </a> </header> </div> );} export default App;",
"e": 6752,
"s": 5992,
"text": null
},
{
"code": null,
"e": 6862,
"s": 6752,
"text": "Step to run the application: Save your file and run npm server by entering following command in the terminal."
},
{
"code": null,
"e": 6872,
"s": 6862,
"text": "npm start"
},
{
"code": null,
"e": 6940,
"s": 6872,
"text": "Output: After running the server, your output would look like this "
},
{
"code": null,
"e": 6947,
"s": 6940,
"text": "OUTPUT"
},
{
"code": null,
"e": 6956,
"s": 6947,
"text": "avgaur22"
},
{
"code": null,
"e": 6968,
"s": 6956,
"text": "kashishsoda"
},
{
"code": null,
"e": 6975,
"s": 6968,
"text": "Picked"
},
{
"code": null,
"e": 6991,
"s": 6975,
"text": "React-Questions"
},
{
"code": null,
"e": 6999,
"s": 6991,
"text": "ReactJS"
},
{
"code": null,
"e": 7016,
"s": 6999,
"text": "Web Technologies"
},
{
"code": null,
"e": 7114,
"s": 7016,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7152,
"s": 7114,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 7171,
"s": 7152,
"text": "ReactJS setState()"
},
{
"code": null,
"e": 7239,
"s": 7171,
"text": "How to pass data from one component to other component in ReactJS ?"
},
{
"code": null,
"e": 7274,
"s": 7239,
"text": "Re-rendering Components in ReactJS"
},
{
"code": null,
"e": 7295,
"s": 7274,
"text": "ReactJS defaultProps"
},
{
"code": null,
"e": 7328,
"s": 7295,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 7390,
"s": 7328,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 7451,
"s": 7390,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 7501,
"s": 7451,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python – Group similar elements into Matrix
|
30 Dec, 2020
Sometimes, while working with Python Matrix, we can have a problem in which we need to perform grouping of all the elements with are same. This kind of problem can have application in data domains. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [1, 3, 4, 4, 2, 3]Output : [[1], [2], [3, 3], [4, 4]]
Input : test_list = [1, 3, 4, 2]Output : [[1], [2], [3], [4]]
Method #1 : Using list comprehension + groupby()The combination of above functions provide possible solution to this problem. In this, we perform task of grouping using groupby() and list comprehension assists in iteration.
# Python3 code to demonstrate working of # Group similar elements into Matrix# Using list comprehension + groupby()from itertools import groupby # initializing listtest_list = [1, 3, 5, 1, 3, 2, 5, 4, 2] # printing original list print("The original list : " + str(test_list)) # Group similar elements into Matrix# Using list comprehension + groupby()res = [list(val) for key, val in groupby(sorted(test_list))] # printing result print("Matrix after grouping : " + str(res))
The original list : [1, 3, 5, 1, 3, 2, 5, 4, 2]
Matrix after grouping : [[1, 1], [2, 2], [3, 3], [4], [5, 5]]
Method #2 : Using list comprehension + Counter()This is yet another approach to this problem. In this, we get the values along with it’s frequency using Counter() and then employ list comprehension to multiply each element with frequency to get duplicates
# Python3 code to demonstrate working of # Group similar elements into Matrix# Using list comprehension + Counter()from collections import Counter # initializing listtest_list = [1, 3, 5, 1, 3, 2, 5, 4, 2] # printing original list print("The original list : " + str(test_list)) # Group similar elements into Matrix# Using list comprehension + Counter()temp = Counter(test_list)res = [[key] * val for key, val in temp.items()] # printing result print("Matrix after grouping : " + str(res))
The original list : [1, 3, 5, 1, 3, 2, 5, 4, 2]
Matrix after grouping : [[1, 1], [2, 2], [3, 3], [4], [5, 5]]
Python list-programs
Python matrix-program
Python-list-of-lists
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Dec, 2020"
},
{
"code": null,
"e": 290,
"s": 28,
"text": "Sometimes, while working with Python Matrix, we can have a problem in which we need to perform grouping of all the elements with are same. This kind of problem can have application in data domains. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 364,
"s": 290,
"text": "Input : test_list = [1, 3, 4, 4, 2, 3]Output : [[1], [2], [3, 3], [4, 4]]"
},
{
"code": null,
"e": 426,
"s": 364,
"text": "Input : test_list = [1, 3, 4, 2]Output : [[1], [2], [3], [4]]"
},
{
"code": null,
"e": 650,
"s": 426,
"text": "Method #1 : Using list comprehension + groupby()The combination of above functions provide possible solution to this problem. In this, we perform task of grouping using groupby() and list comprehension assists in iteration."
},
{
"code": "# Python3 code to demonstrate working of # Group similar elements into Matrix# Using list comprehension + groupby()from itertools import groupby # initializing listtest_list = [1, 3, 5, 1, 3, 2, 5, 4, 2] # printing original list print(\"The original list : \" + str(test_list)) # Group similar elements into Matrix# Using list comprehension + groupby()res = [list(val) for key, val in groupby(sorted(test_list))] # printing result print(\"Matrix after grouping : \" + str(res))",
"e": 1138,
"s": 650,
"text": null
},
{
"code": null,
"e": 1249,
"s": 1138,
"text": "The original list : [1, 3, 5, 1, 3, 2, 5, 4, 2]\nMatrix after grouping : [[1, 1], [2, 2], [3, 3], [4], [5, 5]]\n"
},
{
"code": null,
"e": 1507,
"s": 1251,
"text": "Method #2 : Using list comprehension + Counter()This is yet another approach to this problem. In this, we get the values along with it’s frequency using Counter() and then employ list comprehension to multiply each element with frequency to get duplicates"
},
{
"code": "# Python3 code to demonstrate working of # Group similar elements into Matrix# Using list comprehension + Counter()from collections import Counter # initializing listtest_list = [1, 3, 5, 1, 3, 2, 5, 4, 2] # printing original list print(\"The original list : \" + str(test_list)) # Group similar elements into Matrix# Using list comprehension + Counter()temp = Counter(test_list)res = [[key] * val for key, val in temp.items()] # printing result print(\"Matrix after grouping : \" + str(res))",
"e": 2000,
"s": 1507,
"text": null
},
{
"code": null,
"e": 2111,
"s": 2000,
"text": "The original list : [1, 3, 5, 1, 3, 2, 5, 4, 2]\nMatrix after grouping : [[1, 1], [2, 2], [3, 3], [4], [5, 5]]\n"
},
{
"code": null,
"e": 2132,
"s": 2111,
"text": "Python list-programs"
},
{
"code": null,
"e": 2154,
"s": 2132,
"text": "Python matrix-program"
},
{
"code": null,
"e": 2175,
"s": 2154,
"text": "Python-list-of-lists"
},
{
"code": null,
"e": 2182,
"s": 2175,
"text": "Python"
},
{
"code": null,
"e": 2198,
"s": 2182,
"text": "Python Programs"
},
{
"code": null,
"e": 2296,
"s": 2198,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2314,
"s": 2296,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2356,
"s": 2314,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2378,
"s": 2356,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2413,
"s": 2378,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2439,
"s": 2413,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2482,
"s": 2439,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2504,
"s": 2482,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2543,
"s": 2504,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2581,
"s": 2543,
"text": "Python | Convert a list to dictionary"
}
] |
Circuit Switching in Computer Network
|
13 Jun, 2022
In circuit switching network resources (bandwidth) are divided into pieces and bit delay is constant during a connection. The dedicated path/circuit established between sender and receiver provides a guaranteed data rate. Data can be transmitted without any delays once the circuit is established.
Telephone system network is one of the example of Circuit switching. TDM (Time Division Multiplexing) and FDM (Frequency Division Multiplexing) are two methods of multiplexing multiple signals into a single carrier.
Frequency Division Multiplexing : Divides into multiple bands Frequency Division Multiplexing or FDM is used when multiple data signals are combined for simultaneous transmission via a shared communication medium.It is a technique by which the total bandwidth is divided into a series of non-overlapping frequency sub-bands,where each sub-band carry different signal. Practical use in radio spectrum & optical fibre to share multiple independent signals.
Time Division Multiplexing : Divides into frames Time-division multiplexing (TDM) is a method of transmitting and receiving independent signals over a common signal path by means of synchronized switches at each end of the transmission line. TDM is used for long-distance communication links and bears heavy data traffic loads from end user. Time division multiplexing (TDM) is also known as a digital circuit switched.
Advantages of Circuit Switching: It has the following advantages :
The main advantage of circuit switching is that a committed transmission channel is established between the computers which give a guaranteed data rate.In-circuit switching, there is no delay in data flow because of the dedicated transmission path.
The main advantage of circuit switching is that a committed transmission channel is established between the computers which give a guaranteed data rate.
In-circuit switching, there is no delay in data flow because of the dedicated transmission path.
Disadvantages of Circuit Switching: It has the following disadvantages :
It takes a long time to establish a connection.More bandwidth is required in setting up dedicated channels.It cannot be used to transmit any other data even if the channel is free as the connection is dedicated to circuit switching.
It takes a long time to establish a connection.
More bandwidth is required in setting up dedicated channels.
It cannot be used to transmit any other data even if the channel is free as the connection is dedicated to circuit switching.
Formulas in Circuit Switching :
Transmission rate = Link Rate or Bit rate /
no. of slots = R/h bps
Transmission time = size of file /
transmission rate
= x / (R/h) = (x*h)/R second
Total time to send packet to destination =
Transmission time + circuit setup time
Question on Circuit switching – These questions will help you understand circuit switching Example 1 : How long it takes to send a file of ‘x bits’ from host A to host B over a circuit switched network that uses TDM with ‘h slots’ and have a bit rate of ‘R Mbps’, circuit establish time is k seconds.Find total time?
Explanation : Transmission rate = Link Rate or Bit rate / no. of slots = R/h bps Transmission time = size of file/ transmission rate = x / (R/h) = (x*h)/R
Total time = transmission time + circuit setup time = (x*h)/R secs + k secs Example 2 : If a link transmits F frames/sec and each slot has B bits then find the transmission rate?
Explanation : Since it is not mention how many slots in each frame we take one frame has one slot. The transmission rate is the amount of data sent in 1 second. Transmission rate = F * B bits/sec
To know the difference between Circuit Switching and Packet Switching refer – Difference b/w Circuit switch & packet switch
References : https://en.wikipedia.org/wiki/Circuit_switching https://en.wikipedia.org/wiki/Frequency-division_multiplexing
This article is contributed by Shaurya Uppal. 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.
ashushrma378
pall58183
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
GSM in Wireless Communication
Differences between IPv4 and IPv6
Difference between MANET and VANET
Classification of MAC protocols
Difference between FDMA, TDMA and CDMA
MANET Routing Protocols
GPRS architecture in wireless communication
Socket Programming in Python
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 353,
"s": 54,
"text": "In circuit switching network resources (bandwidth) are divided into pieces and bit delay is constant during a connection. The dedicated path/circuit established between sender and receiver provides a guaranteed data rate. Data can be transmitted without any delays once the circuit is established. "
},
{
"code": null,
"e": 570,
"s": 353,
"text": "Telephone system network is one of the example of Circuit switching. TDM (Time Division Multiplexing) and FDM (Frequency Division Multiplexing) are two methods of multiplexing multiple signals into a single carrier. "
},
{
"code": null,
"e": 1028,
"s": 572,
"text": "Frequency Division Multiplexing : Divides into multiple bands Frequency Division Multiplexing or FDM is used when multiple data signals are combined for simultaneous transmission via a shared communication medium.It is a technique by which the total bandwidth is divided into a series of non-overlapping frequency sub-bands,where each sub-band carry different signal. Practical use in radio spectrum & optical fibre to share multiple independent signals. "
},
{
"code": null,
"e": 1448,
"s": 1028,
"text": "Time Division Multiplexing : Divides into frames Time-division multiplexing (TDM) is a method of transmitting and receiving independent signals over a common signal path by means of synchronized switches at each end of the transmission line. TDM is used for long-distance communication links and bears heavy data traffic loads from end user. Time division multiplexing (TDM) is also known as a digital circuit switched."
},
{
"code": null,
"e": 1517,
"s": 1448,
"text": "Advantages of Circuit Switching: It has the following advantages : "
},
{
"code": null,
"e": 1766,
"s": 1517,
"text": "The main advantage of circuit switching is that a committed transmission channel is established between the computers which give a guaranteed data rate.In-circuit switching, there is no delay in data flow because of the dedicated transmission path."
},
{
"code": null,
"e": 1919,
"s": 1766,
"text": "The main advantage of circuit switching is that a committed transmission channel is established between the computers which give a guaranteed data rate."
},
{
"code": null,
"e": 2016,
"s": 1919,
"text": "In-circuit switching, there is no delay in data flow because of the dedicated transmission path."
},
{
"code": null,
"e": 2091,
"s": 2016,
"text": "Disadvantages of Circuit Switching: It has the following disadvantages : "
},
{
"code": null,
"e": 2324,
"s": 2091,
"text": "It takes a long time to establish a connection.More bandwidth is required in setting up dedicated channels.It cannot be used to transmit any other data even if the channel is free as the connection is dedicated to circuit switching."
},
{
"code": null,
"e": 2372,
"s": 2324,
"text": "It takes a long time to establish a connection."
},
{
"code": null,
"e": 2433,
"s": 2372,
"text": "More bandwidth is required in setting up dedicated channels."
},
{
"code": null,
"e": 2559,
"s": 2433,
"text": "It cannot be used to transmit any other data even if the channel is free as the connection is dedicated to circuit switching."
},
{
"code": null,
"e": 2593,
"s": 2559,
"text": "Formulas in Circuit Switching : "
},
{
"code": null,
"e": 2900,
"s": 2593,
"text": "Transmission rate = Link Rate or Bit rate / \n no. of slots = R/h bps\nTransmission time = size of file / \n transmission rate \n = x / (R/h) = (x*h)/R second\nTotal time to send packet to destination =\n Transmission time + circuit setup time "
},
{
"code": null,
"e": 3219,
"s": 2900,
"text": "Question on Circuit switching – These questions will help you understand circuit switching Example 1 : How long it takes to send a file of ‘x bits’ from host A to host B over a circuit switched network that uses TDM with ‘h slots’ and have a bit rate of ‘R Mbps’, circuit establish time is k seconds.Find total time? "
},
{
"code": null,
"e": 3375,
"s": 3219,
"text": "Explanation : Transmission rate = Link Rate or Bit rate / no. of slots = R/h bps Transmission time = size of file/ transmission rate = x / (R/h) = (x*h)/R "
},
{
"code": null,
"e": 3556,
"s": 3375,
"text": "Total time = transmission time + circuit setup time = (x*h)/R secs + k secs Example 2 : If a link transmits F frames/sec and each slot has B bits then find the transmission rate? "
},
{
"code": null,
"e": 3754,
"s": 3556,
"text": "Explanation : Since it is not mention how many slots in each frame we take one frame has one slot. The transmission rate is the amount of data sent in 1 second. Transmission rate = F * B bits/sec "
},
{
"code": null,
"e": 3880,
"s": 3754,
"text": "To know the difference between Circuit Switching and Packet Switching refer – Difference b/w Circuit switch & packet switch "
},
{
"code": null,
"e": 4004,
"s": 3880,
"text": "References : https://en.wikipedia.org/wiki/Circuit_switching https://en.wikipedia.org/wiki/Frequency-division_multiplexing "
},
{
"code": null,
"e": 4302,
"s": 4004,
"text": "This article is contributed by Shaurya Uppal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 4428,
"s": 4302,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 4441,
"s": 4428,
"text": "ashushrma378"
},
{
"code": null,
"e": 4451,
"s": 4441,
"text": "pall58183"
},
{
"code": null,
"e": 4469,
"s": 4451,
"text": "Computer Networks"
},
{
"code": null,
"e": 4487,
"s": 4469,
"text": "Computer Networks"
},
{
"code": null,
"e": 4585,
"s": 4487,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4615,
"s": 4585,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 4655,
"s": 4615,
"text": "Mobile Internet Protocol (or Mobile IP)"
},
{
"code": null,
"e": 4685,
"s": 4655,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 4719,
"s": 4685,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 4754,
"s": 4719,
"text": "Difference between MANET and VANET"
},
{
"code": null,
"e": 4786,
"s": 4754,
"text": "Classification of MAC protocols"
},
{
"code": null,
"e": 4825,
"s": 4786,
"text": "Difference between FDMA, TDMA and CDMA"
},
{
"code": null,
"e": 4849,
"s": 4825,
"text": "MANET Routing Protocols"
},
{
"code": null,
"e": 4893,
"s": 4849,
"text": "GPRS architecture in wireless communication"
}
] |
Program to find the diameter, cycles and edges of a Wheel Graph
|
02 Dec, 2019
Wheel Graph: A Wheel graph is a graph formed by connecting a single universal vertex to all vertices of a cycle. Properties:-
Wheel graphs are Planar graphs.
There is always a Hamiltonian cycle in the Wheel graph.
Chromatic Number is 3 and 4, if n is odd and even respectively.
Problem Statement: Given the Number of Vertices in a Wheel Graph. The task is to find:
The Number of Cycles in the Wheel Graph.Number of edges in Wheel Graph.The diameter of a Wheel Graph.Examples:Input: vertices = 4
Output: Number of cycle = 7
Number of edge = 6
Diameter = 1
Input: vertices = 6
Output: Number of cycle = 21
Number of edge = 10
Diameter = 2
Recommended: Please try your approach on {IDE} first, before moving on to the solution.Example #1: For vertices = 4 Wheel Graph, total cycle is 7:Example #2: For vertices = 5 and 7 Wheel Graph Number of edges = 8 and 12 respectively:Example #3:For vertices = 4, the Diameter is 1 as We can go from any vertices to any vertices by covering only 1 edge.Formula to calculate the cycles, edges and diameter:-Number of Cycle = (vertices * vertices) - (3 * vertices) + 3
Number of edge = 2 * (vertices - 1)
Diameter = if vertices = 4, Diameter = 1
if vertices > 4, Diameter = 2
Below is the required implementation:C++JavaPython3C#PHPC++// C++ Program to find the diameter, // cycles and edges of a Wheel Graph#include <bits/stdc++.h>using namespace std; // Function that calculates the// Number of Cycle in Wheel Graph.int totalCycle(int vertices){ int result = 0; // calculates no. of Cycle. result = pow(vertices, 2) - (3 * vertices) + 3; return result;} // Function that calculates the// Number of Edges in Wheel graph.int Edges(int vertices){ int result = 0; result = 2 * (vertices - 1); return result;} // Function that calculates the// Diameter in Wheel Graph.int Diameter(int vertices){ int result = 0; // calculates Diameter. if (vertices == 4) result = 1; else result = 2; return result;} // Driver Codeint main(){ int vertices = 4; cout << "Number of Cycle = " << totalCycle(vertices) << endl; cout << "Number of Edges = " << Edges(vertices) << endl; cout << "Diameter = " << Diameter(vertices); return 0;}Java//Java Program to find the diameter, // cycles and edges of a Wheel Graphimport java.io.*; class GFG{ // Function that calculates the // Number of Cycle in Wheel Graph. static int totalCycle(double vertices) { double result = 0; int result1 = 0; // calculates no. of Cycle. result = Math.pow(vertices, 2) - (3 * vertices) + 3; result1 = (int)(result); return result1; } // Function that calculates the // Number of Edges in Wheel graph. static int Edges(int vertices) { int result = 0; result = 2 * (vertices - 1); return result; } // Function that calculates the // Diameter in Wheel Graph. static int Diameter(int vertices) { int result = 0; // calculates Diameter. if (vertices == 4) result = 1; else result = 2; return result; } //Driver Code public static void main(String[] args) { int vertices = 4; System.out.println("Number of Cycle = " + totalCycle(vertices)); System.out.println("Number of Edges = " + Edges(vertices)); System.out.println("Diameter = " + Diameter(vertices)); }}Python3# Python3 Program to find the diameter, # cycles and edges of a Wheel Graph # Function that calculates the # Number of Cycle in Wheel Graph. def totalCycle(vertices): result = 0 # calculates no. of Cycle. result = (pow(vertices, 2) - (3 * vertices) + 3) return result # Function that calculates the # Number of Edges in Wheel graph. def Edges(vertices): result = 0 result = 2 * (vertices - 1) return result # Function that calculates the # Diameter in Wheel Graph. def Diameter(vertices): result = 0 # calculates Diameter. if vertices == 4: result = 1 else: result = 2 return result # Driver Code if __name__ == "__main__": vertices = 4 print("Number of Cycle =", totalCycle(vertices)) print("Number of Edges =", Edges(vertices)) print("Diameter =", Diameter(vertices)) # This code is contributed by Rituraj JainC#// C# Program to find the diameter, // cycles and edges of a Wheel Graphusing System;class GFG{// Function that calculates the // Number of Cycle in Wheel Graph. static int totalCycle(double vertices) { double result = 0; int result1 = 0; // calculates no. of Cycle. result = Math.Pow(vertices, 2) - (3 * vertices) + 3; result1 = (int)(result); return result1; } // Function that calculates the // Number of Edges in Wheel graph. static int Edges(int vertices) { int result = 0; result = 2 * (vertices - 1); return result; } // Function that calculates the // Diameter in Wheel Graph. static int Diameter(int vertices) { int result = 0; // calculates Diameter. if (vertices == 4) result = 1; else result = 2; return result; } // Driver Codepublic static void Main(){ int vertices = 4; Console.WriteLine("Number of Cycle = " + totalCycle(vertices)); Console.WriteLine("Number of Edges = " + Edges(vertices)); Console.WriteLine("Diameter = " + Diameter(vertices));}} // This code is contributed by inder_vermaPHP<?php// PHP Program to find the diameter, // cycles and edges of a Wheel Graph // Function that calculates the// Number of Cycle in Wheel Graph.function totalCycle($vertices){ $result = 0; // calculates no. of Cycle. $result = pow($vertices, 2) - (3 * $vertices) + 3; return $result;} // Function that calculates the// Number of Edges in Wheel graph.function Edges($vertices){ $result = 0; $result = 2 * ($vertices - 1); return $result;} // Function that calculates the// Diameter in Wheel Graph.function Diameter($vertices){ $result = 0; // calculates Diameter. if ($vertices == 4) $result = 1; else $result = 2; return $result;} // Driver Code$vertices = 4; echo "Number of Cycle = " , totalCycle($vertices), "\n";echo "Number of Edges = " , Edges($vertices), "\n" ;echo "Diameter = " , Diameter($vertices); // This code is contributed by inder_verma?>Output:Number of Cycle = 7
Number of Edges = 6
Diameter = 1
My Personal Notes
arrow_drop_upSave
The Number of Cycles in the Wheel Graph.
Number of edges in Wheel Graph.
The diameter of a Wheel Graph.
Examples:Input: vertices = 4
Output: Number of cycle = 7
Number of edge = 6
Diameter = 1
Input: vertices = 6
Output: Number of cycle = 21
Number of edge = 10
Diameter = 2
Recommended: Please try your approach on {IDE} first, before moving on to the solution.Example #1: For vertices = 4 Wheel Graph, total cycle is 7:Example #2: For vertices = 5 and 7 Wheel Graph Number of edges = 8 and 12 respectively:Example #3:For vertices = 4, the Diameter is 1 as We can go from any vertices to any vertices by covering only 1 edge.Formula to calculate the cycles, edges and diameter:-Number of Cycle = (vertices * vertices) - (3 * vertices) + 3
Number of edge = 2 * (vertices - 1)
Diameter = if vertices = 4, Diameter = 1
if vertices > 4, Diameter = 2
Below is the required implementation:C++JavaPython3C#PHPC++// C++ Program to find the diameter, // cycles and edges of a Wheel Graph#include <bits/stdc++.h>using namespace std; // Function that calculates the// Number of Cycle in Wheel Graph.int totalCycle(int vertices){ int result = 0; // calculates no. of Cycle. result = pow(vertices, 2) - (3 * vertices) + 3; return result;} // Function that calculates the// Number of Edges in Wheel graph.int Edges(int vertices){ int result = 0; result = 2 * (vertices - 1); return result;} // Function that calculates the// Diameter in Wheel Graph.int Diameter(int vertices){ int result = 0; // calculates Diameter. if (vertices == 4) result = 1; else result = 2; return result;} // Driver Codeint main(){ int vertices = 4; cout << "Number of Cycle = " << totalCycle(vertices) << endl; cout << "Number of Edges = " << Edges(vertices) << endl; cout << "Diameter = " << Diameter(vertices); return 0;}Java//Java Program to find the diameter, // cycles and edges of a Wheel Graphimport java.io.*; class GFG{ // Function that calculates the // Number of Cycle in Wheel Graph. static int totalCycle(double vertices) { double result = 0; int result1 = 0; // calculates no. of Cycle. result = Math.pow(vertices, 2) - (3 * vertices) + 3; result1 = (int)(result); return result1; } // Function that calculates the // Number of Edges in Wheel graph. static int Edges(int vertices) { int result = 0; result = 2 * (vertices - 1); return result; } // Function that calculates the // Diameter in Wheel Graph. static int Diameter(int vertices) { int result = 0; // calculates Diameter. if (vertices == 4) result = 1; else result = 2; return result; } //Driver Code public static void main(String[] args) { int vertices = 4; System.out.println("Number of Cycle = " + totalCycle(vertices)); System.out.println("Number of Edges = " + Edges(vertices)); System.out.println("Diameter = " + Diameter(vertices)); }}Python3# Python3 Program to find the diameter, # cycles and edges of a Wheel Graph # Function that calculates the # Number of Cycle in Wheel Graph. def totalCycle(vertices): result = 0 # calculates no. of Cycle. result = (pow(vertices, 2) - (3 * vertices) + 3) return result # Function that calculates the # Number of Edges in Wheel graph. def Edges(vertices): result = 0 result = 2 * (vertices - 1) return result # Function that calculates the # Diameter in Wheel Graph. def Diameter(vertices): result = 0 # calculates Diameter. if vertices == 4: result = 1 else: result = 2 return result # Driver Code if __name__ == "__main__": vertices = 4 print("Number of Cycle =", totalCycle(vertices)) print("Number of Edges =", Edges(vertices)) print("Diameter =", Diameter(vertices)) # This code is contributed by Rituraj JainC#// C# Program to find the diameter, // cycles and edges of a Wheel Graphusing System;class GFG{// Function that calculates the // Number of Cycle in Wheel Graph. static int totalCycle(double vertices) { double result = 0; int result1 = 0; // calculates no. of Cycle. result = Math.Pow(vertices, 2) - (3 * vertices) + 3; result1 = (int)(result); return result1; } // Function that calculates the // Number of Edges in Wheel graph. static int Edges(int vertices) { int result = 0; result = 2 * (vertices - 1); return result; } // Function that calculates the // Diameter in Wheel Graph. static int Diameter(int vertices) { int result = 0; // calculates Diameter. if (vertices == 4) result = 1; else result = 2; return result; } // Driver Codepublic static void Main(){ int vertices = 4; Console.WriteLine("Number of Cycle = " + totalCycle(vertices)); Console.WriteLine("Number of Edges = " + Edges(vertices)); Console.WriteLine("Diameter = " + Diameter(vertices));}} // This code is contributed by inder_vermaPHP<?php// PHP Program to find the diameter, // cycles and edges of a Wheel Graph // Function that calculates the// Number of Cycle in Wheel Graph.function totalCycle($vertices){ $result = 0; // calculates no. of Cycle. $result = pow($vertices, 2) - (3 * $vertices) + 3; return $result;} // Function that calculates the// Number of Edges in Wheel graph.function Edges($vertices){ $result = 0; $result = 2 * ($vertices - 1); return $result;} // Function that calculates the// Diameter in Wheel Graph.function Diameter($vertices){ $result = 0; // calculates Diameter. if ($vertices == 4) $result = 1; else $result = 2; return $result;} // Driver Code$vertices = 4; echo "Number of Cycle = " , totalCycle($vertices), "\n";echo "Number of Edges = " , Edges($vertices), "\n" ;echo "Diameter = " , Diameter($vertices); // This code is contributed by inder_verma?>Output:Number of Cycle = 7
Number of Edges = 6
Diameter = 1
My Personal Notes
arrow_drop_upSave
Examples:
Input: vertices = 4
Output: Number of cycle = 7
Number of edge = 6
Diameter = 1
Input: vertices = 6
Output: Number of cycle = 21
Number of edge = 10
Diameter = 2
Example #1: For vertices = 4 Wheel Graph, total cycle is 7:
Example #2: For vertices = 5 and 7 Wheel Graph Number of edges = 8 and 12 respectively:
Example #3:For vertices = 4, the Diameter is 1 as We can go from any vertices to any vertices by covering only 1 edge.
Formula to calculate the cycles, edges and diameter:-
Number of Cycle = (vertices * vertices) - (3 * vertices) + 3
Number of edge = 2 * (vertices - 1)
Diameter = if vertices = 4, Diameter = 1
if vertices > 4, Diameter = 2
Below is the required implementation:
C++
Java
Python3
C#
PHP
// C++ Program to find the diameter, // cycles and edges of a Wheel Graph#include <bits/stdc++.h>using namespace std; // Function that calculates the// Number of Cycle in Wheel Graph.int totalCycle(int vertices){ int result = 0; // calculates no. of Cycle. result = pow(vertices, 2) - (3 * vertices) + 3; return result;} // Function that calculates the// Number of Edges in Wheel graph.int Edges(int vertices){ int result = 0; result = 2 * (vertices - 1); return result;} // Function that calculates the// Diameter in Wheel Graph.int Diameter(int vertices){ int result = 0; // calculates Diameter. if (vertices == 4) result = 1; else result = 2; return result;} // Driver Codeint main(){ int vertices = 4; cout << "Number of Cycle = " << totalCycle(vertices) << endl; cout << "Number of Edges = " << Edges(vertices) << endl; cout << "Diameter = " << Diameter(vertices); return 0;}
//Java Program to find the diameter, // cycles and edges of a Wheel Graphimport java.io.*; class GFG{ // Function that calculates the // Number of Cycle in Wheel Graph. static int totalCycle(double vertices) { double result = 0; int result1 = 0; // calculates no. of Cycle. result = Math.pow(vertices, 2) - (3 * vertices) + 3; result1 = (int)(result); return result1; } // Function that calculates the // Number of Edges in Wheel graph. static int Edges(int vertices) { int result = 0; result = 2 * (vertices - 1); return result; } // Function that calculates the // Diameter in Wheel Graph. static int Diameter(int vertices) { int result = 0; // calculates Diameter. if (vertices == 4) result = 1; else result = 2; return result; } //Driver Code public static void main(String[] args) { int vertices = 4; System.out.println("Number of Cycle = " + totalCycle(vertices)); System.out.println("Number of Edges = " + Edges(vertices)); System.out.println("Diameter = " + Diameter(vertices)); }}
# Python3 Program to find the diameter, # cycles and edges of a Wheel Graph # Function that calculates the # Number of Cycle in Wheel Graph. def totalCycle(vertices): result = 0 # calculates no. of Cycle. result = (pow(vertices, 2) - (3 * vertices) + 3) return result # Function that calculates the # Number of Edges in Wheel graph. def Edges(vertices): result = 0 result = 2 * (vertices - 1) return result # Function that calculates the # Diameter in Wheel Graph. def Diameter(vertices): result = 0 # calculates Diameter. if vertices == 4: result = 1 else: result = 2 return result # Driver Code if __name__ == "__main__": vertices = 4 print("Number of Cycle =", totalCycle(vertices)) print("Number of Edges =", Edges(vertices)) print("Diameter =", Diameter(vertices)) # This code is contributed by Rituraj Jain
// C# Program to find the diameter, // cycles and edges of a Wheel Graphusing System;class GFG{// Function that calculates the // Number of Cycle in Wheel Graph. static int totalCycle(double vertices) { double result = 0; int result1 = 0; // calculates no. of Cycle. result = Math.Pow(vertices, 2) - (3 * vertices) + 3; result1 = (int)(result); return result1; } // Function that calculates the // Number of Edges in Wheel graph. static int Edges(int vertices) { int result = 0; result = 2 * (vertices - 1); return result; } // Function that calculates the // Diameter in Wheel Graph. static int Diameter(int vertices) { int result = 0; // calculates Diameter. if (vertices == 4) result = 1; else result = 2; return result; } // Driver Codepublic static void Main(){ int vertices = 4; Console.WriteLine("Number of Cycle = " + totalCycle(vertices)); Console.WriteLine("Number of Edges = " + Edges(vertices)); Console.WriteLine("Diameter = " + Diameter(vertices));}} // This code is contributed by inder_verma
<?php// PHP Program to find the diameter, // cycles and edges of a Wheel Graph // Function that calculates the// Number of Cycle in Wheel Graph.function totalCycle($vertices){ $result = 0; // calculates no. of Cycle. $result = pow($vertices, 2) - (3 * $vertices) + 3; return $result;} // Function that calculates the// Number of Edges in Wheel graph.function Edges($vertices){ $result = 0; $result = 2 * ($vertices - 1); return $result;} // Function that calculates the// Diameter in Wheel Graph.function Diameter($vertices){ $result = 0; // calculates Diameter. if ($vertices == 4) $result = 1; else $result = 2; return $result;} // Driver Code$vertices = 4; echo "Number of Cycle = " , totalCycle($vertices), "\n";echo "Number of Edges = " , Edges($vertices), "\n" ;echo "Diameter = " , Diameter($vertices); // This code is contributed by inder_verma?>
Number of Cycle = 7
Number of Edges = 6
Diameter = 1
Naman_Garg
inderDuMCA
rituraj_jain
Akanksha_Rai
Data Structures-Graph
Graph
School Programming
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Check if a given graph is tree or not
Minimum steps to reach target by a Knight | Set 1
Total number of Spanning Trees in a Graph
C++ Classes and Objects
Python Dictionary
Object Oriented Programming in C++
Inheritance in C++
Arrays in C/C++
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Dec, 2019"
},
{
"code": null,
"e": 154,
"s": 28,
"text": "Wheel Graph: A Wheel graph is a graph formed by connecting a single universal vertex to all vertices of a cycle. Properties:-"
},
{
"code": null,
"e": 186,
"s": 154,
"text": "Wheel graphs are Planar graphs."
},
{
"code": null,
"e": 242,
"s": 186,
"text": "There is always a Hamiltonian cycle in the Wheel graph."
},
{
"code": null,
"e": 306,
"s": 242,
"text": "Chromatic Number is 3 and 4, if n is odd and even respectively."
},
{
"code": null,
"e": 393,
"s": 306,
"text": "Problem Statement: Given the Number of Vertices in a Wheel Graph. The task is to find:"
},
{
"code": null,
"e": 6810,
"s": 393,
"text": "The Number of Cycles in the Wheel Graph.Number of edges in Wheel Graph.The diameter of a Wheel Graph.Examples:Input: vertices = 4\nOutput: Number of cycle = 7\n Number of edge = 6\n Diameter = 1\n\nInput: vertices = 6\nOutput: Number of cycle = 21\n Number of edge = 10\n Diameter = 2\n\nRecommended: Please try your approach on {IDE} first, before moving on to the solution.Example #1: For vertices = 4 Wheel Graph, total cycle is 7:Example #2: For vertices = 5 and 7 Wheel Graph Number of edges = 8 and 12 respectively:Example #3:For vertices = 4, the Diameter is 1 as We can go from any vertices to any vertices by covering only 1 edge.Formula to calculate the cycles, edges and diameter:-Number of Cycle = (vertices * vertices) - (3 * vertices) + 3\nNumber of edge = 2 * (vertices - 1)\nDiameter = if vertices = 4, Diameter = 1\n if vertices > 4, Diameter = 2\nBelow is the required implementation:C++JavaPython3C#PHPC++// C++ Program to find the diameter, // cycles and edges of a Wheel Graph#include <bits/stdc++.h>using namespace std; // Function that calculates the// Number of Cycle in Wheel Graph.int totalCycle(int vertices){ int result = 0; // calculates no. of Cycle. result = pow(vertices, 2) - (3 * vertices) + 3; return result;} // Function that calculates the// Number of Edges in Wheel graph.int Edges(int vertices){ int result = 0; result = 2 * (vertices - 1); return result;} // Function that calculates the// Diameter in Wheel Graph.int Diameter(int vertices){ int result = 0; // calculates Diameter. if (vertices == 4) result = 1; else result = 2; return result;} // Driver Codeint main(){ int vertices = 4; cout << \"Number of Cycle = \" << totalCycle(vertices) << endl; cout << \"Number of Edges = \" << Edges(vertices) << endl; cout << \"Diameter = \" << Diameter(vertices); return 0;}Java//Java Program to find the diameter, // cycles and edges of a Wheel Graphimport java.io.*; class GFG{ // Function that calculates the // Number of Cycle in Wheel Graph. static int totalCycle(double vertices) { double result = 0; int result1 = 0; // calculates no. of Cycle. result = Math.pow(vertices, 2) - (3 * vertices) + 3; result1 = (int)(result); return result1; } // Function that calculates the // Number of Edges in Wheel graph. static int Edges(int vertices) { int result = 0; result = 2 * (vertices - 1); return result; } // Function that calculates the // Diameter in Wheel Graph. static int Diameter(int vertices) { int result = 0; // calculates Diameter. if (vertices == 4) result = 1; else result = 2; return result; } //Driver Code public static void main(String[] args) { int vertices = 4; System.out.println(\"Number of Cycle = \" + totalCycle(vertices)); System.out.println(\"Number of Edges = \" + Edges(vertices)); System.out.println(\"Diameter = \" + Diameter(vertices)); }}Python3# Python3 Program to find the diameter, # cycles and edges of a Wheel Graph # Function that calculates the # Number of Cycle in Wheel Graph. def totalCycle(vertices): result = 0 # calculates no. of Cycle. result = (pow(vertices, 2) - (3 * vertices) + 3) return result # Function that calculates the # Number of Edges in Wheel graph. def Edges(vertices): result = 0 result = 2 * (vertices - 1) return result # Function that calculates the # Diameter in Wheel Graph. def Diameter(vertices): result = 0 # calculates Diameter. if vertices == 4: result = 1 else: result = 2 return result # Driver Code if __name__ == \"__main__\": vertices = 4 print(\"Number of Cycle =\", totalCycle(vertices)) print(\"Number of Edges =\", Edges(vertices)) print(\"Diameter =\", Diameter(vertices)) # This code is contributed by Rituraj JainC#// C# Program to find the diameter, // cycles and edges of a Wheel Graphusing System;class GFG{// Function that calculates the // Number of Cycle in Wheel Graph. static int totalCycle(double vertices) { double result = 0; int result1 = 0; // calculates no. of Cycle. result = Math.Pow(vertices, 2) - (3 * vertices) + 3; result1 = (int)(result); return result1; } // Function that calculates the // Number of Edges in Wheel graph. static int Edges(int vertices) { int result = 0; result = 2 * (vertices - 1); return result; } // Function that calculates the // Diameter in Wheel Graph. static int Diameter(int vertices) { int result = 0; // calculates Diameter. if (vertices == 4) result = 1; else result = 2; return result; } // Driver Codepublic static void Main(){ int vertices = 4; Console.WriteLine(\"Number of Cycle = \" + totalCycle(vertices)); Console.WriteLine(\"Number of Edges = \" + Edges(vertices)); Console.WriteLine(\"Diameter = \" + Diameter(vertices));}} // This code is contributed by inder_vermaPHP<?php// PHP Program to find the diameter, // cycles and edges of a Wheel Graph // Function that calculates the// Number of Cycle in Wheel Graph.function totalCycle($vertices){ $result = 0; // calculates no. of Cycle. $result = pow($vertices, 2) - (3 * $vertices) + 3; return $result;} // Function that calculates the// Number of Edges in Wheel graph.function Edges($vertices){ $result = 0; $result = 2 * ($vertices - 1); return $result;} // Function that calculates the// Diameter in Wheel Graph.function Diameter($vertices){ $result = 0; // calculates Diameter. if ($vertices == 4) $result = 1; else $result = 2; return $result;} // Driver Code$vertices = 4; echo \"Number of Cycle = \" , totalCycle($vertices), \"\\n\";echo \"Number of Edges = \" , Edges($vertices), \"\\n\" ;echo \"Diameter = \" , Diameter($vertices); // This code is contributed by inder_verma?>Output:Number of Cycle = 7\nNumber of Edges = 6\nDiameter = 1\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 6851,
"s": 6810,
"text": "The Number of Cycles in the Wheel Graph."
},
{
"code": null,
"e": 6883,
"s": 6851,
"text": "Number of edges in Wheel Graph."
},
{
"code": null,
"e": 6914,
"s": 6883,
"text": "The diameter of a Wheel Graph."
},
{
"code": null,
"e": 13230,
"s": 6914,
"text": "Examples:Input: vertices = 4\nOutput: Number of cycle = 7\n Number of edge = 6\n Diameter = 1\n\nInput: vertices = 6\nOutput: Number of cycle = 21\n Number of edge = 10\n Diameter = 2\n\nRecommended: Please try your approach on {IDE} first, before moving on to the solution.Example #1: For vertices = 4 Wheel Graph, total cycle is 7:Example #2: For vertices = 5 and 7 Wheel Graph Number of edges = 8 and 12 respectively:Example #3:For vertices = 4, the Diameter is 1 as We can go from any vertices to any vertices by covering only 1 edge.Formula to calculate the cycles, edges and diameter:-Number of Cycle = (vertices * vertices) - (3 * vertices) + 3\nNumber of edge = 2 * (vertices - 1)\nDiameter = if vertices = 4, Diameter = 1\n if vertices > 4, Diameter = 2\nBelow is the required implementation:C++JavaPython3C#PHPC++// C++ Program to find the diameter, // cycles and edges of a Wheel Graph#include <bits/stdc++.h>using namespace std; // Function that calculates the// Number of Cycle in Wheel Graph.int totalCycle(int vertices){ int result = 0; // calculates no. of Cycle. result = pow(vertices, 2) - (3 * vertices) + 3; return result;} // Function that calculates the// Number of Edges in Wheel graph.int Edges(int vertices){ int result = 0; result = 2 * (vertices - 1); return result;} // Function that calculates the// Diameter in Wheel Graph.int Diameter(int vertices){ int result = 0; // calculates Diameter. if (vertices == 4) result = 1; else result = 2; return result;} // Driver Codeint main(){ int vertices = 4; cout << \"Number of Cycle = \" << totalCycle(vertices) << endl; cout << \"Number of Edges = \" << Edges(vertices) << endl; cout << \"Diameter = \" << Diameter(vertices); return 0;}Java//Java Program to find the diameter, // cycles and edges of a Wheel Graphimport java.io.*; class GFG{ // Function that calculates the // Number of Cycle in Wheel Graph. static int totalCycle(double vertices) { double result = 0; int result1 = 0; // calculates no. of Cycle. result = Math.pow(vertices, 2) - (3 * vertices) + 3; result1 = (int)(result); return result1; } // Function that calculates the // Number of Edges in Wheel graph. static int Edges(int vertices) { int result = 0; result = 2 * (vertices - 1); return result; } // Function that calculates the // Diameter in Wheel Graph. static int Diameter(int vertices) { int result = 0; // calculates Diameter. if (vertices == 4) result = 1; else result = 2; return result; } //Driver Code public static void main(String[] args) { int vertices = 4; System.out.println(\"Number of Cycle = \" + totalCycle(vertices)); System.out.println(\"Number of Edges = \" + Edges(vertices)); System.out.println(\"Diameter = \" + Diameter(vertices)); }}Python3# Python3 Program to find the diameter, # cycles and edges of a Wheel Graph # Function that calculates the # Number of Cycle in Wheel Graph. def totalCycle(vertices): result = 0 # calculates no. of Cycle. result = (pow(vertices, 2) - (3 * vertices) + 3) return result # Function that calculates the # Number of Edges in Wheel graph. def Edges(vertices): result = 0 result = 2 * (vertices - 1) return result # Function that calculates the # Diameter in Wheel Graph. def Diameter(vertices): result = 0 # calculates Diameter. if vertices == 4: result = 1 else: result = 2 return result # Driver Code if __name__ == \"__main__\": vertices = 4 print(\"Number of Cycle =\", totalCycle(vertices)) print(\"Number of Edges =\", Edges(vertices)) print(\"Diameter =\", Diameter(vertices)) # This code is contributed by Rituraj JainC#// C# Program to find the diameter, // cycles and edges of a Wheel Graphusing System;class GFG{// Function that calculates the // Number of Cycle in Wheel Graph. static int totalCycle(double vertices) { double result = 0; int result1 = 0; // calculates no. of Cycle. result = Math.Pow(vertices, 2) - (3 * vertices) + 3; result1 = (int)(result); return result1; } // Function that calculates the // Number of Edges in Wheel graph. static int Edges(int vertices) { int result = 0; result = 2 * (vertices - 1); return result; } // Function that calculates the // Diameter in Wheel Graph. static int Diameter(int vertices) { int result = 0; // calculates Diameter. if (vertices == 4) result = 1; else result = 2; return result; } // Driver Codepublic static void Main(){ int vertices = 4; Console.WriteLine(\"Number of Cycle = \" + totalCycle(vertices)); Console.WriteLine(\"Number of Edges = \" + Edges(vertices)); Console.WriteLine(\"Diameter = \" + Diameter(vertices));}} // This code is contributed by inder_vermaPHP<?php// PHP Program to find the diameter, // cycles and edges of a Wheel Graph // Function that calculates the// Number of Cycle in Wheel Graph.function totalCycle($vertices){ $result = 0; // calculates no. of Cycle. $result = pow($vertices, 2) - (3 * $vertices) + 3; return $result;} // Function that calculates the// Number of Edges in Wheel graph.function Edges($vertices){ $result = 0; $result = 2 * ($vertices - 1); return $result;} // Function that calculates the// Diameter in Wheel Graph.function Diameter($vertices){ $result = 0; // calculates Diameter. if ($vertices == 4) $result = 1; else $result = 2; return $result;} // Driver Code$vertices = 4; echo \"Number of Cycle = \" , totalCycle($vertices), \"\\n\";echo \"Number of Edges = \" , Edges($vertices), \"\\n\" ;echo \"Diameter = \" , Diameter($vertices); // This code is contributed by inder_verma?>Output:Number of Cycle = 7\nNumber of Edges = 6\nDiameter = 1\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 13240,
"s": 13230,
"text": "Examples:"
},
{
"code": null,
"e": 13441,
"s": 13240,
"text": "Input: vertices = 4\nOutput: Number of cycle = 7\n Number of edge = 6\n Diameter = 1\n\nInput: vertices = 6\nOutput: Number of cycle = 21\n Number of edge = 10\n Diameter = 2\n\n"
},
{
"code": null,
"e": 13501,
"s": 13441,
"text": "Example #1: For vertices = 4 Wheel Graph, total cycle is 7:"
},
{
"code": null,
"e": 13589,
"s": 13501,
"text": "Example #2: For vertices = 5 and 7 Wheel Graph Number of edges = 8 and 12 respectively:"
},
{
"code": null,
"e": 13708,
"s": 13589,
"text": "Example #3:For vertices = 4, the Diameter is 1 as We can go from any vertices to any vertices by covering only 1 edge."
},
{
"code": null,
"e": 13762,
"s": 13708,
"text": "Formula to calculate the cycles, edges and diameter:-"
},
{
"code": null,
"e": 13942,
"s": 13762,
"text": "Number of Cycle = (vertices * vertices) - (3 * vertices) + 3\nNumber of edge = 2 * (vertices - 1)\nDiameter = if vertices = 4, Diameter = 1\n if vertices > 4, Diameter = 2\n"
},
{
"code": null,
"e": 13980,
"s": 13942,
"text": "Below is the required implementation:"
},
{
"code": null,
"e": 13984,
"s": 13980,
"text": "C++"
},
{
"code": null,
"e": 13989,
"s": 13984,
"text": "Java"
},
{
"code": null,
"e": 13997,
"s": 13989,
"text": "Python3"
},
{
"code": null,
"e": 14000,
"s": 13997,
"text": "C#"
},
{
"code": null,
"e": 14004,
"s": 14000,
"text": "PHP"
},
{
"code": "// C++ Program to find the diameter, // cycles and edges of a Wheel Graph#include <bits/stdc++.h>using namespace std; // Function that calculates the// Number of Cycle in Wheel Graph.int totalCycle(int vertices){ int result = 0; // calculates no. of Cycle. result = pow(vertices, 2) - (3 * vertices) + 3; return result;} // Function that calculates the// Number of Edges in Wheel graph.int Edges(int vertices){ int result = 0; result = 2 * (vertices - 1); return result;} // Function that calculates the// Diameter in Wheel Graph.int Diameter(int vertices){ int result = 0; // calculates Diameter. if (vertices == 4) result = 1; else result = 2; return result;} // Driver Codeint main(){ int vertices = 4; cout << \"Number of Cycle = \" << totalCycle(vertices) << endl; cout << \"Number of Edges = \" << Edges(vertices) << endl; cout << \"Diameter = \" << Diameter(vertices); return 0;}",
"e": 14970,
"s": 14004,
"text": null
},
{
"code": "//Java Program to find the diameter, // cycles and edges of a Wheel Graphimport java.io.*; class GFG{ // Function that calculates the // Number of Cycle in Wheel Graph. static int totalCycle(double vertices) { double result = 0; int result1 = 0; // calculates no. of Cycle. result = Math.pow(vertices, 2) - (3 * vertices) + 3; result1 = (int)(result); return result1; } // Function that calculates the // Number of Edges in Wheel graph. static int Edges(int vertices) { int result = 0; result = 2 * (vertices - 1); return result; } // Function that calculates the // Diameter in Wheel Graph. static int Diameter(int vertices) { int result = 0; // calculates Diameter. if (vertices == 4) result = 1; else result = 2; return result; } //Driver Code public static void main(String[] args) { int vertices = 4; System.out.println(\"Number of Cycle = \" + totalCycle(vertices)); System.out.println(\"Number of Edges = \" + Edges(vertices)); System.out.println(\"Diameter = \" + Diameter(vertices)); }}",
"e": 16272,
"s": 14970,
"text": null
},
{
"code": "# Python3 Program to find the diameter, # cycles and edges of a Wheel Graph # Function that calculates the # Number of Cycle in Wheel Graph. def totalCycle(vertices): result = 0 # calculates no. of Cycle. result = (pow(vertices, 2) - (3 * vertices) + 3) return result # Function that calculates the # Number of Edges in Wheel graph. def Edges(vertices): result = 0 result = 2 * (vertices - 1) return result # Function that calculates the # Diameter in Wheel Graph. def Diameter(vertices): result = 0 # calculates Diameter. if vertices == 4: result = 1 else: result = 2 return result # Driver Code if __name__ == \"__main__\": vertices = 4 print(\"Number of Cycle =\", totalCycle(vertices)) print(\"Number of Edges =\", Edges(vertices)) print(\"Diameter =\", Diameter(vertices)) # This code is contributed by Rituraj Jain",
"e": 17206,
"s": 16272,
"text": null
},
{
"code": "// C# Program to find the diameter, // cycles and edges of a Wheel Graphusing System;class GFG{// Function that calculates the // Number of Cycle in Wheel Graph. static int totalCycle(double vertices) { double result = 0; int result1 = 0; // calculates no. of Cycle. result = Math.Pow(vertices, 2) - (3 * vertices) + 3; result1 = (int)(result); return result1; } // Function that calculates the // Number of Edges in Wheel graph. static int Edges(int vertices) { int result = 0; result = 2 * (vertices - 1); return result; } // Function that calculates the // Diameter in Wheel Graph. static int Diameter(int vertices) { int result = 0; // calculates Diameter. if (vertices == 4) result = 1; else result = 2; return result; } // Driver Codepublic static void Main(){ int vertices = 4; Console.WriteLine(\"Number of Cycle = \" + totalCycle(vertices)); Console.WriteLine(\"Number of Edges = \" + Edges(vertices)); Console.WriteLine(\"Diameter = \" + Diameter(vertices));}} // This code is contributed by inder_verma",
"e": 18410,
"s": 17206,
"text": null
},
{
"code": "<?php// PHP Program to find the diameter, // cycles and edges of a Wheel Graph // Function that calculates the// Number of Cycle in Wheel Graph.function totalCycle($vertices){ $result = 0; // calculates no. of Cycle. $result = pow($vertices, 2) - (3 * $vertices) + 3; return $result;} // Function that calculates the// Number of Edges in Wheel graph.function Edges($vertices){ $result = 0; $result = 2 * ($vertices - 1); return $result;} // Function that calculates the// Diameter in Wheel Graph.function Diameter($vertices){ $result = 0; // calculates Diameter. if ($vertices == 4) $result = 1; else $result = 2; return $result;} // Driver Code$vertices = 4; echo \"Number of Cycle = \" , totalCycle($vertices), \"\\n\";echo \"Number of Edges = \" , Edges($vertices), \"\\n\" ;echo \"Diameter = \" , Diameter($vertices); // This code is contributed by inder_verma?>",
"e": 19362,
"s": 18410,
"text": null
},
{
"code": null,
"e": 19416,
"s": 19362,
"text": "Number of Cycle = 7\nNumber of Edges = 6\nDiameter = 1\n"
},
{
"code": null,
"e": 19427,
"s": 19416,
"text": "Naman_Garg"
},
{
"code": null,
"e": 19438,
"s": 19427,
"text": "inderDuMCA"
},
{
"code": null,
"e": 19451,
"s": 19438,
"text": "rituraj_jain"
},
{
"code": null,
"e": 19464,
"s": 19451,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 19486,
"s": 19464,
"text": "Data Structures-Graph"
},
{
"code": null,
"e": 19492,
"s": 19486,
"text": "Graph"
},
{
"code": null,
"e": 19511,
"s": 19492,
"text": "School Programming"
},
{
"code": null,
"e": 19517,
"s": 19511,
"text": "Graph"
},
{
"code": null,
"e": 19615,
"s": 19517,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 19647,
"s": 19615,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 19711,
"s": 19647,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 19749,
"s": 19711,
"text": "Check if a given graph is tree or not"
},
{
"code": null,
"e": 19799,
"s": 19749,
"text": "Minimum steps to reach target by a Knight | Set 1"
},
{
"code": null,
"e": 19841,
"s": 19799,
"text": "Total number of Spanning Trees in a Graph"
},
{
"code": null,
"e": 19865,
"s": 19841,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 19883,
"s": 19865,
"text": "Python Dictionary"
},
{
"code": null,
"e": 19918,
"s": 19883,
"text": "Object Oriented Programming in C++"
},
{
"code": null,
"e": 19937,
"s": 19918,
"text": "Inheritance in C++"
}
] |
Total number of Subsets of size at most K
|
21 Jan, 2022
Given a number N which is the size of the set and a number K, the task is to find the count of subsets, of the set of N elements, having at most K elements in it, i.e. the size of subset is less than or equal to K.Examples:
Input: N = 3, K = 2 Output: 6 Subsets with 1 element in it = {1}, {2}, {3} Subsets with 2 elements in it = {1, 2}, {1, 3}, {1, 2} Since K = 2, therefore only the above subsets will be considered for length atmost K. Therefore the count is 6.Input: N = 5, K = 2 Output: 15
Approach:
Since the number of subsets of exactly K elements that can be made from N items is (NCK). Therefore for “at most”, the required count will be Inorder to calculate the value of NCK, Binomial Coefficient is used. Please refer this article to see how it works. So to get the required subsets for length atmost K, run a loop from 1 to K and add the NCi for each value of i.
Since the number of subsets of exactly K elements that can be made from N items is (NCK). Therefore for “at most”, the required count will be
Inorder to calculate the value of NCK, Binomial Coefficient is used. Please refer this article to see how it works.
So to get the required subsets for length atmost K, run a loop from 1 to K and add the NCi for each value of i.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ code to find total number of// Subsets of size at most K #include <bits/stdc++.h>using namespace std; // Function to compute the value// of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ int C[n + 1][k + 1]; int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Function to calculate sum of// nCj from j = 1 to kint count(int n, int k){ int sum = 0; for (int j = 1; j <= k; j++) { // Calling the nCr function // for each value of j sum = sum + binomialCoeff(n, j); } return sum;} // Driver codeint main(){ int n = 3, k = 2; cout << count(n, k) << endl; n = 5, k = 2; cout << count(n, k) << endl; return 0;}
// Java code to find total number of// Subsets of size at most Kimport java.lang.*;class GFG{ // Function to compute the value// of Binomial Coefficient C(n, k)public static int binomialCoeff(int n, int k){ int[][] C = new int[n + 1][k + 1]; int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Function to calculate sum of// nCj from j = 1 to kpublic static int count(int n, int k){ int sum = 0; for (int j = 1; j <= k; j++) { // Calling the nCr function // for each value of j sum = sum + binomialCoeff(n, j); } return sum;} // Driver codepublic static void main(String args[]){ GFG g = new GFG(); int n = 3, k = 2; System.out.print(count(n, k)); int n1 = 5, k1 = 2; System.out.print(count(n1, k1));}} // This code is contributed by SoumikMondal
# Python code to find total number of# Subsets of size at most K # Function to compute the value# of Binomial Coefficient C(n, k)def binomialCoeff(n, k): C = [[0 for i in range(k + 1)] for j in range(n + 1)]; i, j = 0, 0; # Calculate value of Binomial Coefficient # in bottom up manner for i in range(n + 1): for j in range( min(i, k) + 1): # Base Cases if (j == 0 or j == i): C[i][j] = 1; # Calculate value using previously # stored values else: C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; return C[n][k]; # Function to calculate sum of# nCj from j = 1 to kdef count(n, k): sum = 0; for j in range(1, k+1): # Calling the nCr function # for each value of j sum = sum + binomialCoeff(n, j); return sum; # Driver codeif __name__ == '__main__': n = 3; k = 2; print(count(n, k), end=""); n1 = 5; k1 = 2; print(count(n1, k1)); # This code is contributed by 29AjayKumar
// C# code to find total number of// Subsets of size at most Kusing System; class GFG{ // Function to compute the value // of Binomial Coefficient C(n, k) public static int binomialCoeff(int n, int k) { int[,] C = new int[n + 1, k + 1]; int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.Min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i, j] = 1; // Calculate value using previously // stored values else C[i, j] = C[i - 1, j - 1] + C[i - 1, j]; } } return C[n, k]; } // Function to calculate sum of // nCj from j = 1 to k public static int count(int n, int k) { int sum = 0; for (int j = 1; j <= k; j++) { // Calling the nCr function // for each value of j sum = sum + binomialCoeff(n, j); } return sum; } // Driver code public static void Main() { int n = 3, k = 2; Console.Write(count(n, k)); int n1 = 5, k1 = 2; Console.Write(count(n1, k1)); }} // This code is contributed by AnkitRai01
<script>// Javascript implementation of the// above approach // Function for the binomial coefficientfunction binomialCoeff(n, k){ var C = new Array(n + 1); // Loop to create 2D array using 1D array for (var i = 0; i < C.length; i++) { C[i] = new Array(k + 1); } var i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Function to calculate sum of// nCj from j = 1 to kfunction count(n, k){ var sum = 0; for (var j = 1; j <= k; j++) { // Calling the nCr function // for each value of j sum = sum + binomialCoeff(n, j); } return sum;} // Driver codevar n = 3;var k = 2;document.write(count(n, k)); var n = 5;var k = 2;document.write(count(n, k)); // This code is contributed by ShubhamSingh10</script>
6
15
Time Complexity: O(n2 * k)
Auxiliary Space: O(n + k)
SoumikMondal
ankthon
29AjayKumar
nidhi_biet
SHUBHAMSINGH10
anikakapoor
hcetefil
subhammahato348
subset
Combinatorial
Mathematical
Mathematical
subset
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find the Number of Permutations that satisfy the given condition in an array
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Probability of getting K heads in N coin tosses
Number of handshakes such that a person shakes hands only once
Count ways to partition a Binary String such that each substring contains exactly two 0s
Set in C++ Standard Template Library (STL)
Program for Fibonacci numbers
C++ Data Types
Merge two sorted arrays
Coin Change | DP-7
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jan, 2022"
},
{
"code": null,
"e": 254,
"s": 28,
"text": "Given a number N which is the size of the set and a number K, the task is to find the count of subsets, of the set of N elements, having at most K elements in it, i.e. the size of subset is less than or equal to K.Examples: "
},
{
"code": null,
"e": 528,
"s": 254,
"text": "Input: N = 3, K = 2 Output: 6 Subsets with 1 element in it = {1}, {2}, {3} Subsets with 2 elements in it = {1, 2}, {1, 3}, {1, 2} Since K = 2, therefore only the above subsets will be considered for length atmost K. Therefore the count is 6.Input: N = 5, K = 2 Output: 15 "
},
{
"code": null,
"e": 541,
"s": 530,
"text": "Approach: "
},
{
"code": null,
"e": 912,
"s": 541,
"text": "Since the number of subsets of exactly K elements that can be made from N items is (NCK). Therefore for “at most”, the required count will be Inorder to calculate the value of NCK, Binomial Coefficient is used. Please refer this article to see how it works. So to get the required subsets for length atmost K, run a loop from 1 to K and add the NCi for each value of i."
},
{
"code": null,
"e": 1056,
"s": 912,
"text": "Since the number of subsets of exactly K elements that can be made from N items is (NCK). Therefore for “at most”, the required count will be "
},
{
"code": null,
"e": 1173,
"s": 1056,
"text": "Inorder to calculate the value of NCK, Binomial Coefficient is used. Please refer this article to see how it works. "
},
{
"code": null,
"e": 1285,
"s": 1173,
"text": "So to get the required subsets for length atmost K, run a loop from 1 to K and add the NCi for each value of i."
},
{
"code": null,
"e": 1338,
"s": 1285,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1342,
"s": 1338,
"text": "C++"
},
{
"code": null,
"e": 1347,
"s": 1342,
"text": "Java"
},
{
"code": null,
"e": 1355,
"s": 1347,
"text": "Python3"
},
{
"code": null,
"e": 1358,
"s": 1355,
"text": "C#"
},
{
"code": null,
"e": 1369,
"s": 1358,
"text": "Javascript"
},
{
"code": "// C++ code to find total number of// Subsets of size at most K #include <bits/stdc++.h>using namespace std; // Function to compute the value// of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ int C[n + 1][k + 1]; int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Function to calculate sum of// nCj from j = 1 to kint count(int n, int k){ int sum = 0; for (int j = 1; j <= k; j++) { // Calling the nCr function // for each value of j sum = sum + binomialCoeff(n, j); } return sum;} // Driver codeint main(){ int n = 3, k = 2; cout << count(n, k) << endl; n = 5, k = 2; cout << count(n, k) << endl; return 0;}",
"e": 2428,
"s": 1369,
"text": null
},
{
"code": "// Java code to find total number of// Subsets of size at most Kimport java.lang.*;class GFG{ // Function to compute the value// of Binomial Coefficient C(n, k)public static int binomialCoeff(int n, int k){ int[][] C = new int[n + 1][k + 1]; int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Function to calculate sum of// nCj from j = 1 to kpublic static int count(int n, int k){ int sum = 0; for (int j = 1; j <= k; j++) { // Calling the nCr function // for each value of j sum = sum + binomialCoeff(n, j); } return sum;} // Driver codepublic static void main(String args[]){ GFG g = new GFG(); int n = 3, k = 2; System.out.print(count(n, k)); int n1 = 5, k1 = 2; System.out.print(count(n1, k1));}} // This code is contributed by SoumikMondal",
"e": 3626,
"s": 2428,
"text": null
},
{
"code": "# Python code to find total number of# Subsets of size at most K # Function to compute the value# of Binomial Coefficient C(n, k)def binomialCoeff(n, k): C = [[0 for i in range(k + 1)] for j in range(n + 1)]; i, j = 0, 0; # Calculate value of Binomial Coefficient # in bottom up manner for i in range(n + 1): for j in range( min(i, k) + 1): # Base Cases if (j == 0 or j == i): C[i][j] = 1; # Calculate value using previously # stored values else: C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; return C[n][k]; # Function to calculate sum of# nCj from j = 1 to kdef count(n, k): sum = 0; for j in range(1, k+1): # Calling the nCr function # for each value of j sum = sum + binomialCoeff(n, j); return sum; # Driver codeif __name__ == '__main__': n = 3; k = 2; print(count(n, k), end=\"\"); n1 = 5; k1 = 2; print(count(n1, k1)); # This code is contributed by 29AjayKumar",
"e": 4650,
"s": 3626,
"text": null
},
{
"code": "// C# code to find total number of// Subsets of size at most Kusing System; class GFG{ // Function to compute the value // of Binomial Coefficient C(n, k) public static int binomialCoeff(int n, int k) { int[,] C = new int[n + 1, k + 1]; int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.Min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i, j] = 1; // Calculate value using previously // stored values else C[i, j] = C[i - 1, j - 1] + C[i - 1, j]; } } return C[n, k]; } // Function to calculate sum of // nCj from j = 1 to k public static int count(int n, int k) { int sum = 0; for (int j = 1; j <= k; j++) { // Calling the nCr function // for each value of j sum = sum + binomialCoeff(n, j); } return sum; } // Driver code public static void Main() { int n = 3, k = 2; Console.Write(count(n, k)); int n1 = 5, k1 = 2; Console.Write(count(n1, k1)); }} // This code is contributed by AnkitRai01",
"e": 6010,
"s": 4650,
"text": null
},
{
"code": "<script>// Javascript implementation of the// above approach // Function for the binomial coefficientfunction binomialCoeff(n, k){ var C = new Array(n + 1); // Loop to create 2D array using 1D array for (var i = 0; i < C.length; i++) { C[i] = new Array(k + 1); } var i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Function to calculate sum of// nCj from j = 1 to kfunction count(n, k){ var sum = 0; for (var j = 1; j <= k; j++) { // Calling the nCr function // for each value of j sum = sum + binomialCoeff(n, j); } return sum;} // Driver codevar n = 3;var k = 2;document.write(count(n, k)); var n = 5;var k = 2;document.write(count(n, k)); // This code is contributed by ShubhamSingh10</script>",
"e": 7157,
"s": 6010,
"text": null
},
{
"code": null,
"e": 7162,
"s": 7157,
"text": "6\n15"
},
{
"code": null,
"e": 7189,
"s": 7162,
"text": "Time Complexity: O(n2 * k)"
},
{
"code": null,
"e": 7215,
"s": 7189,
"text": "Auxiliary Space: O(n + k)"
},
{
"code": null,
"e": 7228,
"s": 7215,
"text": "SoumikMondal"
},
{
"code": null,
"e": 7236,
"s": 7228,
"text": "ankthon"
},
{
"code": null,
"e": 7248,
"s": 7236,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7259,
"s": 7248,
"text": "nidhi_biet"
},
{
"code": null,
"e": 7274,
"s": 7259,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 7286,
"s": 7274,
"text": "anikakapoor"
},
{
"code": null,
"e": 7295,
"s": 7286,
"text": "hcetefil"
},
{
"code": null,
"e": 7311,
"s": 7295,
"text": "subhammahato348"
},
{
"code": null,
"e": 7318,
"s": 7311,
"text": "subset"
},
{
"code": null,
"e": 7332,
"s": 7318,
"text": "Combinatorial"
},
{
"code": null,
"e": 7345,
"s": 7332,
"text": "Mathematical"
},
{
"code": null,
"e": 7358,
"s": 7345,
"text": "Mathematical"
},
{
"code": null,
"e": 7365,
"s": 7358,
"text": "subset"
},
{
"code": null,
"e": 7379,
"s": 7365,
"text": "Combinatorial"
},
{
"code": null,
"e": 7477,
"s": 7379,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7554,
"s": 7477,
"text": "Find the Number of Permutations that satisfy the given condition in an array"
},
{
"code": null,
"e": 7626,
"s": 7554,
"text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed"
},
{
"code": null,
"e": 7674,
"s": 7626,
"text": "Probability of getting K heads in N coin tosses"
},
{
"code": null,
"e": 7737,
"s": 7674,
"text": "Number of handshakes such that a person shakes hands only once"
},
{
"code": null,
"e": 7826,
"s": 7737,
"text": "Count ways to partition a Binary String such that each substring contains exactly two 0s"
},
{
"code": null,
"e": 7869,
"s": 7826,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 7899,
"s": 7869,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 7914,
"s": 7899,
"text": "C++ Data Types"
},
{
"code": null,
"e": 7938,
"s": 7914,
"text": "Merge two sorted arrays"
}
] |
Java Class File
|
09 Jun, 2021
A Java class file is a file containing Java bytecode and having .class extension that can be executed by JVM. A Java class file is created by a Java compiler from .java files as a result of successful compilation. As we know that a single Java programming language source file (or we can say .java file) may contain one class or more than one class. So if a .java file has more than one class then each class will compile into a separate class files.For Example: Save this below code as Test.java on your system.
// Compiling this Java program would// result in multiple class files. class Sample{ } // Class Declarationclass Student{ }// Class Declarationclass Test{ public static void main(String[] args) { System.out.println("Class File Structure"); }}
For Compiling:
javac Test.java
After compilation there will be 3 class files in corresponding folder named as:
Sample.class
Student.class
Test.class
What is Java .Class File? | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersWhat is Java .Class File? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 9:37•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ajVWDCN42WI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
A single class file structure contains attributes that describe a class file.Representation of Class File Structure
ClassFile
{
magic_number;
minor_version;
major_version;
constant_pool_count;
constant_pool[];
access_flags;
this_class;
super_class;
interfaces_count;
interfaces[];
fields_count;
fields[];
methods_count;
methods[];
attributes_count;
attributes[];
}
Elements of class file are as follows:
magic_number: The first 4 bytes of class file are termed as magic_number. This is a predefined value which the JVM use to identify whether the .class file is generated by valid compiler or not. The predefined value will be in hexadecimal form i.e. 0xCAFEBABE.Now let’s see what happen when JVM will not find valid magic number. Suppose we have a .java file named as Sample.java as follows and follow step by step process on your system.// class Declaration
class Sample
{
public static void main(String[] args)
{
System.out.println("Magic Number");
}
}
Step 1: Compile using javac Sample.javaStep 2: Now open the Sample.class file. It will looks like following.Step 3: Now erase at least single symbol from this Sample.class file from starting of file and save it.Step 4: Now try to run this using java Sample command and see the magic i.e. you will get run time exception (See the highlighted text in below image):Note: This can vary depending on how much you remove the .class file data.minor_version & major_version: These both together represents .class file version. JVM will use these versions to identify which version of the compiler generates the current .class file. We denotes the version of class file as M.m where M stands for major_version and m stands for minor_versionNote: Lower version compiler generated .class file can be executed by high version JVM but higher version compiler generated .class file cannot be executed by lower version JVM. If we will try to execute we will get run time exception.This demonstration is for Windows OS as follows:Step 1: Open a command prompt window and try to check java compiler version and JVM version using following commands respectively (Highlighted text in image are the commands)Output for 1.8 version will be:Step 2: Now check with another version which may be higher or lower than already installed.thisDownload link.And install this to your PC or laptops and note the installation address.Step 3: Open a second command prompt window and set the path of bin folder of installed jdk installed during 2nd step. And check for Java compiler version ad JVM version.Step 4: Now on 1st command prompt compile the any valid .java file. For example: See above Sample.java file. Compile it as:Step 5: Now on 2nd command prompt window try to run the above compiled code class file and see what happen. There is a run time exception which I have highlighted in below image.Note: Internally jdk 1.5 version means 49.0 and 1.6 means 50.0 and 1.7 means 51.0 etc. class file version where the digits before the decimal point represent the major_version and digits after decimal point represents the minor_version.constant_pool_count: It represents the number of the constants present in the constant pool (When a Java file is compiled, all references to variables and methods are stored in the class’s constant pool as a symbolic reference).constant_pool[]: It represents the information about constants present in constant pool file.access_flags: It provide the information about the modifiers which are declared to the class file.this_class: It represents fully qualified name of the class file.super_class: It represents fully qualified name of the immediate super class of current class. Consider above Sample.java file. When we will compile it, then we can say this_class will be Sample class and super_class will be Object class.interface_count: It returns the number of interfaces implemented by current class file.interface[]: It returns interfaces information implemented by current class file.fields_count: It represents the number of fields (static variable) present in current class file.fields[]: It represent fields (static variable) information present in current class file.method_count: It represents number of methods present in current class file.method[]: It returns information about all methods present in current class file.attributes_count: It returns the number of attributes (instance variables) present in current class file.attributes[]: It provides information about all attributes present in current class file.My Personal Notes
arrow_drop_upSave
magic_number: The first 4 bytes of class file are termed as magic_number. This is a predefined value which the JVM use to identify whether the .class file is generated by valid compiler or not. The predefined value will be in hexadecimal form i.e. 0xCAFEBABE.Now let’s see what happen when JVM will not find valid magic number. Suppose we have a .java file named as Sample.java as follows and follow step by step process on your system.
// class Declaration
class Sample
{
public static void main(String[] args)
{
System.out.println("Magic Number");
}
}
Step 1: Compile using javac Sample.javaStep 2: Now open the Sample.class file. It will looks like following.
Step 3: Now erase at least single symbol from this Sample.class file from starting of file and save it.Step 4: Now try to run this using java Sample command and see the magic i.e. you will get run time exception (See the highlighted text in below image):
Note: This can vary depending on how much you remove the .class file data.
minor_version & major_version: These both together represents .class file version. JVM will use these versions to identify which version of the compiler generates the current .class file. We denotes the version of class file as M.m where M stands for major_version and m stands for minor_version
Note: Lower version compiler generated .class file can be executed by high version JVM but higher version compiler generated .class file cannot be executed by lower version JVM. If we will try to execute we will get run time exception.
This demonstration is for Windows OS as follows:
Step 1: Open a command prompt window and try to check java compiler version and JVM version using following commands respectively (Highlighted text in image are the commands)Output for 1.8 version will be:
Step 2: Now check with another version which may be higher or lower than already installed.thisDownload link.And install this to your PC or laptops and note the installation address.Step 3: Open a second command prompt window and set the path of bin folder of installed jdk installed during 2nd step. And check for Java compiler version ad JVM version.Step 4: Now on 1st command prompt compile the any valid .java file. For example: See above Sample.java file. Compile it as:Step 5: Now on 2nd command prompt window try to run the above compiled code class file and see what happen. There is a run time exception which I have highlighted in below image.
Note: Internally jdk 1.5 version means 49.0 and 1.6 means 50.0 and 1.7 means 51.0 etc. class file version where the digits before the decimal point represent the major_version and digits after decimal point represents the minor_version.
constant_pool_count: It represents the number of the constants present in the constant pool (When a Java file is compiled, all references to variables and methods are stored in the class’s constant pool as a symbolic reference).constant_pool[]: It represents the information about constants present in constant pool file.access_flags: It provide the information about the modifiers which are declared to the class file.this_class: It represents fully qualified name of the class file.super_class: It represents fully qualified name of the immediate super class of current class. Consider above Sample.java file. When we will compile it, then we can say this_class will be Sample class and super_class will be Object class.interface_count: It returns the number of interfaces implemented by current class file.interface[]: It returns interfaces information implemented by current class file.fields_count: It represents the number of fields (static variable) present in current class file.fields[]: It represent fields (static variable) information present in current class file.method_count: It represents number of methods present in current class file.method[]: It returns information about all methods present in current class file.attributes_count: It returns the number of attributes (instance variables) present in current class file.attributes[]: It provides information about all attributes present in current class file.
constant_pool_count: It represents the number of the constants present in the constant pool (When a Java file is compiled, all references to variables and methods are stored in the class’s constant pool as a symbolic reference).
constant_pool[]: It represents the information about constants present in constant pool file.
access_flags: It provide the information about the modifiers which are declared to the class file.
this_class: It represents fully qualified name of the class file.
super_class: It represents fully qualified name of the immediate super class of current class. Consider above Sample.java file. When we will compile it, then we can say this_class will be Sample class and super_class will be Object class.
interface_count: It returns the number of interfaces implemented by current class file.
interface[]: It returns interfaces information implemented by current class file.
fields_count: It represents the number of fields (static variable) present in current class file.
fields[]: It represent fields (static variable) information present in current class file.
method_count: It represents number of methods present in current class file.
method[]: It returns information about all methods present in current class file.
attributes_count: It returns the number of attributes (instance variables) present in current class file.
attributes[]: It provides information about all attributes present in current class file.
Manish Dhanuka
java-basics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Jun, 2021"
},
{
"code": null,
"e": 567,
"s": 54,
"text": "A Java class file is a file containing Java bytecode and having .class extension that can be executed by JVM. A Java class file is created by a Java compiler from .java files as a result of successful compilation. As we know that a single Java programming language source file (or we can say .java file) may contain one class or more than one class. So if a .java file has more than one class then each class will compile into a separate class files.For Example: Save this below code as Test.java on your system."
},
{
"code": "// Compiling this Java program would// result in multiple class files. class Sample{ } // Class Declarationclass Student{ }// Class Declarationclass Test{ public static void main(String[] args) { System.out.println(\"Class File Structure\"); }} ",
"e": 846,
"s": 567,
"text": null
},
{
"code": null,
"e": 861,
"s": 846,
"text": "For Compiling:"
},
{
"code": null,
"e": 877,
"s": 861,
"text": "javac Test.java"
},
{
"code": null,
"e": 957,
"s": 877,
"text": "After compilation there will be 3 class files in corresponding folder named as:"
},
{
"code": null,
"e": 970,
"s": 957,
"text": "Sample.class"
},
{
"code": null,
"e": 984,
"s": 970,
"text": "Student.class"
},
{
"code": null,
"e": 995,
"s": 984,
"text": "Test.class"
},
{
"code": null,
"e": 1863,
"s": 995,
"text": "What is Java .Class File? | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersWhat is Java .Class File? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 9:37•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=ajVWDCN42WI\" 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": 1979,
"s": 1863,
"text": "A single class file structure contains attributes that describe a class file.Representation of Class File Structure"
},
{
"code": null,
"e": 2310,
"s": 1979,
"text": "ClassFile \n{\n magic_number;\n minor_version;\n major_version;\n constant_pool_count;\n constant_pool[];\n access_flags;\n this_class;\n super_class;\n interfaces_count;\n interfaces[];\n fields_count;\n fields[];\n methods_count;\n methods[];\n attributes_count;\n attributes[];\n}\n"
},
{
"code": null,
"e": 2349,
"s": 2310,
"text": "Elements of class file are as follows:"
},
{
"code": null,
"e": 6501,
"s": 2349,
"text": "magic_number: The first 4 bytes of class file are termed as magic_number. This is a predefined value which the JVM use to identify whether the .class file is generated by valid compiler or not. The predefined value will be in hexadecimal form i.e. 0xCAFEBABE.Now let’s see what happen when JVM will not find valid magic number. Suppose we have a .java file named as Sample.java as follows and follow step by step process on your system.// class Declaration\nclass Sample\n{\n public static void main(String[] args)\n {\n System.out.println(\"Magic Number\"); \n }\n}\nStep 1: Compile using javac Sample.javaStep 2: Now open the Sample.class file. It will looks like following.Step 3: Now erase at least single symbol from this Sample.class file from starting of file and save it.Step 4: Now try to run this using java Sample command and see the magic i.e. you will get run time exception (See the highlighted text in below image):Note: This can vary depending on how much you remove the .class file data.minor_version & major_version: These both together represents .class file version. JVM will use these versions to identify which version of the compiler generates the current .class file. We denotes the version of class file as M.m where M stands for major_version and m stands for minor_versionNote: Lower version compiler generated .class file can be executed by high version JVM but higher version compiler generated .class file cannot be executed by lower version JVM. If we will try to execute we will get run time exception.This demonstration is for Windows OS as follows:Step 1: Open a command prompt window and try to check java compiler version and JVM version using following commands respectively (Highlighted text in image are the commands)Output for 1.8 version will be:Step 2: Now check with another version which may be higher or lower than already installed.thisDownload link.And install this to your PC or laptops and note the installation address.Step 3: Open a second command prompt window and set the path of bin folder of installed jdk installed during 2nd step. And check for Java compiler version ad JVM version.Step 4: Now on 1st command prompt compile the any valid .java file. For example: See above Sample.java file. Compile it as:Step 5: Now on 2nd command prompt window try to run the above compiled code class file and see what happen. There is a run time exception which I have highlighted in below image.Note: Internally jdk 1.5 version means 49.0 and 1.6 means 50.0 and 1.7 means 51.0 etc. class file version where the digits before the decimal point represent the major_version and digits after decimal point represents the minor_version.constant_pool_count: It represents the number of the constants present in the constant pool (When a Java file is compiled, all references to variables and methods are stored in the class’s constant pool as a symbolic reference).constant_pool[]: It represents the information about constants present in constant pool file.access_flags: It provide the information about the modifiers which are declared to the class file.this_class: It represents fully qualified name of the class file.super_class: It represents fully qualified name of the immediate super class of current class. Consider above Sample.java file. When we will compile it, then we can say this_class will be Sample class and super_class will be Object class.interface_count: It returns the number of interfaces implemented by current class file.interface[]: It returns interfaces information implemented by current class file.fields_count: It represents the number of fields (static variable) present in current class file.fields[]: It represent fields (static variable) information present in current class file.method_count: It represents number of methods present in current class file.method[]: It returns information about all methods present in current class file.attributes_count: It returns the number of attributes (instance variables) present in current class file.attributes[]: It provides information about all attributes present in current class file.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 6938,
"s": 6501,
"text": "magic_number: The first 4 bytes of class file are termed as magic_number. This is a predefined value which the JVM use to identify whether the .class file is generated by valid compiler or not. The predefined value will be in hexadecimal form i.e. 0xCAFEBABE.Now let’s see what happen when JVM will not find valid magic number. Suppose we have a .java file named as Sample.java as follows and follow step by step process on your system."
},
{
"code": null,
"e": 7083,
"s": 6938,
"text": "// class Declaration\nclass Sample\n{\n public static void main(String[] args)\n {\n System.out.println(\"Magic Number\"); \n }\n}\n"
},
{
"code": null,
"e": 7192,
"s": 7083,
"text": "Step 1: Compile using javac Sample.javaStep 2: Now open the Sample.class file. It will looks like following."
},
{
"code": null,
"e": 7447,
"s": 7192,
"text": "Step 3: Now erase at least single symbol from this Sample.class file from starting of file and save it.Step 4: Now try to run this using java Sample command and see the magic i.e. you will get run time exception (See the highlighted text in below image):"
},
{
"code": null,
"e": 7522,
"s": 7447,
"text": "Note: This can vary depending on how much you remove the .class file data."
},
{
"code": null,
"e": 7818,
"s": 7522,
"text": "minor_version & major_version: These both together represents .class file version. JVM will use these versions to identify which version of the compiler generates the current .class file. We denotes the version of class file as M.m where M stands for major_version and m stands for minor_version"
},
{
"code": null,
"e": 8054,
"s": 7818,
"text": "Note: Lower version compiler generated .class file can be executed by high version JVM but higher version compiler generated .class file cannot be executed by lower version JVM. If we will try to execute we will get run time exception."
},
{
"code": null,
"e": 8103,
"s": 8054,
"text": "This demonstration is for Windows OS as follows:"
},
{
"code": null,
"e": 8309,
"s": 8103,
"text": "Step 1: Open a command prompt window and try to check java compiler version and JVM version using following commands respectively (Highlighted text in image are the commands)Output for 1.8 version will be:"
},
{
"code": null,
"e": 8963,
"s": 8309,
"text": "Step 2: Now check with another version which may be higher or lower than already installed.thisDownload link.And install this to your PC or laptops and note the installation address.Step 3: Open a second command prompt window and set the path of bin folder of installed jdk installed during 2nd step. And check for Java compiler version ad JVM version.Step 4: Now on 1st command prompt compile the any valid .java file. For example: See above Sample.java file. Compile it as:Step 5: Now on 2nd command prompt window try to run the above compiled code class file and see what happen. There is a run time exception which I have highlighted in below image."
},
{
"code": null,
"e": 9200,
"s": 8963,
"text": "Note: Internally jdk 1.5 version means 49.0 and 1.6 means 50.0 and 1.7 means 51.0 etc. class file version where the digits before the decimal point represent the major_version and digits after decimal point represents the minor_version."
},
{
"code": null,
"e": 10629,
"s": 9200,
"text": "constant_pool_count: It represents the number of the constants present in the constant pool (When a Java file is compiled, all references to variables and methods are stored in the class’s constant pool as a symbolic reference).constant_pool[]: It represents the information about constants present in constant pool file.access_flags: It provide the information about the modifiers which are declared to the class file.this_class: It represents fully qualified name of the class file.super_class: It represents fully qualified name of the immediate super class of current class. Consider above Sample.java file. When we will compile it, then we can say this_class will be Sample class and super_class will be Object class.interface_count: It returns the number of interfaces implemented by current class file.interface[]: It returns interfaces information implemented by current class file.fields_count: It represents the number of fields (static variable) present in current class file.fields[]: It represent fields (static variable) information present in current class file.method_count: It represents number of methods present in current class file.method[]: It returns information about all methods present in current class file.attributes_count: It returns the number of attributes (instance variables) present in current class file.attributes[]: It provides information about all attributes present in current class file."
},
{
"code": null,
"e": 10858,
"s": 10629,
"text": "constant_pool_count: It represents the number of the constants present in the constant pool (When a Java file is compiled, all references to variables and methods are stored in the class’s constant pool as a symbolic reference)."
},
{
"code": null,
"e": 10952,
"s": 10858,
"text": "constant_pool[]: It represents the information about constants present in constant pool file."
},
{
"code": null,
"e": 11051,
"s": 10952,
"text": "access_flags: It provide the information about the modifiers which are declared to the class file."
},
{
"code": null,
"e": 11117,
"s": 11051,
"text": "this_class: It represents fully qualified name of the class file."
},
{
"code": null,
"e": 11356,
"s": 11117,
"text": "super_class: It represents fully qualified name of the immediate super class of current class. Consider above Sample.java file. When we will compile it, then we can say this_class will be Sample class and super_class will be Object class."
},
{
"code": null,
"e": 11444,
"s": 11356,
"text": "interface_count: It returns the number of interfaces implemented by current class file."
},
{
"code": null,
"e": 11526,
"s": 11444,
"text": "interface[]: It returns interfaces information implemented by current class file."
},
{
"code": null,
"e": 11624,
"s": 11526,
"text": "fields_count: It represents the number of fields (static variable) present in current class file."
},
{
"code": null,
"e": 11715,
"s": 11624,
"text": "fields[]: It represent fields (static variable) information present in current class file."
},
{
"code": null,
"e": 11792,
"s": 11715,
"text": "method_count: It represents number of methods present in current class file."
},
{
"code": null,
"e": 11874,
"s": 11792,
"text": "method[]: It returns information about all methods present in current class file."
},
{
"code": null,
"e": 11980,
"s": 11874,
"text": "attributes_count: It returns the number of attributes (instance variables) present in current class file."
},
{
"code": null,
"e": 12070,
"s": 11980,
"text": "attributes[]: It provides information about all attributes present in current class file."
},
{
"code": null,
"e": 12085,
"s": 12070,
"text": "Manish Dhanuka"
},
{
"code": null,
"e": 12097,
"s": 12085,
"text": "java-basics"
},
{
"code": null,
"e": 12102,
"s": 12097,
"text": "Java"
},
{
"code": null,
"e": 12107,
"s": 12102,
"text": "Java"
},
{
"code": null,
"e": 12205,
"s": 12107,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12256,
"s": 12205,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 12287,
"s": 12256,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 12306,
"s": 12287,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 12336,
"s": 12306,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 12354,
"s": 12336,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 12369,
"s": 12354,
"text": "Stream In Java"
},
{
"code": null,
"e": 12389,
"s": 12369,
"text": "Collections in Java"
},
{
"code": null,
"e": 12421,
"s": 12389,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 12445,
"s": 12421,
"text": "Singleton Class in Java"
}
] |
How to Filter a Vector in R
|
03 Sep, 2021
In this article, we are going to discuss how to filter a vector in the R programming language.
Filtering a vector means getting the values from the vector by removing the others, we can also say that getting the required elements is known as filtering.
Here we can filter the elements in a vector by using the %in% operator
Syntax:
vec[vec %in% c(elements)]
where
vec is the input vector
elements are the vector elements that we want to get
Example: R program to filter the vector by getting only some values
R
# create a vector with id and namesvector=c(1,2,3,4,5,"sravan","boby","ojaswi","gnanesh","rohith") # display vectorprint(vector) print("=======") # get the data - "sravan","rohith",3 from# the vectorprint(vector[vector %in% c("sravan","rohith",3)]) print("=======") # get the data - "sravan","ojaswi",3,1,2 from# the vectorprint(vector[vector %in% c("sravan","ojaswi",3,1,2)]) print("=======") # get the data - 1,2,3,4,5 from the vectorprint(vector[vector %in% c(1,2,3,4,5)])
Output:
[1] “1” “2” “3” “4” “5” “sravan” “boby”
[8] “ojaswi” “gnanesh” “rohith”
[1] “=======”
[1] “3” “sravan” “rohith”
[1] “=======”
[1] “1” “2” “3” “sravan” “ojaswi”
[1] “=======”
[1] “1” “2” “3” “4” “5”
We can also specify the condition from the index operator.
Syntax:
vector[condition(s)]
where the vector is the input vector and condition defines the condition to follow for filtering.
Example: R program to filter vector using the conditions
R
# create a vector with id and namesvector=c(1,2,3,4,5,"sravan","boby","ojaswi","gnanesh","rohith") # display vectorprint(vector) print("=======") # get the data where element not equal to 1print(vector[vector != 1]) print("=======") # get the data where element equal to 1print(vector[vector == 1])
Output:
[1] “1” “2” “3” “4” “5” “sravan” “boby”
[8] “ojaswi” “gnanesh” “rohith”
[1] “=======”
[1] “2” “3” “4” “5” “sravan” “boby” “ojaswi”
[8] “gnanesh” “rohith”
[1] “=======”
[1] “1”
surinderdawra388
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Sep, 2021"
},
{
"code": null,
"e": 123,
"s": 28,
"text": "In this article, we are going to discuss how to filter a vector in the R programming language."
},
{
"code": null,
"e": 281,
"s": 123,
"text": "Filtering a vector means getting the values from the vector by removing the others, we can also say that getting the required elements is known as filtering."
},
{
"code": null,
"e": 352,
"s": 281,
"text": "Here we can filter the elements in a vector by using the %in% operator"
},
{
"code": null,
"e": 360,
"s": 352,
"text": "Syntax:"
},
{
"code": null,
"e": 387,
"s": 360,
"text": " vec[vec %in% c(elements)]"
},
{
"code": null,
"e": 393,
"s": 387,
"text": "where"
},
{
"code": null,
"e": 417,
"s": 393,
"text": "vec is the input vector"
},
{
"code": null,
"e": 470,
"s": 417,
"text": "elements are the vector elements that we want to get"
},
{
"code": null,
"e": 539,
"s": 470,
"text": "Example: R program to filter the vector by getting only some values"
},
{
"code": null,
"e": 541,
"s": 539,
"text": "R"
},
{
"code": "# create a vector with id and namesvector=c(1,2,3,4,5,\"sravan\",\"boby\",\"ojaswi\",\"gnanesh\",\"rohith\") # display vectorprint(vector) print(\"=======\") # get the data - \"sravan\",\"rohith\",3 from# the vectorprint(vector[vector %in% c(\"sravan\",\"rohith\",3)]) print(\"=======\") # get the data - \"sravan\",\"ojaswi\",3,1,2 from# the vectorprint(vector[vector %in% c(\"sravan\",\"ojaswi\",3,1,2)]) print(\"=======\") # get the data - 1,2,3,4,5 from the vectorprint(vector[vector %in% c(1,2,3,4,5)])",
"e": 1020,
"s": 541,
"text": null
},
{
"code": null,
"e": 1028,
"s": 1020,
"text": "Output:"
},
{
"code": null,
"e": 1103,
"s": 1028,
"text": "[1] “1” “2” “3” “4” “5” “sravan” “boby” "
},
{
"code": null,
"e": 1138,
"s": 1103,
"text": "[8] “ojaswi” “gnanesh” “rohith” "
},
{
"code": null,
"e": 1152,
"s": 1138,
"text": "[1] “=======”"
},
{
"code": null,
"e": 1183,
"s": 1152,
"text": "[1] “3” “sravan” “rohith”"
},
{
"code": null,
"e": 1197,
"s": 1183,
"text": "[1] “=======”"
},
{
"code": null,
"e": 1246,
"s": 1197,
"text": "[1] “1” “2” “3” “sravan” “ojaswi”"
},
{
"code": null,
"e": 1260,
"s": 1246,
"text": "[1] “=======”"
},
{
"code": null,
"e": 1284,
"s": 1260,
"text": "[1] “1” “2” “3” “4” “5”"
},
{
"code": null,
"e": 1344,
"s": 1284,
"text": "We can also specify the condition from the index operator. "
},
{
"code": null,
"e": 1352,
"s": 1344,
"text": "Syntax:"
},
{
"code": null,
"e": 1373,
"s": 1352,
"text": "vector[condition(s)]"
},
{
"code": null,
"e": 1472,
"s": 1373,
"text": "where the vector is the input vector and condition defines the condition to follow for filtering. "
},
{
"code": null,
"e": 1529,
"s": 1472,
"text": "Example: R program to filter vector using the conditions"
},
{
"code": null,
"e": 1531,
"s": 1529,
"text": "R"
},
{
"code": "# create a vector with id and namesvector=c(1,2,3,4,5,\"sravan\",\"boby\",\"ojaswi\",\"gnanesh\",\"rohith\") # display vectorprint(vector) print(\"=======\") # get the data where element not equal to 1print(vector[vector != 1]) print(\"=======\") # get the data where element equal to 1print(vector[vector == 1])",
"e": 1831,
"s": 1531,
"text": null
},
{
"code": null,
"e": 1839,
"s": 1831,
"text": "Output:"
},
{
"code": null,
"e": 1914,
"s": 1839,
"text": "[1] “1” “2” “3” “4” “5” “sravan” “boby” "
},
{
"code": null,
"e": 1949,
"s": 1914,
"text": "[8] “ojaswi” “gnanesh” “rohith” "
},
{
"code": null,
"e": 1963,
"s": 1949,
"text": "[1] “=======”"
},
{
"code": null,
"e": 2038,
"s": 1963,
"text": "[1] “2” “3” “4” “5” “sravan” “boby” “ojaswi” "
},
{
"code": null,
"e": 2063,
"s": 2038,
"text": "[8] “gnanesh” “rohith” "
},
{
"code": null,
"e": 2077,
"s": 2063,
"text": "[1] “=======”"
},
{
"code": null,
"e": 2085,
"s": 2077,
"text": "[1] “1”"
},
{
"code": null,
"e": 2102,
"s": 2085,
"text": "surinderdawra388"
},
{
"code": null,
"e": 2109,
"s": 2102,
"text": "Picked"
},
{
"code": null,
"e": 2127,
"s": 2109,
"text": "R Vector-Programs"
},
{
"code": null,
"e": 2137,
"s": 2127,
"text": "R-Vectors"
},
{
"code": null,
"e": 2148,
"s": 2137,
"text": "R Language"
},
{
"code": null,
"e": 2159,
"s": 2148,
"text": "R Programs"
},
{
"code": null,
"e": 2257,
"s": 2159,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2309,
"s": 2257,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2367,
"s": 2309,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2402,
"s": 2367,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 2440,
"s": 2402,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 2457,
"s": 2440,
"text": "R - if statement"
},
{
"code": null,
"e": 2515,
"s": 2457,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2564,
"s": 2515,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2607,
"s": 2564,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 2645,
"s": 2607,
"text": "Merge DataFrames by Column Names in R"
}
] |
How to use BroadcastReceiver in Kotlin?
|
This example demonstrates how to use BroadcastReceiver in Kotlin .
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:padding="8dp"
android:text="Tutorials Point"
android:textColor="@color/colorPrimaryDark"
android:textSize="48sp"
android:textStyle="bold" />
<Switch
android:id="@+id/wifiSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.wifi.WifiManager
import android.os.Bundle
import android.widget.Switch
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var wifiSwitch: Switch
lateinit var wifiManager: WifiManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
wifiSwitch = findViewById(R.id.wifiSwitch)
wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
wifiSwitch.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
wifiManager.isWifiEnabled = true
wifiSwitch.text = "WiFi is ON"
} else {
wifiManager.isWifiEnabled = false
wifiSwitch.text = "WiFi is OFF"
}
}
}
override fun onStart() {
super.onStart()
val intentFilter = IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION)
registerReceiver(wifiStateReceiver, intentFilter)
}
override fun onStop() {
super.onStop()
unregisterReceiver(wifiStateReceiver)
}
private val wifiStateReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_UNKNOWN)) {
WifiManager.WIFI_STATE_ENABLED -> {
wifiSwitch.isChecked = true
wifiSwitch.text = "WiFi is ON"
Toast.makeText(this@MainActivity, "Wifi is On", Toast.LENGTH_SHORT).show()
}
WifiManager.WIFI_STATE_DISABLED -> {
wifiSwitch.isChecked = false
wifiSwitch.text = "WiFi is OFF"
Toast.makeText(this@MainActivity, "Wifi is Off", Toast.LENGTH_SHORT).show()
}
}
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q20">
<uses-permission android:name="android.permission.CHANGE_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" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
|
[
{
"code": null,
"e": 1254,
"s": 1187,
"text": "This example demonstrates how to use BroadcastReceiver in Kotlin ."
},
{
"code": null,
"e": 1382,
"s": 1254,
"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": 1447,
"s": 1382,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2309,
"s": 1447,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:padding=\"8dp\"\n android:text=\"Tutorials Point\"\n android:textColor=\"@color/colorPrimaryDark\"\n android:textSize=\"48sp\"\n android:textStyle=\"bold\" />\n <Switch\n android:id=\"@+id/wifiSwitch\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2364,
"s": 2309,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 4460,
"s": 2364,
"text": "import android.content.BroadcastReceiver\nimport android.content.Context\nimport android.content.Intent\nimport android.content.IntentFilter\nimport android.net.wifi.WifiManager\nimport android.os.Bundle\nimport android.widget.Switch\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var wifiSwitch: Switch\n lateinit var wifiManager: WifiManager\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n wifiSwitch = findViewById(R.id.wifiSwitch)\n wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager\n wifiSwitch.setOnCheckedChangeListener { _, isChecked ->\n if (isChecked) {\n wifiManager.isWifiEnabled = true\n wifiSwitch.text = \"WiFi is ON\"\n } else {\n wifiManager.isWifiEnabled = false\n wifiSwitch.text = \"WiFi is OFF\"\n }\n }\n }\n override fun onStart() {\n super.onStart()\n val intentFilter = IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION)\n registerReceiver(wifiStateReceiver, intentFilter)\n }\n override fun onStop() {\n super.onStop()\n unregisterReceiver(wifiStateReceiver)\n }\n private val wifiStateReceiver: BroadcastReceiver = object : BroadcastReceiver() {\n override fun onReceive(context: Context, intent: Intent) {\n when (intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,\n WifiManager.WIFI_STATE_UNKNOWN)) {\n WifiManager.WIFI_STATE_ENABLED -> {\n wifiSwitch.isChecked = true\n wifiSwitch.text = \"WiFi is ON\"\n Toast.makeText(this@MainActivity, \"Wifi is On\", Toast.LENGTH_SHORT).show()\n }\n WifiManager.WIFI_STATE_DISABLED -> {\n wifiSwitch.isChecked = false\n wifiSwitch.text = \"WiFi is OFF\"\n Toast.makeText(this@MainActivity, \"Wifi is Off\", Toast.LENGTH_SHORT).show()\n }\n }\n }\n }\n}"
},
{
"code": null,
"e": 4515,
"s": 4460,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5254,
"s": 4515,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.q20\">\n<uses-permission android:name=\"android.permission.CHANGE_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 <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5602,
"s": 5254,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
Python program to count positive and negative numbers in a list
|
26 Oct, 2018
Given a list of numbers, write a Python program to count positive and negative numbers in a List.
Example:
Input: list1 = [2, -7, 5, -64, -14]
Output: pos = 2, neg = 3
Input: list2 = [-12, 14, 95, 3]
Output: pos = 3, neg = 1
Example #1: Count positive and negative numbers from given list using for loop
Iterate each element in the list using for loop and check if num >= 0, the condition to check positive numbers. If the condition satisfies, then increase pos_count else increase neg_count.
# Python program to count positive and negative numbers in a List # list of numberslist1 = [10, -21, 4, -45, 66, -93, 1] pos_count, neg_count = 0, 0 # iterating each number in listfor num in list1: # checking condition if num >= 0: pos_count += 1 else: neg_count += 1 print("Positive numbers in the list: ", pos_count)print("Negative numbers in the list: ", neg_count)
Output:
Positive numbers in the list: 4
Negative numbers in the list: 3
Example #2: Using while loop
# Python program to count positive and negative numbers in a List # list of numberslist1 = [-10, -21, -4, -45, -66, 93, 11] pos_count, neg_count = 0, 0num = 0 # using while loop while(num < len(list1)): # checking condition if list1[num] >= 0: pos_count += 1 else: neg_count += 1 # increment num num += 1 print("Positive numbers in the list: ", pos_count)print("Negative numbers in the list: ", neg_count)
Output:
Positive numbers in the list: 2
Negative numbers in the list: 5
Example #3 : Using Python Lambda Expressions
# Python program to count positive# and negative numbers in a List # list of numberslist1 = [10, -21, -4, 45, 66, 93, -11] neg_count = len(list(filter(lambda x: (x < 0), list1))) # we can also do len(list1) - neg_countpos_count = len(list(filter(lambda x: (x >= 0), list1))) print("Positive numbers in the list: ", pos_count)print("Negative numbers in the list: ", neg_count)
Output:
Positive numbers in the list: 4
Negative numbers in the list: 3
Example #4 : Using List Comprehension
# Python program to count positive# and negative numbers in a List # list of numberslist1 = [-10, -21, -4, -45, -66, -93, 11] only_pos = [num for num in list1 if num >= 1]pos_count = len(only_pos) print("Positive numbers in the list: ", pos_count)print("Negative numbers in the list: ", len(list1) - pos_count)
Output:
Positive numbers in the list: 1
Negative numbers in the list: 6
Python list-programs
python-list
Python
Python Programs
School Programming
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
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": "\n26 Oct, 2018"
},
{
"code": null,
"e": 126,
"s": 28,
"text": "Given a list of numbers, write a Python program to count positive and negative numbers in a List."
},
{
"code": null,
"e": 135,
"s": 126,
"text": "Example:"
},
{
"code": null,
"e": 254,
"s": 135,
"text": "Input: list1 = [2, -7, 5, -64, -14]\nOutput: pos = 2, neg = 3\n\nInput: list2 = [-12, 14, 95, 3]\nOutput: pos = 3, neg = 1"
},
{
"code": null,
"e": 333,
"s": 254,
"text": "Example #1: Count positive and negative numbers from given list using for loop"
},
{
"code": null,
"e": 522,
"s": 333,
"text": "Iterate each element in the list using for loop and check if num >= 0, the condition to check positive numbers. If the condition satisfies, then increase pos_count else increase neg_count."
},
{
"code": "# Python program to count positive and negative numbers in a List # list of numberslist1 = [10, -21, 4, -45, 66, -93, 1] pos_count, neg_count = 0, 0 # iterating each number in listfor num in list1: # checking condition if num >= 0: pos_count += 1 else: neg_count += 1 print(\"Positive numbers in the list: \", pos_count)print(\"Negative numbers in the list: \", neg_count)",
"e": 934,
"s": 522,
"text": null
},
{
"code": null,
"e": 942,
"s": 934,
"text": "Output:"
},
{
"code": null,
"e": 1009,
"s": 942,
"text": "Positive numbers in the list: 4\nNegative numbers in the list: 3\n"
},
{
"code": null,
"e": 1040,
"s": 1011,
"text": "Example #2: Using while loop"
},
{
"code": "# Python program to count positive and negative numbers in a List # list of numberslist1 = [-10, -21, -4, -45, -66, 93, 11] pos_count, neg_count = 0, 0num = 0 # using while loop while(num < len(list1)): # checking condition if list1[num] >= 0: pos_count += 1 else: neg_count += 1 # increment num num += 1 print(\"Positive numbers in the list: \", pos_count)print(\"Negative numbers in the list: \", neg_count)",
"e": 1500,
"s": 1040,
"text": null
},
{
"code": null,
"e": 1508,
"s": 1500,
"text": "Output:"
},
{
"code": null,
"e": 1575,
"s": 1508,
"text": "Positive numbers in the list: 2\nNegative numbers in the list: 5\n"
},
{
"code": null,
"e": 1622,
"s": 1577,
"text": "Example #3 : Using Python Lambda Expressions"
},
{
"code": "# Python program to count positive# and negative numbers in a List # list of numberslist1 = [10, -21, -4, 45, 66, 93, -11] neg_count = len(list(filter(lambda x: (x < 0), list1))) # we can also do len(list1) - neg_countpos_count = len(list(filter(lambda x: (x >= 0), list1))) print(\"Positive numbers in the list: \", pos_count)print(\"Negative numbers in the list: \", neg_count)",
"e": 2002,
"s": 1622,
"text": null
},
{
"code": null,
"e": 2010,
"s": 2002,
"text": "Output:"
},
{
"code": null,
"e": 2077,
"s": 2010,
"text": "Positive numbers in the list: 4\nNegative numbers in the list: 3\n"
},
{
"code": null,
"e": 2117,
"s": 2079,
"text": "Example #4 : Using List Comprehension"
},
{
"code": "# Python program to count positive# and negative numbers in a List # list of numberslist1 = [-10, -21, -4, -45, -66, -93, 11] only_pos = [num for num in list1 if num >= 1]pos_count = len(only_pos) print(\"Positive numbers in the list: \", pos_count)print(\"Negative numbers in the list: \", len(list1) - pos_count)",
"e": 2431,
"s": 2117,
"text": null
},
{
"code": null,
"e": 2439,
"s": 2431,
"text": "Output:"
},
{
"code": null,
"e": 2506,
"s": 2439,
"text": "Positive numbers in the list: 1\nNegative numbers in the list: 6\n"
},
{
"code": null,
"e": 2527,
"s": 2506,
"text": "Python list-programs"
},
{
"code": null,
"e": 2539,
"s": 2527,
"text": "python-list"
},
{
"code": null,
"e": 2546,
"s": 2539,
"text": "Python"
},
{
"code": null,
"e": 2562,
"s": 2546,
"text": "Python Programs"
},
{
"code": null,
"e": 2581,
"s": 2562,
"text": "School Programming"
},
{
"code": null,
"e": 2593,
"s": 2581,
"text": "python-list"
},
{
"code": null,
"e": 2691,
"s": 2593,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2733,
"s": 2691,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2755,
"s": 2733,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2781,
"s": 2755,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2813,
"s": 2781,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2842,
"s": 2813,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2864,
"s": 2842,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2903,
"s": 2864,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2941,
"s": 2903,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2990,
"s": 2941,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Creating Tabbed Widget With Python-Tkinter
|
26 Mar, 2020
Python offers a range of GUI frameworks that can be used to develop GUI based applications in Python. The most widely used Python interface is Tk interface or tkinter( as renamed in Python 3.x) . The Tkinter module offers a wide range of widgets that can be used to develop GUI applications much faster and easier compared to the other interfaces offered by Python. The tkinter.ttk module serves as an improvement to the already existing tk module. The Ttk module is equipped with 18 widgets, 12 of which existed in the Tkinter module such as Button, Checkbutton, PanedWindow, Radiobutton, Entry, Frame, Label, LabelFrame, Menubutton, Scale, Scrollbar, and Spinbox. The newly added widgets are Combobox, Notebook, Sizegrip, Progressbar, Separator, and Treeview. In this article, the Notebook widget of ttk module is put into use to create a tabbed widget. The ttk.Notebook widget manages a collection of windows and displays one at a time. Each child window is associated with a tab. The user can select one tab at a time to view the content of the window.Steps to create a tkinter tabbed widget :
Import tkinter moduleimport tkinter as tk
from tkinter import *Note: Name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’. Python 3.x is used here.Import tkinter ttk module which contains the Notebook widgetfrom tkinter import ttkCreate the parent window (root).root = tk.Tk()
Syntax:Tk()Explanation:Used to create the parent window. Tk class is instantiated without any arguments (here).Add title to the parent window (root).root.title("Tab Widget")Syntax:title(name)Parameter:name: used to pass the desired name to the parent window (root).Creating Tab ControltabControl = ttk.Notebook(root)Syntax:Notebook(master=None, **options)Parameter:master: parent window (root).options: The options accepted by the Notebook() method are height, padding and width. Options are not used in this program.Creating the tabstab1 = ttk.Frame(tabControl)
tab2 = ttk.Frame(tabControl)Syntax:Frame(master=None, **options)Parameter:master: tabControl is the parent widget for the tabs.options: The options accepted by the Frame() method are class_, cursor, padding, relief, style, takefocus, height and width. Options are not used in this program.Explanation:The Frame widget acts like a container and is used to group other widgets together. Here the Frame widget is used to group the tab widgets together.Adding the tabtabControl.add(tab1, text='Tab 1')
tabControl.add(tab2, text='Tab 2')Syntax:add(child, **options)Parameter:child: tab1 and tab2 are the child widget of tabControl.options: The options supported by add() method are sticky, state, padding, text, image, compound, underline.Explanation:The add() method is present in tk.ttk.Notebook class. It is used to add new tabs to the Notebook widget.Packing the tab control to make the tabs visibletabControl.pack(expand=1, fill="both")Syntax:pack(**options)Parameter:expand: The expand option ensures equal distribution of space between widgets that have non zero expand value when the parent widget is expanded.fill: The fill option ensures that the widget occupies the space allocated to it. Now fill=”both” specifies that the widget occupies the space along both X and Y axis, fill=”X” specifies that the widget occupies the space along X axis and fill=”Y” specifies that the widget occupies the space along Y axis.Explanation:The pack() method is used to organize widgets in blocks before placing them in the parent widget. This can be done using various options like fill, expand and side.Creating Label widget as a child of the parent window (root)ttk.Label(tab1, text=”Welcome to GeeksForGeeks”).grid(column=0, row=0, padx=30, pady=30)ttk.Label(tab2, text=”Lets dive into the world of computers”).grid(column=0, row=0, padx=30, pady=30)Syntax:Label(master, **options)Parameter:master: The tabs act as parent for the Label widget.options: The options supported by Label() method are anchor, bg, bitmap, bd, cursor, font, fg, height, width, image, justify, relief, padx, pady, textvariable, underline and wraplength.Explanation:The Label widget is used to display text or images on the screen.The text displayed on the screen can further be formatted using the various options available in the Label widget.Syntax:grid(**options)Parameter:options: The options supported by grid() method are column, columnspan, row, rowspan, padx, pady, ipadx, ipady and sticky.Explanation:The grid() method is used to split the parent widget in rows and columns more specifically a 2D table. It can be used to specify the position of the widgets in the parent widget. Here grid() method specifies the position of the Label widget ie. basically the position of the text in the parent window.Run the applicationroot.mainloop() Syntax: mainloop()Explanation:The mainloop() acts like an infinite loop and is used to run an application.Complete program is as follows:import tkinter as tk from tkinter import ttk root = tk.Tk()root.title("Tab Widget")tabControl = ttk.Notebook(root) tab1 = ttk.Frame(tabControl)tab2 = ttk.Frame(tabControl) tabControl.add(tab1, text ='Tab 1')tabControl.add(tab2, text ='Tab 2')tabControl.pack(expand = 1, fill ="both") ttk.Label(tab1, text ="Welcome to \ GeeksForGeeks").grid(column = 0, row = 0, padx = 30, pady = 30) ttk.Label(tab2, text ="Lets dive into the\ world of computers").grid(column = 0, row = 0, padx = 30, pady = 30) root.mainloop() OutputMy Personal Notes
arrow_drop_upSave
Import tkinter moduleimport tkinter as tk
from tkinter import *Note: Name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’. Python 3.x is used here.
import tkinter as tk
from tkinter import *
Note: Name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’. Python 3.x is used here.
Import tkinter ttk module which contains the Notebook widgetfrom tkinter import ttk
from tkinter import ttk
Create the parent window (root).root = tk.Tk()
Syntax:Tk()Explanation:Used to create the parent window. Tk class is instantiated without any arguments (here).
root = tk.Tk()
Syntax:
Tk()
Explanation:Used to create the parent window. Tk class is instantiated without any arguments (here).
Add title to the parent window (root).root.title("Tab Widget")Syntax:title(name)Parameter:name: used to pass the desired name to the parent window (root).
root.title("Tab Widget")
Syntax:
title(name)
Parameter:name: used to pass the desired name to the parent window (root).
Creating Tab ControltabControl = ttk.Notebook(root)Syntax:Notebook(master=None, **options)Parameter:master: parent window (root).options: The options accepted by the Notebook() method are height, padding and width. Options are not used in this program.
tabControl = ttk.Notebook(root)
Syntax:
Notebook(master=None, **options)
Parameter:
master: parent window (root).
options: The options accepted by the Notebook() method are height, padding and width. Options are not used in this program.
Creating the tabstab1 = ttk.Frame(tabControl)
tab2 = ttk.Frame(tabControl)Syntax:Frame(master=None, **options)Parameter:master: tabControl is the parent widget for the tabs.options: The options accepted by the Frame() method are class_, cursor, padding, relief, style, takefocus, height and width. Options are not used in this program.Explanation:The Frame widget acts like a container and is used to group other widgets together. Here the Frame widget is used to group the tab widgets together.
tab1 = ttk.Frame(tabControl)
tab2 = ttk.Frame(tabControl)
Syntax:
Frame(master=None, **options)
Parameter:
master: tabControl is the parent widget for the tabs.
options: The options accepted by the Frame() method are class_, cursor, padding, relief, style, takefocus, height and width. Options are not used in this program.
Explanation:The Frame widget acts like a container and is used to group other widgets together. Here the Frame widget is used to group the tab widgets together.
Adding the tabtabControl.add(tab1, text='Tab 1')
tabControl.add(tab2, text='Tab 2')Syntax:add(child, **options)Parameter:child: tab1 and tab2 are the child widget of tabControl.options: The options supported by add() method are sticky, state, padding, text, image, compound, underline.Explanation:The add() method is present in tk.ttk.Notebook class. It is used to add new tabs to the Notebook widget.
tabControl.add(tab1, text='Tab 1')
tabControl.add(tab2, text='Tab 2')
Syntax:
add(child, **options)
Parameter:
child: tab1 and tab2 are the child widget of tabControl.
options: The options supported by add() method are sticky, state, padding, text, image, compound, underline.
Explanation:The add() method is present in tk.ttk.Notebook class. It is used to add new tabs to the Notebook widget.
Packing the tab control to make the tabs visibletabControl.pack(expand=1, fill="both")Syntax:pack(**options)Parameter:expand: The expand option ensures equal distribution of space between widgets that have non zero expand value when the parent widget is expanded.fill: The fill option ensures that the widget occupies the space allocated to it. Now fill=”both” specifies that the widget occupies the space along both X and Y axis, fill=”X” specifies that the widget occupies the space along X axis and fill=”Y” specifies that the widget occupies the space along Y axis.Explanation:The pack() method is used to organize widgets in blocks before placing them in the parent widget. This can be done using various options like fill, expand and side.
tabControl.pack(expand=1, fill="both")
Syntax:
pack(**options)
Parameter:
expand: The expand option ensures equal distribution of space between widgets that have non zero expand value when the parent widget is expanded.
fill: The fill option ensures that the widget occupies the space allocated to it. Now fill=”both” specifies that the widget occupies the space along both X and Y axis, fill=”X” specifies that the widget occupies the space along X axis and fill=”Y” specifies that the widget occupies the space along Y axis.
Explanation:The pack() method is used to organize widgets in blocks before placing them in the parent widget. This can be done using various options like fill, expand and side.
Creating Label widget as a child of the parent window (root)ttk.Label(tab1, text=”Welcome to GeeksForGeeks”).grid(column=0, row=0, padx=30, pady=30)ttk.Label(tab2, text=”Lets dive into the world of computers”).grid(column=0, row=0, padx=30, pady=30)Syntax:Label(master, **options)Parameter:master: The tabs act as parent for the Label widget.options: The options supported by Label() method are anchor, bg, bitmap, bd, cursor, font, fg, height, width, image, justify, relief, padx, pady, textvariable, underline and wraplength.Explanation:The Label widget is used to display text or images on the screen.The text displayed on the screen can further be formatted using the various options available in the Label widget.Syntax:grid(**options)Parameter:options: The options supported by grid() method are column, columnspan, row, rowspan, padx, pady, ipadx, ipady and sticky.Explanation:The grid() method is used to split the parent widget in rows and columns more specifically a 2D table. It can be used to specify the position of the widgets in the parent widget. Here grid() method specifies the position of the Label widget ie. basically the position of the text in the parent window.
ttk.Label(tab1, text=”Welcome to GeeksForGeeks”).grid(column=0, row=0, padx=30, pady=30)ttk.Label(tab2, text=”Lets dive into the world of computers”).grid(column=0, row=0, padx=30, pady=30)
Syntax:
Label(master, **options)
Parameter:
master: The tabs act as parent for the Label widget.
options: The options supported by Label() method are anchor, bg, bitmap, bd, cursor, font, fg, height, width, image, justify, relief, padx, pady, textvariable, underline and wraplength.
Explanation:The Label widget is used to display text or images on the screen.The text displayed on the screen can further be formatted using the various options available in the Label widget.
Syntax:
grid(**options)
Parameter:
options: The options supported by grid() method are column, columnspan, row, rowspan, padx, pady, ipadx, ipady and sticky.
Explanation:The grid() method is used to split the parent widget in rows and columns more specifically a 2D table. It can be used to specify the position of the widgets in the parent widget. Here grid() method specifies the position of the Label widget ie. basically the position of the text in the parent window.
Run the applicationroot.mainloop() Syntax: mainloop()Explanation:The mainloop() acts like an infinite loop and is used to run an application.
root.mainloop()
Syntax: mainloop()Explanation:The mainloop() acts like an infinite loop and is used to run an application.
Complete program is as follows:
import tkinter as tk from tkinter import ttk root = tk.Tk()root.title("Tab Widget")tabControl = ttk.Notebook(root) tab1 = ttk.Frame(tabControl)tab2 = ttk.Frame(tabControl) tabControl.add(tab1, text ='Tab 1')tabControl.add(tab2, text ='Tab 2')tabControl.pack(expand = 1, fill ="both") ttk.Label(tab1, text ="Welcome to \ GeeksForGeeks").grid(column = 0, row = 0, padx = 30, pady = 30) ttk.Label(tab2, text ="Lets dive into the\ world of computers").grid(column = 0, row = 0, padx = 30, pady = 30) root.mainloop()
Output
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 1126,
"s": 28,
"text": "Python offers a range of GUI frameworks that can be used to develop GUI based applications in Python. The most widely used Python interface is Tk interface or tkinter( as renamed in Python 3.x) . The Tkinter module offers a wide range of widgets that can be used to develop GUI applications much faster and easier compared to the other interfaces offered by Python. The tkinter.ttk module serves as an improvement to the already existing tk module. The Ttk module is equipped with 18 widgets, 12 of which existed in the Tkinter module such as Button, Checkbutton, PanedWindow, Radiobutton, Entry, Frame, Label, LabelFrame, Menubutton, Scale, Scrollbar, and Spinbox. The newly added widgets are Combobox, Notebook, Sizegrip, Progressbar, Separator, and Treeview. In this article, the Notebook widget of ttk module is put into use to create a tabbed widget. The ttk.Notebook widget manages a collection of windows and displays one at a time. Each child window is associated with a tab. The user can select one tab at a time to view the content of the window.Steps to create a tkinter tabbed widget :"
},
{
"code": null,
"e": 5761,
"s": 1126,
"text": "Import tkinter moduleimport tkinter as tk\nfrom tkinter import *Note: Name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’. Python 3.x is used here.Import tkinter ttk module which contains the Notebook widgetfrom tkinter import ttkCreate the parent window (root).root = tk.Tk()\nSyntax:Tk()Explanation:Used to create the parent window. Tk class is instantiated without any arguments (here).Add title to the parent window (root).root.title(\"Tab Widget\")Syntax:title(name)Parameter:name: used to pass the desired name to the parent window (root).Creating Tab ControltabControl = ttk.Notebook(root)Syntax:Notebook(master=None, **options)Parameter:master: parent window (root).options: The options accepted by the Notebook() method are height, padding and width. Options are not used in this program.Creating the tabstab1 = ttk.Frame(tabControl)\ntab2 = ttk.Frame(tabControl)Syntax:Frame(master=None, **options)Parameter:master: tabControl is the parent widget for the tabs.options: The options accepted by the Frame() method are class_, cursor, padding, relief, style, takefocus, height and width. Options are not used in this program.Explanation:The Frame widget acts like a container and is used to group other widgets together. Here the Frame widget is used to group the tab widgets together.Adding the tabtabControl.add(tab1, text='Tab 1')\ntabControl.add(tab2, text='Tab 2')Syntax:add(child, **options)Parameter:child: tab1 and tab2 are the child widget of tabControl.options: The options supported by add() method are sticky, state, padding, text, image, compound, underline.Explanation:The add() method is present in tk.ttk.Notebook class. It is used to add new tabs to the Notebook widget.Packing the tab control to make the tabs visibletabControl.pack(expand=1, fill=\"both\")Syntax:pack(**options)Parameter:expand: The expand option ensures equal distribution of space between widgets that have non zero expand value when the parent widget is expanded.fill: The fill option ensures that the widget occupies the space allocated to it. Now fill=”both” specifies that the widget occupies the space along both X and Y axis, fill=”X” specifies that the widget occupies the space along X axis and fill=”Y” specifies that the widget occupies the space along Y axis.Explanation:The pack() method is used to organize widgets in blocks before placing them in the parent widget. This can be done using various options like fill, expand and side.Creating Label widget as a child of the parent window (root)ttk.Label(tab1, text=”Welcome to GeeksForGeeks”).grid(column=0, row=0, padx=30, pady=30)ttk.Label(tab2, text=”Lets dive into the world of computers”).grid(column=0, row=0, padx=30, pady=30)Syntax:Label(master, **options)Parameter:master: The tabs act as parent for the Label widget.options: The options supported by Label() method are anchor, bg, bitmap, bd, cursor, font, fg, height, width, image, justify, relief, padx, pady, textvariable, underline and wraplength.Explanation:The Label widget is used to display text or images on the screen.The text displayed on the screen can further be formatted using the various options available in the Label widget.Syntax:grid(**options)Parameter:options: The options supported by grid() method are column, columnspan, row, rowspan, padx, pady, ipadx, ipady and sticky.Explanation:The grid() method is used to split the parent widget in rows and columns more specifically a 2D table. It can be used to specify the position of the widgets in the parent widget. Here grid() method specifies the position of the Label widget ie. basically the position of the text in the parent window.Run the applicationroot.mainloop() Syntax: mainloop()Explanation:The mainloop() acts like an infinite loop and is used to run an application.Complete program is as follows:import tkinter as tk from tkinter import ttk root = tk.Tk()root.title(\"Tab Widget\")tabControl = ttk.Notebook(root) tab1 = ttk.Frame(tabControl)tab2 = ttk.Frame(tabControl) tabControl.add(tab1, text ='Tab 1')tabControl.add(tab2, text ='Tab 2')tabControl.pack(expand = 1, fill =\"both\") ttk.Label(tab1, text =\"Welcome to \\ GeeksForGeeks\").grid(column = 0, row = 0, padx = 30, pady = 30) ttk.Label(tab2, text =\"Lets dive into the\\ world of computers\").grid(column = 0, row = 0, padx = 30, pady = 30) root.mainloop() OutputMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 5936,
"s": 5761,
"text": "Import tkinter moduleimport tkinter as tk\nfrom tkinter import *Note: Name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’. Python 3.x is used here."
},
{
"code": null,
"e": 5979,
"s": 5936,
"text": "import tkinter as tk\nfrom tkinter import *"
},
{
"code": null,
"e": 6091,
"s": 5979,
"text": "Note: Name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’. Python 3.x is used here."
},
{
"code": null,
"e": 6175,
"s": 6091,
"text": "Import tkinter ttk module which contains the Notebook widgetfrom tkinter import ttk"
},
{
"code": null,
"e": 6199,
"s": 6175,
"text": "from tkinter import ttk"
},
{
"code": null,
"e": 6358,
"s": 6199,
"text": "Create the parent window (root).root = tk.Tk()\nSyntax:Tk()Explanation:Used to create the parent window. Tk class is instantiated without any arguments (here)."
},
{
"code": null,
"e": 6374,
"s": 6358,
"text": "root = tk.Tk()\n"
},
{
"code": null,
"e": 6382,
"s": 6374,
"text": "Syntax:"
},
{
"code": null,
"e": 6387,
"s": 6382,
"text": "Tk()"
},
{
"code": null,
"e": 6488,
"s": 6387,
"text": "Explanation:Used to create the parent window. Tk class is instantiated without any arguments (here)."
},
{
"code": null,
"e": 6643,
"s": 6488,
"text": "Add title to the parent window (root).root.title(\"Tab Widget\")Syntax:title(name)Parameter:name: used to pass the desired name to the parent window (root)."
},
{
"code": null,
"e": 6668,
"s": 6643,
"text": "root.title(\"Tab Widget\")"
},
{
"code": null,
"e": 6676,
"s": 6668,
"text": "Syntax:"
},
{
"code": null,
"e": 6688,
"s": 6676,
"text": "title(name)"
},
{
"code": null,
"e": 6763,
"s": 6688,
"text": "Parameter:name: used to pass the desired name to the parent window (root)."
},
{
"code": null,
"e": 7016,
"s": 6763,
"text": "Creating Tab ControltabControl = ttk.Notebook(root)Syntax:Notebook(master=None, **options)Parameter:master: parent window (root).options: The options accepted by the Notebook() method are height, padding and width. Options are not used in this program."
},
{
"code": null,
"e": 7048,
"s": 7016,
"text": "tabControl = ttk.Notebook(root)"
},
{
"code": null,
"e": 7056,
"s": 7048,
"text": "Syntax:"
},
{
"code": null,
"e": 7089,
"s": 7056,
"text": "Notebook(master=None, **options)"
},
{
"code": null,
"e": 7100,
"s": 7089,
"text": "Parameter:"
},
{
"code": null,
"e": 7130,
"s": 7100,
"text": "master: parent window (root)."
},
{
"code": null,
"e": 7254,
"s": 7130,
"text": "options: The options accepted by the Notebook() method are height, padding and width. Options are not used in this program."
},
{
"code": null,
"e": 7750,
"s": 7254,
"text": "Creating the tabstab1 = ttk.Frame(tabControl)\ntab2 = ttk.Frame(tabControl)Syntax:Frame(master=None, **options)Parameter:master: tabControl is the parent widget for the tabs.options: The options accepted by the Frame() method are class_, cursor, padding, relief, style, takefocus, height and width. Options are not used in this program.Explanation:The Frame widget acts like a container and is used to group other widgets together. Here the Frame widget is used to group the tab widgets together."
},
{
"code": null,
"e": 7808,
"s": 7750,
"text": "tab1 = ttk.Frame(tabControl)\ntab2 = ttk.Frame(tabControl)"
},
{
"code": null,
"e": 7816,
"s": 7808,
"text": "Syntax:"
},
{
"code": null,
"e": 7846,
"s": 7816,
"text": "Frame(master=None, **options)"
},
{
"code": null,
"e": 7857,
"s": 7846,
"text": "Parameter:"
},
{
"code": null,
"e": 7911,
"s": 7857,
"text": "master: tabControl is the parent widget for the tabs."
},
{
"code": null,
"e": 8074,
"s": 7911,
"text": "options: The options accepted by the Frame() method are class_, cursor, padding, relief, style, takefocus, height and width. Options are not used in this program."
},
{
"code": null,
"e": 8235,
"s": 8074,
"text": "Explanation:The Frame widget acts like a container and is used to group other widgets together. Here the Frame widget is used to group the tab widgets together."
},
{
"code": null,
"e": 8637,
"s": 8235,
"text": "Adding the tabtabControl.add(tab1, text='Tab 1')\ntabControl.add(tab2, text='Tab 2')Syntax:add(child, **options)Parameter:child: tab1 and tab2 are the child widget of tabControl.options: The options supported by add() method are sticky, state, padding, text, image, compound, underline.Explanation:The add() method is present in tk.ttk.Notebook class. It is used to add new tabs to the Notebook widget."
},
{
"code": null,
"e": 8707,
"s": 8637,
"text": "tabControl.add(tab1, text='Tab 1')\ntabControl.add(tab2, text='Tab 2')"
},
{
"code": null,
"e": 8715,
"s": 8707,
"text": "Syntax:"
},
{
"code": null,
"e": 8737,
"s": 8715,
"text": "add(child, **options)"
},
{
"code": null,
"e": 8748,
"s": 8737,
"text": "Parameter:"
},
{
"code": null,
"e": 8805,
"s": 8748,
"text": "child: tab1 and tab2 are the child widget of tabControl."
},
{
"code": null,
"e": 8914,
"s": 8805,
"text": "options: The options supported by add() method are sticky, state, padding, text, image, compound, underline."
},
{
"code": null,
"e": 9031,
"s": 8914,
"text": "Explanation:The add() method is present in tk.ttk.Notebook class. It is used to add new tabs to the Notebook widget."
},
{
"code": null,
"e": 9777,
"s": 9031,
"text": "Packing the tab control to make the tabs visibletabControl.pack(expand=1, fill=\"both\")Syntax:pack(**options)Parameter:expand: The expand option ensures equal distribution of space between widgets that have non zero expand value when the parent widget is expanded.fill: The fill option ensures that the widget occupies the space allocated to it. Now fill=”both” specifies that the widget occupies the space along both X and Y axis, fill=”X” specifies that the widget occupies the space along X axis and fill=”Y” specifies that the widget occupies the space along Y axis.Explanation:The pack() method is used to organize widgets in blocks before placing them in the parent widget. This can be done using various options like fill, expand and side."
},
{
"code": null,
"e": 9816,
"s": 9777,
"text": "tabControl.pack(expand=1, fill=\"both\")"
},
{
"code": null,
"e": 9824,
"s": 9816,
"text": "Syntax:"
},
{
"code": null,
"e": 9840,
"s": 9824,
"text": "pack(**options)"
},
{
"code": null,
"e": 9851,
"s": 9840,
"text": "Parameter:"
},
{
"code": null,
"e": 9997,
"s": 9851,
"text": "expand: The expand option ensures equal distribution of space between widgets that have non zero expand value when the parent widget is expanded."
},
{
"code": null,
"e": 10304,
"s": 9997,
"text": "fill: The fill option ensures that the widget occupies the space allocated to it. Now fill=”both” specifies that the widget occupies the space along both X and Y axis, fill=”X” specifies that the widget occupies the space along X axis and fill=”Y” specifies that the widget occupies the space along Y axis."
},
{
"code": null,
"e": 10481,
"s": 10304,
"text": "Explanation:The pack() method is used to organize widgets in blocks before placing them in the parent widget. This can be done using various options like fill, expand and side."
},
{
"code": null,
"e": 11667,
"s": 10481,
"text": "Creating Label widget as a child of the parent window (root)ttk.Label(tab1, text=”Welcome to GeeksForGeeks”).grid(column=0, row=0, padx=30, pady=30)ttk.Label(tab2, text=”Lets dive into the world of computers”).grid(column=0, row=0, padx=30, pady=30)Syntax:Label(master, **options)Parameter:master: The tabs act as parent for the Label widget.options: The options supported by Label() method are anchor, bg, bitmap, bd, cursor, font, fg, height, width, image, justify, relief, padx, pady, textvariable, underline and wraplength.Explanation:The Label widget is used to display text or images on the screen.The text displayed on the screen can further be formatted using the various options available in the Label widget.Syntax:grid(**options)Parameter:options: The options supported by grid() method are column, columnspan, row, rowspan, padx, pady, ipadx, ipady and sticky.Explanation:The grid() method is used to split the parent widget in rows and columns more specifically a 2D table. It can be used to specify the position of the widgets in the parent widget. Here grid() method specifies the position of the Label widget ie. basically the position of the text in the parent window."
},
{
"code": null,
"e": 11857,
"s": 11667,
"text": "ttk.Label(tab1, text=”Welcome to GeeksForGeeks”).grid(column=0, row=0, padx=30, pady=30)ttk.Label(tab2, text=”Lets dive into the world of computers”).grid(column=0, row=0, padx=30, pady=30)"
},
{
"code": null,
"e": 11865,
"s": 11857,
"text": "Syntax:"
},
{
"code": null,
"e": 11890,
"s": 11865,
"text": "Label(master, **options)"
},
{
"code": null,
"e": 11901,
"s": 11890,
"text": "Parameter:"
},
{
"code": null,
"e": 11954,
"s": 11901,
"text": "master: The tabs act as parent for the Label widget."
},
{
"code": null,
"e": 12140,
"s": 11954,
"text": "options: The options supported by Label() method are anchor, bg, bitmap, bd, cursor, font, fg, height, width, image, justify, relief, padx, pady, textvariable, underline and wraplength."
},
{
"code": null,
"e": 12332,
"s": 12140,
"text": "Explanation:The Label widget is used to display text or images on the screen.The text displayed on the screen can further be formatted using the various options available in the Label widget."
},
{
"code": null,
"e": 12340,
"s": 12332,
"text": "Syntax:"
},
{
"code": null,
"e": 12356,
"s": 12340,
"text": "grid(**options)"
},
{
"code": null,
"e": 12367,
"s": 12356,
"text": "Parameter:"
},
{
"code": null,
"e": 12490,
"s": 12367,
"text": "options: The options supported by grid() method are column, columnspan, row, rowspan, padx, pady, ipadx, ipady and sticky."
},
{
"code": null,
"e": 12804,
"s": 12490,
"text": "Explanation:The grid() method is used to split the parent widget in rows and columns more specifically a 2D table. It can be used to specify the position of the widgets in the parent widget. Here grid() method specifies the position of the Label widget ie. basically the position of the text in the parent window."
},
{
"code": null,
"e": 12946,
"s": 12804,
"text": "Run the applicationroot.mainloop() Syntax: mainloop()Explanation:The mainloop() acts like an infinite loop and is used to run an application."
},
{
"code": null,
"e": 12963,
"s": 12946,
"text": "root.mainloop() "
},
{
"code": null,
"e": 13070,
"s": 12963,
"text": "Syntax: mainloop()Explanation:The mainloop() acts like an infinite loop and is used to run an application."
},
{
"code": null,
"e": 13102,
"s": 13070,
"text": "Complete program is as follows:"
},
{
"code": "import tkinter as tk from tkinter import ttk root = tk.Tk()root.title(\"Tab Widget\")tabControl = ttk.Notebook(root) tab1 = ttk.Frame(tabControl)tab2 = ttk.Frame(tabControl) tabControl.add(tab1, text ='Tab 1')tabControl.add(tab2, text ='Tab 2')tabControl.pack(expand = 1, fill =\"both\") ttk.Label(tab1, text =\"Welcome to \\ GeeksForGeeks\").grid(column = 0, row = 0, padx = 30, pady = 30) ttk.Label(tab2, text =\"Lets dive into the\\ world of computers\").grid(column = 0, row = 0, padx = 30, pady = 30) root.mainloop() ",
"e": 13877,
"s": 13102,
"text": null
},
{
"code": null,
"e": 13884,
"s": 13877,
"text": "Output"
},
{
"code": null,
"e": 13899,
"s": 13884,
"text": "Python-tkinter"
},
{
"code": null,
"e": 13906,
"s": 13899,
"text": "Python"
},
{
"code": null,
"e": 14004,
"s": 13906,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14036,
"s": 14004,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 14063,
"s": 14036,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 14084,
"s": 14063,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 14107,
"s": 14084,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 14163,
"s": 14107,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 14194,
"s": 14163,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 14236,
"s": 14194,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 14278,
"s": 14236,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 14317,
"s": 14278,
"text": "Python | datetime.timedelta() function"
}
] |
Java - How to Use Iterator?
|
Often, you will want to cycle through the elements in a collection. For example, you might want to display each element. The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface.
Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements.
Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time.
In general, to use an iterator to cycle through the contents of a collection, follow these steps −
Obtain an iterator to the start of the collection by calling the collection's iterator( ) method.
Obtain an iterator to the start of the collection by calling the collection's iterator( ) method.
Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
Within the loop, obtain each element by calling next( ).
Within the loop, obtain each element by calling next( ).
For collections that implement List, you can also obtain an iterator by calling ListIterator.
boolean hasNext( )
Returns true if there are more elements. Otherwise, returns false.
Object next( )
Returns the next element. Throws NoSuchElementException if there is not a next element.
void remove( )
Removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ).
void add(Object obj)
Inserts obj into the list in front of the element that will be returned by the next call to next( ).
boolean hasNext( )
Returns true if there is a next element. Otherwise, returns false.
boolean hasPrevious( )
Returns true if there is a previous element. Otherwise, returns false.
Object next( )
Returns the next element. A NoSuchElementException is thrown if there is not a next element.
int nextIndex( )
Returns the index of the next element. If there is not a next element, returns the size of the list.
Object previous( )
Returns the previous element. A NoSuchElementException is thrown if there is not a previous element.
int previousIndex( )
Returns the index of the previous element. If there is not a previous element, returns -1.
void remove( )
Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked.
void set(Object obj)
Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ).
Here is an example demonstrating both Iterator and ListIterator. It uses an ArrayList object, but the general principles apply to any type of collection.
Of course, ListIterator is available only to those collections that implement the List interface.
import java.util.*;
public class IteratorDemo {
public static void main(String args[]) {
// Create an array list
ArrayList al = new ArrayList();
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
// Use iterator to display contents of al
System.out.print("Original contents of al: ");
Iterator itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// Modify objects being iterated
ListIterator litr = al.listIterator();
while(litr.hasNext()) {
Object element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// Now, display the list backwards
System.out.print("Modified list backwards: ");
while(litr.hasPrevious()) {
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
This will produce the following result −
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+
|
[
{
"code": null,
"e": 2771,
"s": 2511,
"text": "Often, you will want to cycle through the elements in a collection. For example, you might want to display each element. The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface."
},
{
"code": null,
"e": 2963,
"s": 2771,
"text": "Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements."
},
{
"code": null,
"e": 3260,
"s": 2963,
"text": "Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time."
},
{
"code": null,
"e": 3359,
"s": 3260,
"text": "In general, to use an iterator to cycle through the contents of a collection, follow these steps −"
},
{
"code": null,
"e": 3457,
"s": 3359,
"text": "Obtain an iterator to the start of the collection by calling the collection's iterator( ) method."
},
{
"code": null,
"e": 3555,
"s": 3457,
"text": "Obtain an iterator to the start of the collection by calling the collection's iterator( ) method."
},
{
"code": null,
"e": 3660,
"s": 3555,
"text": "Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true."
},
{
"code": null,
"e": 3765,
"s": 3660,
"text": "Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true."
},
{
"code": null,
"e": 3822,
"s": 3765,
"text": "Within the loop, obtain each element by calling next( )."
},
{
"code": null,
"e": 3879,
"s": 3822,
"text": "Within the loop, obtain each element by calling next( )."
},
{
"code": null,
"e": 3973,
"s": 3879,
"text": "For collections that implement List, you can also obtain an iterator by calling ListIterator."
},
{
"code": null,
"e": 3992,
"s": 3973,
"text": "boolean hasNext( )"
},
{
"code": null,
"e": 4059,
"s": 3992,
"text": "Returns true if there are more elements. Otherwise, returns false."
},
{
"code": null,
"e": 4074,
"s": 4059,
"text": "Object next( )"
},
{
"code": null,
"e": 4162,
"s": 4074,
"text": "Returns the next element. Throws NoSuchElementException if there is not a next element."
},
{
"code": null,
"e": 4177,
"s": 4162,
"text": "void remove( )"
},
{
"code": null,
"e": 4318,
"s": 4177,
"text": "Removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( )."
},
{
"code": null,
"e": 4339,
"s": 4318,
"text": "void add(Object obj)"
},
{
"code": null,
"e": 4440,
"s": 4339,
"text": "Inserts obj into the list in front of the element that will be returned by the next call to next( )."
},
{
"code": null,
"e": 4459,
"s": 4440,
"text": "boolean hasNext( )"
},
{
"code": null,
"e": 4526,
"s": 4459,
"text": "Returns true if there is a next element. Otherwise, returns false."
},
{
"code": null,
"e": 4549,
"s": 4526,
"text": "boolean hasPrevious( )"
},
{
"code": null,
"e": 4620,
"s": 4549,
"text": "Returns true if there is a previous element. Otherwise, returns false."
},
{
"code": null,
"e": 4635,
"s": 4620,
"text": "Object next( )"
},
{
"code": null,
"e": 4728,
"s": 4635,
"text": "Returns the next element. A NoSuchElementException is thrown if there is not a next element."
},
{
"code": null,
"e": 4745,
"s": 4728,
"text": "int nextIndex( )"
},
{
"code": null,
"e": 4846,
"s": 4745,
"text": "Returns the index of the next element. If there is not a next element, returns the size of the list."
},
{
"code": null,
"e": 4865,
"s": 4846,
"text": "Object previous( )"
},
{
"code": null,
"e": 4966,
"s": 4865,
"text": "Returns the previous element. A NoSuchElementException is thrown if there is not a previous element."
},
{
"code": null,
"e": 4987,
"s": 4966,
"text": "int previousIndex( )"
},
{
"code": null,
"e": 5078,
"s": 4987,
"text": "Returns the index of the previous element. If there is not a previous element, returns -1."
},
{
"code": null,
"e": 5093,
"s": 5078,
"text": "void remove( )"
},
{
"code": null,
"e": 5236,
"s": 5093,
"text": "Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked."
},
{
"code": null,
"e": 5257,
"s": 5236,
"text": "void set(Object obj)"
},
{
"code": null,
"e": 5371,
"s": 5257,
"text": "Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( )."
},
{
"code": null,
"e": 5525,
"s": 5371,
"text": "Here is an example demonstrating both Iterator and ListIterator. It uses an ArrayList object, but the general principles apply to any type of collection."
},
{
"code": null,
"e": 5623,
"s": 5525,
"text": "Of course, ListIterator is available only to those collections that implement the List interface."
},
{
"code": null,
"e": 6940,
"s": 5623,
"text": "import java.util.*;\npublic class IteratorDemo {\n\n public static void main(String args[]) {\n // Create an array list\n ArrayList al = new ArrayList();\n \n // add elements to the array list\n al.add(\"C\");\n al.add(\"A\");\n al.add(\"E\");\n al.add(\"B\");\n al.add(\"D\");\n al.add(\"F\");\n\n // Use iterator to display contents of al\n System.out.print(\"Original contents of al: \");\n Iterator itr = al.iterator();\n \n while(itr.hasNext()) {\n Object element = itr.next();\n System.out.print(element + \" \");\n }\n System.out.println();\n \n // Modify objects being iterated\n ListIterator litr = al.listIterator();\n \n while(litr.hasNext()) {\n Object element = litr.next();\n litr.set(element + \"+\");\n }\n System.out.print(\"Modified contents of al: \");\n itr = al.iterator();\n \n while(itr.hasNext()) {\n Object element = itr.next();\n System.out.print(element + \" \");\n }\n System.out.println();\n\n // Now, display the list backwards\n System.out.print(\"Modified list backwards: \");\n \n while(litr.hasPrevious()) {\n Object element = litr.previous();\n System.out.print(element + \" \");\n }\n System.out.println();\n }\n}"
},
{
"code": null,
"e": 6981,
"s": 6940,
"text": "This will produce the following result −"
}
] |
Float compare() Method in Java with Examples
|
22 Jun, 2021
The compare() method of Float Class is a built-in method in Java that compares the two specified float values. The sign of the integer value returned is the same as that of the integer that would be returned by the function call.
Syntax:
public static int compare(float f1, float f2)
Parameters: The function accepts two parameters:
f1: The first float value to be compared.
f2: The second float value to be compared.
Return Value: The function returns value as below:
0: if f1 is numerically equal to f2.
Negative value: if f1 is numerically less than f2.
Positive value: if f1 is numerically greater than f2.
Below programs illustrates the use of Float.compare() function:
Program 1: When two integers are same
Java
// Java Program to illustrate// the Float.compare() method import java.lang.Float; public class GFG { public static void main(String[] args) { // Get the two float values // to be compared Float f1 = 1023f; Float f2 = 1023f; // function call to compare two float values if (Float.compare(f1, f2) == 0) { System.out.println("f1=f2"); } else if (Float.compare(f1, f2) < 0) { System.out.println("f1<f2"); } else { System.out.println("f1>f2"); } }}
f1=f2
Program 2 : When f1<f2
Java
// Java Program to illustrate// the Float.compare() method import java.lang.Float; public class GFG { public static void main(String[] args) { // Get the two float values // to be compared Float f1 = 10f; Float f2 = 1023f; // function call to compare two float values if (Float.compare(f1, f2) == 0) { System.out.println("f1=f2"); } else if (Float.compare(f1, f2) < 0) { System.out.println("f1<f2"); } else { System.out.println("f1>f2"); } }}
f1
Program 3 : When f1>f2
Java
// Java Program to illustrate// the Float.compare() method import java.lang.Float; public class GFG { public static void main(String[] args) { // Get the two float values // to be compared Float f1 = 1023f; Float f2 = 10f; // function call to compare two float values if (Float.compare(f1, f2) == 0) { System.out.println("f1=f2"); } else if (Float.compare(f1, f2) < 0) { System.out.println("f1<f2"); } else { System.out.println("f1>f2"); } }}
f1>f2
Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#compare(float, %20float)
rajeev0719singh
Java-Float
Java-Functions
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Queue Interface In Java
Multidimensional Arrays in Java
How to add an element to an Array in Java?
HashMap in Java with Examples
Stack Class in Java
PriorityQueue in Java
Math pow() method in Java with Example
Initialize an ArrayList in Java
List Interface in Java with Examples
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 259,
"s": 28,
"text": "The compare() method of Float Class is a built-in method in Java that compares the two specified float values. The sign of the integer value returned is the same as that of the integer that would be returned by the function call. "
},
{
"code": null,
"e": 268,
"s": 259,
"text": "Syntax: "
},
{
"code": null,
"e": 314,
"s": 268,
"text": "public static int compare(float f1, float f2)"
},
{
"code": null,
"e": 365,
"s": 314,
"text": "Parameters: The function accepts two parameters: "
},
{
"code": null,
"e": 407,
"s": 365,
"text": "f1: The first float value to be compared."
},
{
"code": null,
"e": 450,
"s": 407,
"text": "f2: The second float value to be compared."
},
{
"code": null,
"e": 503,
"s": 450,
"text": "Return Value: The function returns value as below: "
},
{
"code": null,
"e": 540,
"s": 503,
"text": "0: if f1 is numerically equal to f2."
},
{
"code": null,
"e": 591,
"s": 540,
"text": "Negative value: if f1 is numerically less than f2."
},
{
"code": null,
"e": 645,
"s": 591,
"text": "Positive value: if f1 is numerically greater than f2."
},
{
"code": null,
"e": 709,
"s": 645,
"text": "Below programs illustrates the use of Float.compare() function:"
},
{
"code": null,
"e": 749,
"s": 709,
"text": "Program 1: When two integers are same "
},
{
"code": null,
"e": 754,
"s": 749,
"text": "Java"
},
{
"code": "// Java Program to illustrate// the Float.compare() method import java.lang.Float; public class GFG { public static void main(String[] args) { // Get the two float values // to be compared Float f1 = 1023f; Float f2 = 1023f; // function call to compare two float values if (Float.compare(f1, f2) == 0) { System.out.println(\"f1=f2\"); } else if (Float.compare(f1, f2) < 0) { System.out.println(\"f1<f2\"); } else { System.out.println(\"f1>f2\"); } }}",
"e": 1323,
"s": 754,
"text": null
},
{
"code": null,
"e": 1329,
"s": 1323,
"text": "f1=f2"
},
{
"code": null,
"e": 1354,
"s": 1331,
"text": "Program 2 : When f1<f2"
},
{
"code": null,
"e": 1359,
"s": 1354,
"text": "Java"
},
{
"code": "// Java Program to illustrate// the Float.compare() method import java.lang.Float; public class GFG { public static void main(String[] args) { // Get the two float values // to be compared Float f1 = 10f; Float f2 = 1023f; // function call to compare two float values if (Float.compare(f1, f2) == 0) { System.out.println(\"f1=f2\"); } else if (Float.compare(f1, f2) < 0) { System.out.println(\"f1<f2\"); } else { System.out.println(\"f1>f2\"); } }}",
"e": 1926,
"s": 1359,
"text": null
},
{
"code": null,
"e": 1929,
"s": 1926,
"text": "f1"
},
{
"code": null,
"e": 1952,
"s": 1929,
"text": "Program 3 : When f1>f2"
},
{
"code": null,
"e": 1957,
"s": 1952,
"text": "Java"
},
{
"code": "// Java Program to illustrate// the Float.compare() method import java.lang.Float; public class GFG { public static void main(String[] args) { // Get the two float values // to be compared Float f1 = 1023f; Float f2 = 10f; // function call to compare two float values if (Float.compare(f1, f2) == 0) { System.out.println(\"f1=f2\"); } else if (Float.compare(f1, f2) < 0) { System.out.println(\"f1<f2\"); } else { System.out.println(\"f1>f2\"); } }}",
"e": 2524,
"s": 1957,
"text": null
},
{
"code": null,
"e": 2530,
"s": 2524,
"text": "f1>f2"
},
{
"code": null,
"e": 2632,
"s": 2532,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#compare(float, %20float) "
},
{
"code": null,
"e": 2648,
"s": 2632,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 2659,
"s": 2648,
"text": "Java-Float"
},
{
"code": null,
"e": 2674,
"s": 2659,
"text": "Java-Functions"
},
{
"code": null,
"e": 2692,
"s": 2674,
"text": "Java-lang package"
},
{
"code": null,
"e": 2697,
"s": 2692,
"text": "Java"
},
{
"code": null,
"e": 2702,
"s": 2697,
"text": "Java"
},
{
"code": null,
"e": 2800,
"s": 2702,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2819,
"s": 2800,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2843,
"s": 2819,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 2875,
"s": 2843,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 2918,
"s": 2875,
"text": "How to add an element to an Array in Java?"
},
{
"code": null,
"e": 2948,
"s": 2918,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 2968,
"s": 2948,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 2990,
"s": 2968,
"text": "PriorityQueue in Java"
},
{
"code": null,
"e": 3029,
"s": 2990,
"text": "Math pow() method in Java with Example"
},
{
"code": null,
"e": 3061,
"s": 3029,
"text": "Initialize an ArrayList in Java"
}
] |
Python – Reverse Sort a String
|
17 Jun, 2022
Sorting has always been quite a popular utility with lots of applications everywhere, where Python language has opted. Python in its language offers a sort function to perform this task. But due to fact that not all the containers in Python are mutable, such as string, the sort function doesn’t work as it inplace tries to sort and immutability stops this. Let’s discuss certain ways in which a string can be sorted in a reverse way.
Method #1 : join() + sorted() + reverse key: The combination of above functions can potentially solve this particular problem. This task is performed in 2 steps in which the first step we get the reverse sorted list of characters and then we join the result to get the resultant sorted string.
Python3
# Python3 code to demonstrate# Reverse Sort a String# using join() + sorted() + reverse # initializing stringtest_string = "geekforgeeks" # printing original stringprint("The original string : " + str(test_string)) # using join() + sorted() + reverse# Sorting a stringres = ''.join(sorted(test_string, reverse = True)) # print resultprint("String after reverse sorting : " + str(res))
The original string : geekforgeeks
String after reverse sorting : srokkggfeeee
Method #2 : Using sorted() + reduce() + lambda: This particular task can also be performed using the combination of above 3 functions. Here we join the resultant reverse sorted list of characters using the lambda function joined by the reduce function. Works only for Python2.
Python
# Python code to demonstrate# Reverse Sort a String# using sorted() + reduce() + lambda # initializing stringtest_string = "geekforgeeks" # printing original stringprint("The original string : " + str(test_string)) # using sorted() + reduce() + lambda# Reverse Sort a Stringres = reduce(lambda x, y: x + y, sorted(test_string, reverse = True)) # print resultprint("String after reverse sorting : " + str(res))
The original string : geekforgeeks
String after reverse sorting : srokkggfeeee
Method#3 : Using list() + sort() + join(): This problem can also be solve using the combination of above 3 methods. Here we convert the string to a list and sort this list with the sort function of the list in reverse order and after that join the result into a string.
Python3
# Python code to demonstrate# To Sort and Reverse a String# using list() + sort() + join() # initializing stringtest_string = "geekforgeeks" # printing original stringprint("The original string : " + str(test_string)) # using list() + sort() + join# To Sort and reverse a Stringtemp = list(test_string)temp.sort(reverse = True)res = "".join(temp) # print resultprint("String after reverse sorting : " + res)
The original string : geekforgeeks
String after reverse sorting : srokkggfeeee
satyam00so
Python string-programs
Python-sort
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jun, 2022"
},
{
"code": null,
"e": 463,
"s": 28,
"text": "Sorting has always been quite a popular utility with lots of applications everywhere, where Python language has opted. Python in its language offers a sort function to perform this task. But due to fact that not all the containers in Python are mutable, such as string, the sort function doesn’t work as it inplace tries to sort and immutability stops this. Let’s discuss certain ways in which a string can be sorted in a reverse way."
},
{
"code": null,
"e": 758,
"s": 463,
"text": "Method #1 : join() + sorted() + reverse key: The combination of above functions can potentially solve this particular problem. This task is performed in 2 steps in which the first step we get the reverse sorted list of characters and then we join the result to get the resultant sorted string. "
},
{
"code": null,
"e": 766,
"s": 758,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Reverse Sort a String# using join() + sorted() + reverse # initializing stringtest_string = \"geekforgeeks\" # printing original stringprint(\"The original string : \" + str(test_string)) # using join() + sorted() + reverse# Sorting a stringres = ''.join(sorted(test_string, reverse = True)) # print resultprint(\"String after reverse sorting : \" + str(res))",
"e": 1155,
"s": 766,
"text": null
},
{
"code": null,
"e": 1235,
"s": 1155,
"text": "The original string : geekforgeeks\nString after reverse sorting : srokkggfeeee\n"
},
{
"code": null,
"e": 1514,
"s": 1235,
"text": " Method #2 : Using sorted() + reduce() + lambda: This particular task can also be performed using the combination of above 3 functions. Here we join the resultant reverse sorted list of characters using the lambda function joined by the reduce function. Works only for Python2. "
},
{
"code": null,
"e": 1521,
"s": 1514,
"text": "Python"
},
{
"code": "# Python code to demonstrate# Reverse Sort a String# using sorted() + reduce() + lambda # initializing stringtest_string = \"geekforgeeks\" # printing original stringprint(\"The original string : \" + str(test_string)) # using sorted() + reduce() + lambda# Reverse Sort a Stringres = reduce(lambda x, y: x + y, sorted(test_string, reverse = True)) # print resultprint(\"String after reverse sorting : \" + str(res))",
"e": 1935,
"s": 1521,
"text": null
},
{
"code": null,
"e": 2015,
"s": 1935,
"text": "The original string : geekforgeeks\nString after reverse sorting : srokkggfeeee\n"
},
{
"code": null,
"e": 2286,
"s": 2015,
"text": " Method#3 : Using list() + sort() + join(): This problem can also be solve using the combination of above 3 methods. Here we convert the string to a list and sort this list with the sort function of the list in reverse order and after that join the result into a string."
},
{
"code": null,
"e": 2294,
"s": 2286,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# To Sort and Reverse a String# using list() + sort() + join() # initializing stringtest_string = \"geekforgeeks\" # printing original stringprint(\"The original string : \" + str(test_string)) # using list() + sort() + join# To Sort and reverse a Stringtemp = list(test_string)temp.sort(reverse = True)res = \"\".join(temp) # print resultprint(\"String after reverse sorting : \" + res)",
"e": 2706,
"s": 2294,
"text": null
},
{
"code": null,
"e": 2786,
"s": 2706,
"text": "The original string : geekforgeeks\nString after reverse sorting : srokkggfeeee\n"
},
{
"code": null,
"e": 2797,
"s": 2786,
"text": "satyam00so"
},
{
"code": null,
"e": 2820,
"s": 2797,
"text": "Python string-programs"
},
{
"code": null,
"e": 2832,
"s": 2820,
"text": "Python-sort"
},
{
"code": null,
"e": 2839,
"s": 2832,
"text": "Python"
},
{
"code": null,
"e": 2855,
"s": 2839,
"text": "Python Programs"
},
{
"code": null,
"e": 2953,
"s": 2855,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2995,
"s": 2953,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3017,
"s": 2995,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3052,
"s": 3017,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3078,
"s": 3052,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3110,
"s": 3078,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3153,
"s": 3110,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 3175,
"s": 3153,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3214,
"s": 3175,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3252,
"s": 3214,
"text": "Python | Convert a list to dictionary"
}
] |
Cyclic Redundancy Check in Python
|
13 Jun, 2022
Prerequisites: Know about Cyclic redundancy, Socket Programming
What is CRC? CRC or Cyclic Redundancy Check is a method of detecting accidental changes/errors in the communication channel. CRC uses Generator Polynomial which is available on both sender and receiver sides. An example generator polynomial is of the form of x^3 + 1. This generator polynomial represents key 1001. Another example is x^2 + x. that represents key 110.
Example: Let data send is “EVN” We convert a string to binary string data.
Python
input_string = "EVN" # CONVERT string data to binary string datadata = (''.join(format(ord(x), 'b') for x in input_string))print (data)
100010110101101001110
CRC KEY: 1001 Code: CRC key length -1 -> 000 appended at end of data.
New data: 100010110101101001110000
Key:1001
Now we apply CRC in socket programming python at both sender and receiver sides.
Sender Side
1. The task is to send string data to the server/receiver side. 2. The sender sends a string let us say “EVN”. 3. First, this string is converted to binary string “100010110101101001110” key is known to both the side sender and receiver here key used is 1001. 4. This data is encoded using the CRC code using the key on the client/sender side. 5. This encoded data is sent to the receiver. 6. Receiver later decodes the encoded data string to verify whether there was any error or not.
Python3
# Import socket moduleimport socket def xor(a, b): # initialize result result = [] # Traverse all bits, if bits are # same, then XOR is 0, else 1 for i in range(1, len(b)): if a[i] == b[i]: result.append('0') else: result.append('1') return ''.join(result) # Performs Modulo-2 divisiondef mod2div(divident, divisor): # Number of bits to be XORed at a time. pick = len(divisor) # Slicing the divident to appropriate # length for particular step tmp = divident[0 : pick] while pick < len(divident): if tmp[0] == '1': # replace the divident by the result # of XOR and pull 1 bit down tmp = xor(divisor, tmp) + divident[pick] else: # If leftmost bit is '0' # If the leftmost bit of the dividend (or the # part used in each step) is 0, the step cannot # use the regular divisor; we need to use an # all-0s divisor. tmp = xor('0'*pick, tmp) + divident[pick] # increment pick to move further pick += 1 # For the last n bits, we have to carry it out # normally as increased value of pick will cause # Index Out of Bounds. if tmp[0] == '1': tmp = xor(divisor, tmp) else: tmp = xor('0'*pick, tmp) checkword = tmp return checkword # Function used at the sender side to encode# data by appending remainder of modular division# at the end of data.def encodeData(data, key): l_key = len(key) # Appends n-1 zeroes at end of data appended_data = data + '0'*(l_key-1) remainder = mod2div(appended_data, key) # Append remainder in the original data codeword = data + remainder return codeword # Create a socket objects = socket.socket() # Define the port on which you want to connectport = 12345 # connect to the server on local computers.connect(('127.0.0.1', port)) # Send data to server 'Hello world' ## s.sendall('Hello World') input_string = input("Enter data you want to send->")#s.sendall(input_string)data =(''.join(format(ord(x), 'b') for x in input_string))print("Entered data in binary format :",data)key = "1001" ans = encodeData(data,key)print("Encoded data to be sent to server in binary format :",ans)s.sendto(ans.encode(),('127.0.0.1', 12345)) # receive data from the serverprint("Received feedback from server :",s.recv(1024).decode()) # close the connections.close()
Receiver Side
1. The receiver receives the encoded data string from the sender. 2. Receiver with the help of the key decodes the data and finds out the remainder. 3. If the remainder is zero then it means there is no error in data sent by the sender to the receiver. 4. If the remainder comes out to be non-zero it means there was an error, a Negative Acknowledgement is sent to the sender. The sender then resends the data until the receiver receives the correct data.
Python3
# First of all import the socket libraryimport socket def xor(a, b): # initialize result result = [] # Traverse all bits, if bits are # same, then XOR is 0, else 1 for i in range(1, len(b)): if a[i] == b[i]: result.append('0') else: result.append('1') return ''.join(result) # Performs Modulo-2 divisiondef mod2div(divident, divisor): # Number of bits to be XORed at a time. pick = len(divisor) # Slicing the divident to appropriate # length for particular step tmp = divident[0: pick] while pick < len(divident): if tmp[0] == '1': # replace the divident by the result # of XOR and pull 1 bit down tmp = xor(divisor, tmp) + divident[pick] else: # If leftmost bit is '0' # If the leftmost bit of the dividend (or the # part used in each step) is 0, the step cannot # use the regular divisor; we need to use an # all-0s divisor. tmp = xor('0'*pick, tmp) + divident[pick] # increment pick to move further pick += 1 # For the last n bits, we have to carry it out # normally as increased value of pick will cause # Index Out of Bounds. if tmp[0] == '1': tmp = xor(divisor, tmp) else: tmp = xor('0'*pick, tmp) checkword = tmp return checkword # Function used at the receiver side to decode# data received by sender def decodeData(data, key): l_key = len(key) # Appends n-1 zeroes at end of data appended_data = data.decode() + '0'*(l_key-1) remainder = mod2div(appended_data, key) return remainder # Creating Sockets = socket.socket()print("Socket successfully created") # reserve a port on your computer in our# case it is 12345 but it can be anythingport = 12345 s.bind(('', port))print("socket binded to %s" % (port))# put the socket into listening modes.listen(5)print("socket is listening") while True: # Establish connection with client. c, addr = s.accept() print('Got connection from', addr) # Get data from client data = c.recv(1024) print("Received encoded data in binary format :", data.decode()) if not data: break key = "1001" ans = decodeData(data, key) print("Remainder after decoding is->"+ans) # If remainder is all zeros then no error occurred temp = "0" * (len(key) - 1) if ans == temp: c.sendto(("THANK you Data ->"+data.decode() + " Received No error FOUND").encode(), ('127.0.0.1', 12345)) else: c.sendto(("Error in data").encode(), ('127.0.0.1', 12345)) c.close()
NOTE: How to run the program: 1. You should have a socket programming library.
2. First, run server program then runs client program.
3. Indentation error may occur while you copy-paste the code so be careful while copying.
4. You’ll see the following output in your split terminal.
Akanksha_Rai
pawananjanimth1
marcosarcticseal
nikhatkhan11
Computer Networks
Python
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Network Topology
RSA Algorithm in Cryptography
GSM in Wireless Communication
TCP Server-Client implementation in C
Socket Programming in Python
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 118,
"s": 54,
"text": "Prerequisites: Know about Cyclic redundancy, Socket Programming"
},
{
"code": null,
"e": 487,
"s": 118,
"text": "What is CRC? CRC or Cyclic Redundancy Check is a method of detecting accidental changes/errors in the communication channel. CRC uses Generator Polynomial which is available on both sender and receiver sides. An example generator polynomial is of the form of x^3 + 1. This generator polynomial represents key 1001. Another example is x^2 + x. that represents key 110. "
},
{
"code": null,
"e": 562,
"s": 487,
"text": "Example: Let data send is “EVN” We convert a string to binary string data."
},
{
"code": null,
"e": 569,
"s": 562,
"text": "Python"
},
{
"code": "input_string = \"EVN\" # CONVERT string data to binary string datadata = (''.join(format(ord(x), 'b') for x in input_string))print (data)",
"e": 705,
"s": 569,
"text": null
},
{
"code": null,
"e": 727,
"s": 705,
"text": "100010110101101001110"
},
{
"code": null,
"e": 798,
"s": 727,
"text": "CRC KEY: 1001 Code: CRC key length -1 -> 000 appended at end of data. "
},
{
"code": null,
"e": 842,
"s": 798,
"text": "New data: 100010110101101001110000\nKey:1001"
},
{
"code": null,
"e": 924,
"s": 842,
"text": "Now we apply CRC in socket programming python at both sender and receiver sides. "
},
{
"code": null,
"e": 936,
"s": 924,
"text": "Sender Side"
},
{
"code": null,
"e": 1424,
"s": 936,
"text": "1. The task is to send string data to the server/receiver side. 2. The sender sends a string let us say “EVN”. 3. First, this string is converted to binary string “100010110101101001110” key is known to both the side sender and receiver here key used is 1001. 4. This data is encoded using the CRC code using the key on the client/sender side. 5. This encoded data is sent to the receiver. 6. Receiver later decodes the encoded data string to verify whether there was any error or not. "
},
{
"code": null,
"e": 1432,
"s": 1424,
"text": "Python3"
},
{
"code": "# Import socket moduleimport socket def xor(a, b): # initialize result result = [] # Traverse all bits, if bits are # same, then XOR is 0, else 1 for i in range(1, len(b)): if a[i] == b[i]: result.append('0') else: result.append('1') return ''.join(result) # Performs Modulo-2 divisiondef mod2div(divident, divisor): # Number of bits to be XORed at a time. pick = len(divisor) # Slicing the divident to appropriate # length for particular step tmp = divident[0 : pick] while pick < len(divident): if tmp[0] == '1': # replace the divident by the result # of XOR and pull 1 bit down tmp = xor(divisor, tmp) + divident[pick] else: # If leftmost bit is '0' # If the leftmost bit of the dividend (or the # part used in each step) is 0, the step cannot # use the regular divisor; we need to use an # all-0s divisor. tmp = xor('0'*pick, tmp) + divident[pick] # increment pick to move further pick += 1 # For the last n bits, we have to carry it out # normally as increased value of pick will cause # Index Out of Bounds. if tmp[0] == '1': tmp = xor(divisor, tmp) else: tmp = xor('0'*pick, tmp) checkword = tmp return checkword # Function used at the sender side to encode# data by appending remainder of modular division# at the end of data.def encodeData(data, key): l_key = len(key) # Appends n-1 zeroes at end of data appended_data = data + '0'*(l_key-1) remainder = mod2div(appended_data, key) # Append remainder in the original data codeword = data + remainder return codeword # Create a socket objects = socket.socket() # Define the port on which you want to connectport = 12345 # connect to the server on local computers.connect(('127.0.0.1', port)) # Send data to server 'Hello world' ## s.sendall('Hello World') input_string = input(\"Enter data you want to send->\")#s.sendall(input_string)data =(''.join(format(ord(x), 'b') for x in input_string))print(\"Entered data in binary format :\",data)key = \"1001\" ans = encodeData(data,key)print(\"Encoded data to be sent to server in binary format :\",ans)s.sendto(ans.encode(),('127.0.0.1', 12345)) # receive data from the serverprint(\"Received feedback from server :\",s.recv(1024).decode()) # close the connections.close()",
"e": 3897,
"s": 1432,
"text": null
},
{
"code": null,
"e": 3911,
"s": 3897,
"text": "Receiver Side"
},
{
"code": null,
"e": 4369,
"s": 3911,
"text": "1. The receiver receives the encoded data string from the sender. 2. Receiver with the help of the key decodes the data and finds out the remainder. 3. If the remainder is zero then it means there is no error in data sent by the sender to the receiver. 4. If the remainder comes out to be non-zero it means there was an error, a Negative Acknowledgement is sent to the sender. The sender then resends the data until the receiver receives the correct data. "
},
{
"code": null,
"e": 4377,
"s": 4369,
"text": "Python3"
},
{
"code": "# First of all import the socket libraryimport socket def xor(a, b): # initialize result result = [] # Traverse all bits, if bits are # same, then XOR is 0, else 1 for i in range(1, len(b)): if a[i] == b[i]: result.append('0') else: result.append('1') return ''.join(result) # Performs Modulo-2 divisiondef mod2div(divident, divisor): # Number of bits to be XORed at a time. pick = len(divisor) # Slicing the divident to appropriate # length for particular step tmp = divident[0: pick] while pick < len(divident): if tmp[0] == '1': # replace the divident by the result # of XOR and pull 1 bit down tmp = xor(divisor, tmp) + divident[pick] else: # If leftmost bit is '0' # If the leftmost bit of the dividend (or the # part used in each step) is 0, the step cannot # use the regular divisor; we need to use an # all-0s divisor. tmp = xor('0'*pick, tmp) + divident[pick] # increment pick to move further pick += 1 # For the last n bits, we have to carry it out # normally as increased value of pick will cause # Index Out of Bounds. if tmp[0] == '1': tmp = xor(divisor, tmp) else: tmp = xor('0'*pick, tmp) checkword = tmp return checkword # Function used at the receiver side to decode# data received by sender def decodeData(data, key): l_key = len(key) # Appends n-1 zeroes at end of data appended_data = data.decode() + '0'*(l_key-1) remainder = mod2div(appended_data, key) return remainder # Creating Sockets = socket.socket()print(\"Socket successfully created\") # reserve a port on your computer in our# case it is 12345 but it can be anythingport = 12345 s.bind(('', port))print(\"socket binded to %s\" % (port))# put the socket into listening modes.listen(5)print(\"socket is listening\") while True: # Establish connection with client. c, addr = s.accept() print('Got connection from', addr) # Get data from client data = c.recv(1024) print(\"Received encoded data in binary format :\", data.decode()) if not data: break key = \"1001\" ans = decodeData(data, key) print(\"Remainder after decoding is->\"+ans) # If remainder is all zeros then no error occurred temp = \"0\" * (len(key) - 1) if ans == temp: c.sendto((\"THANK you Data ->\"+data.decode() + \" Received No error FOUND\").encode(), ('127.0.0.1', 12345)) else: c.sendto((\"Error in data\").encode(), ('127.0.0.1', 12345)) c.close()",
"e": 7007,
"s": 4377,
"text": null
},
{
"code": null,
"e": 7087,
"s": 7007,
"text": "NOTE: How to run the program: 1. You should have a socket programming library. "
},
{
"code": null,
"e": 7143,
"s": 7087,
"text": "2. First, run server program then runs client program. "
},
{
"code": null,
"e": 7233,
"s": 7143,
"text": "3. Indentation error may occur while you copy-paste the code so be careful while copying."
},
{
"code": null,
"e": 7292,
"s": 7233,
"text": "4. You’ll see the following output in your split terminal."
},
{
"code": null,
"e": 7305,
"s": 7292,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 7321,
"s": 7305,
"text": "pawananjanimth1"
},
{
"code": null,
"e": 7338,
"s": 7321,
"text": "marcosarcticseal"
},
{
"code": null,
"e": 7351,
"s": 7338,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 7369,
"s": 7351,
"text": "Computer Networks"
},
{
"code": null,
"e": 7376,
"s": 7369,
"text": "Python"
},
{
"code": null,
"e": 7394,
"s": 7376,
"text": "Computer Networks"
},
{
"code": null,
"e": 7492,
"s": 7394,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7518,
"s": 7492,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 7548,
"s": 7518,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 7578,
"s": 7548,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 7616,
"s": 7578,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 7645,
"s": 7616,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 7673,
"s": 7645,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 7723,
"s": 7673,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 7745,
"s": 7723,
"text": "Python map() function"
}
] |
C# Program to count number of Vowels and Consonants in a string
|
You need to check for both the vowels and consonants, but do not forget to check for both the uppercase as well lowercase.
For counting vowels, check for “aeiou” characters separately i.e.
if (myStr[i] == 'a' || myStr[i] == 'e' || myStr[i] == 'i' || myStr[i] == 'o' || myStr[i] == 'u' || myStr[i] == 'A' || myStr[i] == 'E' || myStr[i] == 'I' || myStr[i] == 'O' || myStr[i] == 'U') {
vowel_count++;
}
For counting consonants, check for other characters in elseif condition −
else if ((myStr[i] >= 'a' && myStr[i] <= 'z') || (myStr[i] >= 'A' && myStr[i] <= 'Z')) {
cons_count++;
}
The following is the code to count a number of Vowels and Consonants in a string.
Live Demo
using System;
public class Demo {
public static void Main() {
string myStr;
int i, len, vowel_count, cons_count;
myStr = "Jack Sparrow";
vowel_count = 0;
cons_count = 0;
// find length
len = myStr.Length;
for(i=0; i<len; i++) {
if(myStr[i] =='a' || myStr[i]=='e' || myStr[i]=='i' || myStr[i]=='o' || myStr[i]=='u' || myStr[i]=='A' || myStr[i]=='E' || myStr[i]=='I' || myStr[i]=='O' || myStr[i]=='U') {
vowel_count++;
} else if((myStr[i]>='a' && myStr[i]<='z') || (myStr[i]>='A' && myStr[i]<='Z')) {
cons_count++;
}
}
Console.Write("\nVowel in the string: {0}\n", vowel_count);
Console.Write("Consonant in the string: {0}\n\n", cons_count);
}
}
Vowel in the string: 3
Consonant in the string: 8
|
[
{
"code": null,
"e": 1185,
"s": 1062,
"text": "You need to check for both the vowels and consonants, but do not forget to check for both the uppercase as well lowercase."
},
{
"code": null,
"e": 1251,
"s": 1185,
"text": "For counting vowels, check for “aeiou” characters separately i.e."
},
{
"code": null,
"e": 1465,
"s": 1251,
"text": "if (myStr[i] == 'a' || myStr[i] == 'e' || myStr[i] == 'i' || myStr[i] == 'o' || myStr[i] == 'u' || myStr[i] == 'A' || myStr[i] == 'E' || myStr[i] == 'I' || myStr[i] == 'O' || myStr[i] == 'U') {\n vowel_count++;\n}"
},
{
"code": null,
"e": 1539,
"s": 1465,
"text": "For counting consonants, check for other characters in elseif condition −"
},
{
"code": null,
"e": 1663,
"s": 1539,
"text": "else if ((myStr[i] >= 'a' && myStr[i] <= 'z') || (myStr[i] >= 'A' && myStr[i] <= 'Z')) {\n cons_count++;\n}"
},
{
"code": null,
"e": 1745,
"s": 1663,
"text": "The following is the code to count a number of Vowels and Consonants in a string."
},
{
"code": null,
"e": 1755,
"s": 1745,
"text": "Live Demo"
},
{
"code": null,
"e": 2538,
"s": 1755,
"text": "using System;\npublic class Demo {\n public static void Main() {\n string myStr;\n int i, len, vowel_count, cons_count;\n myStr = \"Jack Sparrow\";\n vowel_count = 0;\n cons_count = 0;\n // find length\n len = myStr.Length;\n for(i=0; i<len; i++) {\n if(myStr[i] =='a' || myStr[i]=='e' || myStr[i]=='i' || myStr[i]=='o' || myStr[i]=='u' || myStr[i]=='A' || myStr[i]=='E' || myStr[i]=='I' || myStr[i]=='O' || myStr[i]=='U') {\n vowel_count++;\n } else if((myStr[i]>='a' && myStr[i]<='z') || (myStr[i]>='A' && myStr[i]<='Z')) {\n cons_count++;\n }\n }\n Console.Write(\"\\nVowel in the string: {0}\\n\", vowel_count);\n Console.Write(\"Consonant in the string: {0}\\n\\n\", cons_count);\n }\n}"
},
{
"code": null,
"e": 2588,
"s": 2538,
"text": "Vowel in the string: 3\nConsonant in the string: 8"
}
] |
Difference between Backbone.js and Angular.js - GeeksforGeeks
|
09 Nov, 2020
AngularJS is considered to be more feature-packed and a more comprehensive arrangement to the client’s needs (Upwork, iStockPhoto, Climate, PayPal are built with Precise), in spite of the fact that any Spine JS designer will tell that Spine contains a parcel of valuable highlights as well. Angular has coordinates built-in utilities, which offer assistance to approve client input sometime recently it gets handled or sent to a server. Angular has devoted investigating tools. Angular checks for any changes and upgrades the comparing fields. Angular includes a prevalent plugin that incorporates offices to form see animations. Backbone permits to integrate third-party libraries well. Backbone employments observables for information official (it watches Models). Backbone features a plausibility to be expanded in arrange to back models and sees overhauling each other. Backbone might work well with other layout motors (more than one). They both back directing and profound connecting to associated with the browser URL. They have a steady open API. They can work with Offbeat Module Definition libraries. They have a devoted plugin source to appear in the framework’s living ecosystem. They both bolster bower reliance management; they have a venture generator, which lets the engineer naturally set up an unused venture whereas utilizing built-in tools.Angular.js AngularJS may be an exceptionally capable JavaScript System. It is utilized in Single Page Application (SPA) ventures. It amplifies HTML DOM with extra properties and makes it more responsive to client activities. AngularJS is an open-source, totally free, and utilized by thousands of designers around the world. It is authorized beneath the Apache permit adaptation 2.0. Angular is an open-source MVC JavaScript (programming dialect) system, which rearranges web improvement by advertising programmed view/model synchronization. In expansion to the two-way official, Precise is lightweight, bolsters all major browsers, and built for making testable JavaScript code. Angular was made by Miško Hevery (http://misko.hevery.com/). From the Angular website: is what HTML would have been on the off chance that it had been outlined for building web applications. It gives your application’s plumbing so you’ll focus on what your app does, instead of how to urge your web browser to do what you need.Example:
javascript
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf 8"> <title>Geeksforgeeks</title> <script src="https://code.angularjs.org/1.6.9/angular.js"> </script></head> <body ng-app="app"> <h1 ng-controller="HelloWorldCtrl"> {{message}} </h1> <script> angular.module("app", []).controller( "HelloWorldCtrl", function($scope) { $scope.message="GeeksforGeeks" } ) </script></body> </html>
Output:
GeeksforGeeks
Features of Angular.js:
REST Easy: Restful activities are rapidly getting to be the standard for communicating from the server to the client. In one line of JavaScript, you’ll be able to rapidly conversation to the server and get the data you wish to associate along with your web pages. AngularJS turns this into a basic JavaScript protest, as Models, taking after the MVVM (Show See View-Model) design.
MVVM to the Rescue: Models conversation to ViewModel objects (through something called the $scope protest), which tune in for changes to the Models. These can at that point be conveyed and rendered by the Sees, which is the HTML that communicates your code. Sees can be steered utilizing the $routeProvider protest, so you’ll deep-link and organize your Sees and Controllers, turning them into safe URLs. AngularJS moreover gives stateless controllers, which initialize and control the $scope protest.
Data Binding and Dependency Injection: Everything within the MVVM design is communicated consequently over the UI at whatever point anything changes. This disposes of the require for wrappers, getters/setters or course statements. AngularJS handles all of this, so you’ll express your information as essentially as with JavaScript primitives, like clusters, or as complex, as you would, like through custom sorts. Since everything happens consequently, you’ll inquire for your conditions as parameters in AngularJS benefit capacities, instead of one mammoth fundamental() call to execute your code.
Extends HTML: Most websites built nowadays are a monster arrangement of labels with small semantic clarity. You wish to form broad and exhaustive CSS classes to precise the deliberate of each question within the DOM. With Precise, you’ll be able to work your HTML like XML, giving you unending conceivable outcomes for labels and traits. Precise fulfills this, by means of its HTML compiler and the utilize of mandates to trigger behaviors based on the newly-created sentence structure you compose.
Backbone js: It could be a Javascript system based upon MVC which makes a difference you in composing secluded code for expansive applications. In their possess words, Backbone.js gives structure to web applications by giving Models with key-value official and custom occasions, Collections with a wealthy API of enumerable capacities, Sees with explanatory occasion taking care of, and interfaces it all to your existing API over a Serene JSON interface. When working on a web application that involves a part of JavaScript, one of the primary things you learn is to stop tying your information to the DOM. It’s all as well simple to make JavaScript applications that conclusion up as tangled heaps of jQuery selectors and callbacks, all attempting quickly to keep information in a matchup between the HTML UI, your JavaScript rationale, and the database on your server. For wealthy client-side applications, a more organized approach is frequently supportive. With Backbone, you speak to your information as Models, which can be made, approved, devastated, and spared to the server. At whatever point a UI activity causes a property of a show to alter, the show triggers a “alter” occasion; all the Sees that show the model’s state can be informed of the altering, so that they are able to reply appropriately, re-rendering themselves with the modern data. In a wrapped up Backbone app, you do not have to compose the stick code that looks into the DOM to discover a component with a particular id and overhaul the HTML physically — when the show changes, the sees essentially upgrade themselves. Philosophically, Backbone is an endeavor to find the negligible set of data-structuring (models and collections) and client interface (sees and URLs) primitives that are by and large valuable when building web applications with JavaScript. In an environment where overarching, decides-everything-for-you systems are commonplace, and numerous libraries require your location to be reorganized to suit to Backbone.js.Example:
javascript
<!DOCTYPE html><html> <head> <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"> </script> <script> $( function(){ ( function(){ var View = Backbone.View.extend( { "el": "body", "template": _.template( "<p>GeeksforGeeks</p>" ), "initialize": function(){ this.render(); }, "render": function(){ this.$el.html( this.template() ); } } ); new View(); })() } ); </script> </head> <body> </body></html>
Output:
GeeksforGeeks
Features of Backbone.js:
Event-driven communication: It’s simple to make little and smooth web applications with systems like jQuery. When a extend develops, in any case, the jQuery declarations and callbacks get increasingly complex and are distributed all over the put. The code gets to be increasingly cluttered and difficult to read. Backbone.js eases this by giving an event-driven communication between sees and models (and other components which we overlook for presently for the sake of effortlessness). You’ll be able to join occasion audience members to any property of a model, which gives you exceptionally nuanced control over what you alter within the see.
Syncing with a back-end: The models in Backbone.js can be effortlessly tied to a back-end. Out-of-the-box the system gives fabulous bolster for Tranquil APIs in that models can outline to a Relaxing endpoint. In case the API is planned accurately, spine is as of now arranged to get to these specifically for study, compose, and erase operations (through GET, POST, and Delete).
Maintainability by following conventions: Traditions are an extraordinary way to present a common coding fashion without the requirement of coming up with a broad set of coding measures. At Visual.ly we found backbone.js to be especially supportive to preserve a clean codebase in spite of having different individuals collaborating on the code. The mystery sauce here is sluggishness. The more you adhere to (the few) backbone conventions the less you’ve got to code, and in turn, the more standardized and clear the code gets to be.
ashushrma378
bunnyram19
AngularJS-Misc
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
Difference between var, let and const keywords in JavaScript
How to Open URL in New Tab using JavaScript ?
Set the value of an input field in JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24282,
"s": 24254,
"text": "\n09 Nov, 2020"
},
{
"code": null,
"e": 26661,
"s": 24282,
"text": "AngularJS is considered to be more feature-packed and a more comprehensive arrangement to the client’s needs (Upwork, iStockPhoto, Climate, PayPal are built with Precise), in spite of the fact that any Spine JS designer will tell that Spine contains a parcel of valuable highlights as well. Angular has coordinates built-in utilities, which offer assistance to approve client input sometime recently it gets handled or sent to a server. Angular has devoted investigating tools. Angular checks for any changes and upgrades the comparing fields. Angular includes a prevalent plugin that incorporates offices to form see animations. Backbone permits to integrate third-party libraries well. Backbone employments observables for information official (it watches Models). Backbone features a plausibility to be expanded in arrange to back models and sees overhauling each other. Backbone might work well with other layout motors (more than one). They both back directing and profound connecting to associated with the browser URL. They have a steady open API. They can work with Offbeat Module Definition libraries. They have a devoted plugin source to appear in the framework’s living ecosystem. They both bolster bower reliance management; they have a venture generator, which lets the engineer naturally set up an unused venture whereas utilizing built-in tools.Angular.js AngularJS may be an exceptionally capable JavaScript System. It is utilized in Single Page Application (SPA) ventures. It amplifies HTML DOM with extra properties and makes it more responsive to client activities. AngularJS is an open-source, totally free, and utilized by thousands of designers around the world. It is authorized beneath the Apache permit adaptation 2.0. Angular is an open-source MVC JavaScript (programming dialect) system, which rearranges web improvement by advertising programmed view/model synchronization. In expansion to the two-way official, Precise is lightweight, bolsters all major browsers, and built for making testable JavaScript code. Angular was made by Miško Hevery (http://misko.hevery.com/). From the Angular website: is what HTML would have been on the off chance that it had been outlined for building web applications. It gives your application’s plumbing so you’ll focus on what your app does, instead of how to urge your web browser to do what you need.Example: "
},
{
"code": null,
"e": 26672,
"s": 26661,
"text": "javascript"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf 8\"> <title>Geeksforgeeks</title> <script src=\"https://code.angularjs.org/1.6.9/angular.js\"> </script></head> <body ng-app=\"app\"> <h1 ng-controller=\"HelloWorldCtrl\"> {{message}} </h1> <script> angular.module(\"app\", []).controller( \"HelloWorldCtrl\", function($scope) { $scope.message=\"GeeksforGeeks\" } ) </script></body> </html>",
"e": 27149,
"s": 26672,
"text": null
},
{
"code": null,
"e": 27159,
"s": 27149,
"text": "Output: "
},
{
"code": null,
"e": 27174,
"s": 27159,
"text": "GeeksforGeeks\n"
},
{
"code": null,
"e": 27200,
"s": 27174,
"text": "Features of Angular.js: "
},
{
"code": null,
"e": 27582,
"s": 27200,
"text": "REST Easy: Restful activities are rapidly getting to be the standard for communicating from the server to the client. In one line of JavaScript, you’ll be able to rapidly conversation to the server and get the data you wish to associate along with your web pages. AngularJS turns this into a basic JavaScript protest, as Models, taking after the MVVM (Show See View-Model) design. "
},
{
"code": null,
"e": 28084,
"s": 27582,
"text": "MVVM to the Rescue: Models conversation to ViewModel objects (through something called the $scope protest), which tune in for changes to the Models. These can at that point be conveyed and rendered by the Sees, which is the HTML that communicates your code. Sees can be steered utilizing the $routeProvider protest, so you’ll deep-link and organize your Sees and Controllers, turning them into safe URLs. AngularJS moreover gives stateless controllers, which initialize and control the $scope protest."
},
{
"code": null,
"e": 28683,
"s": 28084,
"text": "Data Binding and Dependency Injection: Everything within the MVVM design is communicated consequently over the UI at whatever point anything changes. This disposes of the require for wrappers, getters/setters or course statements. AngularJS handles all of this, so you’ll express your information as essentially as with JavaScript primitives, like clusters, or as complex, as you would, like through custom sorts. Since everything happens consequently, you’ll inquire for your conditions as parameters in AngularJS benefit capacities, instead of one mammoth fundamental() call to execute your code."
},
{
"code": null,
"e": 29182,
"s": 28683,
"text": "Extends HTML: Most websites built nowadays are a monster arrangement of labels with small semantic clarity. You wish to form broad and exhaustive CSS classes to precise the deliberate of each question within the DOM. With Precise, you’ll be able to work your HTML like XML, giving you unending conceivable outcomes for labels and traits. Precise fulfills this, by means of its HTML compiler and the utilize of mandates to trigger behaviors based on the newly-created sentence structure you compose."
},
{
"code": null,
"e": 31207,
"s": 29182,
"text": "Backbone js: It could be a Javascript system based upon MVC which makes a difference you in composing secluded code for expansive applications. In their possess words, Backbone.js gives structure to web applications by giving Models with key-value official and custom occasions, Collections with a wealthy API of enumerable capacities, Sees with explanatory occasion taking care of, and interfaces it all to your existing API over a Serene JSON interface. When working on a web application that involves a part of JavaScript, one of the primary things you learn is to stop tying your information to the DOM. It’s all as well simple to make JavaScript applications that conclusion up as tangled heaps of jQuery selectors and callbacks, all attempting quickly to keep information in a matchup between the HTML UI, your JavaScript rationale, and the database on your server. For wealthy client-side applications, a more organized approach is frequently supportive. With Backbone, you speak to your information as Models, which can be made, approved, devastated, and spared to the server. At whatever point a UI activity causes a property of a show to alter, the show triggers a “alter” occasion; all the Sees that show the model’s state can be informed of the altering, so that they are able to reply appropriately, re-rendering themselves with the modern data. In a wrapped up Backbone app, you do not have to compose the stick code that looks into the DOM to discover a component with a particular id and overhaul the HTML physically — when the show changes, the sees essentially upgrade themselves. Philosophically, Backbone is an endeavor to find the negligible set of data-structuring (models and collections) and client interface (sees and URLs) primitives that are by and large valuable when building web applications with JavaScript. In an environment where overarching, decides-everything-for-you systems are commonplace, and numerous libraries require your location to be reorganized to suit to Backbone.js.Example: "
},
{
"code": null,
"e": 31218,
"s": 31207,
"text": "javascript"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://code.jquery.com/jquery-3.1.0.min.js\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js\"> </script> <script> $( function(){ ( function(){ var View = Backbone.View.extend( { \"el\": \"body\", \"template\": _.template( \"<p>GeeksforGeeks</p>\" ), \"initialize\": function(){ this.render(); }, \"render\": function(){ this.$el.html( this.template() ); } } ); new View(); })() } ); </script> </head> <body> </body></html>",
"e": 32202,
"s": 31218,
"text": null
},
{
"code": null,
"e": 32212,
"s": 32202,
"text": "Output: "
},
{
"code": null,
"e": 32227,
"s": 32212,
"text": "GeeksforGeeks\n"
},
{
"code": null,
"e": 32254,
"s": 32227,
"text": "Features of Backbone.js: "
},
{
"code": null,
"e": 32900,
"s": 32254,
"text": "Event-driven communication: It’s simple to make little and smooth web applications with systems like jQuery. When a extend develops, in any case, the jQuery declarations and callbacks get increasingly complex and are distributed all over the put. The code gets to be increasingly cluttered and difficult to read. Backbone.js eases this by giving an event-driven communication between sees and models (and other components which we overlook for presently for the sake of effortlessness). You’ll be able to join occasion audience members to any property of a model, which gives you exceptionally nuanced control over what you alter within the see."
},
{
"code": null,
"e": 33279,
"s": 32900,
"text": "Syncing with a back-end: The models in Backbone.js can be effortlessly tied to a back-end. Out-of-the-box the system gives fabulous bolster for Tranquil APIs in that models can outline to a Relaxing endpoint. In case the API is planned accurately, spine is as of now arranged to get to these specifically for study, compose, and erase operations (through GET, POST, and Delete)."
},
{
"code": null,
"e": 33814,
"s": 33279,
"text": "Maintainability by following conventions: Traditions are an extraordinary way to present a common coding fashion without the requirement of coming up with a broad set of coding measures. At Visual.ly we found backbone.js to be especially supportive to preserve a clean codebase in spite of having different individuals collaborating on the code. The mystery sauce here is sluggishness. The more you adhere to (the few) backbone conventions the less you’ve got to code, and in turn, the more standardized and clear the code gets to be."
},
{
"code": null,
"e": 33831,
"s": 33818,
"text": "ashushrma378"
},
{
"code": null,
"e": 33842,
"s": 33831,
"text": "bunnyram19"
},
{
"code": null,
"e": 33857,
"s": 33842,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 33873,
"s": 33857,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 33884,
"s": 33873,
"text": "JavaScript"
},
{
"code": null,
"e": 33901,
"s": 33884,
"text": "Web Technologies"
},
{
"code": null,
"e": 33999,
"s": 33901,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34008,
"s": 33999,
"text": "Comments"
},
{
"code": null,
"e": 34021,
"s": 34008,
"text": "Old Comments"
},
{
"code": null,
"e": 34066,
"s": 34021,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 34138,
"s": 34066,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 34199,
"s": 34138,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 34245,
"s": 34199,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 34291,
"s": 34245,
"text": "Set the value of an input field in JavaScript"
},
{
"code": null,
"e": 34333,
"s": 34291,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 34366,
"s": 34333,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 34428,
"s": 34366,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 34471,
"s": 34428,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to Set a Single Main Title for All the Subplots in Matplotlib? - GeeksforGeeks
|
03 Jan, 2021
Prerequisites: Matplotlib
A title in matplotlib library describes the main subject of plotting the graphs. Setting a title for just one plot is easy using the title() method. By using this function only the individual title plots can be set but not a single title for all subplots. Hence, to set a single main title for all subplots, suptitle() method is used.
Syntax: suptitle(self, t, **kwargs)
Parameters: This method accept the following parameters that are discussed below:
t : This parameter is the title text.
x: This parameter is the x location of the text in figure coordinates.
y: This parameter is the y location of the text in figure coordinates.
horizontalalignment, ha : This parameter is the horizontal alignment of the text relative to (x, y).
verticalalignment, va : This parameter is the vertical alignment of the text relative to (x, y).
fontsize, size : This parameter is the font size of the text.
fontweight, weight : This parameter is the font weight of the text.
Returns: This method returns the Text instance of the title.
Import module
Create data to be plotted
Set figure title using suptitle()
Plot the graph
Display plot
Implementation using approach given is given below:
Example 1:
Python3
import matplotlib.pyplot as pltimport numpy as np fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5)) x1 = [1, 2, 3, 4, 5, 6]y1 = [45, 34, 30, 45, 50, 38]y2 = [36, 28, 30, 40, 38, 48] labels = ["student 1", "student 2"] fig.suptitle(' Student marks in different subjects ', fontsize=30) # Creating the sub-plots.l1 = ax1.plot(x1, y1, 'o-', color='g')l2 = ax2.plot(x1, y2, 'o-') fig.legend([l1, l2], labels=labels, loc="upper right")plt.subplots_adjust(right=0.9) plt.show()
Output:
Example 2:
Python3
import matplotlib.pyplot as pltimport numpy as np fig, ax = plt.subplots(2, 2)fig.suptitle('** Main Title for all sub plots **', fontsize=20)plt.style.use('seaborn') labels = ['first line', 'second line', 'third line', 'fourth line', 'fifth line'] ax[0, 0].plot([1, 2, 3, 4, 5], [9, 3, 5, 7, 9], '-.', color='g')ax[0, 0].set_title('first subplot')ax[0, 0].set_yticks(np.arange(1, 10)) ax[0, 1].plot([1, 2, 3, 4, 5, 6], [1, 4, 9, 7, 9, 8], '-*', color='m')ax[0, 1].set_title('second subplot')ax[0, 1].set_yticks(np.arange(1, 10)) ax[1, 0].plot([1, 2, 3, 4, 5], [8, 5, 2, 3, 3], '-v', color='r')ax[1, 0].set_title('third subplot')ax[1, 0].set_yticks(np.arange(1, 9)) ax[1, 1].plot([1, 2, 3, 4, 5, 6], [1, 3, 5, 7, 9, 6], 'o-', color='b')ax[1, 1].plot([1, 2, 3, 4, 5, 6, 7, 7], [ 7, 8, 6, 5, 2, 2, 4, 6], 'o-', color='g')ax[1, 1].set_title('fourth subplot')ax[1, 1].set_yticks(np.arange(1, 10)) fig.tight_layout()fig.legend(ax, labels=labels, loc="upper right", borderaxespad=0.1)fig.subplots_adjust(top=0.85) plt.show()
Output:
Picked
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 29937,
"s": 29909,
"text": "\n03 Jan, 2021"
},
{
"code": null,
"e": 29963,
"s": 29937,
"text": "Prerequisites: Matplotlib"
},
{
"code": null,
"e": 30298,
"s": 29963,
"text": "A title in matplotlib library describes the main subject of plotting the graphs. Setting a title for just one plot is easy using the title() method. By using this function only the individual title plots can be set but not a single title for all subplots. Hence, to set a single main title for all subplots, suptitle() method is used."
},
{
"code": null,
"e": 30334,
"s": 30298,
"text": "Syntax: suptitle(self, t, **kwargs)"
},
{
"code": null,
"e": 30416,
"s": 30334,
"text": "Parameters: This method accept the following parameters that are discussed below:"
},
{
"code": null,
"e": 30454,
"s": 30416,
"text": "t : This parameter is the title text."
},
{
"code": null,
"e": 30525,
"s": 30454,
"text": "x: This parameter is the x location of the text in figure coordinates."
},
{
"code": null,
"e": 30596,
"s": 30525,
"text": "y: This parameter is the y location of the text in figure coordinates."
},
{
"code": null,
"e": 30697,
"s": 30596,
"text": "horizontalalignment, ha : This parameter is the horizontal alignment of the text relative to (x, y)."
},
{
"code": null,
"e": 30794,
"s": 30697,
"text": "verticalalignment, va : This parameter is the vertical alignment of the text relative to (x, y)."
},
{
"code": null,
"e": 30856,
"s": 30794,
"text": "fontsize, size : This parameter is the font size of the text."
},
{
"code": null,
"e": 30924,
"s": 30856,
"text": "fontweight, weight : This parameter is the font weight of the text."
},
{
"code": null,
"e": 30985,
"s": 30924,
"text": "Returns: This method returns the Text instance of the title."
},
{
"code": null,
"e": 30999,
"s": 30985,
"text": "Import module"
},
{
"code": null,
"e": 31025,
"s": 30999,
"text": "Create data to be plotted"
},
{
"code": null,
"e": 31059,
"s": 31025,
"text": "Set figure title using suptitle()"
},
{
"code": null,
"e": 31074,
"s": 31059,
"text": "Plot the graph"
},
{
"code": null,
"e": 31087,
"s": 31074,
"text": "Display plot"
},
{
"code": null,
"e": 31139,
"s": 31087,
"text": "Implementation using approach given is given below:"
},
{
"code": null,
"e": 31150,
"s": 31139,
"text": "Example 1:"
},
{
"code": null,
"e": 31158,
"s": 31150,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as np fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5)) x1 = [1, 2, 3, 4, 5, 6]y1 = [45, 34, 30, 45, 50, 38]y2 = [36, 28, 30, 40, 38, 48] labels = [\"student 1\", \"student 2\"] fig.suptitle(' Student marks in different subjects ', fontsize=30) # Creating the sub-plots.l1 = ax1.plot(x1, y1, 'o-', color='g')l2 = ax2.plot(x1, y2, 'o-') fig.legend([l1, l2], labels=labels, loc=\"upper right\")plt.subplots_adjust(right=0.9) plt.show()",
"e": 31651,
"s": 31158,
"text": null
},
{
"code": null,
"e": 31659,
"s": 31651,
"text": "Output:"
},
{
"code": null,
"e": 31671,
"s": 31659,
"text": "Example 2: "
},
{
"code": null,
"e": 31679,
"s": 31671,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as np fig, ax = plt.subplots(2, 2)fig.suptitle('** Main Title for all sub plots **', fontsize=20)plt.style.use('seaborn') labels = ['first line', 'second line', 'third line', 'fourth line', 'fifth line'] ax[0, 0].plot([1, 2, 3, 4, 5], [9, 3, 5, 7, 9], '-.', color='g')ax[0, 0].set_title('first subplot')ax[0, 0].set_yticks(np.arange(1, 10)) ax[0, 1].plot([1, 2, 3, 4, 5, 6], [1, 4, 9, 7, 9, 8], '-*', color='m')ax[0, 1].set_title('second subplot')ax[0, 1].set_yticks(np.arange(1, 10)) ax[1, 0].plot([1, 2, 3, 4, 5], [8, 5, 2, 3, 3], '-v', color='r')ax[1, 0].set_title('third subplot')ax[1, 0].set_yticks(np.arange(1, 9)) ax[1, 1].plot([1, 2, 3, 4, 5, 6], [1, 3, 5, 7, 9, 6], 'o-', color='b')ax[1, 1].plot([1, 2, 3, 4, 5, 6, 7, 7], [ 7, 8, 6, 5, 2, 2, 4, 6], 'o-', color='g')ax[1, 1].set_title('fourth subplot')ax[1, 1].set_yticks(np.arange(1, 10)) fig.tight_layout()fig.legend(ax, labels=labels, loc=\"upper right\", borderaxespad=0.1)fig.subplots_adjust(top=0.85) plt.show()",
"e": 32727,
"s": 31679,
"text": null
},
{
"code": null,
"e": 32735,
"s": 32727,
"text": "Output:"
},
{
"code": null,
"e": 32742,
"s": 32735,
"text": "Picked"
},
{
"code": null,
"e": 32760,
"s": 32742,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 32784,
"s": 32760,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 32791,
"s": 32784,
"text": "Python"
},
{
"code": null,
"e": 32810,
"s": 32791,
"text": "Technical Scripter"
},
{
"code": null,
"e": 32908,
"s": 32810,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32917,
"s": 32908,
"text": "Comments"
},
{
"code": null,
"e": 32930,
"s": 32917,
"text": "Old Comments"
},
{
"code": null,
"e": 32958,
"s": 32930,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 33008,
"s": 32958,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 33030,
"s": 33008,
"text": "Python map() function"
},
{
"code": null,
"e": 33074,
"s": 33030,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 33092,
"s": 33074,
"text": "Python Dictionary"
},
{
"code": null,
"e": 33115,
"s": 33092,
"text": "Taking input in Python"
},
{
"code": null,
"e": 33150,
"s": 33115,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 33172,
"s": 33150,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 33204,
"s": 33172,
"text": "How to Install PIP on Windows ?"
}
] |
Double.CompareTo Method in C# with Examples - GeeksforGeeks
|
19 Mar, 2019
Double.CompareTo Method is used to compare the current instance to a specified object or Double object. It will return an integer which shows whether the value of the current instance is greater than, less than or equal to the value of the specified object or Double object. There are 2 methods in the overload list of this method as follows:
CompareTo(Double) Method
CompareTo(Object) Method
Double.CompareTo() Method is used to compare the current instance to a specified double-precision floating-point number and returns an integer which shows whether the value of this instance is less than, equal to, or greater than the value of the specified double-precision floating-point number.
Syntax:
public int CompareTo (double value);
Here, it takes a double-precision floating-point number to compare.
Return Value: This method returns a signed number indicating the relative values of this instance and value.
Less than zero: This instance is less than value or this instance is not a number (NaN) and value is a number.
Zero: This instance is equal to value or both this instance and value are not a number (NaN), PositiveInfinity, or NegativeInfinity.
Greater than zero: This instance is greater than value or this instance is a number and value is not a number (NaN).
Below programs illustrate the use of Double.CompareTo(Double) Method:
Example 1:
// C# program to demonstrate the// Double.CompareTo(Double)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing value1 double value1 = 10d; // Declaring and initializing value2 double value2 = 20d; // compare both double value // using CompareTo() method int status = value1.CompareTo(value2); // checking the status if (status > 0) Console.WriteLine("{0} is greater than {1}", value1, value2); else if (status < 0) Console.WriteLine("{0} is less than {1}", value1, value2); else Console.WriteLine("{0} is equal to {1}", value1, value2); }}
10 is less than 20
Example 2:
// C# program to demonstrate the// Double.CompareTo(Double)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling get() method get(5d, 7d); get(5.5d, 4.5d); get(10d, 20d); get(7.5d, 19.5d); } // defining get() method public static void get(double value1, double value2) { // compare both double value // using CompareTo() method int status = value1.CompareTo(value2); // checking the status if (status > 0) Console.WriteLine("{0} is greater than {1}", value1, value2); else if (status < 0) Console.WriteLine("{0} is less than {1}", value1, value2); else Console.WriteLine("{0} is equal to {1}", value1, value2); }}
5 is less than 7
5.5 is greater than 4.5
10 is less than 20
7.5 is less than 19.5
Double.CompareTo() Method is used to compare the current instance to a specified object and returns an integer which indicates whether the value of the current instance is less than, equal to, or greater than the value of the specified object.
Syntax:
public int CompareTo (object value);
Here, it takes an object to compare, or null.
Return Value: This method returns a signed number indicating the relative values of this instance and value.
Less than zero: This instance is less than value or this instance is not a number (NaN) and value is a number.
Zero: This instance is equal to value or both this instance and value are not a number (NaN), PositiveInfinity, or NegativeInfinity.
Greater than zero: This instance is greater than value or this instance is a number and value is not a number (NaN).
Exception: It throws ArgumentException if value is not a Double.
Below programs illustrate the use of Double.CompareTo(Object) Method:
Example 1:
// C# program to demonstrate the// Double.CompareTo(object)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // Declaring and initializing value1 double value1 = 10d; // Declaring and initializing value2 object value2 = 20d; // compare both double value // using CompareTo() method int status = value1.CompareTo(value2); // checking the status if (status > 0) Console.WriteLine("{0} is greater than {1}", value1, value2); else if (status < 0) Console.WriteLine("{0} is less than {1}", value1, value2); else Console.WriteLine("{0} is equal to {1}", value1, value2); } catch (ArgumentException e) { Console.WriteLine("value2 must be double"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
10 is less than 20
Example 2: For ArgumentException
// C# program to demonstrate the// Double.CompareTo(object)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // Declaring and initializing value1 double value1 = 10d; // Declaring and initializing value2 object value2 = 1 / 3; // compare both double value // using CompareTo() method int status = value1.CompareTo(value2); // checking the status if (status > 0) Console.WriteLine("{0} is greater than {1}", value1, value2); else if (status < 0) Console.WriteLine("{0} is less than {1}", value1, value2); else Console.WriteLine("{0} is equal to {1}", value1, value2); } catch (ArgumentException e) { Console.WriteLine("value2 must be double"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
value2 must be double
Exception Thrown: System.ArgumentException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.double.compareto?view=netframework-4.7.2
CSharp-Double-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Class and Object
Lambda Expressions in C#
HashSet in C# with Examples
C# | How to use strings in switch statement
C# | Replace() Method
C# | String.Contains() Method
Collections in C#
C# | Abstract Classes
C# | Data Types
Introduction to .NET Framework
|
[
{
"code": null,
"e": 24119,
"s": 24091,
"text": "\n19 Mar, 2019"
},
{
"code": null,
"e": 24462,
"s": 24119,
"text": "Double.CompareTo Method is used to compare the current instance to a specified object or Double object. It will return an integer which shows whether the value of the current instance is greater than, less than or equal to the value of the specified object or Double object. There are 2 methods in the overload list of this method as follows:"
},
{
"code": null,
"e": 24487,
"s": 24462,
"text": "CompareTo(Double) Method"
},
{
"code": null,
"e": 24512,
"s": 24487,
"text": "CompareTo(Object) Method"
},
{
"code": null,
"e": 24809,
"s": 24512,
"text": "Double.CompareTo() Method is used to compare the current instance to a specified double-precision floating-point number and returns an integer which shows whether the value of this instance is less than, equal to, or greater than the value of the specified double-precision floating-point number."
},
{
"code": null,
"e": 24817,
"s": 24809,
"text": "Syntax:"
},
{
"code": null,
"e": 24854,
"s": 24817,
"text": "public int CompareTo (double value);"
},
{
"code": null,
"e": 24922,
"s": 24854,
"text": "Here, it takes a double-precision floating-point number to compare."
},
{
"code": null,
"e": 25031,
"s": 24922,
"text": "Return Value: This method returns a signed number indicating the relative values of this instance and value."
},
{
"code": null,
"e": 25142,
"s": 25031,
"text": "Less than zero: This instance is less than value or this instance is not a number (NaN) and value is a number."
},
{
"code": null,
"e": 25275,
"s": 25142,
"text": "Zero: This instance is equal to value or both this instance and value are not a number (NaN), PositiveInfinity, or NegativeInfinity."
},
{
"code": null,
"e": 25392,
"s": 25275,
"text": "Greater than zero: This instance is greater than value or this instance is a number and value is not a number (NaN)."
},
{
"code": null,
"e": 25462,
"s": 25392,
"text": "Below programs illustrate the use of Double.CompareTo(Double) Method:"
},
{
"code": null,
"e": 25473,
"s": 25462,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Double.CompareTo(Double)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing value1 double value1 = 10d; // Declaring and initializing value2 double value2 = 20d; // compare both double value // using CompareTo() method int status = value1.CompareTo(value2); // checking the status if (status > 0) Console.WriteLine(\"{0} is greater than {1}\", value1, value2); else if (status < 0) Console.WriteLine(\"{0} is less than {1}\", value1, value2); else Console.WriteLine(\"{0} is equal to {1}\", value1, value2); }}",
"e": 26336,
"s": 25473,
"text": null
},
{
"code": null,
"e": 26356,
"s": 26336,
"text": "10 is less than 20\n"
},
{
"code": null,
"e": 26367,
"s": 26356,
"text": "Example 2:"
},
{
"code": "// C# program to demonstrate the// Double.CompareTo(Double)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling get() method get(5d, 7d); get(5.5d, 4.5d); get(10d, 20d); get(7.5d, 19.5d); } // defining get() method public static void get(double value1, double value2) { // compare both double value // using CompareTo() method int status = value1.CompareTo(value2); // checking the status if (status > 0) Console.WriteLine(\"{0} is greater than {1}\", value1, value2); else if (status < 0) Console.WriteLine(\"{0} is less than {1}\", value1, value2); else Console.WriteLine(\"{0} is equal to {1}\", value1, value2); }}",
"e": 27329,
"s": 26367,
"text": null
},
{
"code": null,
"e": 27412,
"s": 27329,
"text": "5 is less than 7\n5.5 is greater than 4.5\n10 is less than 20\n7.5 is less than 19.5\n"
},
{
"code": null,
"e": 27656,
"s": 27412,
"text": "Double.CompareTo() Method is used to compare the current instance to a specified object and returns an integer which indicates whether the value of the current instance is less than, equal to, or greater than the value of the specified object."
},
{
"code": null,
"e": 27664,
"s": 27656,
"text": "Syntax:"
},
{
"code": null,
"e": 27701,
"s": 27664,
"text": "public int CompareTo (object value);"
},
{
"code": null,
"e": 27747,
"s": 27701,
"text": "Here, it takes an object to compare, or null."
},
{
"code": null,
"e": 27856,
"s": 27747,
"text": "Return Value: This method returns a signed number indicating the relative values of this instance and value."
},
{
"code": null,
"e": 27967,
"s": 27856,
"text": "Less than zero: This instance is less than value or this instance is not a number (NaN) and value is a number."
},
{
"code": null,
"e": 28100,
"s": 27967,
"text": "Zero: This instance is equal to value or both this instance and value are not a number (NaN), PositiveInfinity, or NegativeInfinity."
},
{
"code": null,
"e": 28217,
"s": 28100,
"text": "Greater than zero: This instance is greater than value or this instance is a number and value is not a number (NaN)."
},
{
"code": null,
"e": 28282,
"s": 28217,
"text": "Exception: It throws ArgumentException if value is not a Double."
},
{
"code": null,
"e": 28352,
"s": 28282,
"text": "Below programs illustrate the use of Double.CompareTo(Object) Method:"
},
{
"code": null,
"e": 28363,
"s": 28352,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Double.CompareTo(object)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // Declaring and initializing value1 double value1 = 10d; // Declaring and initializing value2 object value2 = 20d; // compare both double value // using CompareTo() method int status = value1.CompareTo(value2); // checking the status if (status > 0) Console.WriteLine(\"{0} is greater than {1}\", value1, value2); else if (status < 0) Console.WriteLine(\"{0} is less than {1}\", value1, value2); else Console.WriteLine(\"{0} is equal to {1}\", value1, value2); } catch (ArgumentException e) { Console.WriteLine(\"value2 must be double\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 29535,
"s": 28363,
"text": null
},
{
"code": null,
"e": 29555,
"s": 29535,
"text": "10 is less than 20\n"
},
{
"code": null,
"e": 29588,
"s": 29555,
"text": "Example 2: For ArgumentException"
},
{
"code": "// C# program to demonstrate the// Double.CompareTo(object)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // Declaring and initializing value1 double value1 = 10d; // Declaring and initializing value2 object value2 = 1 / 3; // compare both double value // using CompareTo() method int status = value1.CompareTo(value2); // checking the status if (status > 0) Console.WriteLine(\"{0} is greater than {1}\", value1, value2); else if (status < 0) Console.WriteLine(\"{0} is less than {1}\", value1, value2); else Console.WriteLine(\"{0} is equal to {1}\", value1, value2); } catch (ArgumentException e) { Console.WriteLine(\"value2 must be double\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 30764,
"s": 29588,
"text": null
},
{
"code": null,
"e": 30830,
"s": 30764,
"text": "value2 must be double\nException Thrown: System.ArgumentException\n"
},
{
"code": null,
"e": 30841,
"s": 30830,
"text": "Reference:"
},
{
"code": null,
"e": 30933,
"s": 30841,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.double.compareto?view=netframework-4.7.2"
},
{
"code": null,
"e": 30954,
"s": 30933,
"text": "CSharp-Double-Struct"
},
{
"code": null,
"e": 30968,
"s": 30954,
"text": "CSharp-method"
},
{
"code": null,
"e": 30971,
"s": 30968,
"text": "C#"
},
{
"code": null,
"e": 31069,
"s": 30971,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31078,
"s": 31069,
"text": "Comments"
},
{
"code": null,
"e": 31091,
"s": 31078,
"text": "Old Comments"
},
{
"code": null,
"e": 31113,
"s": 31091,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 31138,
"s": 31113,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 31166,
"s": 31138,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 31210,
"s": 31166,
"text": "C# | How to use strings in switch statement"
},
{
"code": null,
"e": 31232,
"s": 31210,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 31262,
"s": 31232,
"text": "C# | String.Contains() Method"
},
{
"code": null,
"e": 31280,
"s": 31262,
"text": "Collections in C#"
},
{
"code": null,
"e": 31302,
"s": 31280,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 31318,
"s": 31302,
"text": "C# | Data Types"
}
] |
How to find the largest number contained in a JavaScript array?
|
To get the largest number in the array, you can try to run the following code. It returns the largest number 530 −
Live Demo
<!DOCTYPE html>
<html>
<body>
<script>
var myArr = [340, 25, 530, 299];
var max = myArr.reduce(function(a,b){
return (a > b) ? a : b;
});
document.write("Largest number in the array: "+max);
</script>
</body>
</html>
Largest number in the array: 530
|
[
{
"code": null,
"e": 1177,
"s": 1062,
"text": "To get the largest number in the array, you can try to run the following code. It returns the largest number 530 −"
},
{
"code": null,
"e": 1187,
"s": 1177,
"text": "Live Demo"
},
{
"code": null,
"e": 1470,
"s": 1187,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n var myArr = [340, 25, 530, 299];\n var max = myArr.reduce(function(a,b){\n return (a > b) ? a : b;\n });\n document.write(\"Largest number in the array: \"+max);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 1503,
"s": 1470,
"text": "Largest number in the array: 530"
}
] |
How to set the Visibility of the TextBox in C#? - GeeksforGeeks
|
29 Nov, 2019
In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set a value which shows the TextBox control and its all child TextBox controls are displayed and it is achieved by using the Visible property of the TextBox. If you want to display the given TextBox and its child controls, then set the value of Visible property to true, otherwise set false. The default value of this property is true. In Windows form, you can set this property in two different ways:
1. Design-Time: It is the simplest way to set the Visible property of the TextBox as shown in the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the TextBox control from the ToolBox and drop it on the windows form. You can place TextBox anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the TextBox control to set the Visible property of the TextBox.Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Visible property of the TextBox programmatically with the help of given syntax:
public bool Visible { get; set; }
Here, the value of this property is of System.Boolean type. Following steps are used to set the Visible property of the TextBox:
Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox
TextBox Mytextbox = new TextBox();
// Creating textbox
TextBox Mytextbox = new TextBox();
Step 2 : After creating TextBox, set the Visible property of the TextBox provided by the TextBox class.// Set Visible property
Mytextbox.Visible = true;
// Set Visible property
Mytextbox.Visible = true;
Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form
this.Controls.Add(Mytextbox);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = "Enter Name"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.AutoSize = true; Mytextbox.Name = "text_box1"; Mytextbox.Visible = true; // Add this textbox to form this.Controls.Add(Mytextbox); }}}Output:
// Add this textbox to form
this.Controls.Add(Mytextbox);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = "Enter Name"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.AutoSize = true; Mytextbox.Name = "text_box1"; Mytextbox.Visible = true; // Add this textbox to form this.Controls.Add(Mytextbox); }}}
Output:
CSharp-Windows-Forms-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Partial Classes in C#
Extension Method in C#
Top 50 C# Interview Questions & Answers
HashSet in C# with Examples
C# | Inheritance
Lambda Expressions in C#
C# | .NET Framework (Basic Architecture and Component Stack)
Top 50 ASP.NET Interview Questions and Answers
Hello World in C#
C# | List Class
|
[
{
"code": null,
"e": 23911,
"s": 23883,
"text": "\n29 Nov, 2019"
},
{
"code": null,
"e": 24514,
"s": 23911,
"text": "In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set a value which shows the TextBox control and its all child TextBox controls are displayed and it is achieved by using the Visible property of the TextBox. If you want to display the given TextBox and its child controls, then set the value of Visible property to true, otherwise set false. The default value of this property is true. In Windows form, you can set this property in two different ways:"
},
{
"code": null,
"e": 24629,
"s": 24514,
"text": "1. Design-Time: It is the simplest way to set the Visible property of the TextBox as shown in the following steps:"
},
{
"code": null,
"e": 24745,
"s": 24629,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 24903,
"s": 24745,
"text": "Step 2: Drag the TextBox control from the ToolBox and drop it on the windows form. You can place TextBox anywhere on the windows form according to your need."
},
{
"code": null,
"e": 25035,
"s": 24903,
"text": "Step 3: After drag and drop you will go to the properties of the TextBox control to set the Visible property of the TextBox.Output:"
},
{
"code": null,
"e": 25043,
"s": 25035,
"text": "Output:"
},
{
"code": null,
"e": 25219,
"s": 25043,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Visible property of the TextBox programmatically with the help of given syntax:"
},
{
"code": null,
"e": 25253,
"s": 25219,
"text": "public bool Visible { get; set; }"
},
{
"code": null,
"e": 25382,
"s": 25253,
"text": "Here, the value of this property is of System.Boolean type. Following steps are used to set the Visible property of the TextBox:"
},
{
"code": null,
"e": 25526,
"s": 25382,
"text": "Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox\nTextBox Mytextbox = new TextBox();\n"
},
{
"code": null,
"e": 25582,
"s": 25526,
"text": "// Creating textbox\nTextBox Mytextbox = new TextBox();\n"
},
{
"code": null,
"e": 25736,
"s": 25582,
"text": "Step 2 : After creating TextBox, set the Visible property of the TextBox provided by the TextBox class.// Set Visible property\nMytextbox.Visible = true;\n"
},
{
"code": null,
"e": 25787,
"s": 25736,
"text": "// Set Visible property\nMytextbox.Visible = true;\n"
},
{
"code": null,
"e": 27070,
"s": 25787,
"text": "Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form\nthis.Controls.Add(Mytextbox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = \"Enter Name\"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.AutoSize = true; Mytextbox.Name = \"text_box1\"; Mytextbox.Visible = true; // Add this textbox to form this.Controls.Add(Mytextbox); }}}Output:"
},
{
"code": null,
"e": 27129,
"s": 27070,
"text": "// Add this textbox to form\nthis.Controls.Add(Mytextbox);\n"
},
{
"code": null,
"e": 27138,
"s": 27129,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = \"Enter Name\"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.ForeColor = Color.DarkOliveGreen; Mytextbox.AutoSize = true; Mytextbox.Name = \"text_box1\"; Mytextbox.Visible = true; // Add this textbox to form this.Controls.Add(Mytextbox); }}}",
"e": 28278,
"s": 27138,
"text": null
},
{
"code": null,
"e": 28286,
"s": 28278,
"text": "Output:"
},
{
"code": null,
"e": 28317,
"s": 28286,
"text": "CSharp-Windows-Forms-Namespace"
},
{
"code": null,
"e": 28320,
"s": 28317,
"text": "C#"
},
{
"code": null,
"e": 28418,
"s": 28320,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28427,
"s": 28418,
"text": "Comments"
},
{
"code": null,
"e": 28440,
"s": 28427,
"text": "Old Comments"
},
{
"code": null,
"e": 28462,
"s": 28440,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28485,
"s": 28462,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28525,
"s": 28485,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28553,
"s": 28525,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28570,
"s": 28553,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28595,
"s": 28570,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 28656,
"s": 28595,
"text": "C# | .NET Framework (Basic Architecture and Component Stack)"
},
{
"code": null,
"e": 28703,
"s": 28656,
"text": "Top 50 ASP.NET Interview Questions and Answers"
},
{
"code": null,
"e": 28721,
"s": 28703,
"text": "Hello World in C#"
}
] |
Matplotlib.pyplot.fill_betweenx() in Python - GeeksforGeeks
|
06 Oct, 2021
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.pyplot.fill_betweenx() is used to fill area between two vertical curves. Two points (x1, y) and (x2, y) define the curves. this creates one or more polygons describing the filled areas. The ‘where’ parameter can be used to selectively fill some areas. By default, edges connect the given points directly. The ‘step’ parameter is used, if the filling needs to be a step function.
Syntax: matplotlib.pyplot.fill_betweenx(y, x1, x2=0, where=None, step=None, interpolate=False, *, data=None, **kwargs)Parameters:
y: It is array of length N. These are the y coordinates of the nodes that define the curves.
x1:It is an array of length N or a scalar. This represents the x coordinates of the nodes that define the first curve.
x2: It is an array of length N and is optional in nature. Its default value is 0. This represents the x coordinates of the nodes that define the second curve.
where: it is an array of boolean values of length N. It is defined if there is a need to exclude some vertical regions from being filled. It is important to note that this definition means that an isolated true value in between two two false values is where it will not do the filling. Adjacent False values results in not filling both sides of the True value.
interpolate: It is an optional parameter that accepts boolean values. It is only relevant if where is used and two curves are crossing each other. Semantically where if generally used for x1>x2 or similar cases. By default the filled regions will be placed at the y-array positions defining a filled polygonal area. The section of y that has the intersection are simply clipped. Setting this parameter to True results in calculation of the actual point of intersection and extends to the filled regions till the points.
step: This is an optional parameter that accepts one of the three values namely, ‘pre’, ‘post’ and ‘mid’. This is used to specify where the steps will occur. pre: From every x position the y value is continued constantlyto the left, ie, the interval (x[i-1], x[i]) has the value y[i]. post:From every x position the y value is continued constantly to the right, ie, the interval (x[i], x[i+1]) has the value y[i]. mid: Half way between the x positions these steps occur.
pre: From every x position the y value is continued constantlyto the left, ie, the interval (x[i-1], x[i]) has the value y[i].
post:From every x position the y value is continued constantly to the right, ie, the interval (x[i], x[i+1]) has the value y[i].
mid: Half way between the x positions these steps occur.
Returns: It returns a plotted polygon from the PolyCollection.
other Parameters: **kwargs contains keywords from PolyCollection that controls the polygon properties;
Example 1:
Python3
import matplotlib.pyplot as pltimport numpy as np a = np.linspace(0,2*3.14,50)b = np.sin(a) plt.fill_betweenx(a, b, 0, where = (a > -0.5) & (a <= 1), color='g') plt.plot(a, b)
Output:
Example 2:
Python3
import pylab as pltimport numpy as np N = np.linspace(0,3,200)A1 = N**2 + 3A2 = np.exp(N) + 2A3 = np.cos(N) plt.plot(N, A1, lw = 3)plt.plot(N, A2, lw = 3)plt.plot(N, A3, lw = 3) plt.fill_betweenx(N, A1, A2, color = 'r', alpha = .5)plt.fill_betweenx(N, A1, A3, color = 'g', alpha = .5) plt.show()
Output:
gabaa406
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Convert integer to string in Python
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python
|
[
{
"code": null,
"e": 24499,
"s": 24471,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 24712,
"s": 24499,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. "
},
{
"code": null,
"e": 25107,
"s": 24712,
"text": "The matplotlib.pyplot.fill_betweenx() is used to fill area between two vertical curves. Two points (x1, y) and (x2, y) define the curves. this creates one or more polygons describing the filled areas. The ‘where’ parameter can be used to selectively fill some areas. By default, edges connect the given points directly. The ‘step’ parameter is used, if the filling needs to be a step function. "
},
{
"code": null,
"e": 25239,
"s": 25107,
"text": "Syntax: matplotlib.pyplot.fill_betweenx(y, x1, x2=0, where=None, step=None, interpolate=False, *, data=None, **kwargs)Parameters: "
},
{
"code": null,
"e": 25334,
"s": 25239,
"text": "y: It is array of length N. These are the y coordinates of the nodes that define the curves. "
},
{
"code": null,
"e": 25455,
"s": 25334,
"text": "x1:It is an array of length N or a scalar. This represents the x coordinates of the nodes that define the first curve. "
},
{
"code": null,
"e": 25616,
"s": 25455,
"text": "x2: It is an array of length N and is optional in nature. Its default value is 0. This represents the x coordinates of the nodes that define the second curve. "
},
{
"code": null,
"e": 25979,
"s": 25616,
"text": "where: it is an array of boolean values of length N. It is defined if there is a need to exclude some vertical regions from being filled. It is important to note that this definition means that an isolated true value in between two two false values is where it will not do the filling. Adjacent False values results in not filling both sides of the True value. "
},
{
"code": null,
"e": 26501,
"s": 25979,
"text": "interpolate: It is an optional parameter that accepts boolean values. It is only relevant if where is used and two curves are crossing each other. Semantically where if generally used for x1>x2 or similar cases. By default the filled regions will be placed at the y-array positions defining a filled polygonal area. The section of y that has the intersection are simply clipped. Setting this parameter to True results in calculation of the actual point of intersection and extends to the filled regions till the points. "
},
{
"code": null,
"e": 26976,
"s": 26501,
"text": "step: This is an optional parameter that accepts one of the three values namely, ‘pre’, ‘post’ and ‘mid’. This is used to specify where the steps will occur. pre: From every x position the y value is continued constantlyto the left, ie, the interval (x[i-1], x[i]) has the value y[i]. post:From every x position the y value is continued constantly to the right, ie, the interval (x[i], x[i+1]) has the value y[i]. mid: Half way between the x positions these steps occur. "
},
{
"code": null,
"e": 27105,
"s": 26976,
"text": "pre: From every x position the y value is continued constantlyto the left, ie, the interval (x[i-1], x[i]) has the value y[i]. "
},
{
"code": null,
"e": 27236,
"s": 27105,
"text": "post:From every x position the y value is continued constantly to the right, ie, the interval (x[i], x[i+1]) has the value y[i]. "
},
{
"code": null,
"e": 27295,
"s": 27236,
"text": "mid: Half way between the x positions these steps occur. "
},
{
"code": null,
"e": 27359,
"s": 27295,
"text": "Returns: It returns a plotted polygon from the PolyCollection. "
},
{
"code": null,
"e": 27462,
"s": 27359,
"text": "other Parameters: **kwargs contains keywords from PolyCollection that controls the polygon properties;"
},
{
"code": null,
"e": 27477,
"s": 27464,
"text": "Example 1: "
},
{
"code": null,
"e": 27485,
"s": 27477,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as np a = np.linspace(0,2*3.14,50)b = np.sin(a) plt.fill_betweenx(a, b, 0, where = (a > -0.5) & (a <= 1), color='g') plt.plot(a, b)",
"e": 27695,
"s": 27485,
"text": null
},
{
"code": null,
"e": 27704,
"s": 27695,
"text": "Output: "
},
{
"code": null,
"e": 27717,
"s": 27704,
"text": "Example 2: "
},
{
"code": null,
"e": 27725,
"s": 27717,
"text": "Python3"
},
{
"code": "import pylab as pltimport numpy as np N = np.linspace(0,3,200)A1 = N**2 + 3A2 = np.exp(N) + 2A3 = np.cos(N) plt.plot(N, A1, lw = 3)plt.plot(N, A2, lw = 3)plt.plot(N, A3, lw = 3) plt.fill_betweenx(N, A1, A2, color = 'r', alpha = .5)plt.fill_betweenx(N, A1, A3, color = 'g', alpha = .5) plt.show()",
"e": 28090,
"s": 27725,
"text": null
},
{
"code": null,
"e": 28099,
"s": 28090,
"text": "Output: "
},
{
"code": null,
"e": 28110,
"s": 28101,
"text": "gabaa406"
},
{
"code": null,
"e": 28128,
"s": 28110,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 28135,
"s": 28128,
"text": "Python"
},
{
"code": null,
"e": 28151,
"s": 28135,
"text": "Write From Home"
},
{
"code": null,
"e": 28249,
"s": 28151,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28258,
"s": 28249,
"text": "Comments"
},
{
"code": null,
"e": 28271,
"s": 28258,
"text": "Old Comments"
},
{
"code": null,
"e": 28289,
"s": 28271,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28324,
"s": 28289,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28346,
"s": 28324,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28378,
"s": 28346,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28408,
"s": 28378,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28444,
"s": 28408,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 28480,
"s": 28444,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 28496,
"s": 28480,
"text": "Python infinity"
},
{
"code": null,
"e": 28557,
"s": 28496,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Supercharging MS SQL Server with Python | by James Briggs | Towards Data Science
|
At work, I use SQL a lot. It is not without annoying nuances and limitations, but in the end, it is the foundation of all data professions. For that reason, it is an absolute necessity for anyone working in the land of data. Being competent in SQL is incredibly important.
Although SQL is great, why settle for great? Why don’t we supercharge SQL?
The limitations of SQL stem from it being a declarative language, meaning we tell SQL what we want and SQL will fetch that from a specified database. For many data extraction or simple data manipulation tasks, this is all that is needed.
But what if we want more?
That is exactly what I will show you how to do in this article.
This code is the foundation to supercharging MS SQL server. Once this is built we can connect to SQL from Python with just:
sql = Sql('database123')
Easy right? There are a few things going on, so let’s dissect the code.
class Sql:
The first thing to note, we are containing this within a class. I have found this approach logical as in this format we add or remove processes for this specific database. This will make more sense once seeing how this works.
We initialise our class:
def __init__(self, database, server="XXVIR00012,55000"):
Myself and my colleagues almost always connect to the same server. So I set this common server name as the default argument for server.
Your server name can be found in the ‘Connect to Server’ dialog box or at the top of your window in MS SQL Server Management Studio:
Next, we establish our connection to SQL:
self.cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};" "Server="+self.server+";" "Database="+self.database+";" "Trusted_Connection=yes;")
This is made incredibly easy thanks to the pyodbc module. We simply pass a connection string to the pyodbc.connect(...) function, more details on this can be found here.
Finally, I like to create a query string within the Sql class which is updated with every query passed to the class:
self.query = "-- {}\n\n-- Made in Python".format(datetime.now() .strftime("%d/%m/%Y"))
This allows us to keep a log of our code and also doubles as a more readable output to colleagues that may be more comfortable reading SQL code.
Note that I will exclude the update to self.query sections of the code in the following code snippets, please check the full code in the links provided if needed.
There are a few essential functions that I find incredibly useful and use almost daily. These all focus on transferring data in or out of a database.
Let's start with the following directory:
For our current project, we need to:
import these files to SQL server
union them into a single table
dynamically create multiple tables based on categories within a column
After fleshing out our SQL class a little more this will be as easy as:
Let's start at the top.
This function is contained inside our SQL class. It allows us to easily push a Pandas dataframe to the SQL database.
This is particularly useful when needing to upload a lot of files. However, the true power in allowing Python to import data to SQL comes with Python’s flexibility.
Importing a specific tab across a dozen Excel workbooks into SQL can be a nightmare. But with Python it’s easy. Now we have built a function that allows us to use Python to read those tabs and import them into SQL for us.
This function is actually used in the union and drop functions. It simply allows us to execute SQL code as simply as possible.
The response argument gives us the option to extract the output of our query to a DataFrame. Allowing us to extract all unique values from colX in our generic_jan table using just:
sets = list(sql.manual("SELECT colX AS 'category' FROM generic_jan GROUP BY colX", response=True)['category'])
Now we have built the manual function, creating the union function is easy:
This simply loops through a list of table names we provide via table_list, building a UNION query for all table names given. This is then executed with self.manual(query).
We have the ability to upload a very large number of tables to SQL Server. This is great but can quickly overpopulate our database. To remedy this, we will create a drop function:
Again, this function is incredibly simple thanks to the manual function. This allows us to either drop a single table by providing a string to tables or to drop multiple tables by providing a list of table names to tables.
When combined these incredibly simple functions allow us to massively expand the capabilities of SQL Server by leveraging the strengths of Python.
If you are interested in seeing more please check out the GitHub repo for pysqlplus. This is a small project and is simply built to enhance interaction with MS SQL Server for my own workplace.
Nonetheless, I hope it may help some other users find ways to incorporate some Python into their SQL routines. I personally use this almost daily, it is so simple yet incredibly powerful.
Thanks for reading!
If you are interested in learning more about Python and SQL in the cloud, consider my review on IBMs Fundamentals of Scalable Data Science course available on Coursera here:
|
[
{
"code": null,
"e": 445,
"s": 172,
"text": "At work, I use SQL a lot. It is not without annoying nuances and limitations, but in the end, it is the foundation of all data professions. For that reason, it is an absolute necessity for anyone working in the land of data. Being competent in SQL is incredibly important."
},
{
"code": null,
"e": 520,
"s": 445,
"text": "Although SQL is great, why settle for great? Why don’t we supercharge SQL?"
},
{
"code": null,
"e": 758,
"s": 520,
"text": "The limitations of SQL stem from it being a declarative language, meaning we tell SQL what we want and SQL will fetch that from a specified database. For many data extraction or simple data manipulation tasks, this is all that is needed."
},
{
"code": null,
"e": 784,
"s": 758,
"text": "But what if we want more?"
},
{
"code": null,
"e": 848,
"s": 784,
"text": "That is exactly what I will show you how to do in this article."
},
{
"code": null,
"e": 972,
"s": 848,
"text": "This code is the foundation to supercharging MS SQL server. Once this is built we can connect to SQL from Python with just:"
},
{
"code": null,
"e": 997,
"s": 972,
"text": "sql = Sql('database123')"
},
{
"code": null,
"e": 1069,
"s": 997,
"text": "Easy right? There are a few things going on, so let’s dissect the code."
},
{
"code": null,
"e": 1080,
"s": 1069,
"text": "class Sql:"
},
{
"code": null,
"e": 1306,
"s": 1080,
"text": "The first thing to note, we are containing this within a class. I have found this approach logical as in this format we add or remove processes for this specific database. This will make more sense once seeing how this works."
},
{
"code": null,
"e": 1331,
"s": 1306,
"text": "We initialise our class:"
},
{
"code": null,
"e": 1388,
"s": 1331,
"text": "def __init__(self, database, server=\"XXVIR00012,55000\"):"
},
{
"code": null,
"e": 1524,
"s": 1388,
"text": "Myself and my colleagues almost always connect to the same server. So I set this common server name as the default argument for server."
},
{
"code": null,
"e": 1657,
"s": 1524,
"text": "Your server name can be found in the ‘Connect to Server’ dialog box or at the top of your window in MS SQL Server Management Studio:"
},
{
"code": null,
"e": 1699,
"s": 1657,
"text": "Next, we establish our connection to SQL:"
},
{
"code": null,
"e": 1929,
"s": 1699,
"text": "self.cnxn = pyodbc.connect(\"Driver={SQL Server Native Client 11.0};\" \"Server=\"+self.server+\";\" \"Database=\"+self.database+\";\" \"Trusted_Connection=yes;\")"
},
{
"code": null,
"e": 2099,
"s": 1929,
"text": "This is made incredibly easy thanks to the pyodbc module. We simply pass a connection string to the pyodbc.connect(...) function, more details on this can be found here."
},
{
"code": null,
"e": 2216,
"s": 2099,
"text": "Finally, I like to create a query string within the Sql class which is updated with every query passed to the class:"
},
{
"code": null,
"e": 2348,
"s": 2216,
"text": "self.query = \"-- {}\\n\\n-- Made in Python\".format(datetime.now() .strftime(\"%d/%m/%Y\"))"
},
{
"code": null,
"e": 2493,
"s": 2348,
"text": "This allows us to keep a log of our code and also doubles as a more readable output to colleagues that may be more comfortable reading SQL code."
},
{
"code": null,
"e": 2656,
"s": 2493,
"text": "Note that I will exclude the update to self.query sections of the code in the following code snippets, please check the full code in the links provided if needed."
},
{
"code": null,
"e": 2806,
"s": 2656,
"text": "There are a few essential functions that I find incredibly useful and use almost daily. These all focus on transferring data in or out of a database."
},
{
"code": null,
"e": 2848,
"s": 2806,
"text": "Let's start with the following directory:"
},
{
"code": null,
"e": 2885,
"s": 2848,
"text": "For our current project, we need to:"
},
{
"code": null,
"e": 2918,
"s": 2885,
"text": "import these files to SQL server"
},
{
"code": null,
"e": 2949,
"s": 2918,
"text": "union them into a single table"
},
{
"code": null,
"e": 3020,
"s": 2949,
"text": "dynamically create multiple tables based on categories within a column"
},
{
"code": null,
"e": 3092,
"s": 3020,
"text": "After fleshing out our SQL class a little more this will be as easy as:"
},
{
"code": null,
"e": 3116,
"s": 3092,
"text": "Let's start at the top."
},
{
"code": null,
"e": 3233,
"s": 3116,
"text": "This function is contained inside our SQL class. It allows us to easily push a Pandas dataframe to the SQL database."
},
{
"code": null,
"e": 3398,
"s": 3233,
"text": "This is particularly useful when needing to upload a lot of files. However, the true power in allowing Python to import data to SQL comes with Python’s flexibility."
},
{
"code": null,
"e": 3620,
"s": 3398,
"text": "Importing a specific tab across a dozen Excel workbooks into SQL can be a nightmare. But with Python it’s easy. Now we have built a function that allows us to use Python to read those tabs and import them into SQL for us."
},
{
"code": null,
"e": 3747,
"s": 3620,
"text": "This function is actually used in the union and drop functions. It simply allows us to execute SQL code as simply as possible."
},
{
"code": null,
"e": 3928,
"s": 3747,
"text": "The response argument gives us the option to extract the output of our query to a DataFrame. Allowing us to extract all unique values from colX in our generic_jan table using just:"
},
{
"code": null,
"e": 4039,
"s": 3928,
"text": "sets = list(sql.manual(\"SELECT colX AS 'category' FROM generic_jan GROUP BY colX\", response=True)['category'])"
},
{
"code": null,
"e": 4115,
"s": 4039,
"text": "Now we have built the manual function, creating the union function is easy:"
},
{
"code": null,
"e": 4287,
"s": 4115,
"text": "This simply loops through a list of table names we provide via table_list, building a UNION query for all table names given. This is then executed with self.manual(query)."
},
{
"code": null,
"e": 4467,
"s": 4287,
"text": "We have the ability to upload a very large number of tables to SQL Server. This is great but can quickly overpopulate our database. To remedy this, we will create a drop function:"
},
{
"code": null,
"e": 4690,
"s": 4467,
"text": "Again, this function is incredibly simple thanks to the manual function. This allows us to either drop a single table by providing a string to tables or to drop multiple tables by providing a list of table names to tables."
},
{
"code": null,
"e": 4837,
"s": 4690,
"text": "When combined these incredibly simple functions allow us to massively expand the capabilities of SQL Server by leveraging the strengths of Python."
},
{
"code": null,
"e": 5030,
"s": 4837,
"text": "If you are interested in seeing more please check out the GitHub repo for pysqlplus. This is a small project and is simply built to enhance interaction with MS SQL Server for my own workplace."
},
{
"code": null,
"e": 5218,
"s": 5030,
"text": "Nonetheless, I hope it may help some other users find ways to incorporate some Python into their SQL routines. I personally use this almost daily, it is so simple yet incredibly powerful."
},
{
"code": null,
"e": 5238,
"s": 5218,
"text": "Thanks for reading!"
}
] |
Decimal.ToInt32() Method in C#
|
30 Jan, 2019
This method is used to convert the value of the specified Decimal to the equivalent 32-bit signed integer. A user can also convert a Decimal value to a 32-bit integer by using the Explicit assignment operator.
Syntax: public static int ToInt32 (decimal value);
Here, the value is the decimal number which is to be converted.
Return Value: It returns a 32-bit signed integer equivalent to the specified value.
Exception: This method will give OverflowException if the specified value is less than MinValue or greater than MaxValue.
Below programs illustrate the use of the above-discussed method:
Example 1:
// C# program to demonstrate the// Decimal.ToInt32(Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Taking decimal variables Decimal dec1 = 2147483647M; Decimal dec2 = 21458565.2996m; // using Decimal.ToInt32(Decimal) Method // Here int means Int32 int val1 = Decimal.ToInt32(dec1); // using Decimal.ToInt32(Decimal) Method // Here int means Int32 int val2 = Decimal.ToInt32(dec2); // Printing the Int32 value Console.WriteLine("The Int32 value " + "is : {0}", val1); // Printing the Int32 value Console.WriteLine("The Int32 value " + "is : {0}", val2); } catch (OverflowException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
The Int32 value is : 2147483647
The Int32 value is : 21458565
Example 2: For OverflowException
// C# program to demonstrate the// Decimal.ToInt32(Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Taking decimal variables // taking a decimal number // above the range of Int32 Decimal dec1 = 2147483648M; // Taking the maximum value // of Decimal Decimal dec2 = Decimal.MaxValue; // using Decimal.ToInt32(Decimal) Method // Here int means Int32 // It will give error as decimal number // is above the range of Int32 int val1 = Decimal.ToInt32(dec1); // using Decimal.ToInt32(Decimal) Method // Here int means Int32 // It will give error as Decimal.MaxValue // value is out of range from Int32 int val2 = Decimal.ToInt32(dec2); // Printing the Int32 value Console.WriteLine("The Int32 value " + "is : {0}", val1); // Printing the Int32 value Console.WriteLine("The Int32 value " + "is : {0}", val2); } catch (OverflowException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Exception Thrown: System.OverflowException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.decimal.toint32?view=netframework-4.7.2
CSharp-Decimal-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# | Multiple inheritance using interfaces
Introduction to .NET Framework
C# | Delegates
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
C# | Class and Object
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 Jan, 2019"
},
{
"code": null,
"e": 263,
"s": 53,
"text": "This method is used to convert the value of the specified Decimal to the equivalent 32-bit signed integer. A user can also convert a Decimal value to a 32-bit integer by using the Explicit assignment operator."
},
{
"code": null,
"e": 314,
"s": 263,
"text": "Syntax: public static int ToInt32 (decimal value);"
},
{
"code": null,
"e": 378,
"s": 314,
"text": "Here, the value is the decimal number which is to be converted."
},
{
"code": null,
"e": 462,
"s": 378,
"text": "Return Value: It returns a 32-bit signed integer equivalent to the specified value."
},
{
"code": null,
"e": 584,
"s": 462,
"text": "Exception: This method will give OverflowException if the specified value is less than MinValue or greater than MaxValue."
},
{
"code": null,
"e": 649,
"s": 584,
"text": "Below programs illustrate the use of the above-discussed method:"
},
{
"code": null,
"e": 660,
"s": 649,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Decimal.ToInt32(Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Taking decimal variables Decimal dec1 = 2147483647M; Decimal dec2 = 21458565.2996m; // using Decimal.ToInt32(Decimal) Method // Here int means Int32 int val1 = Decimal.ToInt32(dec1); // using Decimal.ToInt32(Decimal) Method // Here int means Int32 int val2 = Decimal.ToInt32(dec2); // Printing the Int32 value Console.WriteLine(\"The Int32 value \" + \"is : {0}\", val1); // Printing the Int32 value Console.WriteLine(\"The Int32 value \" + \"is : {0}\", val2); } catch (OverflowException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 1744,
"s": 660,
"text": null
},
{
"code": null,
"e": 1807,
"s": 1744,
"text": "The Int32 value is : 2147483647\nThe Int32 value is : 21458565\n"
},
{
"code": null,
"e": 1840,
"s": 1807,
"text": "Example 2: For OverflowException"
},
{
"code": "// C# program to demonstrate the// Decimal.ToInt32(Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Taking decimal variables // taking a decimal number // above the range of Int32 Decimal dec1 = 2147483648M; // Taking the maximum value // of Decimal Decimal dec2 = Decimal.MaxValue; // using Decimal.ToInt32(Decimal) Method // Here int means Int32 // It will give error as decimal number // is above the range of Int32 int val1 = Decimal.ToInt32(dec1); // using Decimal.ToInt32(Decimal) Method // Here int means Int32 // It will give error as Decimal.MaxValue // value is out of range from Int32 int val2 = Decimal.ToInt32(dec2); // Printing the Int32 value Console.WriteLine(\"The Int32 value \" + \"is : {0}\", val1); // Printing the Int32 value Console.WriteLine(\"The Int32 value \" + \"is : {0}\", val2); } catch (OverflowException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 3277,
"s": 1840,
"text": null
},
{
"code": null,
"e": 3321,
"s": 3277,
"text": "Exception Thrown: System.OverflowException\n"
},
{
"code": null,
"e": 3332,
"s": 3321,
"text": "Reference:"
},
{
"code": null,
"e": 3423,
"s": 3332,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.decimal.toint32?view=netframework-4.7.2"
},
{
"code": null,
"e": 3445,
"s": 3423,
"text": "CSharp-Decimal-Struct"
},
{
"code": null,
"e": 3459,
"s": 3445,
"text": "CSharp-method"
},
{
"code": null,
"e": 3462,
"s": 3459,
"text": "C#"
},
{
"code": null,
"e": 3560,
"s": 3462,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3588,
"s": 3560,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 3631,
"s": 3588,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 3662,
"s": 3631,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 3677,
"s": 3662,
"text": "C# | Delegates"
},
{
"code": null,
"e": 3726,
"s": 3677,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 3742,
"s": 3726,
"text": "C# | Data Types"
},
{
"code": null,
"e": 3765,
"s": 3742,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 3805,
"s": 3765,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 3823,
"s": 3805,
"text": "C# | Constructors"
}
] |
C/C++ if else if ladder with Examples
|
22 Nov, 2019
Decision Making in C/C++ helps to write decision driven statements and execute a particular set of code based on certain conditions.
In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax:
if (condition)
statement 1;
else if (condition)
statement 2;
.
.
else
statement;
Working of the if-else-if ladder:
Control falls into the if block.The flow jumps to Condition 1.Condition is tested.If Condition yields true, goto Step 4.If Condition yields false, goto Step 5.The present block is executed. Goto Step 7.The flow jumps to Condition 2.If Condition yields true, goto step 4.If Condition yields false, goto Step 6.The flow jumps to Condition 3.If Condition yields true, goto step 4.If Condition yields false, execute else block. Goto Step 7.Exits the if-else-if ladder.
Control falls into the if block.
The flow jumps to Condition 1.
Condition is tested.If Condition yields true, goto Step 4.If Condition yields false, goto Step 5.
If Condition yields true, goto Step 4.If Condition yields false, goto Step 5.
If Condition yields true, goto Step 4.
If Condition yields false, goto Step 5.
The present block is executed. Goto Step 7.
The flow jumps to Condition 2.If Condition yields true, goto step 4.If Condition yields false, goto Step 6.
If Condition yields true, goto step 4.If Condition yields false, goto Step 6.
If Condition yields true, goto step 4.
If Condition yields false, goto Step 6.
The flow jumps to Condition 3.If Condition yields true, goto step 4.If Condition yields false, execute else block. Goto Step 7.
If Condition yields true, goto step 4.If Condition yields false, execute else block. Goto Step 7.
If Condition yields true, goto step 4.
If Condition yields false, execute else block. Goto Step 7.
Exits the if-else-if ladder.
Flowchart if-else-if ladder:
Example 1:
C
C++
// C program to illustrate nested-if statement #include <stdio.h> int main(){ int i = 20; // Check if i is 10 if (i == 10) printf("i is 10"); // Since i is not 10 // Check if i is 15 else if (i == 15) printf("i is 15"); // Since i is not 15 // Check if i is 20 else if (i == 20) printf("i is 20"); // If none of the above conditions is true // Then execute the else statement else printf("i is not present"); return 0;}
// C++ program to illustrate if-else-if ladder#include <iostream>using namespace std; int main(){ int i = 20; // Check if i is 10 if (i == 10) cout << "i is 10"; // Since i is not 10 // Check if i is 15 else if (i == 15) cout << "i is 15"; // Since i is not 15 // Check if i is 20 else if (i == 20) cout << "i is 20"; // If none of the above conditions is true // Then execute the else statement else cout << "i is not present"; return 0;}
i is 20
Dry running Example 1:
1. Program starts.
2. i is initialized to 20.
3. condition 1 is checked. 20 == 10, yields false.
4. condition 2 is checked. 20 == 15, yields false.
5. condition 3 is checked. 20 == 20, yields true.
5.a) "i is 20" gets printed.
6. "Outside if-else-if" gets printed.
7. Program ends.
Example 2:
C
C++
// C program to illustrate nested-if statement #include <stdio.h> int main(){ int i = 25; // Check if i is between 0 and 10 if (i >= 0 && i <= 10) printf("i is between 0 and 10"); // Since i is not between 0 and 10 // Check if i is between 11 and 15 else if (i >= 11 && i <= 15) printf("i is between 11 and 15"); // Since i is not between 11 and 15 // Check if i is between 16 and 20 else if (i >= 16 && i <= 20) printf("i is between 16 and 20"); // Since i is not between 0 and 20 // It means i is greater than 20 else printf("i is greater than 20");}
// C++ program to illustrate if-else-if ladder #include <iostream>using namespace std; int main(){ int i = 25; // Check if i is between 0 and 10 if (i >= 0 && i <= 10) cout << "i is between 0 and 10" << endl; // Since i is not between 0 and 10 // Check if i is between 11 and 15 else if (i >= 11 && i <= 15) cout << "i is between 11 and 15" << endl; // Since i is not between 11 and 15 // Check if i is between 16 and 20 else if (i >= 16 && i <= 20) cout << "i is between 16 and 20" << endl; // Since i is not between 0 and 20 // It means i is greater than 20 else cout << "i is greater than 20" << endl;}
i is greater than 20
Related Articles:
Decision Making in C / C++C/C++ if else statement with ExamplesC/C++ if statement with ExamplesSwitch Statement in C/C++Break Statement in C/C++Continue Statement in C/C++goto statement in C/C++return statement in C/C++ with Examples
Decision Making in C / C++
C/C++ if else statement with Examples
C/C++ if statement with Examples
Switch Statement in C/C++
Break Statement in C/C++
Continue Statement in C/C++
goto statement in C/C++
return statement in C/C++ with Examples
C Language
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
Exception Handling in C++
What is the purpose of a function prototype?
TCP Server-Client implementation in C
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Nov, 2019"
},
{
"code": null,
"e": 187,
"s": 54,
"text": "Decision Making in C/C++ helps to write decision driven statements and execute a particular set of code based on certain conditions."
},
{
"code": null,
"e": 562,
"s": 187,
"text": "In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed."
},
{
"code": null,
"e": 570,
"s": 562,
"text": "Syntax:"
},
{
"code": null,
"e": 663,
"s": 570,
"text": "if (condition)\n statement 1;\nelse if (condition)\n statement 2;\n.\n.\nelse\n statement;"
},
{
"code": null,
"e": 697,
"s": 663,
"text": "Working of the if-else-if ladder:"
},
{
"code": null,
"e": 1162,
"s": 697,
"text": "Control falls into the if block.The flow jumps to Condition 1.Condition is tested.If Condition yields true, goto Step 4.If Condition yields false, goto Step 5.The present block is executed. Goto Step 7.The flow jumps to Condition 2.If Condition yields true, goto step 4.If Condition yields false, goto Step 6.The flow jumps to Condition 3.If Condition yields true, goto step 4.If Condition yields false, execute else block. Goto Step 7.Exits the if-else-if ladder."
},
{
"code": null,
"e": 1195,
"s": 1162,
"text": "Control falls into the if block."
},
{
"code": null,
"e": 1226,
"s": 1195,
"text": "The flow jumps to Condition 1."
},
{
"code": null,
"e": 1324,
"s": 1226,
"text": "Condition is tested.If Condition yields true, goto Step 4.If Condition yields false, goto Step 5."
},
{
"code": null,
"e": 1402,
"s": 1324,
"text": "If Condition yields true, goto Step 4.If Condition yields false, goto Step 5."
},
{
"code": null,
"e": 1441,
"s": 1402,
"text": "If Condition yields true, goto Step 4."
},
{
"code": null,
"e": 1481,
"s": 1441,
"text": "If Condition yields false, goto Step 5."
},
{
"code": null,
"e": 1525,
"s": 1481,
"text": "The present block is executed. Goto Step 7."
},
{
"code": null,
"e": 1633,
"s": 1525,
"text": "The flow jumps to Condition 2.If Condition yields true, goto step 4.If Condition yields false, goto Step 6."
},
{
"code": null,
"e": 1711,
"s": 1633,
"text": "If Condition yields true, goto step 4.If Condition yields false, goto Step 6."
},
{
"code": null,
"e": 1750,
"s": 1711,
"text": "If Condition yields true, goto step 4."
},
{
"code": null,
"e": 1790,
"s": 1750,
"text": "If Condition yields false, goto Step 6."
},
{
"code": null,
"e": 1918,
"s": 1790,
"text": "The flow jumps to Condition 3.If Condition yields true, goto step 4.If Condition yields false, execute else block. Goto Step 7."
},
{
"code": null,
"e": 2016,
"s": 1918,
"text": "If Condition yields true, goto step 4.If Condition yields false, execute else block. Goto Step 7."
},
{
"code": null,
"e": 2055,
"s": 2016,
"text": "If Condition yields true, goto step 4."
},
{
"code": null,
"e": 2115,
"s": 2055,
"text": "If Condition yields false, execute else block. Goto Step 7."
},
{
"code": null,
"e": 2144,
"s": 2115,
"text": "Exits the if-else-if ladder."
},
{
"code": null,
"e": 2173,
"s": 2144,
"text": "Flowchart if-else-if ladder:"
},
{
"code": null,
"e": 2184,
"s": 2173,
"text": "Example 1:"
},
{
"code": null,
"e": 2186,
"s": 2184,
"text": "C"
},
{
"code": null,
"e": 2190,
"s": 2186,
"text": "C++"
},
{
"code": "// C program to illustrate nested-if statement #include <stdio.h> int main(){ int i = 20; // Check if i is 10 if (i == 10) printf(\"i is 10\"); // Since i is not 10 // Check if i is 15 else if (i == 15) printf(\"i is 15\"); // Since i is not 15 // Check if i is 20 else if (i == 20) printf(\"i is 20\"); // If none of the above conditions is true // Then execute the else statement else printf(\"i is not present\"); return 0;}",
"e": 2689,
"s": 2190,
"text": null
},
{
"code": "// C++ program to illustrate if-else-if ladder#include <iostream>using namespace std; int main(){ int i = 20; // Check if i is 10 if (i == 10) cout << \"i is 10\"; // Since i is not 10 // Check if i is 15 else if (i == 15) cout << \"i is 15\"; // Since i is not 15 // Check if i is 20 else if (i == 20) cout << \"i is 20\"; // If none of the above conditions is true // Then execute the else statement else cout << \"i is not present\"; return 0;}",
"e": 3207,
"s": 2689,
"text": null
},
{
"code": null,
"e": 3216,
"s": 3207,
"text": "i is 20\n"
},
{
"code": null,
"e": 3239,
"s": 3216,
"text": "Dry running Example 1:"
},
{
"code": null,
"e": 3523,
"s": 3239,
"text": "1. Program starts.\n2. i is initialized to 20.\n3. condition 1 is checked. 20 == 10, yields false.\n4. condition 2 is checked. 20 == 15, yields false.\n5. condition 3 is checked. 20 == 20, yields true.\n 5.a) \"i is 20\" gets printed.\n6. \"Outside if-else-if\" gets printed.\n7. Program ends."
},
{
"code": null,
"e": 3534,
"s": 3523,
"text": "Example 2:"
},
{
"code": null,
"e": 3536,
"s": 3534,
"text": "C"
},
{
"code": null,
"e": 3540,
"s": 3536,
"text": "C++"
},
{
"code": "// C program to illustrate nested-if statement #include <stdio.h> int main(){ int i = 25; // Check if i is between 0 and 10 if (i >= 0 && i <= 10) printf(\"i is between 0 and 10\"); // Since i is not between 0 and 10 // Check if i is between 11 and 15 else if (i >= 11 && i <= 15) printf(\"i is between 11 and 15\"); // Since i is not between 11 and 15 // Check if i is between 16 and 20 else if (i >= 16 && i <= 20) printf(\"i is between 16 and 20\"); // Since i is not between 0 and 20 // It means i is greater than 20 else printf(\"i is greater than 20\");}",
"e": 4167,
"s": 3540,
"text": null
},
{
"code": "// C++ program to illustrate if-else-if ladder #include <iostream>using namespace std; int main(){ int i = 25; // Check if i is between 0 and 10 if (i >= 0 && i <= 10) cout << \"i is between 0 and 10\" << endl; // Since i is not between 0 and 10 // Check if i is between 11 and 15 else if (i >= 11 && i <= 15) cout << \"i is between 11 and 15\" << endl; // Since i is not between 11 and 15 // Check if i is between 16 and 20 else if (i >= 16 && i <= 20) cout << \"i is between 16 and 20\" << endl; // Since i is not between 0 and 20 // It means i is greater than 20 else cout << \"i is greater than 20\" << endl;}",
"e": 4847,
"s": 4167,
"text": null
},
{
"code": null,
"e": 4869,
"s": 4847,
"text": "i is greater than 20\n"
},
{
"code": null,
"e": 4887,
"s": 4869,
"text": "Related Articles:"
},
{
"code": null,
"e": 5121,
"s": 4887,
"text": "Decision Making in C / C++C/C++ if else statement with ExamplesC/C++ if statement with ExamplesSwitch Statement in C/C++Break Statement in C/C++Continue Statement in C/C++goto statement in C/C++return statement in C/C++ with Examples"
},
{
"code": null,
"e": 5148,
"s": 5121,
"text": "Decision Making in C / C++"
},
{
"code": null,
"e": 5186,
"s": 5148,
"text": "C/C++ if else statement with Examples"
},
{
"code": null,
"e": 5219,
"s": 5186,
"text": "C/C++ if statement with Examples"
},
{
"code": null,
"e": 5245,
"s": 5219,
"text": "Switch Statement in C/C++"
},
{
"code": null,
"e": 5270,
"s": 5245,
"text": "Break Statement in C/C++"
},
{
"code": null,
"e": 5298,
"s": 5270,
"text": "Continue Statement in C/C++"
},
{
"code": null,
"e": 5322,
"s": 5298,
"text": "goto statement in C/C++"
},
{
"code": null,
"e": 5362,
"s": 5322,
"text": "return statement in C/C++ with Examples"
},
{
"code": null,
"e": 5373,
"s": 5362,
"text": "C Language"
},
{
"code": null,
"e": 5377,
"s": 5373,
"text": "C++"
},
{
"code": null,
"e": 5396,
"s": 5377,
"text": "School Programming"
},
{
"code": null,
"e": 5400,
"s": 5396,
"text": "CPP"
},
{
"code": null,
"e": 5498,
"s": 5400,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5546,
"s": 5498,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 5567,
"s": 5546,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 5593,
"s": 5567,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 5638,
"s": 5593,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 5676,
"s": 5638,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 5694,
"s": 5676,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 5737,
"s": 5694,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5783,
"s": 5737,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 5826,
"s": 5783,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to implement IIR Bandpass Butterworth Filter using Scipy – Python?
|
10 Nov, 2021
IIR stands for Infinite Impulse Response, It is one of the striking features of many linear-time invariant systems that are distinguished by having an impulse response h(t)/h(n) which does not become zero after some point but instead continues infinitely.
It basically behaves just like an ordinary digital Bandpass Butterworth Filter with an infinite impulse response.
The specifications are as follows:
Pass band frequency: 1400-2100 Hz
Stop band frequency: 1050-24500 Hz
Pass band ripple: 0.4dB
Stop band attenuation: 50 dB
Sampling frequency: 7 kHz
We will plot the magnitude, phase, impulse, step response of the filter.
Step-by-step Approach:
Step 1: Importing all the necessary libraries.
Python3
# import required libraryimport numpy as npimport scipy.signal as signalimport matplotlib.pyplot as plt
Step 2: Defining user defined functions mfreqz() and impz(). [mfreqz is a function for magnitude and phase plot & impz is function for impulse and step response]
Python3
def mfreqz(b, a, Fs): # Compute frequency response of the filter # using signal.freqz function wz, hz = signal.freqz(b, a) # Calculate Magnitude from hz in dB Mag = 20*np.log10(abs(hz)) # Calculate phase angle in degree from hz Phase = np.unwrap(np.arctan2(np.imag(hz), np.real(hz)))*(180/np.pi) # Calculate frequency in Hz from wz Freq = wz*Fs/(2*np.pi) # Plot filter magnitude and phase responses using subplot. fig = plt.figure(figsize=(10, 6)) # Plot Magnitude response sub1 = plt.subplot(2, 1, 1) sub1.plot(Freq, Mag, 'r', linewidth=2) sub1.axis([1, Fs/2, -100, 5]) sub1.set_title('Magnitude Response', fontsize=20) sub1.set_xlabel('Frequency [Hz]', fontsize=20) sub1.set_ylabel('Magnitude [dB]', fontsize=20) sub1.grid() # Plot phase angle sub2 = plt.subplot(2, 1, 2) sub2.plot(Freq, Phase, 'g', linewidth=2) sub2.set_ylabel('Phase (degree)', fontsize=20) sub2.set_xlabel(r'Frequency (Hz)', fontsize=20) sub2.set_title(r'Phase response', fontsize=20) sub2.grid() plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Define impz(b,a) to calculate impulse response# and step response of a system# input: b= an array containing numerator coefficients,# a= an array containing denominator coefficientsdef impz(b, a): # Define the impulse sequence of length 60 impulse = np.repeat(0., 60) impulse[0] = 1. x = np.arange(0, 60) # Compute the impulse response response = signal.lfilter(b, a, impulse) # Plot filter impulse and step response: fig = plt.figure(figsize=(10, 6)) plt.subplot(211) plt.stem(x, response, 'm', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Impulse response', fontsize=15) plt.subplot(212) step = np.cumsum(response) # Compute step response of the system plt.stem(x, step, 'g', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Step response', fontsize=15) plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show()
Step 3:Define variables with the given specifications of the filter.
Python3
# Given specificationFs = 7000 # Sampling frequency in Hzfp = np.array([1400, 2100]) # Pass band frequency in Hzfs = np.array([1050, 2450]) # Stop band frequency in HzAp = 0.4 # Pass band ripple in dBAs = 50 # stop band attenuation in dB
Step 4: Computing the cut-off frequency
Python3
# Compute pass band and stop band edge frequencieswp = fp/(Fs/2) # Normalized passband edge frequencies w.r.t. Nyquist ratews = fs/(Fs/2) # Normalized stopband edge frequencies
Step 5: Compute cut-off frequency & order
Python3
# Compute order of the digital Butterworth filter using signal.buttordN, wc = signal.buttord(wp, ws, Ap, As, analog=True)# Print the order of the filter and cutoff frequenciesprint('Order of the filter=', N)print('Cut-off frequency=', wc)
Output:
Step 6: Compute the filter co-efficient
Python3
# Design digital Butterworth band pass# filter using signal.butter functionz, p = signal.butter(N, wc, 'bandpass') # Print numerator and denomerator# coefficients of the filterprint('Numerator Coefficients:', z)print('Denominator Coefficients:', p)
Output:
Step 7: Compute frequency response using signal.freqz() function
Python3
# Compute frequency response of the filter using signal.freqz functionwz, hz = signal.freqz(z, p)
Step 8: Plotting the Magnitude & Phase Response
Python3
# Call mfreqz to plot the magnitude and phase responsemfreqz(z, p, Fs)
Output:
Step 9: Plotting the Impulse and Step Response
Python3
# Call impz function to plot impulse# and step response of the filterimpz(z, p)
Output:
Below is the implementation:
Python3
# import required libraryimport numpy as npimport scipy.signal as signalimport matplotlib.pyplot as plt # Compute magnitude and phase response# using mfreqz functiondef mfreqz(b, a, Fs): # Compute frequency response of the filter # using signal.freqz function wz, hz = signal.freqz(b, a) # Calculate Magnitude from hz in dB Mag = 20*np.log10(abs(hz)) # Calculate phase angle in degree from hz Phase = np.unwrap(np.arctan2(np.imag(hz), np.real(hz)))*(180/np.pi) # Calculate frequency in Hz from wz Freq = wz*Fs/(2*np.pi) # Plot filter magnitude and phase responses using subplot. fig = plt.figure(figsize=(10, 6)) # Plot Magnitude response sub1 = plt.subplot(2, 1, 1) sub1.plot(Freq, Mag, 'r', linewidth=2) sub1.axis([1, Fs/2, -100, 5]) sub1.set_title('Magnitude Response', fontsize=20) sub1.set_xlabel('Frequency [Hz]', fontsize=20) sub1.set_ylabel('Magnitude [dB]', fontsize=20) sub1.grid() # Plot phase angle sub2 = plt.subplot(2, 1, 2) sub2.plot(Freq, Phase, 'g', linewidth=2) sub2.set_ylabel('Phase (degree)', fontsize=20) sub2.set_xlabel(r'Frequency (Hz)', fontsize=20) sub2.set_title(r'Phase response', fontsize=20) sub2.grid() plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Define impz(b,a) to calculate impulse response# and step response of a system# input: b= an array containing numerator coefficients,# a= an array containing denominator coefficientsdef impz(b, a): # Define the impulse sequence of length 60 impulse = np.repeat(0., 60) impulse[0] = 1. x = np.arange(0, 60) # Compute the impulse response response = signal.lfilter(b, a, impulse) # Plot filter impulse and step response: fig = plt.figure(figsize=(10, 6)) plt.subplot(211) plt.stem(x, response, 'm', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Impulse response', fontsize=15) plt.subplot(212) step = np.cumsum(response) # Compute step response of the system plt.stem(x, step, 'g', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Step response', fontsize=15) plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Given specificationFs = 7000 # Sampling frequency in Hzfp = np.array([1400, 2100]) # Pass band frequency in Hzfs = np.array([1050, 2450]) # Stop band frequency in HzAp = 0.4 # Pass band ripple in dBAs = 50 # stop band attenuation in dB # Compute pass band and stop band edge frequencieswp = fp/(Fs/2) # Normalized passband edge frequencies w.r.t. Nyquist ratews = fs/(Fs/2) # Normalized stopband edge frequencies # Compute order of the digital Butterworth filter using signal.buttordN, wc = signal.buttord(wp, ws, Ap, As, analog=True) # Print the order of the filter and cutoff frequenciesprint('Order of the filter=', N)print('Cut-off frequency=', wc) # Design digital Butterworth band pass# filter using signal.butter functionz, p = signal.butter(N, wc, 'bandpass') # Print numerator and denomerator# coefficients of the filterprint('Numerator Coefficients:', z)print('Denominator Coefficients:', p) # Compute frequency response of the filter# using signal.freqz functionwz, hz = signal.freqz(z, p) # Call mfreqz to plot the magnitude and phase responsemfreqz(z, p, Fs) # Call impz function to plot impulse# and step response of the filterimpz(z, p)
Output:
gulshankumarar231
Data Visualization
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 284,
"s": 28,
"text": "IIR stands for Infinite Impulse Response, It is one of the striking features of many linear-time invariant systems that are distinguished by having an impulse response h(t)/h(n) which does not become zero after some point but instead continues infinitely."
},
{
"code": null,
"e": 398,
"s": 284,
"text": "It basically behaves just like an ordinary digital Bandpass Butterworth Filter with an infinite impulse response."
},
{
"code": null,
"e": 435,
"s": 398,
"text": "The specifications are as follows: "
},
{
"code": null,
"e": 469,
"s": 435,
"text": "Pass band frequency: 1400-2100 Hz"
},
{
"code": null,
"e": 504,
"s": 469,
"text": "Stop band frequency: 1050-24500 Hz"
},
{
"code": null,
"e": 528,
"s": 504,
"text": "Pass band ripple: 0.4dB"
},
{
"code": null,
"e": 557,
"s": 528,
"text": "Stop band attenuation: 50 dB"
},
{
"code": null,
"e": 583,
"s": 557,
"text": "Sampling frequency: 7 kHz"
},
{
"code": null,
"e": 656,
"s": 583,
"text": "We will plot the magnitude, phase, impulse, step response of the filter."
},
{
"code": null,
"e": 679,
"s": 656,
"text": "Step-by-step Approach:"
},
{
"code": null,
"e": 726,
"s": 679,
"text": "Step 1: Importing all the necessary libraries."
},
{
"code": null,
"e": 734,
"s": 726,
"text": "Python3"
},
{
"code": "# import required libraryimport numpy as npimport scipy.signal as signalimport matplotlib.pyplot as plt",
"e": 838,
"s": 734,
"text": null
},
{
"code": null,
"e": 1000,
"s": 838,
"text": "Step 2: Defining user defined functions mfreqz() and impz(). [mfreqz is a function for magnitude and phase plot & impz is function for impulse and step response]"
},
{
"code": null,
"e": 1008,
"s": 1000,
"text": "Python3"
},
{
"code": "def mfreqz(b, a, Fs): # Compute frequency response of the filter # using signal.freqz function wz, hz = signal.freqz(b, a) # Calculate Magnitude from hz in dB Mag = 20*np.log10(abs(hz)) # Calculate phase angle in degree from hz Phase = np.unwrap(np.arctan2(np.imag(hz), np.real(hz)))*(180/np.pi) # Calculate frequency in Hz from wz Freq = wz*Fs/(2*np.pi) # Plot filter magnitude and phase responses using subplot. fig = plt.figure(figsize=(10, 6)) # Plot Magnitude response sub1 = plt.subplot(2, 1, 1) sub1.plot(Freq, Mag, 'r', linewidth=2) sub1.axis([1, Fs/2, -100, 5]) sub1.set_title('Magnitude Response', fontsize=20) sub1.set_xlabel('Frequency [Hz]', fontsize=20) sub1.set_ylabel('Magnitude [dB]', fontsize=20) sub1.grid() # Plot phase angle sub2 = plt.subplot(2, 1, 2) sub2.plot(Freq, Phase, 'g', linewidth=2) sub2.set_ylabel('Phase (degree)', fontsize=20) sub2.set_xlabel(r'Frequency (Hz)', fontsize=20) sub2.set_title(r'Phase response', fontsize=20) sub2.grid() plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Define impz(b,a) to calculate impulse response# and step response of a system# input: b= an array containing numerator coefficients,# a= an array containing denominator coefficientsdef impz(b, a): # Define the impulse sequence of length 60 impulse = np.repeat(0., 60) impulse[0] = 1. x = np.arange(0, 60) # Compute the impulse response response = signal.lfilter(b, a, impulse) # Plot filter impulse and step response: fig = plt.figure(figsize=(10, 6)) plt.subplot(211) plt.stem(x, response, 'm', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Impulse response', fontsize=15) plt.subplot(212) step = np.cumsum(response) # Compute step response of the system plt.stem(x, step, 'g', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Step response', fontsize=15) plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show()",
"e": 3169,
"s": 1008,
"text": null
},
{
"code": null,
"e": 3238,
"s": 3169,
"text": "Step 3:Define variables with the given specifications of the filter."
},
{
"code": null,
"e": 3246,
"s": 3238,
"text": "Python3"
},
{
"code": "# Given specificationFs = 7000 # Sampling frequency in Hzfp = np.array([1400, 2100]) # Pass band frequency in Hzfs = np.array([1050, 2450]) # Stop band frequency in HzAp = 0.4 # Pass band ripple in dBAs = 50 # stop band attenuation in dB",
"e": 3489,
"s": 3246,
"text": null
},
{
"code": null,
"e": 3529,
"s": 3489,
"text": "Step 4: Computing the cut-off frequency"
},
{
"code": null,
"e": 3537,
"s": 3529,
"text": "Python3"
},
{
"code": "# Compute pass band and stop band edge frequencieswp = fp/(Fs/2) # Normalized passband edge frequencies w.r.t. Nyquist ratews = fs/(Fs/2) # Normalized stopband edge frequencies",
"e": 3716,
"s": 3537,
"text": null
},
{
"code": null,
"e": 3758,
"s": 3716,
"text": "Step 5: Compute cut-off frequency & order"
},
{
"code": null,
"e": 3766,
"s": 3758,
"text": "Python3"
},
{
"code": "# Compute order of the digital Butterworth filter using signal.buttordN, wc = signal.buttord(wp, ws, Ap, As, analog=True)# Print the order of the filter and cutoff frequenciesprint('Order of the filter=', N)print('Cut-off frequency=', wc)",
"e": 4005,
"s": 3766,
"text": null
},
{
"code": null,
"e": 4013,
"s": 4005,
"text": "Output:"
},
{
"code": null,
"e": 4054,
"s": 4013,
"text": "Step 6: Compute the filter co-efficient "
},
{
"code": null,
"e": 4062,
"s": 4054,
"text": "Python3"
},
{
"code": "# Design digital Butterworth band pass# filter using signal.butter functionz, p = signal.butter(N, wc, 'bandpass') # Print numerator and denomerator# coefficients of the filterprint('Numerator Coefficients:', z)print('Denominator Coefficients:', p)",
"e": 4311,
"s": 4062,
"text": null
},
{
"code": null,
"e": 4319,
"s": 4311,
"text": "Output:"
},
{
"code": null,
"e": 4384,
"s": 4319,
"text": "Step 7: Compute frequency response using signal.freqz() function"
},
{
"code": null,
"e": 4392,
"s": 4384,
"text": "Python3"
},
{
"code": "# Compute frequency response of the filter using signal.freqz functionwz, hz = signal.freqz(z, p)",
"e": 4490,
"s": 4392,
"text": null
},
{
"code": null,
"e": 4538,
"s": 4490,
"text": "Step 8: Plotting the Magnitude & Phase Response"
},
{
"code": null,
"e": 4546,
"s": 4538,
"text": "Python3"
},
{
"code": "# Call mfreqz to plot the magnitude and phase responsemfreqz(z, p, Fs)",
"e": 4617,
"s": 4546,
"text": null
},
{
"code": null,
"e": 4625,
"s": 4617,
"text": "Output:"
},
{
"code": null,
"e": 4672,
"s": 4625,
"text": "Step 9: Plotting the Impulse and Step Response"
},
{
"code": null,
"e": 4680,
"s": 4672,
"text": "Python3"
},
{
"code": "# Call impz function to plot impulse# and step response of the filterimpz(z, p)",
"e": 4760,
"s": 4680,
"text": null
},
{
"code": null,
"e": 4768,
"s": 4760,
"text": "Output:"
},
{
"code": null,
"e": 4797,
"s": 4768,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 4805,
"s": 4797,
"text": "Python3"
},
{
"code": "# import required libraryimport numpy as npimport scipy.signal as signalimport matplotlib.pyplot as plt # Compute magnitude and phase response# using mfreqz functiondef mfreqz(b, a, Fs): # Compute frequency response of the filter # using signal.freqz function wz, hz = signal.freqz(b, a) # Calculate Magnitude from hz in dB Mag = 20*np.log10(abs(hz)) # Calculate phase angle in degree from hz Phase = np.unwrap(np.arctan2(np.imag(hz), np.real(hz)))*(180/np.pi) # Calculate frequency in Hz from wz Freq = wz*Fs/(2*np.pi) # Plot filter magnitude and phase responses using subplot. fig = plt.figure(figsize=(10, 6)) # Plot Magnitude response sub1 = plt.subplot(2, 1, 1) sub1.plot(Freq, Mag, 'r', linewidth=2) sub1.axis([1, Fs/2, -100, 5]) sub1.set_title('Magnitude Response', fontsize=20) sub1.set_xlabel('Frequency [Hz]', fontsize=20) sub1.set_ylabel('Magnitude [dB]', fontsize=20) sub1.grid() # Plot phase angle sub2 = plt.subplot(2, 1, 2) sub2.plot(Freq, Phase, 'g', linewidth=2) sub2.set_ylabel('Phase (degree)', fontsize=20) sub2.set_xlabel(r'Frequency (Hz)', fontsize=20) sub2.set_title(r'Phase response', fontsize=20) sub2.grid() plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Define impz(b,a) to calculate impulse response# and step response of a system# input: b= an array containing numerator coefficients,# a= an array containing denominator coefficientsdef impz(b, a): # Define the impulse sequence of length 60 impulse = np.repeat(0., 60) impulse[0] = 1. x = np.arange(0, 60) # Compute the impulse response response = signal.lfilter(b, a, impulse) # Plot filter impulse and step response: fig = plt.figure(figsize=(10, 6)) plt.subplot(211) plt.stem(x, response, 'm', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Impulse response', fontsize=15) plt.subplot(212) step = np.cumsum(response) # Compute step response of the system plt.stem(x, step, 'g', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Step response', fontsize=15) plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Given specificationFs = 7000 # Sampling frequency in Hzfp = np.array([1400, 2100]) # Pass band frequency in Hzfs = np.array([1050, 2450]) # Stop band frequency in HzAp = 0.4 # Pass band ripple in dBAs = 50 # stop band attenuation in dB # Compute pass band and stop band edge frequencieswp = fp/(Fs/2) # Normalized passband edge frequencies w.r.t. Nyquist ratews = fs/(Fs/2) # Normalized stopband edge frequencies # Compute order of the digital Butterworth filter using signal.buttordN, wc = signal.buttord(wp, ws, Ap, As, analog=True) # Print the order of the filter and cutoff frequenciesprint('Order of the filter=', N)print('Cut-off frequency=', wc) # Design digital Butterworth band pass# filter using signal.butter functionz, p = signal.butter(N, wc, 'bandpass') # Print numerator and denomerator# coefficients of the filterprint('Numerator Coefficients:', z)print('Denominator Coefficients:', p) # Compute frequency response of the filter# using signal.freqz functionwz, hz = signal.freqz(z, p) # Call mfreqz to plot the magnitude and phase responsemfreqz(z, p, Fs) # Call impz function to plot impulse# and step response of the filterimpz(z, p)",
"e": 8289,
"s": 4805,
"text": null
},
{
"code": null,
"e": 8297,
"s": 8289,
"text": "Output:"
},
{
"code": null,
"e": 8315,
"s": 8297,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 8334,
"s": 8315,
"text": "Data Visualization"
},
{
"code": null,
"e": 8347,
"s": 8334,
"text": "Python-scipy"
},
{
"code": null,
"e": 8354,
"s": 8347,
"text": "Python"
},
{
"code": null,
"e": 8452,
"s": 8354,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8484,
"s": 8452,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 8511,
"s": 8484,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 8532,
"s": 8511,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 8555,
"s": 8532,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 8611,
"s": 8555,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 8642,
"s": 8611,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 8684,
"s": 8642,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 8726,
"s": 8684,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 8765,
"s": 8726,
"text": "Python | Get unique values from a list"
}
] |
Detect cycle in an undirected graph using BFS
|
02 Jul, 2021
Given an undirected graph, how to check if there is a cycle in the graph? For example, the following graph has a cycle 1-0-2-1.
We have discussed cycle detection for the directed graph. We have also discussed a union-find algorithm for cycle detection in undirected graphs.. The time complexity of the union-find algorithm is O(ELogV). Like directed graphs, we can use DFS to detect a cycle in an undirected graph in O(V+E) time. We have discussed DFS based solution for cycle detection in an undirected graph. In this article, the BFS based solution is discussed. We do a BFS traversal of the given graph. For every visited vertex ‘v’, if there is an adjacent ‘u’ such that u is already visited and u is not a parent of v, then there is a cycle in the graph. If we don’t find such an adjacent for any vertex, we say that there is no cycle. We use a parent array to keep track of the parent vertex for a vertex so that we do not consider the visited parent as a cycle.
C++
Java
Python3
C#
Javascript
// C++ program to detect cycle// in an undirected graph// using BFS.#include <bits/stdc++.h>using namespace std; void addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} bool isCyclicConntected(vector<int> adj[], int s, int V, vector<bool>& visited){ // Set parent vertex for every vertex as -1. vector<int> parent(V, -1); // Create a queue for BFS queue<int> q; // Mark the current node as // visited and enqueue it visited[s] = true; q.push(s); while (!q.empty()) { // Dequeue a vertex from queue and print it int u = q.front(); q.pop(); // Get all adjacent vertices of the dequeued // vertex u. If a adjacent has not been visited, // then mark it visited and enqueue it. We also // mark parent so that parent is not considered // for cycle. for (auto v : adj[u]) { if (!visited[v]) { visited[v] = true; q.push(v); parent[v] = u; } else if (parent[u] != v) return true; } } return false;} bool isCyclicDisconntected(vector<int> adj[], int V){ // Mark all the vertices as not visited vector<bool> visited(V, false); for (int i = 0; i < V; i++) if (!visited[i] && isCyclicConntected(adj, i, V, visited)) return true; return false;} // Driver program to test methods of graph classint main(){ int V = 4; vector<int> adj[V]; addEdge(adj, 0, 1); addEdge(adj, 1, 2); addEdge(adj, 2, 0); addEdge(adj, 2, 3); if (isCyclicDisconntected(adj, V)) cout << "Yes"; else cout << "No"; return 0;}
// Java program to detect cycle in// an undirected graph using BFS.import java.util.ArrayList;import java.util.Arrays;import java.util.LinkedList;import java.util.Queue; class cycle{ public static void main(String arg[]) { int V = 4; @SuppressWarnings("unchecked") ArrayList <Integer> adj[] = new ArrayList[V]; for(int i = 0; i < 4; i++) adj[i] = new ArrayList<Integer>(); addEdge(adj, 0, 1); addEdge(adj, 1, 2); addEdge(adj, 2, 0); addEdge(adj, 2, 3); if (isCyclicDisconntected(adj, V)) System.out.println("Yes"); else System.out.println("No"); } static void addEdge(ArrayList<Integer> adj[], int u, int v) { adj[u].add(v); adj[v].add(u); } static boolean isCyclicConntected( ArrayList<Integer> adj[], int s, int V, boolean visited[]) { // Set parent vertex for every vertex as -1. int parent[] = new int[V]; Arrays.fill(parent, -1); // Create a queue for BFS Queue<Integer> q = new LinkedList<>(); // Mark the current node as // visited and enqueue it visited[s] = true; q.add(s); while (!q.isEmpty()) { // Dequeue a vertex from // queue and print it int u = q.poll(); // Get all adjacent vertices // of the dequeued vertex u. // If a adjacent has not been // visited, then mark it visited // and enqueue it. We also mark parent // so that parent is not considered // for cycle. for (int i = 0; i < adj[u].size(); i++) { int v = adj[u].get(i); if (!visited[v]) { visited[v] = true; q.add(v); parent[v] = u; } else if (parent[u] != v) return true; } } return false; } static boolean isCyclicDisconntected( ArrayList<Integer> adj[], int V) { // Mark all the vertices as not visited boolean visited[] = new boolean[V]; Arrays.fill(visited,false); for (int i = 0; i < V; i++) if (!visited[i] && isCyclicConntected(adj, i, V, visited)) return true; return false; }} // This code is contributed by mayukh Sengupta
# Python3 program to detect cycle in# an undirected graph using BFS.from collections import deque def addEdge(adj: list, u, v): adj[u].append(v) adj[v].append(u) def isCyclicConnected(adj: list, s, V, visited: list): # Set parent vertex for every vertex as -1. parent = [-1] * V # Create a queue for BFS q = deque() # Mark the current node as # visited and enqueue it visited[s] = True q.append(s) while q != []: # Dequeue a vertex from queue and print it u = q.pop() # Get all adjacent vertices of the dequeued # vertex u. If a adjacent has not been visited, # then mark it visited and enqueue it. We also # mark parent so that parent is not considered # for cycle. for v in adj[u]: if not visited[v]: visited[v] = True q.append(v) parent[v] = u elif parent[u] != v: return True return False def isCyclicDisconnected(adj: list, V): # Mark all the vertices as not visited visited = [False] * V for i in range(V): if not visited[i] and \ isCyclicConnected(adj, i, V, visited): return True return False # Driver Codeif __name__ == "__main__": V = 4 adj = [[] for i in range(V)] addEdge(adj, 0, 1) addEdge(adj, 1, 2) addEdge(adj, 2, 0) addEdge(adj, 2, 3) if isCyclicDisconnected(adj, V): print("Yes") else: print("No") # This code is contributed by# sanjeev2552
// A C# program to detect cycle in// an undirected graph using BFS.using System;using System.Collections.Generic; class GFG{ public static void Main(String []arg) { int V = 4; List<int> []adj = new List<int>[V]; for (int i = 0; i < 4; i++) { adj[i] = new List<int>(); } addEdge(adj, 0, 1); addEdge(adj, 1, 2); addEdge(adj, 2, 0); addEdge(adj, 2, 3); if (isCyclicDisconntected(adj, V)) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } } static void addEdge(List<int> []adj, int u, int v) { adj[u].Add(v); adj[v].Add(u); } static bool isCyclicConntected(List<int> []adj, int s, int V, bool []visited) { // Set parent vertex for every vertex as -1. int []parent = new int[V]; for (int i = 0; i < V; i++) parent[i] = -1; // Create a queue for BFS Queue<int> q = new Queue<int>(); // Mark the current node as // visited and enqueue it visited[s] = true; q.Enqueue(s); while (q.Count != 0) { // Dequeue a vertex from // queue and print it int u = q.Dequeue(); // Get all adjacent vertices // of the dequeued vertex u. // If a adjacent has not been // visited, then mark it visited // and enqueue it. We also mark parent // so that parent is not considered // for cycle. for (int i = 0; i < adj[u].Count; i++) { int v = adj[u][i]; if (!visited[v]) { visited[v] = true; q.Enqueue(v); parent[v] = u; } else if (parent[u] != v) { return true; } } } return false; } static bool isCyclicDisconntected(List<int> []adj, int V) { // Mark all the vertices as not visited bool []visited = new bool[V]; for (int i = 0; i < V; i++) { if (!visited[i] && isCyclicConntected(adj, i, V, visited)) { return true; } } return false; }} // This code is contributed by PrinciRaj1992
<script> // A JavaScript program to detect cycle in// an undirected graph using BFS.var V = 4;var adj = Array.from(Array(V), ()=>Array()); addEdge(adj, 0, 1);addEdge(adj, 1, 2);addEdge(adj, 2, 0);addEdge(adj, 2, 3);if (isCyclicDisconntected(adj, V)){ document.write("Yes");}else{ document.write("No");} function addEdge(adj, u, v){ adj[u].push(v); adj[v].push(u);}function isCyclicConntected(adj, s, V, visited){ // Set parent vertex for every vertex as -1. var parent = Array(V).fill(-1); // Create a queue for BFS var q = []; // Mark the current node as // visited and enqueue it visited[s] = true; q.push(s); while (q.length != 0) { // Dequeue a vertex from // queue and print it var u = q.shift(); // Get all adjacent vertices // of the dequeued vertex u. // If a adjacent has not been // visited, then mark it visited // and enqueue it. We also mark parent // so that parent is not considered // for cycle. for (var i = 0; i < adj[u].length; i++) { var v = adj[u][i]; if (!visited[v]) { visited[v] = true; q.push(v); parent[v] = u; } else if (parent[u] != v) { return true; } } } return false;}function isCyclicDisconntected(adj, V){ // Mark all the vertices as not visited var visited = Array(V).fill(false); for (var i = 0; i < V; i++) { if (!visited[i] && isCyclicConntected(adj, i, V, visited)) { return true; } } return false;} </script>
Output:
Yes
Time Complexity: The program does a simple BFS Traversal of graph and graph is represented using adjacency list. So the time complexity is O(V+E)
mayukh Sengupta
princiraj1992
sanjeev2552
TanmayChakraborty
shubhanshuarya007
sauravraj4
itsok
BFS
graph-connectivity
graph-cycle
Graph
Graph
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in a directed graph
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Find if there is a path between two vertices in an undirected graph
Minimum steps to reach target by a Knight | Set 1
Top 50 Graph Coding Problems for Interviews
Bridges in a graph
Longest Path in a Directed Acyclic Graph
Water Jug problem using BFS
Graph Coloring | Set 1 (Introduction and Applications)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Jul, 2021"
},
{
"code": null,
"e": 183,
"s": 54,
"text": "Given an undirected graph, how to check if there is a cycle in the graph? For example, the following graph has a cycle 1-0-2-1. "
},
{
"code": null,
"e": 1025,
"s": 183,
"text": "We have discussed cycle detection for the directed graph. We have also discussed a union-find algorithm for cycle detection in undirected graphs.. The time complexity of the union-find algorithm is O(ELogV). Like directed graphs, we can use DFS to detect a cycle in an undirected graph in O(V+E) time. We have discussed DFS based solution for cycle detection in an undirected graph. In this article, the BFS based solution is discussed. We do a BFS traversal of the given graph. For every visited vertex ‘v’, if there is an adjacent ‘u’ such that u is already visited and u is not a parent of v, then there is a cycle in the graph. If we don’t find such an adjacent for any vertex, we say that there is no cycle. We use a parent array to keep track of the parent vertex for a vertex so that we do not consider the visited parent as a cycle. "
},
{
"code": null,
"e": 1029,
"s": 1025,
"text": "C++"
},
{
"code": null,
"e": 1034,
"s": 1029,
"text": "Java"
},
{
"code": null,
"e": 1042,
"s": 1034,
"text": "Python3"
},
{
"code": null,
"e": 1045,
"s": 1042,
"text": "C#"
},
{
"code": null,
"e": 1056,
"s": 1045,
"text": "Javascript"
},
{
"code": "// C++ program to detect cycle// in an undirected graph// using BFS.#include <bits/stdc++.h>using namespace std; void addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} bool isCyclicConntected(vector<int> adj[], int s, int V, vector<bool>& visited){ // Set parent vertex for every vertex as -1. vector<int> parent(V, -1); // Create a queue for BFS queue<int> q; // Mark the current node as // visited and enqueue it visited[s] = true; q.push(s); while (!q.empty()) { // Dequeue a vertex from queue and print it int u = q.front(); q.pop(); // Get all adjacent vertices of the dequeued // vertex u. If a adjacent has not been visited, // then mark it visited and enqueue it. We also // mark parent so that parent is not considered // for cycle. for (auto v : adj[u]) { if (!visited[v]) { visited[v] = true; q.push(v); parent[v] = u; } else if (parent[u] != v) return true; } } return false;} bool isCyclicDisconntected(vector<int> adj[], int V){ // Mark all the vertices as not visited vector<bool> visited(V, false); for (int i = 0; i < V; i++) if (!visited[i] && isCyclicConntected(adj, i, V, visited)) return true; return false;} // Driver program to test methods of graph classint main(){ int V = 4; vector<int> adj[V]; addEdge(adj, 0, 1); addEdge(adj, 1, 2); addEdge(adj, 2, 0); addEdge(adj, 2, 3); if (isCyclicDisconntected(adj, V)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 2816,
"s": 1056,
"text": null
},
{
"code": "// Java program to detect cycle in// an undirected graph using BFS.import java.util.ArrayList;import java.util.Arrays;import java.util.LinkedList;import java.util.Queue; class cycle{ public static void main(String arg[]) { int V = 4; @SuppressWarnings(\"unchecked\") ArrayList <Integer> adj[] = new ArrayList[V]; for(int i = 0; i < 4; i++) adj[i] = new ArrayList<Integer>(); addEdge(adj, 0, 1); addEdge(adj, 1, 2); addEdge(adj, 2, 0); addEdge(adj, 2, 3); if (isCyclicDisconntected(adj, V)) System.out.println(\"Yes\"); else System.out.println(\"No\"); } static void addEdge(ArrayList<Integer> adj[], int u, int v) { adj[u].add(v); adj[v].add(u); } static boolean isCyclicConntected( ArrayList<Integer> adj[], int s, int V, boolean visited[]) { // Set parent vertex for every vertex as -1. int parent[] = new int[V]; Arrays.fill(parent, -1); // Create a queue for BFS Queue<Integer> q = new LinkedList<>(); // Mark the current node as // visited and enqueue it visited[s] = true; q.add(s); while (!q.isEmpty()) { // Dequeue a vertex from // queue and print it int u = q.poll(); // Get all adjacent vertices // of the dequeued vertex u. // If a adjacent has not been // visited, then mark it visited // and enqueue it. We also mark parent // so that parent is not considered // for cycle. for (int i = 0; i < adj[u].size(); i++) { int v = adj[u].get(i); if (!visited[v]) { visited[v] = true; q.add(v); parent[v] = u; } else if (parent[u] != v) return true; } } return false; } static boolean isCyclicDisconntected( ArrayList<Integer> adj[], int V) { // Mark all the vertices as not visited boolean visited[] = new boolean[V]; Arrays.fill(visited,false); for (int i = 0; i < V; i++) if (!visited[i] && isCyclicConntected(adj, i, V, visited)) return true; return false; }} // This code is contributed by mayukh Sengupta",
"e": 5007,
"s": 2816,
"text": null
},
{
"code": "# Python3 program to detect cycle in# an undirected graph using BFS.from collections import deque def addEdge(adj: list, u, v): adj[u].append(v) adj[v].append(u) def isCyclicConnected(adj: list, s, V, visited: list): # Set parent vertex for every vertex as -1. parent = [-1] * V # Create a queue for BFS q = deque() # Mark the current node as # visited and enqueue it visited[s] = True q.append(s) while q != []: # Dequeue a vertex from queue and print it u = q.pop() # Get all adjacent vertices of the dequeued # vertex u. If a adjacent has not been visited, # then mark it visited and enqueue it. We also # mark parent so that parent is not considered # for cycle. for v in adj[u]: if not visited[v]: visited[v] = True q.append(v) parent[v] = u elif parent[u] != v: return True return False def isCyclicDisconnected(adj: list, V): # Mark all the vertices as not visited visited = [False] * V for i in range(V): if not visited[i] and \\ isCyclicConnected(adj, i, V, visited): return True return False # Driver Codeif __name__ == \"__main__\": V = 4 adj = [[] for i in range(V)] addEdge(adj, 0, 1) addEdge(adj, 1, 2) addEdge(adj, 2, 0) addEdge(adj, 2, 3) if isCyclicDisconnected(adj, V): print(\"Yes\") else: print(\"No\") # This code is contributed by# sanjeev2552",
"e": 6553,
"s": 5007,
"text": null
},
{
"code": "// A C# program to detect cycle in// an undirected graph using BFS.using System;using System.Collections.Generic; class GFG{ public static void Main(String []arg) { int V = 4; List<int> []adj = new List<int>[V]; for (int i = 0; i < 4; i++) { adj[i] = new List<int>(); } addEdge(adj, 0, 1); addEdge(adj, 1, 2); addEdge(adj, 2, 0); addEdge(adj, 2, 3); if (isCyclicDisconntected(adj, V)) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); } } static void addEdge(List<int> []adj, int u, int v) { adj[u].Add(v); adj[v].Add(u); } static bool isCyclicConntected(List<int> []adj, int s, int V, bool []visited) { // Set parent vertex for every vertex as -1. int []parent = new int[V]; for (int i = 0; i < V; i++) parent[i] = -1; // Create a queue for BFS Queue<int> q = new Queue<int>(); // Mark the current node as // visited and enqueue it visited[s] = true; q.Enqueue(s); while (q.Count != 0) { // Dequeue a vertex from // queue and print it int u = q.Dequeue(); // Get all adjacent vertices // of the dequeued vertex u. // If a adjacent has not been // visited, then mark it visited // and enqueue it. We also mark parent // so that parent is not considered // for cycle. for (int i = 0; i < adj[u].Count; i++) { int v = adj[u][i]; if (!visited[v]) { visited[v] = true; q.Enqueue(v); parent[v] = u; } else if (parent[u] != v) { return true; } } } return false; } static bool isCyclicDisconntected(List<int> []adj, int V) { // Mark all the vertices as not visited bool []visited = new bool[V]; for (int i = 0; i < V; i++) { if (!visited[i] && isCyclicConntected(adj, i, V, visited)) { return true; } } return false; }} // This code is contributed by PrinciRaj1992",
"e": 8986,
"s": 6553,
"text": null
},
{
"code": "<script> // A JavaScript program to detect cycle in// an undirected graph using BFS.var V = 4;var adj = Array.from(Array(V), ()=>Array()); addEdge(adj, 0, 1);addEdge(adj, 1, 2);addEdge(adj, 2, 0);addEdge(adj, 2, 3);if (isCyclicDisconntected(adj, V)){ document.write(\"Yes\");}else{ document.write(\"No\");} function addEdge(adj, u, v){ adj[u].push(v); adj[v].push(u);}function isCyclicConntected(adj, s, V, visited){ // Set parent vertex for every vertex as -1. var parent = Array(V).fill(-1); // Create a queue for BFS var q = []; // Mark the current node as // visited and enqueue it visited[s] = true; q.push(s); while (q.length != 0) { // Dequeue a vertex from // queue and print it var u = q.shift(); // Get all adjacent vertices // of the dequeued vertex u. // If a adjacent has not been // visited, then mark it visited // and enqueue it. We also mark parent // so that parent is not considered // for cycle. for (var i = 0; i < adj[u].length; i++) { var v = adj[u][i]; if (!visited[v]) { visited[v] = true; q.push(v); parent[v] = u; } else if (parent[u] != v) { return true; } } } return false;}function isCyclicDisconntected(adj, V){ // Mark all the vertices as not visited var visited = Array(V).fill(false); for (var i = 0; i < V; i++) { if (!visited[i] && isCyclicConntected(adj, i, V, visited)) { return true; } } return false;} </script>",
"e": 10676,
"s": 8986,
"text": null
},
{
"code": null,
"e": 10685,
"s": 10676,
"text": "Output: "
},
{
"code": null,
"e": 10689,
"s": 10685,
"text": "Yes"
},
{
"code": null,
"e": 10835,
"s": 10689,
"text": "Time Complexity: The program does a simple BFS Traversal of graph and graph is represented using adjacency list. So the time complexity is O(V+E)"
},
{
"code": null,
"e": 10851,
"s": 10835,
"text": "mayukh Sengupta"
},
{
"code": null,
"e": 10865,
"s": 10851,
"text": "princiraj1992"
},
{
"code": null,
"e": 10877,
"s": 10865,
"text": "sanjeev2552"
},
{
"code": null,
"e": 10895,
"s": 10877,
"text": "TanmayChakraborty"
},
{
"code": null,
"e": 10913,
"s": 10895,
"text": "shubhanshuarya007"
},
{
"code": null,
"e": 10924,
"s": 10913,
"text": "sauravraj4"
},
{
"code": null,
"e": 10930,
"s": 10924,
"text": "itsok"
},
{
"code": null,
"e": 10934,
"s": 10930,
"text": "BFS"
},
{
"code": null,
"e": 10953,
"s": 10934,
"text": "graph-connectivity"
},
{
"code": null,
"e": 10965,
"s": 10953,
"text": "graph-cycle"
},
{
"code": null,
"e": 10971,
"s": 10965,
"text": "Graph"
},
{
"code": null,
"e": 10977,
"s": 10971,
"text": "Graph"
},
{
"code": null,
"e": 10981,
"s": 10977,
"text": "BFS"
},
{
"code": null,
"e": 11079,
"s": 10981,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11144,
"s": 11079,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 11176,
"s": 11144,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 11240,
"s": 11176,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 11308,
"s": 11240,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 11358,
"s": 11308,
"text": "Minimum steps to reach target by a Knight | Set 1"
},
{
"code": null,
"e": 11402,
"s": 11358,
"text": "Top 50 Graph Coding Problems for Interviews"
},
{
"code": null,
"e": 11421,
"s": 11402,
"text": "Bridges in a graph"
},
{
"code": null,
"e": 11462,
"s": 11421,
"text": "Longest Path in a Directed Acyclic Graph"
},
{
"code": null,
"e": 11490,
"s": 11462,
"text": "Water Jug problem using BFS"
}
] |
turtle.title() function in Python
|
26 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to set the title of turtle-window. It requires only one argument as “titlestring” a string, to appear in the titlebar of the turtle graphics window. In other words, it is a string to display the title of the turtle window. By default title of the turtle graphics window is “Python Turtle Graphics”.
Syntax :
turtle.title()
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle # make turtle object # and set sizesc = turtle.Screen()sc.setup(400,300)
Output :
Example 2 :
Python3
# import packageimport turtle # make turtle object # and set sizesc = turtle.Screen()sc.setup(400,300) # set turtle screen titleturtle.title("Turtle Window For GFG")
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jul, 2020"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 566,
"s": 245,
"text": "This function is used to set the title of turtle-window. It requires only one argument as “titlestring” a string, to appear in the titlebar of the turtle graphics window. In other words, it is a string to display the title of the turtle window. By default title of the turtle graphics window is “Python Turtle Graphics”."
},
{
"code": null,
"e": 575,
"s": 566,
"text": "Syntax :"
},
{
"code": null,
"e": 591,
"s": 575,
"text": "turtle.title()\n"
},
{
"code": null,
"e": 660,
"s": 591,
"text": "Below is the implementation of the above method with some examples :"
},
{
"code": null,
"e": 672,
"s": 660,
"text": "Example 1 :"
},
{
"code": null,
"e": 680,
"s": 672,
"text": "Python3"
},
{
"code": "# import packageimport turtle # make turtle object # and set sizesc = turtle.Screen()sc.setup(400,300)",
"e": 786,
"s": 680,
"text": null
},
{
"code": null,
"e": 795,
"s": 786,
"text": "Output :"
},
{
"code": null,
"e": 807,
"s": 795,
"text": "Example 2 :"
},
{
"code": null,
"e": 815,
"s": 807,
"text": "Python3"
},
{
"code": "# import packageimport turtle # make turtle object # and set sizesc = turtle.Screen()sc.setup(400,300) # set turtle screen titleturtle.title(\"Turtle Window For GFG\")",
"e": 985,
"s": 815,
"text": null
},
{
"code": null,
"e": 994,
"s": 985,
"text": "Output :"
},
{
"code": null,
"e": 1008,
"s": 994,
"text": "Python-turtle"
},
{
"code": null,
"e": 1015,
"s": 1008,
"text": "Python"
},
{
"code": null,
"e": 1113,
"s": 1015,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1145,
"s": 1113,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1172,
"s": 1145,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1193,
"s": 1172,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1216,
"s": 1193,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1272,
"s": 1216,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1303,
"s": 1272,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1345,
"s": 1303,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1387,
"s": 1345,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1426,
"s": 1387,
"text": "Python | datetime.timedelta() function"
}
] |
Queue in Java
|
The queue interface is provided in java.util package and it implements the Collection interface. The queue implements FIFO i.e. First In First Out. This means that the elements entered first are the ones that are deleted first.
A program that demonstrates queue in Java is given as follows −
Live Demo
import java.util.LinkedList;
import java.util.Queue;
public class Example {
public static void main(String[] args) {
Queue<Integer> q = new LinkedList<>();
q.add(6);
q.add(1);
q.add(8);
q.add(4);
q.add(7);
System.out.println("The queue is: " + q);
int num1 = q.remove();
System.out.println("The element deleted from the head is: " + num1);
System.out.println("The queue after deletion is: " + q);
int head = q.peek();
System.out.println("The head of the queue is: " + head);
int size = q.size();
System.out.println("The size of the queue is: " + size);
}
}
The queue is: [6, 1, 8, 4, 7]
The element deleted from the head is: 6
The queue after deletion is: [1, 8, 4, 7]
The head of the queue is: 1
The size of the queue is: 4
Now let us understand the above program.
Five elements are inserted in the queue. Then the queue is displayed. The code snippet that demonstrates this is given as follows −
Queue<Integer> q = new LinkedList<>();
q.add(6);
q.add(1);
q.add(8);
q.add(4);
q.add(7);
System.out.println("The queue is: " + q);
The element from the head of the queue is deleted and it is displayed. Then the size of the queue is displayed. The code snippet that demonstrates this is given as follows −
int num1 = q.remove();
System.out.println("The element deleted from the head is: " + num1);
System.out.println("The queue after deletion is: " + q);
int head = q.peek();
System.out.println("The head of the queue is: " + head);
int size = q.size();
System.out.println("The size of the queue is: " + size);
|
[
{
"code": null,
"e": 1415,
"s": 1187,
"text": "The queue interface is provided in java.util package and it implements the Collection interface. The queue implements FIFO i.e. First In First Out. This means that the elements entered first are the ones that are deleted first."
},
{
"code": null,
"e": 1479,
"s": 1415,
"text": "A program that demonstrates queue in Java is given as follows −"
},
{
"code": null,
"e": 1490,
"s": 1479,
"text": " Live Demo"
},
{
"code": null,
"e": 2098,
"s": 1490,
"text": "import java.util.LinkedList;\nimport java.util.Queue;\npublic class Example {\n public static void main(String[] args) {\n Queue<Integer> q = new LinkedList<>();\n q.add(6);\n q.add(1);\n q.add(8);\n q.add(4);\n q.add(7);\n System.out.println(\"The queue is: \" + q);\n int num1 = q.remove();\nSystem.out.println(\"The element deleted from the head is: \" + num1);\nSystem.out.println(\"The queue after deletion is: \" + q);\nint head = q.peek();\nSystem.out.println(\"The head of the queue is: \" + head);\nint size = q.size();\nSystem.out.println(\"The size of the queue is: \" + size);\n}\n}"
},
{
"code": null,
"e": 2266,
"s": 2098,
"text": "The queue is: [6, 1, 8, 4, 7]\nThe element deleted from the head is: 6\nThe queue after deletion is: [1, 8, 4, 7]\nThe head of the queue is: 1\nThe size of the queue is: 4"
},
{
"code": null,
"e": 2307,
"s": 2266,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2439,
"s": 2307,
"text": "Five elements are inserted in the queue. Then the queue is displayed. The code snippet that demonstrates this is given as follows −"
},
{
"code": null,
"e": 2570,
"s": 2439,
"text": "Queue<Integer> q = new LinkedList<>();\nq.add(6);\nq.add(1);\nq.add(8);\nq.add(4);\nq.add(7);\nSystem.out.println(\"The queue is: \" + q);"
},
{
"code": null,
"e": 2744,
"s": 2570,
"text": "The element from the head of the queue is deleted and it is displayed. Then the size of the queue is displayed. The code snippet that demonstrates this is given as follows −"
},
{
"code": null,
"e": 3049,
"s": 2744,
"text": "int num1 = q.remove();\nSystem.out.println(\"The element deleted from the head is: \" + num1);\nSystem.out.println(\"The queue after deletion is: \" + q);\nint head = q.peek();\nSystem.out.println(\"The head of the queue is: \" + head);\nint size = q.size();\nSystem.out.println(\"The size of the queue is: \" + size);"
}
] |
HTTP REST API Calls in ElectronJS
|
16 Jun, 2022
ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.
We already know about the importance of HTTP REST API’s in any system. They are used everywhere globally and there are dedicated resources available on the internet which cover everything regarding HTTP REST API’s, standards, and protocols in detail. Some of the more famous resources for HTTP REST are mentioned here and here. NodeJS provides extensive support for making HTTP REST API calls via built in modules and external packages. NodeJS provides us with built-in HTTP and HTTPS modules and some of the most famous npm packages used in NodeJS are axios, request and node-fetch. Since Electron is essentially a Node application, all of the above-mentioned packages are supported and can be used in Electron as well. For a short tutorial on how to use axios package in Electron for making REST API calls, Refer the article: Geo Information in ElectronJS. In addition to the above, Electron also provides us with a built-in net Module for this very purpose. The net module is used for issuing HTTP/HTTPS REST requests using Chromium’s native networking library. This tutorial will demonstrate how to make HTTP REST API calls in Electron using the net module and the advantages and features of the net module.
We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.The net Module is a client-side API in Electron for issuing HTTP/HTTPS requests. As mentioned above, It is similar to the HTTP and HTTPS modules of NodeJS but it uses Chromium’s native networking library instead of the NodeJS implementation and therefore offers better support for web proxies. Some other advantages of the net Module are:
Automatic management of system proxy configuration, support of the WPAD(Web Proxy Auto-Discovery) protocol and proxy pac configuration files.
Automatic tunneling of HTTPS requests.
Support for authenticating proxies using basic, digest, NTLM, Kerberos or negotiate authentication schemes.
Support for traffic monitoring proxies: Fiddler-like proxies used for access control and monitoring.
Project Structure:
Example: Follow the Steps given in Dynamic Styling in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to setup the Electron application remain the same. package.json:
{
"name": "electron-net",
"version": "1.0.0",
"description": "Making HTTP REST API Calls - net Module in Electron ",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"keywords": [
"electron"
],
"author": "Radhesh Khanna",
"license": "ISC",
"dependencies": {
"electron": "^8.3.0"
}
}
Output:
HTTP REST API Calls in Electron The net module in Electron is part of the Main Process. To import and use the net module in the Renderer Process, we will be using Electron remote module. In this tutorial, we have used httpbin.org which is a simple and free 3rd Party HTTP REST Request & Response Service. It provides sample HTTP REST API’s which are publicly available and do not require any authentication and authorization. It also provides many other features such as authentication tests, redirects, cookies, dynamic and randomized data, etc, through sample REST API’s. We will be making HTTP GET and HTTP POST Requests to this service for demonstration purposes using the net module. All the components used in the net Module including design and implementation such as Instance methods, Instance events and Instance properties are similar to NodeJS implementation. This net module can only be used after the ready event of the app module is emitted. This module is supported on all OS platforms and environments.
index.html: Add the following snippet in that file.
html
<h3>Making HTTP REST API Calls using net Module in Electron</h3> <button id="get"> Make Sample GET Request </button> <br><br> <button id="post"> Make Sample POST Request </button><!-- Adding Individual Renderer Process JS File --><script src="index.js"></script>
index.js: The Make Sample GET Request and Make Sample POST Request buttons do not have any functionality associated with them yet.
javascript
const electron = require('electron');// Importing the net Module from electron remoteconst net = electron.remote.net; var get = document.getElementById('get');get.addEventListener('click', () => { const request = net.request({ method: 'GET', protocol: 'http:', hostname: 'httpbin.org', path: '/get', redirect: 'follow' }); request.on('response', (response) => { console.log(`STATUS: ${response.statusCode}`); console.log(`HEADERS: ${JSON.stringify(response.headers)}`); response.on('data', (chunk) => { console.log(`BODY: ${chunk}`) }); }); request.on('finish', () => { console.log('Request is Finished') }); request.on('abort', () => { console.log('Request is Aborted') }); request.on('error', (error) => { console.log(`ERROR: ${JSON.stringify(error)}`) }); request.on('close', (error) => { console.log('Last Transaction has occurred') }); request.setHeader('Content-Type', 'application/json'); request.end();}); var post = document.getElementById('post');post.addEventListener('click', () => { var body = JSON.stringify({ key: 1 }); const request = net.request({ method: 'POST', protocol: 'http:', hostname: 'httpbin.org', path: '/post', redirect: 'follow' }); request.on('response', (response) => { console.log(`STATUS: ${response.statusCode}`); console.log(`HEADERS: ${JSON.stringify(response.headers)}`); response.on('data', (chunk) => { console.log(`BODY: ${chunk}`) }); }); request.on('finish', () => { console.log('Request is Finished') }); request.on('abort', () => { console.log('Request is Aborted') }); request.on('error', (error) => { console.log(`ERROR: ${JSON.stringify(error)}`) }); request.on('close', (error) => { console.log('Last Transaction has occurred') }); request.setHeader('Content-Type', 'application/json'); request.write(body, 'utf-8'); request.end();});
Explanation: The net module supports only one Instance method. This net.request(options) Instance method uses the ClientRequest Instance. Every call to this Instance method created and returns a new ClientRequest Instance. This instance method is used to issue both secure and insecure HTTP requests according to the specified protocol scheme in the options object. For more detailed information on the net.request() method. It takes in the following parameters.
Options: The Object/String This Parameter can take in an Object or just a simple String value. This represents the ClientRequest Constructor options and is directly forwarded to the ClientRequest Instance. If this parameter is a String, it is interpreted as the request URL. If it is an object, it is expected to fully specify an HTTP request as supported by the ClientRequest constructor.
All Instance methods, events, and properties further used in the above code are part of the ClientRequest Instance. The ClientRequest Instance makes the actual HTTP/HTTPS requests and it implements the Writable Stream interface and is therefore an EventEmitter. A detailed Explanation of the ClientRequest constructor options is given below. It supports the following parameters:
Method: This parameter specifies the HTTP request method. It defaults to the HTTP GET method.
URL: This parameter specifies the HTTP request URL. This parameter must be provided in the absolute form with the protocol specified as http: or https:. In case the protocol is not provided, no default value is set and hence the HTTP request will fail. For a simple HTTP GET request, specifying the method and the url parameters are sufficient to make the call. The URL parameter can further be dissected into other parameters as well.
Session: This parameter specifies the Electron Session Instance with which the request is associated.
Partition: String (Optional) This parameter specifies the name of the partition as derived from the Session Instance with which the request is associated. The default value is an empty string. If the session parameter and the partition parameter are defined together, the session parameter takes precedence. Thus if a session Instance is explicitly specified and passed, the partition parameter is ignored.
useSessionCookies: This parameter specifies whether to send cookies with this request as derived from the Session Instance. This will make the net modules request’s cookie behavior match a NodeJS fetch request. The default value is false.
Protocol: String (Optional) This parameter specifies the protocol scheme of the HTTP request. Currently supported values are http: or https:. The default value is http:. This parameter strictly follows the NodeJS model as described in the URL Module.
Host: This parameter specifies the server host i.e. the base URL provided as a concatenation of the hostname parameter and the port number parameter in the format of hostname:port as followed in the URL standards. This parameter strictly follows the NodeJS model as described in the URL Module.
Hostname: String (Optional) This parameter specifies the server host name. It can be a DNS (Domain Name Service) server name or an IP Address. This parameter strictly follows the NodeJS model as described in the URL Module.
Port: Integer (Optional) This parameter specifies the server’s listening port number. This parameter strictly follows the NodeJS model as described in the URL Module.
Path: String (Optional) This parameter specifies the path part of the request URL i.e. the part that follows after the base URL hostname/host/port parameters. This parameter can contain the Query String parameters or the path parameters as well that are required to be passed to the REST API. The Query String parameters are defined after the? With a key-value pair in the URL. This parameter strictly follows the NodeJS model as described in the URL Module.
redirect: String (Optional) This parameter defines the redirect mode for the HTTP request. It can hold any of the following values:follow Follows default behaviour of the HTTP request.error Aborts any or all redirections in the HTTP request.manual Cancels the Redirection unless the request.followRedirect() Instance method is invoked synchronously while the redirect Instance event is emitted.
follow Follows default behaviour of the HTTP request.
error Aborts any or all redirections in the HTTP request.
manual Cancels the Redirection unless the request.followRedirect() Instance method is invoked synchronously while the redirect Instance event is emitted.
The ClientRequest Instance supports the following Instance Events.
response: Event This Instance event is emitted when the HTTP request has been processed and returns a response from the REST API. This Instance event is emitted on the net module object (In this case, request object). It returns a single response: Object which represents the Incoming HTTP response packet which includes the HTTP Status, HTTP Headers, HTTP body, etc.
finish: Event This Instance event is emitted just after the last chunk of the HTTP request’s data has been received and written into the request object.
abort: Event This Instance event is emitted when the HTTP request is aborted. This event will not be emitted if the request is already closed i.e. the close Instance event has been fired.
error: Event This Instance event is emitted when the net module fails to issue an HTTP network request which can happen due to a variety of reasons such as Bad Gateway, No network connection, etc. Typically when the request object emits an error Instance event, a close Instance event is also emitted just after and no response object will be provided. This event returns an error object which contains some information about the failure of the HTTP request such as the HTTP status code, etc.
close: Event This Instance event is emitted as the last event in the HTTP request-response transaction after the Handshake is complete. This event indicates that no further events will be emitted on either the request or response objects and marks the transaction as complete.
Additionally, the ClientRequest Instance supports a single Instance Property.
request.chunkedEncoding This Instance property takes in a Boolean value. This property specifies whether the HTTP request will use HTTP chunked transfer encoding or not. This property can only be set before the first write operation i.e. before the request.write() Instance method as the HTTP headers are not yet put on the wire. Trying to set the chunkedEncoding property after the first write will throw an error. The default value is false. Using chunkedEncoding Instance property as true is strongly recommended if you need to send a large request body as data will be streamed in small chunks instead of being internally buffered inside Electron process memory.
Based on the ClientRequest constructor options and the Instance events and properties we have covered up till now, we notice that some critical parameters for HTTP requests are missing such as the headers and the body in case of the HTTP POST request. This is because these parameters were removed from the constructor options object from the previous versions of Electron and added as separate Instance methods in the newer versions. The ClientRequest Instance supports the following Instance Method.
request.setHeader(name, value) This Instance method is used to add an extra HTTP header or overwrite an existing header apart from default HTTP headers. The header name will be used as it is without lowercasing it. It can be called only before first write i.e. before the request.write() Instance method is called. Calling this method after the first write will throw an error. If the passed value is not a String, its toString() method will be called to obtain the final value before setting the headers in the HTTP request packet.
request.getHeader(name) This Instance method is used to return the value of the header as passed in the name: String parameter. The returned value is a string containing the value.
request.removeHeader(name) This Instance method is used to remove the header as passed in the name: String parameter. It can be called only before first write i.e. before the request.write() Instance method is called. Calling this method after the first write will throw an error. This method does not return any values.
request.write(chunk, encoding, callback) This Instance method adds a chunk of data to the request body. This Instance method is where we set the Body of the HTTP POST Request. The first write operation may cause the request headers to be issued on the wire. After the first write operation, it is not allowed to add or remove a custom header. It takes in the following parameters:chunk: String/Buffer A chunk of the request body’s data. If it is a String value, it is converted internally into a Buffer using the specified encoding in the encoding parameter.encoding: String (Optional) This parameter as mentioned above, is used to convert the chunk parameter String value into a Buffer object. The default value used for encoding is utf-8 which is the default encoding used when transferring HTTP requests over the wire.callback: Function (Optional) This callback function is essentially a dummy function introduced for the purpose of keeping similarity with the NodeJS API. It is called asynchronously after chunk content has been delivered to the Chromium networking layer.
chunk: String/Buffer A chunk of the request body’s data. If it is a String value, it is converted internally into a Buffer using the specified encoding in the encoding parameter.
encoding: String (Optional) This parameter as mentioned above, is used to convert the chunk parameter String value into a Buffer object. The default value used for encoding is utf-8 which is the default encoding used when transferring HTTP requests over the wire.
callback: Function (Optional) This callback function is essentially a dummy function introduced for the purpose of keeping similarity with the NodeJS API. It is called asynchronously after chunk content has been delivered to the Chromium networking layer.
request.abort() This Instance method if called, cancels an ongoing HTTP Transaction. If the close Instance event is already emitted, this Instance method will have no effect. Else abort and close Instance events are emitted. Additionally, if there is an ongoing response object, it will also emit the abort Instance event.
request.followRedirect() This Instance method continues and forces through any pending redirection of the HTTP request. This Instance method can only be called when a redirect Instance event is emitted.
At this point, upon launching the Electron application, we should be able to make Successful HTTP REST API calls to the httpbin.org HTTP Service, GET and POST Sample APIs and check the responses that we are getting from these APIs. Output:
clintra
nikhatkhan11
ElectronJS
HTML
JavaScript
Node.js
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
HTTP headers | Content-Type
How to Insert Form Data into Database using PHP ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime."
},
{
"code": null,
"e": 1541,
"s": 328,
"text": "We already know about the importance of HTTP REST API’s in any system. They are used everywhere globally and there are dedicated resources available on the internet which cover everything regarding HTTP REST API’s, standards, and protocols in detail. Some of the more famous resources for HTTP REST are mentioned here and here. NodeJS provides extensive support for making HTTP REST API calls via built in modules and external packages. NodeJS provides us with built-in HTTP and HTTPS modules and some of the most famous npm packages used in NodeJS are axios, request and node-fetch. Since Electron is essentially a Node application, all of the above-mentioned packages are supported and can be used in Electron as well. For a short tutorial on how to use axios package in Electron for making REST API calls, Refer the article: Geo Information in ElectronJS. In addition to the above, Electron also provides us with a built-in net Module for this very purpose. The net module is used for issuing HTTP/HTTPS REST requests using Chromium’s native networking library. This tutorial will demonstrate how to make HTTP REST API calls in Electron using the net module and the advantages and features of the net module. "
},
{
"code": null,
"e": 2050,
"s": 1541,
"text": "We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.The net Module is a client-side API in Electron for issuing HTTP/HTTPS requests. As mentioned above, It is similar to the HTTP and HTTPS modules of NodeJS but it uses Chromium’s native networking library instead of the NodeJS implementation and therefore offers better support for web proxies. Some other advantages of the net Module are: "
},
{
"code": null,
"e": 2192,
"s": 2050,
"text": "Automatic management of system proxy configuration, support of the WPAD(Web Proxy Auto-Discovery) protocol and proxy pac configuration files."
},
{
"code": null,
"e": 2231,
"s": 2192,
"text": "Automatic tunneling of HTTPS requests."
},
{
"code": null,
"e": 2339,
"s": 2231,
"text": "Support for authenticating proxies using basic, digest, NTLM, Kerberos or negotiate authentication schemes."
},
{
"code": null,
"e": 2440,
"s": 2339,
"text": "Support for traffic monitoring proxies: Fiddler-like proxies used for access control and monitoring."
},
{
"code": null,
"e": 2463,
"s": 2442,
"text": "Project Structure: "
},
{
"code": null,
"e": 2935,
"s": 2463,
"text": "Example: Follow the Steps given in Dynamic Styling in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to setup the Electron application remain the same. package.json: "
},
{
"code": null,
"e": 3262,
"s": 2935,
"text": "{\n \"name\": \"electron-net\",\n \"version\": \"1.0.0\",\n \"description\": \"Making HTTP REST API Calls - net Module in Electron \",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.3.0\"\n }\n}"
},
{
"code": null,
"e": 3271,
"s": 3262,
"text": "Output: "
},
{
"code": null,
"e": 4290,
"s": 3271,
"text": "HTTP REST API Calls in Electron The net module in Electron is part of the Main Process. To import and use the net module in the Renderer Process, we will be using Electron remote module. In this tutorial, we have used httpbin.org which is a simple and free 3rd Party HTTP REST Request & Response Service. It provides sample HTTP REST API’s which are publicly available and do not require any authentication and authorization. It also provides many other features such as authentication tests, redirects, cookies, dynamic and randomized data, etc, through sample REST API’s. We will be making HTTP GET and HTTP POST Requests to this service for demonstration purposes using the net module. All the components used in the net Module including design and implementation such as Instance methods, Instance events and Instance properties are similar to NodeJS implementation. This net module can only be used after the ready event of the app module is emitted. This module is supported on all OS platforms and environments."
},
{
"code": null,
"e": 4342,
"s": 4290,
"text": "index.html: Add the following snippet in that file."
},
{
"code": null,
"e": 4347,
"s": 4342,
"text": "html"
},
{
"code": "<h3>Making HTTP REST API Calls using net Module in Electron</h3> <button id=\"get\"> Make Sample GET Request </button> <br><br> <button id=\"post\"> Make Sample POST Request </button><!-- Adding Individual Renderer Process JS File --><script src=\"index.js\"></script>",
"e": 4628,
"s": 4347,
"text": null
},
{
"code": null,
"e": 4762,
"s": 4631,
"text": "index.js: The Make Sample GET Request and Make Sample POST Request buttons do not have any functionality associated with them yet."
},
{
"code": null,
"e": 4775,
"s": 4764,
"text": "javascript"
},
{
"code": "const electron = require('electron');// Importing the net Module from electron remoteconst net = electron.remote.net; var get = document.getElementById('get');get.addEventListener('click', () => { const request = net.request({ method: 'GET', protocol: 'http:', hostname: 'httpbin.org', path: '/get', redirect: 'follow' }); request.on('response', (response) => { console.log(`STATUS: ${response.statusCode}`); console.log(`HEADERS: ${JSON.stringify(response.headers)}`); response.on('data', (chunk) => { console.log(`BODY: ${chunk}`) }); }); request.on('finish', () => { console.log('Request is Finished') }); request.on('abort', () => { console.log('Request is Aborted') }); request.on('error', (error) => { console.log(`ERROR: ${JSON.stringify(error)}`) }); request.on('close', (error) => { console.log('Last Transaction has occurred') }); request.setHeader('Content-Type', 'application/json'); request.end();}); var post = document.getElementById('post');post.addEventListener('click', () => { var body = JSON.stringify({ key: 1 }); const request = net.request({ method: 'POST', protocol: 'http:', hostname: 'httpbin.org', path: '/post', redirect: 'follow' }); request.on('response', (response) => { console.log(`STATUS: ${response.statusCode}`); console.log(`HEADERS: ${JSON.stringify(response.headers)}`); response.on('data', (chunk) => { console.log(`BODY: ${chunk}`) }); }); request.on('finish', () => { console.log('Request is Finished') }); request.on('abort', () => { console.log('Request is Aborted') }); request.on('error', (error) => { console.log(`ERROR: ${JSON.stringify(error)}`) }); request.on('close', (error) => { console.log('Last Transaction has occurred') }); request.setHeader('Content-Type', 'application/json'); request.write(body, 'utf-8'); request.end();});",
"e": 6855,
"s": 4775,
"text": null
},
{
"code": null,
"e": 7319,
"s": 6855,
"text": "Explanation: The net module supports only one Instance method. This net.request(options) Instance method uses the ClientRequest Instance. Every call to this Instance method created and returns a new ClientRequest Instance. This instance method is used to issue both secure and insecure HTTP requests according to the specified protocol scheme in the options object. For more detailed information on the net.request() method. It takes in the following parameters. "
},
{
"code": null,
"e": 7709,
"s": 7319,
"text": "Options: The Object/String This Parameter can take in an Object or just a simple String value. This represents the ClientRequest Constructor options and is directly forwarded to the ClientRequest Instance. If this parameter is a String, it is interpreted as the request URL. If it is an object, it is expected to fully specify an HTTP request as supported by the ClientRequest constructor."
},
{
"code": null,
"e": 8090,
"s": 7709,
"text": "All Instance methods, events, and properties further used in the above code are part of the ClientRequest Instance. The ClientRequest Instance makes the actual HTTP/HTTPS requests and it implements the Writable Stream interface and is therefore an EventEmitter. A detailed Explanation of the ClientRequest constructor options is given below. It supports the following parameters: "
},
{
"code": null,
"e": 8184,
"s": 8090,
"text": "Method: This parameter specifies the HTTP request method. It defaults to the HTTP GET method."
},
{
"code": null,
"e": 8620,
"s": 8184,
"text": "URL: This parameter specifies the HTTP request URL. This parameter must be provided in the absolute form with the protocol specified as http: or https:. In case the protocol is not provided, no default value is set and hence the HTTP request will fail. For a simple HTTP GET request, specifying the method and the url parameters are sufficient to make the call. The URL parameter can further be dissected into other parameters as well."
},
{
"code": null,
"e": 8722,
"s": 8620,
"text": "Session: This parameter specifies the Electron Session Instance with which the request is associated."
},
{
"code": null,
"e": 9129,
"s": 8722,
"text": "Partition: String (Optional) This parameter specifies the name of the partition as derived from the Session Instance with which the request is associated. The default value is an empty string. If the session parameter and the partition parameter are defined together, the session parameter takes precedence. Thus if a session Instance is explicitly specified and passed, the partition parameter is ignored."
},
{
"code": null,
"e": 9368,
"s": 9129,
"text": "useSessionCookies: This parameter specifies whether to send cookies with this request as derived from the Session Instance. This will make the net modules request’s cookie behavior match a NodeJS fetch request. The default value is false."
},
{
"code": null,
"e": 9619,
"s": 9368,
"text": "Protocol: String (Optional) This parameter specifies the protocol scheme of the HTTP request. Currently supported values are http: or https:. The default value is http:. This parameter strictly follows the NodeJS model as described in the URL Module."
},
{
"code": null,
"e": 9914,
"s": 9619,
"text": "Host: This parameter specifies the server host i.e. the base URL provided as a concatenation of the hostname parameter and the port number parameter in the format of hostname:port as followed in the URL standards. This parameter strictly follows the NodeJS model as described in the URL Module."
},
{
"code": null,
"e": 10138,
"s": 9914,
"text": "Hostname: String (Optional) This parameter specifies the server host name. It can be a DNS (Domain Name Service) server name or an IP Address. This parameter strictly follows the NodeJS model as described in the URL Module."
},
{
"code": null,
"e": 10305,
"s": 10138,
"text": "Port: Integer (Optional) This parameter specifies the server’s listening port number. This parameter strictly follows the NodeJS model as described in the URL Module."
},
{
"code": null,
"e": 10764,
"s": 10305,
"text": "Path: String (Optional) This parameter specifies the path part of the request URL i.e. the part that follows after the base URL hostname/host/port parameters. This parameter can contain the Query String parameters or the path parameters as well that are required to be passed to the REST API. The Query String parameters are defined after the? With a key-value pair in the URL. This parameter strictly follows the NodeJS model as described in the URL Module."
},
{
"code": null,
"e": 11159,
"s": 10764,
"text": "redirect: String (Optional) This parameter defines the redirect mode for the HTTP request. It can hold any of the following values:follow Follows default behaviour of the HTTP request.error Aborts any or all redirections in the HTTP request.manual Cancels the Redirection unless the request.followRedirect() Instance method is invoked synchronously while the redirect Instance event is emitted."
},
{
"code": null,
"e": 11213,
"s": 11159,
"text": "follow Follows default behaviour of the HTTP request."
},
{
"code": null,
"e": 11271,
"s": 11213,
"text": "error Aborts any or all redirections in the HTTP request."
},
{
"code": null,
"e": 11425,
"s": 11271,
"text": "manual Cancels the Redirection unless the request.followRedirect() Instance method is invoked synchronously while the redirect Instance event is emitted."
},
{
"code": null,
"e": 11493,
"s": 11425,
"text": "The ClientRequest Instance supports the following Instance Events. "
},
{
"code": null,
"e": 11861,
"s": 11493,
"text": "response: Event This Instance event is emitted when the HTTP request has been processed and returns a response from the REST API. This Instance event is emitted on the net module object (In this case, request object). It returns a single response: Object which represents the Incoming HTTP response packet which includes the HTTP Status, HTTP Headers, HTTP body, etc."
},
{
"code": null,
"e": 12014,
"s": 11861,
"text": "finish: Event This Instance event is emitted just after the last chunk of the HTTP request’s data has been received and written into the request object."
},
{
"code": null,
"e": 12202,
"s": 12014,
"text": "abort: Event This Instance event is emitted when the HTTP request is aborted. This event will not be emitted if the request is already closed i.e. the close Instance event has been fired."
},
{
"code": null,
"e": 12695,
"s": 12202,
"text": "error: Event This Instance event is emitted when the net module fails to issue an HTTP network request which can happen due to a variety of reasons such as Bad Gateway, No network connection, etc. Typically when the request object emits an error Instance event, a close Instance event is also emitted just after and no response object will be provided. This event returns an error object which contains some information about the failure of the HTTP request such as the HTTP status code, etc."
},
{
"code": null,
"e": 12972,
"s": 12695,
"text": "close: Event This Instance event is emitted as the last event in the HTTP request-response transaction after the Handshake is complete. This event indicates that no further events will be emitted on either the request or response objects and marks the transaction as complete."
},
{
"code": null,
"e": 13051,
"s": 12972,
"text": "Additionally, the ClientRequest Instance supports a single Instance Property. "
},
{
"code": null,
"e": 13718,
"s": 13051,
"text": "request.chunkedEncoding This Instance property takes in a Boolean value. This property specifies whether the HTTP request will use HTTP chunked transfer encoding or not. This property can only be set before the first write operation i.e. before the request.write() Instance method as the HTTP headers are not yet put on the wire. Trying to set the chunkedEncoding property after the first write will throw an error. The default value is false. Using chunkedEncoding Instance property as true is strongly recommended if you need to send a large request body as data will be streamed in small chunks instead of being internally buffered inside Electron process memory."
},
{
"code": null,
"e": 14221,
"s": 13718,
"text": "Based on the ClientRequest constructor options and the Instance events and properties we have covered up till now, we notice that some critical parameters for HTTP requests are missing such as the headers and the body in case of the HTTP POST request. This is because these parameters were removed from the constructor options object from the previous versions of Electron and added as separate Instance methods in the newer versions. The ClientRequest Instance supports the following Instance Method. "
},
{
"code": null,
"e": 14754,
"s": 14221,
"text": "request.setHeader(name, value) This Instance method is used to add an extra HTTP header or overwrite an existing header apart from default HTTP headers. The header name will be used as it is without lowercasing it. It can be called only before first write i.e. before the request.write() Instance method is called. Calling this method after the first write will throw an error. If the passed value is not a String, its toString() method will be called to obtain the final value before setting the headers in the HTTP request packet."
},
{
"code": null,
"e": 14935,
"s": 14754,
"text": "request.getHeader(name) This Instance method is used to return the value of the header as passed in the name: String parameter. The returned value is a string containing the value."
},
{
"code": null,
"e": 15256,
"s": 14935,
"text": "request.removeHeader(name) This Instance method is used to remove the header as passed in the name: String parameter. It can be called only before first write i.e. before the request.write() Instance method is called. Calling this method after the first write will throw an error. This method does not return any values."
},
{
"code": null,
"e": 16333,
"s": 15256,
"text": "request.write(chunk, encoding, callback) This Instance method adds a chunk of data to the request body. This Instance method is where we set the Body of the HTTP POST Request. The first write operation may cause the request headers to be issued on the wire. After the first write operation, it is not allowed to add or remove a custom header. It takes in the following parameters:chunk: String/Buffer A chunk of the request body’s data. If it is a String value, it is converted internally into a Buffer using the specified encoding in the encoding parameter.encoding: String (Optional) This parameter as mentioned above, is used to convert the chunk parameter String value into a Buffer object. The default value used for encoding is utf-8 which is the default encoding used when transferring HTTP requests over the wire.callback: Function (Optional) This callback function is essentially a dummy function introduced for the purpose of keeping similarity with the NodeJS API. It is called asynchronously after chunk content has been delivered to the Chromium networking layer."
},
{
"code": null,
"e": 16512,
"s": 16333,
"text": "chunk: String/Buffer A chunk of the request body’s data. If it is a String value, it is converted internally into a Buffer using the specified encoding in the encoding parameter."
},
{
"code": null,
"e": 16776,
"s": 16512,
"text": "encoding: String (Optional) This parameter as mentioned above, is used to convert the chunk parameter String value into a Buffer object. The default value used for encoding is utf-8 which is the default encoding used when transferring HTTP requests over the wire."
},
{
"code": null,
"e": 17032,
"s": 16776,
"text": "callback: Function (Optional) This callback function is essentially a dummy function introduced for the purpose of keeping similarity with the NodeJS API. It is called asynchronously after chunk content has been delivered to the Chromium networking layer."
},
{
"code": null,
"e": 17355,
"s": 17032,
"text": "request.abort() This Instance method if called, cancels an ongoing HTTP Transaction. If the close Instance event is already emitted, this Instance method will have no effect. Else abort and close Instance events are emitted. Additionally, if there is an ongoing response object, it will also emit the abort Instance event."
},
{
"code": null,
"e": 17558,
"s": 17355,
"text": "request.followRedirect() This Instance method continues and forces through any pending redirection of the HTTP request. This Instance method can only be called when a redirect Instance event is emitted."
},
{
"code": null,
"e": 17799,
"s": 17558,
"text": "At this point, upon launching the Electron application, we should be able to make Successful HTTP REST API calls to the httpbin.org HTTP Service, GET and POST Sample APIs and check the responses that we are getting from these APIs. Output: "
},
{
"code": null,
"e": 17809,
"s": 17801,
"text": "clintra"
},
{
"code": null,
"e": 17822,
"s": 17809,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 17833,
"s": 17822,
"text": "ElectronJS"
},
{
"code": null,
"e": 17838,
"s": 17833,
"text": "HTML"
},
{
"code": null,
"e": 17849,
"s": 17838,
"text": "JavaScript"
},
{
"code": null,
"e": 17857,
"s": 17849,
"text": "Node.js"
},
{
"code": null,
"e": 17874,
"s": 17857,
"text": "Web Technologies"
},
{
"code": null,
"e": 17879,
"s": 17874,
"text": "HTML"
},
{
"code": null,
"e": 17977,
"s": 17879,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 18001,
"s": 17977,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 18038,
"s": 18001,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 18077,
"s": 18038,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 18105,
"s": 18077,
"text": "HTTP headers | Content-Type"
},
{
"code": null,
"e": 18155,
"s": 18105,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 18216,
"s": 18155,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 18288,
"s": 18216,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 18328,
"s": 18288,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 18369,
"s": 18328,
"text": "Difference Between PUT and PATCH Request"
}
] |
How to reverse column order in a matrix with Python?
|
08 Sep, 2021
In this article, we will see how to reverse the column order of a matrix in Python.
Examples:
Input:
arr = [[10,20,30],
[40,50,60],
[70,80,90]]
Output:
30 20 10
60 50 40
90 80 70
Input:
arr = [[15,30],
[45,60],
[75,90],
[105,120]]
Output:
30 15
60 45
90 75
120 105
Matrices are created in python by using nested lists/arrays. However, a more efficient way to handle arrays in python is the NumPy library. To create arrays using NumPy use this or matrix in python once go through this.
Method 1:
Iterate through each rowFor every row, use list comprehension to reverse the row (i.e. a[::-1])Append the reversed rows into a new matrixPrint the matrix
Iterate through each row
For every row, use list comprehension to reverse the row (i.e. a[::-1])
Append the reversed rows into a new matrix
Print the matrix
Example:
Python3
# creating a 3X4 matrix using nested listsmatrix_1 = [['c1', 'c2', 'c3'], [10, 20, 30], [40, 50, 60], [70, 80, 90]] # creating an empty array to store the reversed column matrixmatrix_2 = [] # looping through matrix_1 and appending matrix_2for i in range(len(matrix_1)): matrix_2.append(matrix_1[i][::-1]) print('Matrix before changing column order:\n')for rows in matrix_1: print(rows)print('\nMatrix after changing column order:\n')for rows in matrix_2: print(rows)
Output:
Method 2:
An array object in NumPy is called ndarray, which is created using the array() function. To reverse column order in a matrix, we make use of the numpy.fliplr() method. The method flips the entries in each row in the left/right direction. Column data is preserved but appears in a different order than before.
Syntax: numpy.fliplr(m)
Parameters: m (array_like) – Input array must be at least 2-D.
Returned Value: ndarray – A view of m is returned with the columns reversed, and this operation’s time complexity is O(1).
Example:
Python3
import numpy as np # creating a numpy array(matrix) with 3-columns and 4-rowsarr = np.array([ ['c1', 'c2', 'c3'], [10, 20, 30], [40, 50, 60], [70, 80, 90]]) # reversing column order in matrixflipped_arr = np.fliplr(arr) print('Array before changing column order:\n', arr)print('\nArray after changing column order:\n', flipped_arr)
Output:
Flipped_arr contains a reversed column order matrix where the column order has changed from c1,c2,c3 to c3,c2,c1, and the elements of each column remain intact under their respective headers (c1,c2,c3).
adnanirshad158
Picked
Python-Matrix
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Sep, 2021"
},
{
"code": null,
"e": 112,
"s": 28,
"text": "In this article, we will see how to reverse the column order of a matrix in Python."
},
{
"code": null,
"e": 122,
"s": 112,
"text": "Examples:"
},
{
"code": null,
"e": 332,
"s": 122,
"text": "Input: \narr = [[10,20,30],\n [40,50,60],\n [70,80,90]]\nOutput:\n30 20 10 \n60 50 40\n90 80 70 \n\nInput:\narr = [[15,30],\n [45,60],\n [75,90],\n [105,120]]\nOutput:\n30 15\n60 45\n90 75\n120 105"
},
{
"code": null,
"e": 552,
"s": 332,
"text": "Matrices are created in python by using nested lists/arrays. However, a more efficient way to handle arrays in python is the NumPy library. To create arrays using NumPy use this or matrix in python once go through this."
},
{
"code": null,
"e": 562,
"s": 552,
"text": "Method 1:"
},
{
"code": null,
"e": 716,
"s": 562,
"text": "Iterate through each rowFor every row, use list comprehension to reverse the row (i.e. a[::-1])Append the reversed rows into a new matrixPrint the matrix"
},
{
"code": null,
"e": 741,
"s": 716,
"text": "Iterate through each row"
},
{
"code": null,
"e": 813,
"s": 741,
"text": "For every row, use list comprehension to reverse the row (i.e. a[::-1])"
},
{
"code": null,
"e": 856,
"s": 813,
"text": "Append the reversed rows into a new matrix"
},
{
"code": null,
"e": 873,
"s": 856,
"text": "Print the matrix"
},
{
"code": null,
"e": 882,
"s": 873,
"text": "Example:"
},
{
"code": null,
"e": 890,
"s": 882,
"text": "Python3"
},
{
"code": "# creating a 3X4 matrix using nested listsmatrix_1 = [['c1', 'c2', 'c3'], [10, 20, 30], [40, 50, 60], [70, 80, 90]] # creating an empty array to store the reversed column matrixmatrix_2 = [] # looping through matrix_1 and appending matrix_2for i in range(len(matrix_1)): matrix_2.append(matrix_1[i][::-1]) print('Matrix before changing column order:\\n')for rows in matrix_1: print(rows)print('\\nMatrix after changing column order:\\n')for rows in matrix_2: print(rows)",
"e": 1400,
"s": 890,
"text": null
},
{
"code": null,
"e": 1408,
"s": 1400,
"text": "Output:"
},
{
"code": null,
"e": 1418,
"s": 1408,
"text": "Method 2:"
},
{
"code": null,
"e": 1727,
"s": 1418,
"text": "An array object in NumPy is called ndarray, which is created using the array() function. To reverse column order in a matrix, we make use of the numpy.fliplr() method. The method flips the entries in each row in the left/right direction. Column data is preserved but appears in a different order than before."
},
{
"code": null,
"e": 1752,
"s": 1727,
"text": "Syntax: numpy.fliplr(m)"
},
{
"code": null,
"e": 1815,
"s": 1752,
"text": "Parameters: m (array_like) – Input array must be at least 2-D."
},
{
"code": null,
"e": 1938,
"s": 1815,
"text": "Returned Value: ndarray – A view of m is returned with the columns reversed, and this operation’s time complexity is O(1)."
},
{
"code": null,
"e": 1947,
"s": 1938,
"text": "Example:"
},
{
"code": null,
"e": 1955,
"s": 1947,
"text": "Python3"
},
{
"code": "import numpy as np # creating a numpy array(matrix) with 3-columns and 4-rowsarr = np.array([ ['c1', 'c2', 'c3'], [10, 20, 30], [40, 50, 60], [70, 80, 90]]) # reversing column order in matrixflipped_arr = np.fliplr(arr) print('Array before changing column order:\\n', arr)print('\\nArray after changing column order:\\n', flipped_arr)",
"e": 2299,
"s": 1955,
"text": null
},
{
"code": null,
"e": 2307,
"s": 2299,
"text": "Output:"
},
{
"code": null,
"e": 2510,
"s": 2307,
"text": "Flipped_arr contains a reversed column order matrix where the column order has changed from c1,c2,c3 to c3,c2,c1, and the elements of each column remain intact under their respective headers (c1,c2,c3)."
},
{
"code": null,
"e": 2525,
"s": 2510,
"text": "adnanirshad158"
},
{
"code": null,
"e": 2532,
"s": 2525,
"text": "Picked"
},
{
"code": null,
"e": 2546,
"s": 2532,
"text": "Python-Matrix"
},
{
"code": null,
"e": 2553,
"s": 2546,
"text": "Python"
},
{
"code": null,
"e": 2651,
"s": 2553,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2696,
"s": 2651,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 2746,
"s": 2696,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 2762,
"s": 2746,
"text": "Deque in Python"
},
{
"code": null,
"e": 2778,
"s": 2762,
"text": "Queue in Python"
},
{
"code": null,
"e": 2800,
"s": 2778,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2842,
"s": 2800,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2869,
"s": 2842,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2892,
"s": 2869,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 2911,
"s": 2892,
"text": "reduce() in Python"
}
] |
How to declare a multi dimensional dictionary in Python?
|
Let us declare three dictionary objects as below −
>>> d1={"name":"Ravi","age":25, "marks":60}
>>> d2={"name":"Anil","age":23, "marks":75}
>>> d3={"name":"Asha", "age":20, "marks":70}
Now we shall use them as values in a parent dictionary
>>>twodimdict={1:d1,2:d2,3:d3}
>>>twodimdict
{1: {'name': 'Ravi', 'age': 25, 'marks': 60}, 2: {'name': 'Anil', 'age': 23, 'marks': 75}, 3: {'name': 'Asha', 'age': 20, 'marks': 70}}
Here d1, d2 and d3 are assigned as value to keys 1,2,3
twodimdict [1] returns d1. Value of a key inside d1 can be obtained as below −
>>>twodimdict[1]
{'name': 'Ravi', 'age': 25, 'marks': 60}
>>>twodimdict[1]["age"]
25
Note that the dictionary items are not indexed.
|
[
{
"code": null,
"e": 1238,
"s": 1187,
"text": "Let us declare three dictionary objects as below −"
},
{
"code": null,
"e": 1371,
"s": 1238,
"text": ">>> d1={\"name\":\"Ravi\",\"age\":25, \"marks\":60}\n>>> d2={\"name\":\"Anil\",\"age\":23, \"marks\":75}\n>>> d3={\"name\":\"Asha\", \"age\":20, \"marks\":70}"
},
{
"code": null,
"e": 1426,
"s": 1371,
"text": "Now we shall use them as values in a parent dictionary"
},
{
"code": null,
"e": 1607,
"s": 1426,
"text": ">>>twodimdict={1:d1,2:d2,3:d3}\n>>>twodimdict\n{1: {'name': 'Ravi', 'age': 25, 'marks': 60}, 2: {'name': 'Anil', 'age': 23, 'marks': 75}, 3: {'name': 'Asha', 'age': 20, 'marks': 70}}"
},
{
"code": null,
"e": 1662,
"s": 1607,
"text": "Here d1, d2 and d3 are assigned as value to keys 1,2,3"
},
{
"code": null,
"e": 1741,
"s": 1662,
"text": "twodimdict [1] returns d1. Value of a key inside d1 can be obtained as below −"
},
{
"code": null,
"e": 1826,
"s": 1741,
"text": ">>>twodimdict[1]\n{'name': 'Ravi', 'age': 25, 'marks': 60}\n>>>twodimdict[1][\"age\"]\n25"
},
{
"code": null,
"e": 1874,
"s": 1826,
"text": "Note that the dictionary items are not indexed."
}
] |
Serialize and Deserialize a Binary Tree
|
23 Jun, 2022
Serialization is to store tree in a file so that it can be later restored. The structure of tree must be maintained. Deserialization is reading tree back from file.
Following are some simpler versions of the problem:
If given Tree is Binary Search Tree? If the given Binary Tree is Binary Search Tree, we can store it by either storing preorder or postorder traversal. In case of Binary Search Trees, only preorder or postorder traversal is sufficient to store structure information.
If given Binary Tree is Complete Tree? A Binary Tree is complete if all levels are completely filled except possibly the last level and all nodes of last level are as left as possible (Binary Heaps are complete Binary Tree). For a complete Binary Tree, level order traversal is sufficient to store the tree. We know that the first node is root, next two nodes are nodes of next level, next four nodes are nodes of 2nd level and so on.
If given Binary Tree is Full Tree? A full Binary is a Binary Tree where every node has either 0 or 2 children. It is easy to serialize such trees as every internal node has 2 children. We can simply store preorder traversal and store a bit with every node to indicate whether the node is an internal node or a leaf node.
How to store a general Binary Tree? A simple solution is to store both Inorder and Preorder traversals. This solution requires space twice the size of Binary Tree. We can save space by storing Preorder traversal and a marker for NULL pointers.
Let the marker for NULL pointers be '-1'
Input:
12
/
13
Output: 12 13 -1 -1 -1
Input:
20
/ \
8 22
Output: 20 8 -1 -1 22 -1 -1
Input:
20
/
8
/ \
4 12
/ \
10 14
Output: 20 8 4 -1 -1 12 10 -1 -1 14 -1 -1 -1
Input:
20
/
8
/
10
/
5
Output: 20 8 10 5 -1 -1 -1 -1 -1
Input:
20
\
8
\
10
\
5
Output: 20 -1 8 -1 10 -1 5 -1 -1
Deserialization can be done by simply reading data from file one by one.
Following is the implementation of the above idea.
C++
Java
// A C++ program to demonstrate serialization and deserialization of// Binary Tree#include <iostream>#define MARKER -1 /* A binary tree Node has key, pointer to left and right children */struct Node{ int key; struct Node* left, *right;}; /* Helper function that allocates a new Node with the given key and NULL left and right pointers. */struct Node* newNode(int key){ struct Node* temp = new Node(); temp->key = key; temp->left = temp->right = NULL; return (temp);} // This function stores a tree in a file pointed by fpvoid serialize(Node *root, FILE *fp){ // If current node is NULL, store marker if (root == NULL) { fprintf(fp, "%d ", MARKER); return; } // Else, store current node and recur for its children fprintf(fp, "%d ", root->key); serialize(root->left, fp); serialize(root->right, fp);} // This function constructs a tree from a file pointed by 'fp'void deSerialize(Node *&root, FILE *fp){ // Read next item from file. If there are no more items or next // item is marker, then return int val; if ( !fscanf(fp, "%d ", &val) || val == MARKER) return; // Else create node with this item and recur for children root = newNode(val); deSerialize(root->left, fp); deSerialize(root->right, fp);} // A simple inorder traversal used for testing the constructed treevoid inorder(Node *root){ if (root) { inorder(root->left); printf("%d ", root->key); inorder(root->right); }} /* Driver program to test above functions*/int main(){ // Let us construct a tree shown in the above figure struct Node *root = newNode(20); root->left = newNode(8); root->right = newNode(22); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); // Let us open a file and serialize the tree into the file FILE *fp = fopen("tree.txt", "w"); if (fp == NULL) { puts("Could not open file"); return 0; } serialize(root, fp); fclose(fp); // Let us deserialize the stored tree into root1 Node *root1 = NULL; fp = fopen("tree.txt", "r"); deSerialize(root1, fp); printf("Inorder Traversal of the tree constructed from file:\n"); inorder(root1); return 0;}
// A JAVA program to demonstrate serialization and// deserialization of Binary Treeimport java.util.*; /* A binary tree Node has key, pointer to left and right * children */class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }} class BinaryTree { TreeNode root; // Encodes a tree to a single string. public static String serialize(TreeNode root) { if (root == null) { return null; } Stack<TreeNode> s = new Stack<>(); s.push(root); List<String> l = new ArrayList<>(); while (!s.isEmpty()) { TreeNode t = s.pop(); // If current node is NULL, store marker if (t == null) { l.add("#"); } else { // Else, store current node and recur for // its children l.add("" + t.val); s.push(t.right); s.push(t.left); } } return String.join(",", l); } static int t; // Decodes your encoded data to tree. public static TreeNode deserialize(String data) { if (data == null) return null; t = 0; String[] arr = data.split(","); return helper(arr); } public static TreeNode helper(String[] arr) { if (arr[t].equals("#")) return null; // create node with this item and recur for children TreeNode root = new TreeNode(Integer.parseInt(arr[t])); t++; root.left = helper(arr); t++; root.right = helper(arr); return root; } // A simple inorder traversal used for testing the // constructed tree static void inorder(TreeNode root) { if (root != null) { inorder(root.left); System.out.print(root.val + " "); inorder(root.right); } } /* Driver program to test above functions*/ public static void main(String args[]) { // Let us construct a tree shown in the above figure BinaryTree tree = new BinaryTree(); tree.root = new TreeNode(20); tree.root.left = new TreeNode(8); tree.root.right = new TreeNode(22); tree.root.left.left = new TreeNode(4); tree.root.left.right = new TreeNode(12); tree.root.left.right.left = new TreeNode(10); tree.root.left.right.right = new TreeNode(14); String serialized = serialize(tree.root); System.out.println("Serialized view of the tree:"); System.out.println(serialized); System.out.println(); // Let us deserialize the stored tree into root1 TreeNode t = deserialize(serialized); System.out.println( "Inorder Traversal of the tree constructed from serialized String:"); inorder(t); }}
How much extra space is required in above solution? If there are n keys, then the above solution requires n+1 markers which may be better than simple solution (storing keys twice) in situations where keys are big or keys have big data items associated with them.
Can we optimize it further? The above solution can be optimized in many ways. If we take a closer look at above serialized trees, we can observe that all leaf nodes require two markers. One simple optimization is to store a separate bit with every node to indicate that the node is internal or external. This way we don’t have to store two markers with every leaf node as leaves can be identified by extra bit. We still need marker for internal nodes with one child. For example in the following diagram ‘ is used to indicate an internal node set bit, and ‘/’ is used as NULL marker. The diagram is taken from here.
Please note that there are always more leaf nodes than internal nodes in a Binary Tree (Number of leaf nodes is number of internal nodes (with degree 2) plus 1, so this optimization makes sense.
How to serialize n-ary tree? In an n-ary tree, there is no designated left or right child. We can store an ‘end of children’ marker with every node. The following diagram shows serialization where ‘)’ is used as end of children marker. We will soon be covering implementation for n-ary tree. The diagram is taken from here.
sanjanab
wishcode
nobody_cares
simranarora5sos
ShubhamGupta110
mukhil99
hardikkoriintern
Accolite
Adobe
Amazon
Flipkart
InMobi
Linkedin
MAQ Software
Microsoft
Paytm
Quikr
Yahoo
Tree
Paytm
Flipkart
Accolite
Amazon
Microsoft
MAQ Software
Adobe
Linkedin
Quikr
Yahoo
InMobi
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
What is Data Structure: Types, Classifications and Applications
Diameter of a Binary Tree
Decision Tree
Diagonal Traversal of Binary Tree
Print Left View of a Binary Tree
Top 50 Tree Coding Problems for Interviews
Segment Tree | Set 1 (Sum of given range)
Inorder Tree Traversal without recursion and without stack!
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 217,
"s": 52,
"text": "Serialization is to store tree in a file so that it can be later restored. The structure of tree must be maintained. Deserialization is reading tree back from file."
},
{
"code": null,
"e": 269,
"s": 217,
"text": "Following are some simpler versions of the problem:"
},
{
"code": null,
"e": 537,
"s": 269,
"text": "If given Tree is Binary Search Tree? If the given Binary Tree is Binary Search Tree, we can store it by either storing preorder or postorder traversal. In case of Binary Search Trees, only preorder or postorder traversal is sufficient to store structure information. "
},
{
"code": null,
"e": 973,
"s": 537,
"text": "If given Binary Tree is Complete Tree? A Binary Tree is complete if all levels are completely filled except possibly the last level and all nodes of last level are as left as possible (Binary Heaps are complete Binary Tree). For a complete Binary Tree, level order traversal is sufficient to store the tree. We know that the first node is root, next two nodes are nodes of next level, next four nodes are nodes of 2nd level and so on. "
},
{
"code": null,
"e": 1294,
"s": 973,
"text": "If given Binary Tree is Full Tree? A full Binary is a Binary Tree where every node has either 0 or 2 children. It is easy to serialize such trees as every internal node has 2 children. We can simply store preorder traversal and store a bit with every node to indicate whether the node is an internal node or a leaf node."
},
{
"code": null,
"e": 1539,
"s": 1294,
"text": "How to store a general Binary Tree? A simple solution is to store both Inorder and Preorder traversals. This solution requires space twice the size of Binary Tree. We can save space by storing Preorder traversal and a marker for NULL pointers. "
},
{
"code": null,
"e": 2106,
"s": 1539,
"text": "Let the marker for NULL pointers be '-1'\nInput:\n 12\n /\n 13\nOutput: 12 13 -1 -1 -1\n\nInput:\n 20\n / \\\n 8 22 \nOutput: 20 8 -1 -1 22 -1 -1 \n\nInput:\n 20\n / \n 8 \n / \\\n 4 12 \n / \\\n 10 14\nOutput: 20 8 4 -1 -1 12 10 -1 -1 14 -1 -1 -1 \n\nInput:\n 20\n / \n 8 \n /\n 10\n /\n 5\nOutput: 20 8 10 5 -1 -1 -1 -1 -1 \n\nInput:\n 20\n \\\n 8\n \\ \n 10\n \\\n 5 \nOutput: 20 -1 8 -1 10 -1 5 -1 -1"
},
{
"code": null,
"e": 2180,
"s": 2106,
"text": "Deserialization can be done by simply reading data from file one by one. "
},
{
"code": null,
"e": 2232,
"s": 2180,
"text": "Following is the implementation of the above idea. "
},
{
"code": null,
"e": 2236,
"s": 2232,
"text": "C++"
},
{
"code": null,
"e": 2241,
"s": 2236,
"text": "Java"
},
{
"code": "// A C++ program to demonstrate serialization and deserialization of// Binary Tree#include <iostream>#define MARKER -1 /* A binary tree Node has key, pointer to left and right children */struct Node{ int key; struct Node* left, *right;}; /* Helper function that allocates a new Node with the given key and NULL left and right pointers. */struct Node* newNode(int key){ struct Node* temp = new Node(); temp->key = key; temp->left = temp->right = NULL; return (temp);} // This function stores a tree in a file pointed by fpvoid serialize(Node *root, FILE *fp){ // If current node is NULL, store marker if (root == NULL) { fprintf(fp, \"%d \", MARKER); return; } // Else, store current node and recur for its children fprintf(fp, \"%d \", root->key); serialize(root->left, fp); serialize(root->right, fp);} // This function constructs a tree from a file pointed by 'fp'void deSerialize(Node *&root, FILE *fp){ // Read next item from file. If there are no more items or next // item is marker, then return int val; if ( !fscanf(fp, \"%d \", &val) || val == MARKER) return; // Else create node with this item and recur for children root = newNode(val); deSerialize(root->left, fp); deSerialize(root->right, fp);} // A simple inorder traversal used for testing the constructed treevoid inorder(Node *root){ if (root) { inorder(root->left); printf(\"%d \", root->key); inorder(root->right); }} /* Driver program to test above functions*/int main(){ // Let us construct a tree shown in the above figure struct Node *root = newNode(20); root->left = newNode(8); root->right = newNode(22); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); // Let us open a file and serialize the tree into the file FILE *fp = fopen(\"tree.txt\", \"w\"); if (fp == NULL) { puts(\"Could not open file\"); return 0; } serialize(root, fp); fclose(fp); // Let us deserialize the stored tree into root1 Node *root1 = NULL; fp = fopen(\"tree.txt\", \"r\"); deSerialize(root1, fp); printf(\"Inorder Traversal of the tree constructed from file:\\n\"); inorder(root1); return 0;}",
"e": 4611,
"s": 2241,
"text": null
},
{
"code": "// A JAVA program to demonstrate serialization and// deserialization of Binary Treeimport java.util.*; /* A binary tree Node has key, pointer to left and right * children */class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }} class BinaryTree { TreeNode root; // Encodes a tree to a single string. public static String serialize(TreeNode root) { if (root == null) { return null; } Stack<TreeNode> s = new Stack<>(); s.push(root); List<String> l = new ArrayList<>(); while (!s.isEmpty()) { TreeNode t = s.pop(); // If current node is NULL, store marker if (t == null) { l.add(\"#\"); } else { // Else, store current node and recur for // its children l.add(\"\" + t.val); s.push(t.right); s.push(t.left); } } return String.join(\",\", l); } static int t; // Decodes your encoded data to tree. public static TreeNode deserialize(String data) { if (data == null) return null; t = 0; String[] arr = data.split(\",\"); return helper(arr); } public static TreeNode helper(String[] arr) { if (arr[t].equals(\"#\")) return null; // create node with this item and recur for children TreeNode root = new TreeNode(Integer.parseInt(arr[t])); t++; root.left = helper(arr); t++; root.right = helper(arr); return root; } // A simple inorder traversal used for testing the // constructed tree static void inorder(TreeNode root) { if (root != null) { inorder(root.left); System.out.print(root.val + \" \"); inorder(root.right); } } /* Driver program to test above functions*/ public static void main(String args[]) { // Let us construct a tree shown in the above figure BinaryTree tree = new BinaryTree(); tree.root = new TreeNode(20); tree.root.left = new TreeNode(8); tree.root.right = new TreeNode(22); tree.root.left.left = new TreeNode(4); tree.root.left.right = new TreeNode(12); tree.root.left.right.left = new TreeNode(10); tree.root.left.right.right = new TreeNode(14); String serialized = serialize(tree.root); System.out.println(\"Serialized view of the tree:\"); System.out.println(serialized); System.out.println(); // Let us deserialize the stored tree into root1 TreeNode t = deserialize(serialized); System.out.println( \"Inorder Traversal of the tree constructed from serialized String:\"); inorder(t); }}",
"e": 7440,
"s": 4611,
"text": null
},
{
"code": null,
"e": 7703,
"s": 7440,
"text": "How much extra space is required in above solution? If there are n keys, then the above solution requires n+1 markers which may be better than simple solution (storing keys twice) in situations where keys are big or keys have big data items associated with them."
},
{
"code": null,
"e": 8320,
"s": 7703,
"text": "Can we optimize it further? The above solution can be optimized in many ways. If we take a closer look at above serialized trees, we can observe that all leaf nodes require two markers. One simple optimization is to store a separate bit with every node to indicate that the node is internal or external. This way we don’t have to store two markers with every leaf node as leaves can be identified by extra bit. We still need marker for internal nodes with one child. For example in the following diagram ‘ is used to indicate an internal node set bit, and ‘/’ is used as NULL marker. The diagram is taken from here. "
},
{
"code": null,
"e": 8515,
"s": 8320,
"text": "Please note that there are always more leaf nodes than internal nodes in a Binary Tree (Number of leaf nodes is number of internal nodes (with degree 2) plus 1, so this optimization makes sense."
},
{
"code": null,
"e": 8840,
"s": 8515,
"text": "How to serialize n-ary tree? In an n-ary tree, there is no designated left or right child. We can store an ‘end of children’ marker with every node. The following diagram shows serialization where ‘)’ is used as end of children marker. We will soon be covering implementation for n-ary tree. The diagram is taken from here. "
},
{
"code": null,
"e": 8849,
"s": 8840,
"text": "sanjanab"
},
{
"code": null,
"e": 8858,
"s": 8849,
"text": "wishcode"
},
{
"code": null,
"e": 8871,
"s": 8858,
"text": "nobody_cares"
},
{
"code": null,
"e": 8887,
"s": 8871,
"text": "simranarora5sos"
},
{
"code": null,
"e": 8903,
"s": 8887,
"text": "ShubhamGupta110"
},
{
"code": null,
"e": 8912,
"s": 8903,
"text": "mukhil99"
},
{
"code": null,
"e": 8929,
"s": 8912,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 8938,
"s": 8929,
"text": "Accolite"
},
{
"code": null,
"e": 8944,
"s": 8938,
"text": "Adobe"
},
{
"code": null,
"e": 8951,
"s": 8944,
"text": "Amazon"
},
{
"code": null,
"e": 8960,
"s": 8951,
"text": "Flipkart"
},
{
"code": null,
"e": 8967,
"s": 8960,
"text": "InMobi"
},
{
"code": null,
"e": 8976,
"s": 8967,
"text": "Linkedin"
},
{
"code": null,
"e": 8989,
"s": 8976,
"text": "MAQ Software"
},
{
"code": null,
"e": 8999,
"s": 8989,
"text": "Microsoft"
},
{
"code": null,
"e": 9005,
"s": 8999,
"text": "Paytm"
},
{
"code": null,
"e": 9011,
"s": 9005,
"text": "Quikr"
},
{
"code": null,
"e": 9017,
"s": 9011,
"text": "Yahoo"
},
{
"code": null,
"e": 9022,
"s": 9017,
"text": "Tree"
},
{
"code": null,
"e": 9028,
"s": 9022,
"text": "Paytm"
},
{
"code": null,
"e": 9037,
"s": 9028,
"text": "Flipkart"
},
{
"code": null,
"e": 9046,
"s": 9037,
"text": "Accolite"
},
{
"code": null,
"e": 9053,
"s": 9046,
"text": "Amazon"
},
{
"code": null,
"e": 9063,
"s": 9053,
"text": "Microsoft"
},
{
"code": null,
"e": 9076,
"s": 9063,
"text": "MAQ Software"
},
{
"code": null,
"e": 9082,
"s": 9076,
"text": "Adobe"
},
{
"code": null,
"e": 9091,
"s": 9082,
"text": "Linkedin"
},
{
"code": null,
"e": 9097,
"s": 9091,
"text": "Quikr"
},
{
"code": null,
"e": 9103,
"s": 9097,
"text": "Yahoo"
},
{
"code": null,
"e": 9110,
"s": 9103,
"text": "InMobi"
},
{
"code": null,
"e": 9115,
"s": 9110,
"text": "Tree"
},
{
"code": null,
"e": 9213,
"s": 9115,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9245,
"s": 9213,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 9281,
"s": 9245,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 9345,
"s": 9281,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 9371,
"s": 9345,
"text": "Diameter of a Binary Tree"
},
{
"code": null,
"e": 9385,
"s": 9371,
"text": "Decision Tree"
},
{
"code": null,
"e": 9419,
"s": 9385,
"text": "Diagonal Traversal of Binary Tree"
},
{
"code": null,
"e": 9452,
"s": 9419,
"text": "Print Left View of a Binary Tree"
},
{
"code": null,
"e": 9495,
"s": 9452,
"text": "Top 50 Tree Coding Problems for Interviews"
},
{
"code": null,
"e": 9537,
"s": 9495,
"text": "Segment Tree | Set 1 (Sum of given range)"
}
] |
How to Deploy Next.js App to Vercel ?
|
14 Jul, 2021
Introduction: Vercel is a deployment tool used by frontend developers to instantly deploy and host web applications without knowing complex configurations.
Easy to use and has a lifetime free tier service which is beneficial for beginners who want to deploy their side-project with minimal support.
Can create an account using GitHub, GitLab, Bitbucket, or with Email.
Allows developers to use a custom domain that is HTTPS enabled.
Can be used to build unlimited websites and APIs.
Changes in data lead to an automatic push of the web page thereby reducing the constraint of static generation.
High-Performance Edge Network leads to faster routing.
Each pull request has its preview URL which is useful while running tests or gathering feedbacks.
Step 1: Create a Next.js App and setup Vercel Account: Create the Next.js app by running the following command:
npx create-next-app
or
yarn create next-app
Once the Next.js app is created, go to Vercel website and signup with GitHub/Email-id to create an account. To deploy our application, we need to install the Vercel CLI. Run the following command to install Vercel globally (You can also install Vercel locally in your project folder).
npm i -g vercel
To check if vercel is installed in our machine, run the command:
vercel --version
If vercel is installed correctly, it will install the latest version i.e, 23.0.0
Login in to your vercel account by running the following command
vercel login
You will be prompted with the following question – Enter your email: Enter your mail for confirmation.
Step 2: Deployment: Once you’ve logged in, in order to deploy your Next.js project you need to run ‘vercel’ command.
vercel
The command will show the latest Vercel version and ask the following questions:
Set up and deploy “~/projectname”? [Y/n]:Which scope do you want to deploy to?Link to an existing project? [y/n]What’s your project name?In which directory is your code located?Want to override the settings? [y/n]
Set up and deploy “~/projectname”? [Y/n]:
Which scope do you want to deploy to?
Link to an existing project? [y/n]
What’s your project name?
In which directory is your code located?
Want to override the settings? [y/n]
After you’ve completed these questions, head to your Vercel account and click on the Visit button to see your project live on Vercel.
Note: After deploying your project from the command line, Vercel creates a .vercel folder that contains the project.json file. This file contains the orgId and the projectId keys which are confidential and ‘SHOULD NOT’ be pushed to Git.
Step 3(Optional): Using Git and GitHub for Automation: Vercel automatically deploys any changes made to your Git repository. Each time a new pull or merge request is created, Vercel creates a new build and setups a new deployment.
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Jul, 2021"
},
{
"code": null,
"e": 185,
"s": 28,
"text": "Introduction: Vercel is a deployment tool used by frontend developers to instantly deploy and host web applications without knowing complex configurations. "
},
{
"code": null,
"e": 328,
"s": 185,
"text": "Easy to use and has a lifetime free tier service which is beneficial for beginners who want to deploy their side-project with minimal support."
},
{
"code": null,
"e": 398,
"s": 328,
"text": "Can create an account using GitHub, GitLab, Bitbucket, or with Email."
},
{
"code": null,
"e": 462,
"s": 398,
"text": "Allows developers to use a custom domain that is HTTPS enabled."
},
{
"code": null,
"e": 512,
"s": 462,
"text": "Can be used to build unlimited websites and APIs."
},
{
"code": null,
"e": 624,
"s": 512,
"text": "Changes in data lead to an automatic push of the web page thereby reducing the constraint of static generation."
},
{
"code": null,
"e": 679,
"s": 624,
"text": "High-Performance Edge Network leads to faster routing."
},
{
"code": null,
"e": 777,
"s": 679,
"text": "Each pull request has its preview URL which is useful while running tests or gathering feedbacks."
},
{
"code": null,
"e": 889,
"s": 777,
"text": "Step 1: Create a Next.js App and setup Vercel Account: Create the Next.js app by running the following command:"
},
{
"code": null,
"e": 912,
"s": 889,
"text": "npx create-next-app"
},
{
"code": null,
"e": 915,
"s": 912,
"text": "or"
},
{
"code": null,
"e": 941,
"s": 915,
"text": "yarn create next-app "
},
{
"code": null,
"e": 1226,
"s": 941,
"text": "Once the Next.js app is created, go to Vercel website and signup with GitHub/Email-id to create an account. To deploy our application, we need to install the Vercel CLI. Run the following command to install Vercel globally (You can also install Vercel locally in your project folder)."
},
{
"code": null,
"e": 1242,
"s": 1226,
"text": "npm i -g vercel"
},
{
"code": null,
"e": 1309,
"s": 1244,
"text": "To check if vercel is installed in our machine, run the command:"
},
{
"code": null,
"e": 1326,
"s": 1309,
"text": "vercel --version"
},
{
"code": null,
"e": 1407,
"s": 1326,
"text": "If vercel is installed correctly, it will install the latest version i.e, 23.0.0"
},
{
"code": null,
"e": 1473,
"s": 1407,
"text": "Login in to your vercel account by running the following command "
},
{
"code": null,
"e": 1486,
"s": 1473,
"text": "vercel login"
},
{
"code": null,
"e": 1589,
"s": 1486,
"text": "You will be prompted with the following question – Enter your email: Enter your mail for confirmation."
},
{
"code": null,
"e": 1706,
"s": 1589,
"text": "Step 2: Deployment: Once you’ve logged in, in order to deploy your Next.js project you need to run ‘vercel’ command."
},
{
"code": null,
"e": 1713,
"s": 1706,
"text": "vercel"
},
{
"code": null,
"e": 1794,
"s": 1713,
"text": "The command will show the latest Vercel version and ask the following questions:"
},
{
"code": null,
"e": 2008,
"s": 1794,
"text": "Set up and deploy “~/projectname”? [Y/n]:Which scope do you want to deploy to?Link to an existing project? [y/n]What’s your project name?In which directory is your code located?Want to override the settings? [y/n]"
},
{
"code": null,
"e": 2050,
"s": 2008,
"text": "Set up and deploy “~/projectname”? [Y/n]:"
},
{
"code": null,
"e": 2088,
"s": 2050,
"text": "Which scope do you want to deploy to?"
},
{
"code": null,
"e": 2123,
"s": 2088,
"text": "Link to an existing project? [y/n]"
},
{
"code": null,
"e": 2149,
"s": 2123,
"text": "What’s your project name?"
},
{
"code": null,
"e": 2190,
"s": 2149,
"text": "In which directory is your code located?"
},
{
"code": null,
"e": 2227,
"s": 2190,
"text": "Want to override the settings? [y/n]"
},
{
"code": null,
"e": 2361,
"s": 2227,
"text": "After you’ve completed these questions, head to your Vercel account and click on the Visit button to see your project live on Vercel."
},
{
"code": null,
"e": 2598,
"s": 2361,
"text": "Note: After deploying your project from the command line, Vercel creates a .vercel folder that contains the project.json file. This file contains the orgId and the projectId keys which are confidential and ‘SHOULD NOT’ be pushed to Git."
},
{
"code": null,
"e": 2829,
"s": 2598,
"text": "Step 3(Optional): Using Git and GitHub for Automation: Vercel automatically deploys any changes made to your Git repository. Each time a new pull or merge request is created, Vercel creates a new build and setups a new deployment."
},
{
"code": null,
"e": 2845,
"s": 2829,
"text": "React-Questions"
},
{
"code": null,
"e": 2853,
"s": 2845,
"text": "ReactJS"
},
{
"code": null,
"e": 2870,
"s": 2853,
"text": "Web Technologies"
}
] |
Code introspection in Python - GeeksforGeeks
|
07 Dec, 2018
Introspection is an ability to determine the type of an object at runtime. Everything in python is an object. Every object in Python may have attributes and methods. By using introspection, we can dynamically examine python objects. Code Introspection is used for examining the classes, methods, objects, modules, keywords and get information about them so that we can utilize it. Introspection reveals useful information about your program’s objects. Python, being a dynamic, object-oriented programming language, provides tremendous introspection support. Python’s support for introspection runs deep and wide throughout the language.Python provides some built-in functions that are used for code introspection.They are:1.type() : This function returns the type of an object.
# Python program showing# a use of type function import math # print type of mathprint(type(math)) # print type of 1 print(type(1)) # print type of "1"print(type("1")) # print type of rkrk =[1, 2, 3, 4, 5, "radha"] print(type(rk))print(type(rk[1]))print(type(rk[5]))
Output:
<class 'module'>
<class 'int'>
<class 'str'>
<class 'list'>
<class 'int'>
<class 'str'>
2.dir() :This function return list of methods and attributes associated with that object.
# Python program showing# a use of dir() function import mathrk =[1, 2, 3, 4, 5] # print methods and attributes of rkprint(dir(rk))rk =(1, 2, 3, 4, 5) # print methods and attributes of rkprint(dir(rk))rk ={1, 2, 3, 4, 5} print(dir(rk))print(dir(math))
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
3.str() :This function converts everything into a string .
# Python program showing# a use of str() function a = 1print(type(a)) # converting integer# into stringa = str(a)print(type(a)) s =[1, 2, 3, 4, 5]print(type(s)) # converting list# into strings = str(s)print(type(s))
Output:
<class 'int'>
<class 'str'>
<class 'list'>
<class 'str'>
4.id() :This function returns a special id of an object.
# Python program showing# a use of id() function import matha =[1, 2, 3, 4, 5] # print id of aprint(id(a))b =(1, 2, 3, 4, 5) # print id of bprint(id(b))c ={1, 2, 3, 4, 5} # print id of cprint(id(c))print(id(math))
Output:
139787756828232
139787757942656
139787757391432
139787756815768
Picked
python-basics
python-oop-concepts
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24228,
"s": 24200,
"text": "\n07 Dec, 2018"
},
{
"code": null,
"e": 25006,
"s": 24228,
"text": "Introspection is an ability to determine the type of an object at runtime. Everything in python is an object. Every object in Python may have attributes and methods. By using introspection, we can dynamically examine python objects. Code Introspection is used for examining the classes, methods, objects, modules, keywords and get information about them so that we can utilize it. Introspection reveals useful information about your program’s objects. Python, being a dynamic, object-oriented programming language, provides tremendous introspection support. Python’s support for introspection runs deep and wide throughout the language.Python provides some built-in functions that are used for code introspection.They are:1.type() : This function returns the type of an object."
},
{
"code": "# Python program showing# a use of type function import math # print type of mathprint(type(math)) # print type of 1 print(type(1)) # print type of \"1\"print(type(\"1\")) # print type of rkrk =[1, 2, 3, 4, 5, \"radha\"] print(type(rk))print(type(rk[1]))print(type(rk[5]))",
"e": 25280,
"s": 25006,
"text": null
},
{
"code": null,
"e": 25288,
"s": 25280,
"text": "Output:"
},
{
"code": null,
"e": 25377,
"s": 25288,
"text": "<class 'module'>\n<class 'int'>\n<class 'str'>\n<class 'list'>\n<class 'int'>\n<class 'str'>\n"
},
{
"code": null,
"e": 25468,
"s": 25377,
"text": " 2.dir() :This function return list of methods and attributes associated with that object."
},
{
"code": "# Python program showing# a use of dir() function import mathrk =[1, 2, 3, 4, 5] # print methods and attributes of rkprint(dir(rk))rk =(1, 2, 3, 4, 5) # print methods and attributes of rkprint(dir(rk))rk ={1, 2, 3, 4, 5} print(dir(rk))print(dir(math))",
"e": 25724,
"s": 25468,
"text": null
},
{
"code": null,
"e": 27147,
"s": 25724,
"text": "['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']\n['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']\n['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']\n"
},
{
"code": null,
"e": 27207,
"s": 27147,
"text": " 3.str() :This function converts everything into a string ."
},
{
"code": "# Python program showing# a use of str() function a = 1print(type(a)) # converting integer# into stringa = str(a)print(type(a)) s =[1, 2, 3, 4, 5]print(type(s)) # converting list# into strings = str(s)print(type(s))",
"e": 27427,
"s": 27207,
"text": null
},
{
"code": null,
"e": 27435,
"s": 27427,
"text": "Output:"
},
{
"code": null,
"e": 27493,
"s": 27435,
"text": "<class 'int'>\n<class 'str'>\n<class 'list'>\n<class 'str'>\n"
},
{
"code": null,
"e": 27551,
"s": 27493,
"text": " 4.id() :This function returns a special id of an object."
},
{
"code": "# Python program showing# a use of id() function import matha =[1, 2, 3, 4, 5] # print id of aprint(id(a))b =(1, 2, 3, 4, 5) # print id of bprint(id(b))c ={1, 2, 3, 4, 5} # print id of cprint(id(c))print(id(math))",
"e": 27773,
"s": 27551,
"text": null
},
{
"code": null,
"e": 27781,
"s": 27773,
"text": "Output:"
},
{
"code": null,
"e": 27846,
"s": 27781,
"text": "139787756828232\n139787757942656\n139787757391432\n139787756815768\n"
},
{
"code": null,
"e": 27853,
"s": 27846,
"text": "Picked"
},
{
"code": null,
"e": 27867,
"s": 27853,
"text": "python-basics"
},
{
"code": null,
"e": 27887,
"s": 27867,
"text": "python-oop-concepts"
},
{
"code": null,
"e": 27894,
"s": 27887,
"text": "Python"
},
{
"code": null,
"e": 27992,
"s": 27894,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28010,
"s": 27992,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28045,
"s": 28010,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28067,
"s": 28045,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28099,
"s": 28067,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28129,
"s": 28099,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28171,
"s": 28129,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28197,
"s": 28171,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28240,
"s": 28197,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28277,
"s": 28240,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Parsing A Boolean Expression in Python
|
Suppose we have a boolean expression, we have to find the result after evaluating that expression.
An expression can either be −
"t", evaluating to True;
"t", evaluating to True;
"f", evaluating to False;
"f", evaluating to False;
"!(expression)", evaluating to the logical NOT of the inner expression;
"!(expression)", evaluating to the logical NOT of the inner expression;
"&(expr1,expr2,...)", evaluating to the logical AND of 2 or more inner expressions;
"&(expr1,expr2,...)", evaluating to the logical AND of 2 or more inner expressions;
"|(expr1,expr2,...)", evaluating to the logical OR of 2 or more inner expressions;
"|(expr1,expr2,...)", evaluating to the logical OR of 2 or more inner expressions;
So, if the input is like "|(!(t),&(t,f,t))", then the output will be fasle, this is because !(t) is false, then &(t,f,t) is also false, so the OR of all false values will be false.
To solve this, we will follow these steps −
define solve(), this will take e, i
define solve(), this will take e, i
if e[i] is same as "f", then −return (False, i + 1)
if e[i] is same as "f", then −
return (False, i + 1)
return (False, i + 1)
Otherwise when e[i] is same as "t" −
Otherwise when e[i] is same as "t" −
return (True,i + 1)
return (True,i + 1)
op := e[i], i := i + 2
op := e[i], i := i + 2
Define one stack
Define one stack
while e[i] is not closing parentheses, do −if e[i] is same as ",", then −i := i + 1Ignore following part, skip to the next iterationres,i := solve(e, i)push res into stack
while e[i] is not closing parentheses, do −
if e[i] is same as ",", then −i := i + 1Ignore following part, skip to the next iteration
if e[i] is same as ",", then −
i := i + 1
i := i + 1
Ignore following part, skip to the next iteration
Ignore following part, skip to the next iteration
res,i := solve(e, i)
res,i := solve(e, i)
push res into stack
push res into stack
if op is same as "&", then −return true when all elements are true in stack, otherwise false, i + 1
if op is same as "&", then −
return true when all elements are true in stack, otherwise false, i + 1
return true when all elements are true in stack, otherwise false, i + 1
otherwise when op is same as " OR " −return true when at least one elements is true in stack, otherwise false, i + 1
otherwise when op is same as " OR " −
return true when at least one elements is true in stack, otherwise false, i + 1
return true when at least one elements is true in stack, otherwise false, i + 1
return (inverse of stack[0], i + 1)
return (inverse of stack[0], i + 1)
From the main method, do the following −
From the main method, do the following −
s,y := solve(expression, 0)
s,y := solve(expression, 0)
return s
return s
Let us see the following implementation to get better understanding −
Live Demo
class Solution(object):
def parseBoolExpr(self, expression):
s,y = self.solve(expression,0)
return s
def solve(self,e,i):
if e[i] =="f":
return False,i+1
elif e[i] == "t":
return True,i+1
op = e[i]
i = i+2
stack = []
while e[i]!=")":
if e[i] == ",":
i+=1
continue
res,i = self.solve(e,i)
stack.append(res)
if op == "&":
return all(stack),i+1
elif op == "|":
return any(stack),i+1
return not stack[0],i+1
ob = Solution()
print(ob.parseBoolExpr("|(!(t),&(t,f,t))"))
"|(!(t),&(t,f,t))"
False
|
[
{
"code": null,
"e": 1161,
"s": 1062,
"text": "Suppose we have a boolean expression, we have to find the result after evaluating that expression."
},
{
"code": null,
"e": 1191,
"s": 1161,
"text": "An expression can either be −"
},
{
"code": null,
"e": 1216,
"s": 1191,
"text": "\"t\", evaluating to True;"
},
{
"code": null,
"e": 1241,
"s": 1216,
"text": "\"t\", evaluating to True;"
},
{
"code": null,
"e": 1267,
"s": 1241,
"text": "\"f\", evaluating to False;"
},
{
"code": null,
"e": 1293,
"s": 1267,
"text": "\"f\", evaluating to False;"
},
{
"code": null,
"e": 1365,
"s": 1293,
"text": "\"!(expression)\", evaluating to the logical NOT of the inner expression;"
},
{
"code": null,
"e": 1437,
"s": 1365,
"text": "\"!(expression)\", evaluating to the logical NOT of the inner expression;"
},
{
"code": null,
"e": 1521,
"s": 1437,
"text": "\"&(expr1,expr2,...)\", evaluating to the logical AND of 2 or more inner expressions;"
},
{
"code": null,
"e": 1605,
"s": 1521,
"text": "\"&(expr1,expr2,...)\", evaluating to the logical AND of 2 or more inner expressions;"
},
{
"code": null,
"e": 1688,
"s": 1605,
"text": "\"|(expr1,expr2,...)\", evaluating to the logical OR of 2 or more inner expressions;"
},
{
"code": null,
"e": 1771,
"s": 1688,
"text": "\"|(expr1,expr2,...)\", evaluating to the logical OR of 2 or more inner expressions;"
},
{
"code": null,
"e": 1952,
"s": 1771,
"text": "So, if the input is like \"|(!(t),&(t,f,t))\", then the output will be fasle, this is because !(t) is false, then &(t,f,t) is also false, so the OR of all false values will be false."
},
{
"code": null,
"e": 1996,
"s": 1952,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 2032,
"s": 1996,
"text": "define solve(), this will take e, i"
},
{
"code": null,
"e": 2068,
"s": 2032,
"text": "define solve(), this will take e, i"
},
{
"code": null,
"e": 2120,
"s": 2068,
"text": "if e[i] is same as \"f\", then −return (False, i + 1)"
},
{
"code": null,
"e": 2151,
"s": 2120,
"text": "if e[i] is same as \"f\", then −"
},
{
"code": null,
"e": 2173,
"s": 2151,
"text": "return (False, i + 1)"
},
{
"code": null,
"e": 2195,
"s": 2173,
"text": "return (False, i + 1)"
},
{
"code": null,
"e": 2232,
"s": 2195,
"text": "Otherwise when e[i] is same as \"t\" −"
},
{
"code": null,
"e": 2269,
"s": 2232,
"text": "Otherwise when e[i] is same as \"t\" −"
},
{
"code": null,
"e": 2289,
"s": 2269,
"text": "return (True,i + 1)"
},
{
"code": null,
"e": 2309,
"s": 2289,
"text": "return (True,i + 1)"
},
{
"code": null,
"e": 2332,
"s": 2309,
"text": "op := e[i], i := i + 2"
},
{
"code": null,
"e": 2355,
"s": 2332,
"text": "op := e[i], i := i + 2"
},
{
"code": null,
"e": 2372,
"s": 2355,
"text": "Define one stack"
},
{
"code": null,
"e": 2389,
"s": 2372,
"text": "Define one stack"
},
{
"code": null,
"e": 2561,
"s": 2389,
"text": "while e[i] is not closing parentheses, do −if e[i] is same as \",\", then −i := i + 1Ignore following part, skip to the next iterationres,i := solve(e, i)push res into stack"
},
{
"code": null,
"e": 2605,
"s": 2561,
"text": "while e[i] is not closing parentheses, do −"
},
{
"code": null,
"e": 2695,
"s": 2605,
"text": "if e[i] is same as \",\", then −i := i + 1Ignore following part, skip to the next iteration"
},
{
"code": null,
"e": 2726,
"s": 2695,
"text": "if e[i] is same as \",\", then −"
},
{
"code": null,
"e": 2737,
"s": 2726,
"text": "i := i + 1"
},
{
"code": null,
"e": 2748,
"s": 2737,
"text": "i := i + 1"
},
{
"code": null,
"e": 2798,
"s": 2748,
"text": "Ignore following part, skip to the next iteration"
},
{
"code": null,
"e": 2848,
"s": 2798,
"text": "Ignore following part, skip to the next iteration"
},
{
"code": null,
"e": 2869,
"s": 2848,
"text": "res,i := solve(e, i)"
},
{
"code": null,
"e": 2890,
"s": 2869,
"text": "res,i := solve(e, i)"
},
{
"code": null,
"e": 2910,
"s": 2890,
"text": "push res into stack"
},
{
"code": null,
"e": 2930,
"s": 2910,
"text": "push res into stack"
},
{
"code": null,
"e": 3030,
"s": 2930,
"text": "if op is same as \"&\", then −return true when all elements are true in stack, otherwise false, i + 1"
},
{
"code": null,
"e": 3059,
"s": 3030,
"text": "if op is same as \"&\", then −"
},
{
"code": null,
"e": 3131,
"s": 3059,
"text": "return true when all elements are true in stack, otherwise false, i + 1"
},
{
"code": null,
"e": 3203,
"s": 3131,
"text": "return true when all elements are true in stack, otherwise false, i + 1"
},
{
"code": null,
"e": 3320,
"s": 3203,
"text": "otherwise when op is same as \" OR \" −return true when at least one elements is true in stack, otherwise false, i + 1"
},
{
"code": null,
"e": 3358,
"s": 3320,
"text": "otherwise when op is same as \" OR \" −"
},
{
"code": null,
"e": 3438,
"s": 3358,
"text": "return true when at least one elements is true in stack, otherwise false, i + 1"
},
{
"code": null,
"e": 3518,
"s": 3438,
"text": "return true when at least one elements is true in stack, otherwise false, i + 1"
},
{
"code": null,
"e": 3554,
"s": 3518,
"text": "return (inverse of stack[0], i + 1)"
},
{
"code": null,
"e": 3590,
"s": 3554,
"text": "return (inverse of stack[0], i + 1)"
},
{
"code": null,
"e": 3631,
"s": 3590,
"text": "From the main method, do the following −"
},
{
"code": null,
"e": 3672,
"s": 3631,
"text": "From the main method, do the following −"
},
{
"code": null,
"e": 3700,
"s": 3672,
"text": "s,y := solve(expression, 0)"
},
{
"code": null,
"e": 3728,
"s": 3700,
"text": "s,y := solve(expression, 0)"
},
{
"code": null,
"e": 3737,
"s": 3728,
"text": "return s"
},
{
"code": null,
"e": 3746,
"s": 3737,
"text": "return s"
},
{
"code": null,
"e": 3816,
"s": 3746,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3827,
"s": 3816,
"text": " Live Demo"
},
{
"code": null,
"e": 4450,
"s": 3827,
"text": "class Solution(object):\n def parseBoolExpr(self, expression):\n s,y = self.solve(expression,0)\n return s\n def solve(self,e,i):\n if e[i] ==\"f\":\n return False,i+1\n elif e[i] == \"t\":\n return True,i+1\n op = e[i]\n i = i+2\n stack = []\n while e[i]!=\")\":\n if e[i] == \",\":\n i+=1\n continue\n res,i = self.solve(e,i)\n stack.append(res)\n if op == \"&\":\n return all(stack),i+1\n elif op == \"|\":\n return any(stack),i+1\n return not stack[0],i+1\nob = Solution()\nprint(ob.parseBoolExpr(\"|(!(t),&(t,f,t))\"))"
},
{
"code": null,
"e": 4469,
"s": 4450,
"text": "\"|(!(t),&(t,f,t))\""
},
{
"code": null,
"e": 4475,
"s": 4469,
"text": "False"
}
] |
Check if the number is a Prime power number - GeeksforGeeks
|
02 Mar, 2022
Given an integer N, the task is to check if the number is a Prime power number. If yes, then print the number along with its power which is equal to N. Else print -1.
A prime power is a positive integer power of a single prime number. For example: 7 = 71, 9 = 32 and 32 = 25 are prime powers, while 6 = 2 × 3, 12 = 22 × 3 and 36 = 62 = 22 × 32 are not. (The number 1 is not counted as a prime power.)
Note: If there is no such prime number, print -1.
Examples:
Input: N = 49 Output: 72 Explanation: N can be represented as a power of prime number 7. N = 49 = 72
Input: N = 100 Output: -1 Explanation: N cannot be represented as a power of any prime number.
Approach: The idea is to use the Sieve of Eratosthenes to find all the prime numbers. Then, Iterate over all the prime numbers and check that if any prime number divides the given number N, if yes then divide it until it becomes 1 or not divisible by that prime number. Finally, check that the number is equal to 1, If yes then return the prime number otherwise given number cannot be expressed as a prime number raised to some power.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to check if// a number is a prime power number#include<bits/stdc++.h>using namespace std; // Array to store the// prime numbersbool is_prime[1000001];vector<int> primes; // Function to mark the prime// numbers using Sieve of// Eratosthenesvoid SieveOfEratosthenes(int n){ int p = 2; for(int i = 0; i < n; i++) is_prime[i] = true; while (p * p <= n) { // If prime[p] is not // changed, then it is a prime if (is_prime[p] == true) { // Update all multiples of p for(int i = p * p; i < n + 1; i += p) { is_prime[i] = false; } } p += 1; } for(int i = 2; i < n + 1; i++) { if (is_prime[i]) primes.push_back(i); }} // Function to check if the// number can be represented// as a power of primepair<int, int> power_of_prime(int n){ for(auto i : primes) { if (n % i == 0) { int c = 0; while(n % i == 0) { n /= i; c += 1; } if(n == 1) return {i, c}; else return {-1, 1}; } }} // Driver Code int main(){ int n = 49; SieveOfEratosthenes(int(sqrt(n)) + 1); // Function Call pair<int, int> p = power_of_prime(n); if (p.first > 1) cout << p.first << " ^ " << p.second << endl; else cout << -1 << endl;} // This code is contributed by Surendra_Gangwar
// Java implementation to check if // a number is a prime power numberimport java.io.*;import java.util.*;import java.lang.Math; class GFG{ // Array to store the // prime numbers static ArrayList<Integer> primes = new ArrayList<Integer>(); // Function to mark the prime // numbers using Sieve of // Eratosthenespublic static void sieveOfEratosthenes(int n){ // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. boolean prime[] = new boolean[n + 1]; for(int i = 0; i < n; i++) prime[i] = true; for(int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if(prime[p] == true) { // Update all multiples of p for(int i = p * 2; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for(int i = 2; i <= n; i++) { if(prime[i] == true) primes.add(i); }} // Function to check if the // number can be represented // as a power of primepublic static int[] power_of_prime(int n){ for(int ii = 0; ii < primes.size(); ii++) { int i = primes.get(ii); if (n % i == 0) { int c = 0; while(n % i == 0) { n /= i; c += 1; } if(n == 1) return new int[]{i, c}; else return new int[]{-1, 1}; } } return new int[]{-1, 1};} // Driver codepublic static void main(String args[]){ int n = 49; int sq = (int)(Math.sqrt(n)); sieveOfEratosthenes(sq + 1); // Function call int arr[] = power_of_prime(n); if (arr[0] > 1) System.out.println(arr[0] + " ^ " + arr[1]); else System.out.println("-1");}} // This code is contributed by grand_master
# Python3 implementation to check# if a number is a prime power number from math import * # Array to store the# prime numbersis_prime = [True for i in range(10**6 + 1)]primes =[] # Function to mark the prime# numbers using Sieve of# Eratosthenesdef SieveOfEratosthenes(n): p = 2 while (p * p <= n): # If prime[p] is not # changed, then it is a prime if (is_prime[p] == True): # Update all multiples of p for i in range(p * p, n + 1, p): is_prime[i] = False p += 1 for i in range(2, n + 1): if is_prime[i]: primes.append(i) # Function to check if the# number can be represented# as a power of primedef power_of_prime(n): for i in primes: if n % i == 0: c = 0 while n % i == 0: n//= i c += 1 if n == 1: return (i, c) else: return (-1, 1) # Driver Code if __name__ == "__main__": n = 49 SieveOfEratosthenes(int(sqrt(n))+1) # Function Call num, power = power_of_prime(n) if num > 1: print(num, "^", power) else: print(-1)
// C# implementation to check if// a number is a prime power numberusing System;using System.Collections; class GFG{ // Array to store the// prime numbers static ArrayList primes = new ArrayList(); // Function to mark the prime// numbers using Sieve of// Eratosthenespublic static void sieveOfEratosthenes(int n){ // Create a boolean array "prime[0..n]" // and initialize all entries it as true. // A value in prime[i] will finally be // false if i is Not a prime, else true. bool []prime = new bool[n + 1]; for(int i = 0; i < n; i++) prime[i] = true; for(int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for(int i = p * 2; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for(int i = 2; i <= n; i++) { if (prime[i] == true) primes.Add(i); }} // Function to check if the// number can be represented// as a power of primepublic static int[] power_of_prime(int n){ for(int ii = 0; ii < primes.Count; ii++) { int i = (int)primes[ii]; if (n % i == 0) { int c = 0; while (n % i == 0) { n /= i; c += 1; } if (n == 1) return new int[]{i, c}; else return new int[]{-1, 1}; } } return new int[]{-1, 1};} // Driver codepublic static void Main(string []args){ int n = 49; int sq = (int)(Math.Sqrt(n)); sieveOfEratosthenes(sq + 1); // Function call int []arr = power_of_prime(n); if (arr[0] > 1) Console.Write(arr[0] + " ^ " + arr[1]); else Console.Write("-1");}} // This code is contributed by rutvik_56
<script> // Javascript implementation to check if// a number is a prime power number // Array to store the// prime numbers let primes = []; // Function to mark the prime// numbers using Sieve of// Eratosthenesfunction sieveOfEratosthenes(n){ // Create a boolean array "prime[0..n]" // and initialize all entries it as true. // A value in prime[i] will finally be // false if i is Not a prime, else true. let prime = Array.from({length: n+1}, (_, i) => 0); for(let i = 0; i < n; i++) prime[i] = true; for(let p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for(let i = p * 2; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for(let i = 2; i <= n; i++) { if (prime[i] == true) primes.push(i); }} // Function to check if the// number can be represented// as a power of primefunction power_of_prime(n){ for(let ii = 0; ii < primes.length; ii++) { let i = primes[ii]; if (n % i == 0) { let c = 0; while (n % i == 0) { n /= i; c += 1; } if (n == 1) return [i, c]; else return [-1, 1]; } } return [-1, 1];} // Driver Code let n = 49; let sq = (Math.sqrt(n)); sieveOfEratosthenes(sq + 1); // Function call let arr = power_of_prime(n); if (arr[0] > 1) document.write(arr[0] + " ^ " + arr[1]); else document.write("-1"); </script>
7 ^ 2
SURENDRA_GANGWAR
grand_master
rutvik_56
code_hunt
saurabh1990aror
sweetyty
maths-power
Prime Number
Competitive Programming
Mathematical
School Programming
Mathematical
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Shortest path in a directed graph by Dijkstra’s algorithm
Breadth First Traversal ( BFS ) on a 2D array
Multistage Graph (Shortest Path)
Runtime Errors
Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 25126,
"s": 25098,
"text": "\n02 Mar, 2022"
},
{
"code": null,
"e": 25294,
"s": 25126,
"text": "Given an integer N, the task is to check if the number is a Prime power number. If yes, then print the number along with its power which is equal to N. Else print -1. "
},
{
"code": null,
"e": 25528,
"s": 25294,
"text": "A prime power is a positive integer power of a single prime number. For example: 7 = 71, 9 = 32 and 32 = 25 are prime powers, while 6 = 2 × 3, 12 = 22 × 3 and 36 = 62 = 22 × 32 are not. (The number 1 is not counted as a prime power.)"
},
{
"code": null,
"e": 25579,
"s": 25528,
"text": "Note: If there is no such prime number, print -1. "
},
{
"code": null,
"e": 25590,
"s": 25579,
"text": "Examples: "
},
{
"code": null,
"e": 25691,
"s": 25590,
"text": "Input: N = 49 Output: 72 Explanation: N can be represented as a power of prime number 7. N = 49 = 72"
},
{
"code": null,
"e": 25786,
"s": 25691,
"text": "Input: N = 100 Output: -1 Explanation: N cannot be represented as a power of any prime number."
},
{
"code": null,
"e": 26221,
"s": 25786,
"text": "Approach: The idea is to use the Sieve of Eratosthenes to find all the prime numbers. Then, Iterate over all the prime numbers and check that if any prime number divides the given number N, if yes then divide it until it becomes 1 or not divisible by that prime number. Finally, check that the number is equal to 1, If yes then return the prime number otherwise given number cannot be expressed as a prime number raised to some power."
},
{
"code": null,
"e": 26273,
"s": 26221,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26277,
"s": 26273,
"text": "C++"
},
{
"code": null,
"e": 26282,
"s": 26277,
"text": "Java"
},
{
"code": null,
"e": 26290,
"s": 26282,
"text": "Python3"
},
{
"code": null,
"e": 26293,
"s": 26290,
"text": "C#"
},
{
"code": null,
"e": 26304,
"s": 26293,
"text": "Javascript"
},
{
"code": "// C++ implementation to check if// a number is a prime power number#include<bits/stdc++.h>using namespace std; // Array to store the// prime numbersbool is_prime[1000001];vector<int> primes; // Function to mark the prime// numbers using Sieve of// Eratosthenesvoid SieveOfEratosthenes(int n){ int p = 2; for(int i = 0; i < n; i++) is_prime[i] = true; while (p * p <= n) { // If prime[p] is not // changed, then it is a prime if (is_prime[p] == true) { // Update all multiples of p for(int i = p * p; i < n + 1; i += p) { is_prime[i] = false; } } p += 1; } for(int i = 2; i < n + 1; i++) { if (is_prime[i]) primes.push_back(i); }} // Function to check if the// number can be represented// as a power of primepair<int, int> power_of_prime(int n){ for(auto i : primes) { if (n % i == 0) { int c = 0; while(n % i == 0) { n /= i; c += 1; } if(n == 1) return {i, c}; else return {-1, 1}; } }} // Driver Code int main(){ int n = 49; SieveOfEratosthenes(int(sqrt(n)) + 1); // Function Call pair<int, int> p = power_of_prime(n); if (p.first > 1) cout << p.first << \" ^ \" << p.second << endl; else cout << -1 << endl;} // This code is contributed by Surendra_Gangwar",
"e": 27853,
"s": 26304,
"text": null
},
{
"code": "// Java implementation to check if // a number is a prime power numberimport java.io.*;import java.util.*;import java.lang.Math; class GFG{ // Array to store the // prime numbers static ArrayList<Integer> primes = new ArrayList<Integer>(); // Function to mark the prime // numbers using Sieve of // Eratosthenespublic static void sieveOfEratosthenes(int n){ // Create a boolean array \"prime[0..n]\" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. boolean prime[] = new boolean[n + 1]; for(int i = 0; i < n; i++) prime[i] = true; for(int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if(prime[p] == true) { // Update all multiples of p for(int i = p * 2; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for(int i = 2; i <= n; i++) { if(prime[i] == true) primes.add(i); }} // Function to check if the // number can be represented // as a power of primepublic static int[] power_of_prime(int n){ for(int ii = 0; ii < primes.size(); ii++) { int i = primes.get(ii); if (n % i == 0) { int c = 0; while(n % i == 0) { n /= i; c += 1; } if(n == 1) return new int[]{i, c}; else return new int[]{-1, 1}; } } return new int[]{-1, 1};} // Driver codepublic static void main(String args[]){ int n = 49; int sq = (int)(Math.sqrt(n)); sieveOfEratosthenes(sq + 1); // Function call int arr[] = power_of_prime(n); if (arr[0] > 1) System.out.println(arr[0] + \" ^ \" + arr[1]); else System.out.println(\"-1\");}} // This code is contributed by grand_master",
"e": 29798,
"s": 27853,
"text": null
},
{
"code": "# Python3 implementation to check# if a number is a prime power number from math import * # Array to store the# prime numbersis_prime = [True for i in range(10**6 + 1)]primes =[] # Function to mark the prime# numbers using Sieve of# Eratosthenesdef SieveOfEratosthenes(n): p = 2 while (p * p <= n): # If prime[p] is not # changed, then it is a prime if (is_prime[p] == True): # Update all multiples of p for i in range(p * p, n + 1, p): is_prime[i] = False p += 1 for i in range(2, n + 1): if is_prime[i]: primes.append(i) # Function to check if the# number can be represented# as a power of primedef power_of_prime(n): for i in primes: if n % i == 0: c = 0 while n % i == 0: n//= i c += 1 if n == 1: return (i, c) else: return (-1, 1) # Driver Code if __name__ == \"__main__\": n = 49 SieveOfEratosthenes(int(sqrt(n))+1) # Function Call num, power = power_of_prime(n) if num > 1: print(num, \"^\", power) else: print(-1)",
"e": 30966,
"s": 29798,
"text": null
},
{
"code": "// C# implementation to check if// a number is a prime power numberusing System;using System.Collections; class GFG{ // Array to store the// prime numbers static ArrayList primes = new ArrayList(); // Function to mark the prime// numbers using Sieve of// Eratosthenespublic static void sieveOfEratosthenes(int n){ // Create a boolean array \"prime[0..n]\" // and initialize all entries it as true. // A value in prime[i] will finally be // false if i is Not a prime, else true. bool []prime = new bool[n + 1]; for(int i = 0; i < n; i++) prime[i] = true; for(int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for(int i = p * 2; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for(int i = 2; i <= n; i++) { if (prime[i] == true) primes.Add(i); }} // Function to check if the// number can be represented// as a power of primepublic static int[] power_of_prime(int n){ for(int ii = 0; ii < primes.Count; ii++) { int i = (int)primes[ii]; if (n % i == 0) { int c = 0; while (n % i == 0) { n /= i; c += 1; } if (n == 1) return new int[]{i, c}; else return new int[]{-1, 1}; } } return new int[]{-1, 1};} // Driver codepublic static void Main(string []args){ int n = 49; int sq = (int)(Math.Sqrt(n)); sieveOfEratosthenes(sq + 1); // Function call int []arr = power_of_prime(n); if (arr[0] > 1) Console.Write(arr[0] + \" ^ \" + arr[1]); else Console.Write(\"-1\");}} // This code is contributed by rutvik_56",
"e": 32877,
"s": 30966,
"text": null
},
{
"code": "<script> // Javascript implementation to check if// a number is a prime power number // Array to store the// prime numbers let primes = []; // Function to mark the prime// numbers using Sieve of// Eratosthenesfunction sieveOfEratosthenes(n){ // Create a boolean array \"prime[0..n]\" // and initialize all entries it as true. // A value in prime[i] will finally be // false if i is Not a prime, else true. let prime = Array.from({length: n+1}, (_, i) => 0); for(let i = 0; i < n; i++) prime[i] = true; for(let p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for(let i = p * 2; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for(let i = 2; i <= n; i++) { if (prime[i] == true) primes.push(i); }} // Function to check if the// number can be represented// as a power of primefunction power_of_prime(n){ for(let ii = 0; ii < primes.length; ii++) { let i = primes[ii]; if (n % i == 0) { let c = 0; while (n % i == 0) { n /= i; c += 1; } if (n == 1) return [i, c]; else return [-1, 1]; } } return [-1, 1];} // Driver Code let n = 49; let sq = (Math.sqrt(n)); sieveOfEratosthenes(sq + 1); // Function call let arr = power_of_prime(n); if (arr[0] > 1) document.write(arr[0] + \" ^ \" + arr[1]); else document.write(\"-1\"); </script>",
"e": 34646,
"s": 32877,
"text": null
},
{
"code": null,
"e": 34652,
"s": 34646,
"text": "7 ^ 2"
},
{
"code": null,
"e": 34671,
"s": 34654,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 34684,
"s": 34671,
"text": "grand_master"
},
{
"code": null,
"e": 34694,
"s": 34684,
"text": "rutvik_56"
},
{
"code": null,
"e": 34704,
"s": 34694,
"text": "code_hunt"
},
{
"code": null,
"e": 34720,
"s": 34704,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 34729,
"s": 34720,
"text": "sweetyty"
},
{
"code": null,
"e": 34741,
"s": 34729,
"text": "maths-power"
},
{
"code": null,
"e": 34754,
"s": 34741,
"text": "Prime Number"
},
{
"code": null,
"e": 34778,
"s": 34754,
"text": "Competitive Programming"
},
{
"code": null,
"e": 34791,
"s": 34778,
"text": "Mathematical"
},
{
"code": null,
"e": 34810,
"s": 34791,
"text": "School Programming"
},
{
"code": null,
"e": 34823,
"s": 34810,
"text": "Mathematical"
},
{
"code": null,
"e": 34836,
"s": 34823,
"text": "Prime Number"
},
{
"code": null,
"e": 34934,
"s": 34836,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34992,
"s": 34934,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 35038,
"s": 34992,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 35071,
"s": 35038,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 35086,
"s": 35071,
"text": "Runtime Errors"
},
{
"code": null,
"e": 35170,
"s": 35086,
"text": "Graph implementation using STL for competitive programming | Set 2 (Weighted graph)"
},
{
"code": null,
"e": 35200,
"s": 35170,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 35260,
"s": 35200,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 35275,
"s": 35260,
"text": "C++ Data Types"
},
{
"code": null,
"e": 35318,
"s": 35275,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
AI Search Algorithms Every Data Scientist Should Know | by Aaron (Ari) Bornstein | Towards Data Science
|
TL;DR The post below outlines a few of the key search algorithms in AI, why they are important, what and what they are used for.
While in recent years, search and planning algorithms have taken a back seat to machine and deep learning methods, better understanding these algorithms can boost the performance of your models. Additionally as more powerful computational technologies such as quantum computing emerge it is very likely that search based AI will make a comeback .
Before we get started lets define what search in AI means.
Search in AI is the process of navigating from a starting state to a goal state by transitioning through intermediate states.
Almost any AI problem can be defined in these terms.
State — A potential outcome of a problem
Transition — The act of moving between states.
Starting State — Where to start searching from.
Intermediate State- The states between the starting state and the goal state that we need to transition to.
Goal State — The state to stop searching.
Search Space — A collection of states.
Uninformed search is used when there is no information about the cost of navigating between states.
There are three main classical algorithms for uninformed search:
DFS — Traverse the search space using a LIFO Stack to determine the next node. Advantages: Good for deep graphs, memory efficient. Disadvantages: Can get stuck in loops.
en.wikipedia.org
IDFS — Traverse the search space, using a LIFO Stack, to determine the next node when it reaches a certain depth then it clears the stack, increments the depth limit and starts the search again.
en.wikipedia.org
BFS- Traverse the search space using a queue FIFO to determine the next node.
en.wikipedia.org
An informed search is used when we know the cost or have a solid estimate of the cost between states.
UCF- Traverse the search space with a priority queue and a score. The score for a given state is calculated by the cost of getting to the state from the parent along the path it was discovered.
algorithmicthoughts.wordpress.com
A* — Traverse the search space with a priority queue and a score. The score of a state is calculated by the cost of getting to the state from the parent along the path it was discovered, combined with a heuristic value for the given state.
The admissible value of heuristic must abide by the two following properties.
A state’s heuristic value must be less than the lowest cost path of getting from a state to the goal node.
The heuristic value must be less than the value of the cost between the path to the state and the heuristic value of each parent node.
en.wikipedia.org
IDA* — An IDFS version of A*
en.wikipedia.org
We use local search algorithms when there is more than one possible goal state but some outcomes are better than others and we need to discover the best. Used a lot in optimization of machine learning algorithms.
Hill Climbing- A greedy search method that detriments the next state based on the value thats the smallest until it hits a local maximum.
en.wikipedia.org
Simulated annealing- Starts with a hill climb until it hits a local maximum then uses a temperature function to decide whether to stop or continue to a worse state with the hopes of finding a better
en.wikipedia.org
GSAT — An implementation of Hill Climbing for the CNF domain. Chooses a random set of boolean values for each possible parameter, if the values match all the preconditions goal state return else we flip the values to satisfy the largest amount of possible preconditions of the goal state and then repeat this process with a new random set of values for each of the boolean values we flipped on the last iteration.
en.wikipedia.org
Genetic Search- Generate initial population of states, prune those under a threshold that have the lowest values using a fitness function. Randomly combine the survivors, then mutate a couple of bits and evaluate fitness and repeat.
en.wikipedia.org
Beam Search- Preform uniform cost search with the top n values likelyhood values of the current and previous outputs of a model.
en.wikipedia.org
Monte Carlo Search — A randomized search algorithm that will return the best estimate of the correct search result when terminated. Monte Carlo algorithms are always fast, but only probably correct.
en.wikipedia.org
Las Vegas Search Is a randomized search algorithm unlike Monte Carlo it will only return when the correct result is found. Las Vegas algorithms are always correct, but only probably fast.
// Las Vegas algorithm2 repeat:3 k = RandInt(n)4 if A[k] == 1,5 return k;
en.wikipedia.org
Atlantic City Search — Is a bounded probabilistic polynomial time search algorithm that combines the strengths and weaknesses of the Las Vegas and Monte Carlos Search algorithms.
en.wikipedia.org
If you enjoyed this article, keep your eyes out for new content shortly and follow me here on medium or twitter @pythiccoder. To get started experimenting with these algorithms check out Azure Notebooks as well as the graph data base features of CosmosDB on Azure.
If you don’t have one yet you can pick up a free Azure Subscription below.
azure.microsoft.com
Aaron (Ari) Bornstein is an avid AI enthusiast with a passion for history, engaging with new technologies and computational medicine. As an Open Source Engineer at Microsoft’s Cloud Developer Advocacy team, he collaborates with Israeli Hi-Tech Community, to solve real world problems with game changing technologies that are then documented, open sourced, and shared with the rest of the world.
|
[
{
"code": null,
"e": 300,
"s": 171,
"text": "TL;DR The post below outlines a few of the key search algorithms in AI, why they are important, what and what they are used for."
},
{
"code": null,
"e": 647,
"s": 300,
"text": "While in recent years, search and planning algorithms have taken a back seat to machine and deep learning methods, better understanding these algorithms can boost the performance of your models. Additionally as more powerful computational technologies such as quantum computing emerge it is very likely that search based AI will make a comeback ."
},
{
"code": null,
"e": 706,
"s": 647,
"text": "Before we get started lets define what search in AI means."
},
{
"code": null,
"e": 832,
"s": 706,
"text": "Search in AI is the process of navigating from a starting state to a goal state by transitioning through intermediate states."
},
{
"code": null,
"e": 885,
"s": 832,
"text": "Almost any AI problem can be defined in these terms."
},
{
"code": null,
"e": 926,
"s": 885,
"text": "State — A potential outcome of a problem"
},
{
"code": null,
"e": 973,
"s": 926,
"text": "Transition — The act of moving between states."
},
{
"code": null,
"e": 1021,
"s": 973,
"text": "Starting State — Where to start searching from."
},
{
"code": null,
"e": 1129,
"s": 1021,
"text": "Intermediate State- The states between the starting state and the goal state that we need to transition to."
},
{
"code": null,
"e": 1171,
"s": 1129,
"text": "Goal State — The state to stop searching."
},
{
"code": null,
"e": 1210,
"s": 1171,
"text": "Search Space — A collection of states."
},
{
"code": null,
"e": 1310,
"s": 1210,
"text": "Uninformed search is used when there is no information about the cost of navigating between states."
},
{
"code": null,
"e": 1375,
"s": 1310,
"text": "There are three main classical algorithms for uninformed search:"
},
{
"code": null,
"e": 1545,
"s": 1375,
"text": "DFS — Traverse the search space using a LIFO Stack to determine the next node. Advantages: Good for deep graphs, memory efficient. Disadvantages: Can get stuck in loops."
},
{
"code": null,
"e": 1562,
"s": 1545,
"text": "en.wikipedia.org"
},
{
"code": null,
"e": 1757,
"s": 1562,
"text": "IDFS — Traverse the search space, using a LIFO Stack, to determine the next node when it reaches a certain depth then it clears the stack, increments the depth limit and starts the search again."
},
{
"code": null,
"e": 1774,
"s": 1757,
"text": "en.wikipedia.org"
},
{
"code": null,
"e": 1852,
"s": 1774,
"text": "BFS- Traverse the search space using a queue FIFO to determine the next node."
},
{
"code": null,
"e": 1869,
"s": 1852,
"text": "en.wikipedia.org"
},
{
"code": null,
"e": 1971,
"s": 1869,
"text": "An informed search is used when we know the cost or have a solid estimate of the cost between states."
},
{
"code": null,
"e": 2165,
"s": 1971,
"text": "UCF- Traverse the search space with a priority queue and a score. The score for a given state is calculated by the cost of getting to the state from the parent along the path it was discovered."
},
{
"code": null,
"e": 2199,
"s": 2165,
"text": "algorithmicthoughts.wordpress.com"
},
{
"code": null,
"e": 2439,
"s": 2199,
"text": "A* — Traverse the search space with a priority queue and a score. The score of a state is calculated by the cost of getting to the state from the parent along the path it was discovered, combined with a heuristic value for the given state."
},
{
"code": null,
"e": 2517,
"s": 2439,
"text": "The admissible value of heuristic must abide by the two following properties."
},
{
"code": null,
"e": 2624,
"s": 2517,
"text": "A state’s heuristic value must be less than the lowest cost path of getting from a state to the goal node."
},
{
"code": null,
"e": 2759,
"s": 2624,
"text": "The heuristic value must be less than the value of the cost between the path to the state and the heuristic value of each parent node."
},
{
"code": null,
"e": 2776,
"s": 2759,
"text": "en.wikipedia.org"
},
{
"code": null,
"e": 2805,
"s": 2776,
"text": "IDA* — An IDFS version of A*"
},
{
"code": null,
"e": 2822,
"s": 2805,
"text": "en.wikipedia.org"
},
{
"code": null,
"e": 3035,
"s": 2822,
"text": "We use local search algorithms when there is more than one possible goal state but some outcomes are better than others and we need to discover the best. Used a lot in optimization of machine learning algorithms."
},
{
"code": null,
"e": 3173,
"s": 3035,
"text": "Hill Climbing- A greedy search method that detriments the next state based on the value thats the smallest until it hits a local maximum."
},
{
"code": null,
"e": 3190,
"s": 3173,
"text": "en.wikipedia.org"
},
{
"code": null,
"e": 3389,
"s": 3190,
"text": "Simulated annealing- Starts with a hill climb until it hits a local maximum then uses a temperature function to decide whether to stop or continue to a worse state with the hopes of finding a better"
},
{
"code": null,
"e": 3406,
"s": 3389,
"text": "en.wikipedia.org"
},
{
"code": null,
"e": 3820,
"s": 3406,
"text": "GSAT — An implementation of Hill Climbing for the CNF domain. Chooses a random set of boolean values for each possible parameter, if the values match all the preconditions goal state return else we flip the values to satisfy the largest amount of possible preconditions of the goal state and then repeat this process with a new random set of values for each of the boolean values we flipped on the last iteration."
},
{
"code": null,
"e": 3837,
"s": 3820,
"text": "en.wikipedia.org"
},
{
"code": null,
"e": 4070,
"s": 3837,
"text": "Genetic Search- Generate initial population of states, prune those under a threshold that have the lowest values using a fitness function. Randomly combine the survivors, then mutate a couple of bits and evaluate fitness and repeat."
},
{
"code": null,
"e": 4087,
"s": 4070,
"text": "en.wikipedia.org"
},
{
"code": null,
"e": 4216,
"s": 4087,
"text": "Beam Search- Preform uniform cost search with the top n values likelyhood values of the current and previous outputs of a model."
},
{
"code": null,
"e": 4233,
"s": 4216,
"text": "en.wikipedia.org"
},
{
"code": null,
"e": 4432,
"s": 4233,
"text": "Monte Carlo Search — A randomized search algorithm that will return the best estimate of the correct search result when terminated. Monte Carlo algorithms are always fast, but only probably correct."
},
{
"code": null,
"e": 4449,
"s": 4432,
"text": "en.wikipedia.org"
},
{
"code": null,
"e": 4637,
"s": 4449,
"text": "Las Vegas Search Is a randomized search algorithm unlike Monte Carlo it will only return when the correct result is found. Las Vegas algorithms are always correct, but only probably fast."
},
{
"code": null,
"e": 4727,
"s": 4637,
"text": "// Las Vegas algorithm2 repeat:3 k = RandInt(n)4 if A[k] == 1,5 return k;"
},
{
"code": null,
"e": 4744,
"s": 4727,
"text": "en.wikipedia.org"
},
{
"code": null,
"e": 4923,
"s": 4744,
"text": "Atlantic City Search — Is a bounded probabilistic polynomial time search algorithm that combines the strengths and weaknesses of the Las Vegas and Monte Carlos Search algorithms."
},
{
"code": null,
"e": 4940,
"s": 4923,
"text": "en.wikipedia.org"
},
{
"code": null,
"e": 5205,
"s": 4940,
"text": "If you enjoyed this article, keep your eyes out for new content shortly and follow me here on medium or twitter @pythiccoder. To get started experimenting with these algorithms check out Azure Notebooks as well as the graph data base features of CosmosDB on Azure."
},
{
"code": null,
"e": 5280,
"s": 5205,
"text": "If you don’t have one yet you can pick up a free Azure Subscription below."
},
{
"code": null,
"e": 5300,
"s": 5280,
"text": "azure.microsoft.com"
}
] |
ASP.NET - Directives
|
ASP.NET directives are instructions to specify optional settings, such as registering a custom control and page language. These settings describe how the web forms (.aspx) or user controls (.ascx) pages are processed by the .Net framework.
The syntax for declaring a directive is:
<%@ directive_name attribute=value [attribute=value] %>
In this section, we will just introduce the ASP.NET directives and we will use most of these directives throughout the tutorials.
The Application directive defines application-specific attributes. It is provided at the top of the global.aspx file.
The basic syntax of Application directive is:
<%@ Application Language="C#" %>
The attributes of the Application directive are:
The Assembly directive links an assembly to the page or the application at parse time. This could appear either in the global.asax file for application-wide linking, in the page file, a user control file for linking to a page or user control.
The basic syntax of Assembly directive is:
<%@ Assembly Name ="myassembly" %>
The attributes of the Assembly directive are:
The control directive is used with the user controls and appears in the user control (.ascx) files.
The basic syntax of Control directive is:
<%@ Control Language="C#" EnableViewState="false" %>
The attributes of the Control directive are:
The Implement directive indicates that the web page, master page or user control page must implement the specified .Net framework interface.
The basic syntax for implements directive is:
<%@ Implements Interface="interface_name" %>
The Import directive imports a namespace into a web page, user control page of application. If the Import directive is specified in the global.asax file, then it is applied to the entire application. If it is in a page of user control page, then it is applied to that page or control.
The basic syntax for import directive is:
<%@ namespace="System.Drawing" %>
The Master directive specifies a page file as being the mater page.
The basic syntax of sample MasterPage directive is:
<%@ MasterPage Language="C#" AutoEventWireup="true" CodeFile="SiteMater.master.cs" Inherits="SiteMaster" %>
The MasterType directive assigns a class name to the Master property of a page, to make it strongly typed.
The basic syntax of MasterType directive is:
<%@ MasterType attribute="value"[attribute="value" ...] %>
The OutputCache directive controls the output caching policies of a web page or a user control.
The basic syntax of OutputCache directive is:
<%@ OutputCache Duration="15" VaryByParam="None" %>
The Page directive defines the attributes specific to the page file for the page parser and the compiler.
The basic syntax of Page directive is:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Trace="true" %>
The attributes of the Page directive are:
The PreviousPageType directive assigns a class to a page, so that the page is strongly typed.
The basic syntax for a sample PreviousPagetype directive is:
<%@ PreviousPageType attribute="value"[attribute="value" ...] %>
The Reference directive indicates that another page or user control should be compiled and linked to the current page.
The basic syntax of Reference directive is:
<%@ Reference Page ="somepage.aspx" %>
The Register derivative is used for registering the custom server controls and user controls.
The basic syntax of Register directive is:
<%@ Register Src="~/footer.ascx" TagName="footer" TagPrefix="Tfooter" %>
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2587,
"s": 2347,
"text": "ASP.NET directives are instructions to specify optional settings, such as registering a custom control and page language. These settings describe how the web forms (.aspx) or user controls (.ascx) pages are processed by the .Net framework."
},
{
"code": null,
"e": 2628,
"s": 2587,
"text": "The syntax for declaring a directive is:"
},
{
"code": null,
"e": 2687,
"s": 2628,
"text": "<%@ directive_name attribute=value [attribute=value] %>"
},
{
"code": null,
"e": 2817,
"s": 2687,
"text": "In this section, we will just introduce the ASP.NET directives and we will use most of these directives throughout the tutorials."
},
{
"code": null,
"e": 2935,
"s": 2817,
"text": "The Application directive defines application-specific attributes. It is provided at the top of the global.aspx file."
},
{
"code": null,
"e": 2981,
"s": 2935,
"text": "The basic syntax of Application directive is:"
},
{
"code": null,
"e": 3014,
"s": 2981,
"text": "<%@ Application Language=\"C#\" %>"
},
{
"code": null,
"e": 3063,
"s": 3014,
"text": "The attributes of the Application directive are:"
},
{
"code": null,
"e": 3306,
"s": 3063,
"text": "The Assembly directive links an assembly to the page or the application at parse time. This could appear either in the global.asax file for application-wide linking, in the page file, a user control file for linking to a page or user control."
},
{
"code": null,
"e": 3349,
"s": 3306,
"text": "The basic syntax of Assembly directive is:"
},
{
"code": null,
"e": 3384,
"s": 3349,
"text": "<%@ Assembly Name =\"myassembly\" %>"
},
{
"code": null,
"e": 3431,
"s": 3384,
"text": "The attributes of the Assembly directive are:"
},
{
"code": null,
"e": 3531,
"s": 3431,
"text": "The control directive is used with the user controls and appears in the user control (.ascx) files."
},
{
"code": null,
"e": 3573,
"s": 3531,
"text": "The basic syntax of Control directive is:"
},
{
"code": null,
"e": 3627,
"s": 3573,
"text": "<%@ Control Language=\"C#\" EnableViewState=\"false\" %>"
},
{
"code": null,
"e": 3672,
"s": 3627,
"text": "The attributes of the Control directive are:"
},
{
"code": null,
"e": 3813,
"s": 3672,
"text": "The Implement directive indicates that the web page, master page or user control page must implement the specified .Net framework interface."
},
{
"code": null,
"e": 3859,
"s": 3813,
"text": "The basic syntax for implements directive is:"
},
{
"code": null,
"e": 3905,
"s": 3859,
"text": "<%@ Implements Interface=\"interface_name\" %>"
},
{
"code": null,
"e": 4190,
"s": 3905,
"text": "The Import directive imports a namespace into a web page, user control page of application. If the Import directive is specified in the global.asax file, then it is applied to the entire application. If it is in a page of user control page, then it is applied to that page or control."
},
{
"code": null,
"e": 4232,
"s": 4190,
"text": "The basic syntax for import directive is:"
},
{
"code": null,
"e": 4266,
"s": 4232,
"text": "<%@ namespace=\"System.Drawing\" %>"
},
{
"code": null,
"e": 4334,
"s": 4266,
"text": "The Master directive specifies a page file as being the mater page."
},
{
"code": null,
"e": 4386,
"s": 4334,
"text": "The basic syntax of sample MasterPage directive is:"
},
{
"code": null,
"e": 4497,
"s": 4386,
"text": "<%@ MasterPage Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"SiteMater.master.cs\" Inherits=\"SiteMaster\" %>"
},
{
"code": null,
"e": 4604,
"s": 4497,
"text": "The MasterType directive assigns a class name to the Master property of a page, to make it strongly typed."
},
{
"code": null,
"e": 4649,
"s": 4604,
"text": "The basic syntax of MasterType directive is:"
},
{
"code": null,
"e": 4709,
"s": 4649,
"text": "<%@ MasterType attribute=\"value\"[attribute=\"value\" ...] %>"
},
{
"code": null,
"e": 4805,
"s": 4709,
"text": "The OutputCache directive controls the output caching policies of a web page or a user control."
},
{
"code": null,
"e": 4851,
"s": 4805,
"text": "The basic syntax of OutputCache directive is:"
},
{
"code": null,
"e": 4904,
"s": 4851,
"text": "<%@ OutputCache Duration=\"15\" VaryByParam=\"None\" %>"
},
{
"code": null,
"e": 5010,
"s": 4904,
"text": "The Page directive defines the attributes specific to the page file for the page parser and the compiler."
},
{
"code": null,
"e": 5049,
"s": 5010,
"text": "The basic syntax of Page directive is:"
},
{
"code": null,
"e": 5161,
"s": 5049,
"text": "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"Default.aspx.cs\" Inherits=\"_Default\" Trace=\"true\" %>"
},
{
"code": null,
"e": 5203,
"s": 5161,
"text": "The attributes of the Page directive are:"
},
{
"code": null,
"e": 5297,
"s": 5203,
"text": "The PreviousPageType directive assigns a class to a page, so that the page is strongly typed."
},
{
"code": null,
"e": 5358,
"s": 5297,
"text": "The basic syntax for a sample PreviousPagetype directive is:"
},
{
"code": null,
"e": 5425,
"s": 5358,
"text": "<%@ PreviousPageType attribute=\"value\"[attribute=\"value\" ...] %>"
},
{
"code": null,
"e": 5544,
"s": 5425,
"text": "The Reference directive indicates that another page or user control should be compiled and linked to the current page."
},
{
"code": null,
"e": 5588,
"s": 5544,
"text": "The basic syntax of Reference directive is:"
},
{
"code": null,
"e": 5627,
"s": 5588,
"text": "<%@ Reference Page =\"somepage.aspx\" %>"
},
{
"code": null,
"e": 5721,
"s": 5627,
"text": "The Register derivative is used for registering the custom server controls and user controls."
},
{
"code": null,
"e": 5765,
"s": 5721,
"text": "The basic syntax of Register directive is:"
},
{
"code": null,
"e": 5838,
"s": 5765,
"text": "<%@ Register Src=\"~/footer.ascx\" TagName=\"footer\" TagPrefix=\"Tfooter\" %>"
},
{
"code": null,
"e": 5873,
"s": 5838,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5887,
"s": 5873,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5922,
"s": 5887,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5945,
"s": 5922,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 5979,
"s": 5945,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 5999,
"s": 5979,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 6034,
"s": 5999,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6051,
"s": 6034,
"text": " University Code"
},
{
"code": null,
"e": 6086,
"s": 6051,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6103,
"s": 6086,
"text": " University Code"
},
{
"code": null,
"e": 6137,
"s": 6103,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 6152,
"s": 6137,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 6159,
"s": 6152,
"text": " Print"
},
{
"code": null,
"e": 6170,
"s": 6159,
"text": " Add Notes"
}
] |
How to access Static variable of Outer class from Static Inner class in java?
|
A class with in another class is known as inner class, you cannot declare a class static unless it is an inner class. A static inner class is just like other class variables. You can access it (static inner class) without instantiation
You can access the static variable of an outer class just using the class name. Following Java example demonstrates how to access static variables of a class from a static inner class.
public class Outer {
static int data = 200;
static class InnerDemo {
public void my_method() {
System.out.println("This is my nested class");
System.out.println(Outer.data);
}
}
public static void main(String args[]) {
Outer.InnerDemo nested = new Outer.InnerDemo();
nested.my_method();
}
}
This is my nested class
200
|
[
{
"code": null,
"e": 1298,
"s": 1062,
"text": "A class with in another class is known as inner class, you cannot declare a class static unless it is an inner class. A static inner class is just like other class variables. You can access it (static inner class) without instantiation"
},
{
"code": null,
"e": 1483,
"s": 1298,
"text": "You can access the static variable of an outer class just using the class name. Following Java example demonstrates how to access static variables of a class from a static inner class."
},
{
"code": null,
"e": 1831,
"s": 1483,
"text": "public class Outer {\n static int data = 200;\n static class InnerDemo {\n public void my_method() {\n System.out.println(\"This is my nested class\");\n System.out.println(Outer.data);\n }\n }\n public static void main(String args[]) {\n Outer.InnerDemo nested = new Outer.InnerDemo();\n nested.my_method();\n }\n}"
},
{
"code": null,
"e": 1859,
"s": 1831,
"text": "This is my nested class\n200"
}
] |
C++ Program to Perform Inorder Non-Recursive Traversal of a Given Binary Tree
|
If a binary tree is traversed in-order, the left subtree is visited first, then the root and later the right sub-tree. The output the key in ascending order in in_order traversal. This is a C++ Program for Inorder Tree Traversal without Recursion.
Begin
Declare a structure n.
Declare d of the integer datatype.
Declare a pointer l against structure n.
Declare a pointer r against structure n.
Declare a constructor of structure n.
Pass an integer variable d to parameter.
this->d = d
l = r = NULL
Declare inOrder(struct n *root) function.
Declare a stack s.
Declare a pointer current against structure n.
Initialize n *current = root.
while (current != NULL || s.empty() == false)
while (current != NULL)
s.push(current)
current = current->l
current = s.top()
s.pop()
print current->d.
current = current->r.
insert values in nodes of tree.
Call inOrder(root) function to travern the tree.
End.
Live Demo
#include<bits/stdc++.h>
using namespace std;
struct n {
int d;
struct n* l;
struct n* r;
n (int d) {
this->d = d;
l = r = NULL;
}
};
void inOrder(struct n *root) {
stack<n *> s;
n *current = root;
while (current != NULL || s.empty() == false) {
while (current != NULL) {
s.push(current);
current = current->l;
}
current = s.top();
s.pop();
cout << current->d << " ";
current = current->r;
}
}
int main() {
struct n* root = new n(6);
root->l = new n(4);
root->r= new n(7);
root->l->l = new n(8);
root->l->r= new n(5);
root->r->l = new n(9);
root->r->r = new n(10);
inOrder(root);
return 0;
}
8 4 5 6 9 7 10
|
[
{
"code": null,
"e": 1310,
"s": 1062,
"text": "If a binary tree is traversed in-order, the left subtree is visited first, then the root and later the right sub-tree. The output the key in ascending order in in_order traversal. This is a C++ Program for Inorder Tree Traversal without Recursion."
},
{
"code": null,
"e": 2117,
"s": 1310,
"text": "Begin\n Declare a structure n.\n Declare d of the integer datatype.\n Declare a pointer l against structure n.\n Declare a pointer r against structure n.\n Declare a constructor of structure n.\n Pass an integer variable d to parameter.\n this->d = d\n l = r = NULL\n Declare inOrder(struct n *root) function.\n Declare a stack s.\n Declare a pointer current against structure n.\n Initialize n *current = root.\n while (current != NULL || s.empty() == false)\n while (current != NULL)\n s.push(current)\n current = current->l\n current = s.top()\n s.pop()\n print current->d.\n current = current->r.\n insert values in nodes of tree.\n Call inOrder(root) function to travern the tree.\nEnd.\n"
},
{
"code": null,
"e": 2128,
"s": 2117,
"text": " Live Demo"
},
{
"code": null,
"e": 2839,
"s": 2128,
"text": "#include<bits/stdc++.h>\nusing namespace std;\nstruct n {\n int d;\n struct n* l;\n struct n* r;\n n (int d) {\n this->d = d;\n l = r = NULL;\n }\n};\nvoid inOrder(struct n *root) {\n stack<n *> s;\n n *current = root;\n while (current != NULL || s.empty() == false) {\n while (current != NULL) {\n s.push(current);\n current = current->l;\n }\n current = s.top();\n s.pop();\n cout << current->d << \" \";\n current = current->r;\n }\n}\nint main() {\n struct n* root = new n(6);\n root->l = new n(4);\n root->r= new n(7);\n root->l->l = new n(8);\n root->l->r= new n(5);\n root->r->l = new n(9);\n root->r->r = new n(10);\n inOrder(root);\n return 0;\n}"
},
{
"code": null,
"e": 2854,
"s": 2839,
"text": "8 4 5 6 9 7 10"
}
] |
C# Program to skip elements of an array from the end
|
Declare an array and initialize elements.
int[] marks = { 45, 50, 60, 70, 85 };
Use the SkipLast() method to skip elements of an array from the end.
IEnumerable<int> selMarks = marks.AsQueryable().SkipLast(3);
The elements are skipped and rest of the elements is returned as shown below −
Live Demo
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
public static void Main() {
int[] marks = { 45, 50, 60, 70, 85 };
Console.WriteLine("Array...");
foreach (int res in marks)
Console.WriteLine(res);
IEnumerable<int> selMarks = marks.AsQueryable().SkipLast(3);
Console.WriteLine("Array after skipping last 3 elements...");
foreach (int res in selMarks)
Console.WriteLine(res);
}
}
Array...
45
50
60
70
85
Array after skipping last 3 elements...
45
50
|
[
{
"code": null,
"e": 1104,
"s": 1062,
"text": "Declare an array and initialize elements."
},
{
"code": null,
"e": 1142,
"s": 1104,
"text": "int[] marks = { 45, 50, 60, 70, 85 };"
},
{
"code": null,
"e": 1211,
"s": 1142,
"text": "Use the SkipLast() method to skip elements of an array from the end."
},
{
"code": null,
"e": 1272,
"s": 1211,
"text": "IEnumerable<int> selMarks = marks.AsQueryable().SkipLast(3);"
},
{
"code": null,
"e": 1351,
"s": 1272,
"text": "The elements are skipped and rest of the elements is returned as shown below −"
},
{
"code": null,
"e": 1362,
"s": 1351,
"text": " Live Demo"
},
{
"code": null,
"e": 1834,
"s": 1362,
"text": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main() {\n int[] marks = { 45, 50, 60, 70, 85 };\n Console.WriteLine(\"Array...\");\n\n foreach (int res in marks)\n Console.WriteLine(res);\n IEnumerable<int> selMarks = marks.AsQueryable().SkipLast(3);\n Console.WriteLine(\"Array after skipping last 3 elements...\");\n\n foreach (int res in selMarks)\n Console.WriteLine(res);\n }\n}"
},
{
"code": null,
"e": 1904,
"s": 1834,
"text": "Array...\n45\n50\n60\n70\n85\nArray after skipping last 3 elements...\n45\n50"
}
] |
Search and Replace with Java regular expressions
|
Java provides the java.util.regex package for pattern matching with regular expressions. Java regular expressions are very similar to the Perl programming language and very easy to learn.
A regular expression is a special sequence of characters that help you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data.
The replaceFirst() and replaceAll() methods replace the text that matches a given regular expression. As their names indicate, replaceFirst replaces the first occurrence, and replaceAll replaces all occurrences.
Live Demo
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches {
private static String REGEX = "dog";
private static String INPUT = "The dog says meow. " + "All dogs say meow.";
private static String REPLACE = "cat";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
//get a matcher object
Matcher m = p.matcher(INPUT);
INPUT = m.replaceAll(REPLACE);
System.out.println(INPUT);
}
}
The cat says meow. All cats say meow.
|
[
{
"code": null,
"e": 1250,
"s": 1062,
"text": "Java provides the java.util.regex package for pattern matching with regular expressions. Java regular expressions are very similar to the Perl programming language and very easy to learn."
},
{
"code": null,
"e": 1478,
"s": 1250,
"text": "A regular expression is a special sequence of characters that help you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data."
},
{
"code": null,
"e": 1690,
"s": 1478,
"text": "The replaceFirst() and replaceAll() methods replace the text that matches a given regular expression. As their names indicate, replaceFirst replaces the first occurrence, and replaceAll replaces all occurrences."
},
{
"code": null,
"e": 1700,
"s": 1690,
"text": "Live Demo"
},
{
"code": null,
"e": 2182,
"s": 1700,
"text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class RegexMatches {\n private static String REGEX = \"dog\";\n private static String INPUT = \"The dog says meow. \" + \"All dogs say meow.\";\n private static String REPLACE = \"cat\";\n\n public static void main(String[] args) {\n Pattern p = Pattern.compile(REGEX);\n //get a matcher object\n Matcher m = p.matcher(INPUT);\n INPUT = m.replaceAll(REPLACE);\n System.out.println(INPUT);\n }\n}"
},
{
"code": null,
"e": 2220,
"s": 2182,
"text": "The cat says meow. All cats say meow."
}
] |
How to Create Blink Effect on TextView in Android? - GeeksforGeeks
|
21 Apr, 2021
In this article, we are going to implement a very important feature related to TextView. Here we are adding the blink text feature on a TextView. This feature can be used to show important announcements or notifications in an App. Even we can add this feature to show important links for the user. So here we are going to learn how to implement that feature. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
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"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="20dp" android:orientation="vertical" android:padding="20dp" tools:context=".MainActivity"> <TextView android:id="@+id/blinktext" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_margin="15dp" android:gravity="center" android:text="Blink Effect" android:textColor="@color/black" android:textSize="30dp" /> <Button android:id="@+id/blinkb" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="15dp" android:background="@color/teal_200" android:padding="20dp" android:text="Blink Text" /> </LinearLayout>
Step 3: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.animation.ArgbEvaluator;import android.animation.ObjectAnimator;import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.view.animation.Animation;import android.widget.Button;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { TextView blinkt; Button blinkb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); blinkb = findViewById(R.id.blinkb); blinkt = findViewById(R.id.blinktext); blinkb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // adding the color to be shown ObjectAnimator animator = ObjectAnimator.ofInt(blinkt, "backgroundColor", Color.BLUE, Color.RED, Color.GREEN); // duration of one color animator.setDuration(500); animator.setEvaluator(new ArgbEvaluator()); // color will be show in reverse manner animator.setRepeatCount(Animation.REVERSE); // It will be repeated up to infinite time animator.setRepeatCount(Animation.INFINITE); animator.start(); } }); }}
Output:
Android-View
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Retrofit with Kotlin Coroutine in Android
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Android Listview in Java with Example
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
|
[
{
"code": null,
"e": 25036,
"s": 25008,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 25560,
"s": 25036,
"text": "In this article, we are going to implement a very important feature related to TextView. Here we are adding the blink text feature on a TextView. This feature can be used to show important announcements or notifications in an App. Even we can add this feature to show important links for the user. So here we are going to learn how to implement that feature. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 25589,
"s": 25560,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 25751,
"s": 25589,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 25799,
"s": 25751,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 25942,
"s": 25799,
"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": 25946,
"s": 25942,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"20dp\" android:orientation=\"vertical\" android:padding=\"20dp\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/blinktext\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_alignParentTop=\"true\" android:layout_centerHorizontal=\"true\" android:layout_margin=\"15dp\" android:gravity=\"center\" android:text=\"Blink Effect\" android:textColor=\"@color/black\" android:textSize=\"30dp\" /> <Button android:id=\"@+id/blinkb\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"15dp\" android:background=\"@color/teal_200\" android:padding=\"20dp\" android:text=\"Blink Text\" /> </LinearLayout>",
"e": 27018,
"s": 25946,
"text": null
},
{
"code": null,
"e": 27066,
"s": 27018,
"text": "Step 3: Working with the MainActivity.java file"
},
{
"code": null,
"e": 27256,
"s": 27066,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 27261,
"s": 27256,
"text": "Java"
},
{
"code": "import android.animation.ArgbEvaluator;import android.animation.ObjectAnimator;import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.view.animation.Animation;import android.widget.Button;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { TextView blinkt; Button blinkb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); blinkb = findViewById(R.id.blinkb); blinkt = findViewById(R.id.blinktext); blinkb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // adding the color to be shown ObjectAnimator animator = ObjectAnimator.ofInt(blinkt, \"backgroundColor\", Color.BLUE, Color.RED, Color.GREEN); // duration of one color animator.setDuration(500); animator.setEvaluator(new ArgbEvaluator()); // color will be show in reverse manner animator.setRepeatCount(Animation.REVERSE); // It will be repeated up to infinite time animator.setRepeatCount(Animation.INFINITE); animator.start(); } }); }}",
"e": 28741,
"s": 27261,
"text": null
},
{
"code": null,
"e": 28749,
"s": 28741,
"text": "Output:"
},
{
"code": null,
"e": 28762,
"s": 28749,
"text": "Android-View"
},
{
"code": null,
"e": 28770,
"s": 28762,
"text": "Android"
},
{
"code": null,
"e": 28775,
"s": 28770,
"text": "Java"
},
{
"code": null,
"e": 28780,
"s": 28775,
"text": "Java"
},
{
"code": null,
"e": 28788,
"s": 28780,
"text": "Android"
},
{
"code": null,
"e": 28886,
"s": 28788,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28895,
"s": 28886,
"text": "Comments"
},
{
"code": null,
"e": 28908,
"s": 28895,
"text": "Old Comments"
},
{
"code": null,
"e": 28950,
"s": 28908,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 28989,
"s": 28950,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 29039,
"s": 28989,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 29090,
"s": 29039,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 29128,
"s": 29090,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 29143,
"s": 29128,
"text": "Arrays in Java"
},
{
"code": null,
"e": 29187,
"s": 29143,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 29209,
"s": 29187,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 29234,
"s": 29209,
"text": "Reverse a string in Java"
}
] |
TimeSpan.FromTicks() Method in C#
|
The TimeSpan.FromTicks() method in C# is used to return a TimeSpan that represents a specified time, where the specification is in units of ticks.
The syntax is as follows -
public static TimeSpan FromTicks (long val);
Above, the parameter val is the number of ticks that represent a time.
Let us now see an example -
Live Demo
using System;
public class Demo {
public static void Main() {
TimeSpan span1 = TimeSpan.FromTicks(18768768);
TimeSpan span2 = new TimeSpan(-9, 45, 50);
TimeSpan span3 = TimeSpan.FromHours(5);
TimeSpan span4 = TimeSpan.FromMilliseconds(10000);
TimeSpan span5 = TimeSpan.FromMinutes(2);
TimeSpan span6 = TimeSpan.FromMinutes(20);
Console.WriteLine("TimeSpan1 = "+span1);
Console.WriteLine("TimeSpan2 = "+span2);
Console.WriteLine("TimeSpan3 = "+span3);
Console.WriteLine("TimeSpan4 = "+span4);
Console.WriteLine("TimeSpan5 = "+span5);
Console.WriteLine("Result (Comparison of span1 and span2) = "+TimeSpan.Compare(span1, span2));
Console.WriteLine("Result (Comparison of span2 and span3) = "+TimeSpan.Compare(span2, span3));
Console.WriteLine("Result (Comparison of span1 and span3) = "+TimeSpan.Compare(span1, span3));
Console.WriteLine("Result (Comparison of span3 and span4) = "+TimeSpan.Compare(span3, span4));
Console.WriteLine("Result (Comparison of span4 and span5) = "+TimeSpan.Compare(span4, span5));
}
}
This will produce the following output -
TimeSpan1 = 00:00:01.8768768
TimeSpan2 = -08:14:10
TimeSpan3 = 05:00:00
TimeSpan4 = 00:00:10
TimeSpan5 = 00:02:00
Result (Comparison of span1 and span2) = 1
Result (Comparison of span2 and span3) = -1
Result (Comparison of span1 and span3) = -1
Result (Comparison of span3 and span4) = 1
Result (Comparison of span4 and span5) = -1
Let us now see another example -
Live Demo
using System;
public class Demo {
public static void Main() {
TimeSpan span1 = TimeSpan.FromTicks(1);
TimeSpan span2 = new TimeSpan(1);
TimeSpan span3 = TimeSpan.FromHours(1);
TimeSpan span4 = TimeSpan.FromMilliseconds(1);
TimeSpan span5 = TimeSpan.FromMinutes(1);
TimeSpan span6 = TimeSpan.FromMinutes(1);
Console.WriteLine("TimeSpan1 = "+span1);
Console.WriteLine("TimeSpan2 = "+span2);
Console.WriteLine("TimeSpan3 = "+span3);
Console.WriteLine("TimeSpan4 = "+span4);
Console.WriteLine("TimeSpan5 = "+span5);
Console.WriteLine("Result (Comparison of span1 and span2) = "+TimeSpan.Compare(span1, span2));
Console.WriteLine("Result (Comparison of span2 and span3) = "+TimeSpan.Compare(span2, span3));
Console.WriteLine("Result (Comparison of span1 and span3) = "+TimeSpan.Compare(span1, span3));
Console.WriteLine("Result (Comparison of span3 and span4) = "+TimeSpan.Compare(span3, span4));
Console.WriteLine("Result (Comparison of span4 and span5) = "+TimeSpan.Compare(span4, span5));
}
}
TimeSpan1 = 00:00:00.0000001
TimeSpan2 = 00:00:00.0000001
TimeSpan3 = 01:00:00
TimeSpan4 = 00:00:00.0010000
TimeSpan5 = 00:01:00
Result (Comparison of span1 and span2) = 0
Result (Comparison of span2 and span3) = -1
Result (Comparison of span1 and span3) = -1
Result (Comparison of span3 and span4) = 1
Result (Comparison of span4 and span5) = -1
|
[
{
"code": null,
"e": 1209,
"s": 1062,
"text": "The TimeSpan.FromTicks() method in C# is used to return a TimeSpan that represents a specified time, where the specification is in units of ticks."
},
{
"code": null,
"e": 1236,
"s": 1209,
"text": "The syntax is as follows -"
},
{
"code": null,
"e": 1281,
"s": 1236,
"text": "public static TimeSpan FromTicks (long val);"
},
{
"code": null,
"e": 1352,
"s": 1281,
"text": "Above, the parameter val is the number of ticks that represent a time."
},
{
"code": null,
"e": 1380,
"s": 1352,
"text": "Let us now see an example -"
},
{
"code": null,
"e": 1391,
"s": 1380,
"text": " Live Demo"
},
{
"code": null,
"e": 2505,
"s": 1391,
"text": "using System;\npublic class Demo {\n public static void Main() {\n TimeSpan span1 = TimeSpan.FromTicks(18768768);\n TimeSpan span2 = new TimeSpan(-9, 45, 50);\n TimeSpan span3 = TimeSpan.FromHours(5);\n TimeSpan span4 = TimeSpan.FromMilliseconds(10000);\n TimeSpan span5 = TimeSpan.FromMinutes(2);\n TimeSpan span6 = TimeSpan.FromMinutes(20);\n Console.WriteLine(\"TimeSpan1 = \"+span1);\n Console.WriteLine(\"TimeSpan2 = \"+span2);\n Console.WriteLine(\"TimeSpan3 = \"+span3);\n Console.WriteLine(\"TimeSpan4 = \"+span4);\n Console.WriteLine(\"TimeSpan5 = \"+span5);\n Console.WriteLine(\"Result (Comparison of span1 and span2) = \"+TimeSpan.Compare(span1, span2));\n Console.WriteLine(\"Result (Comparison of span2 and span3) = \"+TimeSpan.Compare(span2, span3));\n Console.WriteLine(\"Result (Comparison of span1 and span3) = \"+TimeSpan.Compare(span1, span3));\n Console.WriteLine(\"Result (Comparison of span3 and span4) = \"+TimeSpan.Compare(span3, span4));\n Console.WriteLine(\"Result (Comparison of span4 and span5) = \"+TimeSpan.Compare(span4, span5));\n }\n}"
},
{
"code": null,
"e": 2546,
"s": 2505,
"text": "This will produce the following output -"
},
{
"code": null,
"e": 2878,
"s": 2546,
"text": "TimeSpan1 = 00:00:01.8768768\nTimeSpan2 = -08:14:10\nTimeSpan3 = 05:00:00\nTimeSpan4 = 00:00:10\nTimeSpan5 = 00:02:00\nResult (Comparison of span1 and span2) = 1\nResult (Comparison of span2 and span3) = -1\nResult (Comparison of span1 and span3) = -1\nResult (Comparison of span3 and span4) = 1\nResult (Comparison of span4 and span5) = -1"
},
{
"code": null,
"e": 2911,
"s": 2878,
"text": "Let us now see another example -"
},
{
"code": null,
"e": 2922,
"s": 2911,
"text": " Live Demo"
},
{
"code": null,
"e": 4015,
"s": 2922,
"text": "using System;\npublic class Demo {\n public static void Main() {\n TimeSpan span1 = TimeSpan.FromTicks(1);\n TimeSpan span2 = new TimeSpan(1);\n TimeSpan span3 = TimeSpan.FromHours(1);\n TimeSpan span4 = TimeSpan.FromMilliseconds(1);\n TimeSpan span5 = TimeSpan.FromMinutes(1);\n TimeSpan span6 = TimeSpan.FromMinutes(1);\n Console.WriteLine(\"TimeSpan1 = \"+span1);\n Console.WriteLine(\"TimeSpan2 = \"+span2);\n Console.WriteLine(\"TimeSpan3 = \"+span3);\n Console.WriteLine(\"TimeSpan4 = \"+span4);\n Console.WriteLine(\"TimeSpan5 = \"+span5);\n Console.WriteLine(\"Result (Comparison of span1 and span2) = \"+TimeSpan.Compare(span1, span2));\n Console.WriteLine(\"Result (Comparison of span2 and span3) = \"+TimeSpan.Compare(span2, span3));\n Console.WriteLine(\"Result (Comparison of span1 and span3) = \"+TimeSpan.Compare(span1, span3));\n Console.WriteLine(\"Result (Comparison of span3 and span4) = \"+TimeSpan.Compare(span3, span4));\n Console.WriteLine(\"Result (Comparison of span4 and span5) = \"+TimeSpan.Compare(span4, span5));\n }\n}"
},
{
"code": null,
"e": 4362,
"s": 4015,
"text": "TimeSpan1 = 00:00:00.0000001\nTimeSpan2 = 00:00:00.0000001\nTimeSpan3 = 01:00:00\nTimeSpan4 = 00:00:00.0010000\nTimeSpan5 = 00:01:00\nResult (Comparison of span1 and span2) = 0\nResult (Comparison of span2 and span3) = -1\nResult (Comparison of span1 and span3) = -1\nResult (Comparison of span3 and span4) = 1\nResult (Comparison of span4 and span5) = -1"
}
] |
Automating Version Tags and Changelogs for your Python Projects | by Niels D. Goet | Towards Data Science
|
Tired of keeping track of whether your code changes warrant a minor or major version increment? Too busy to keep a neat and tidy changelog? Try using commitizen, a command-line utility that “forces” you to write commit messages following the Conventional commits standard (or a different, user-defined format). Once configured, commitizen will bump the semantic versioning of your code automatically based on your commits, and update your changelog.
Commitizen is configured in five simple steps. First, you need to install commitizen:
pip install commitizen
Second, add a reference to your code’s current version number to your __init__.py file, or add a separate __version__.py file as shown below:
Third, update your .pre-commit-config.yaml to include a pre-commit hook for commitizen (if you’re unfamiliar with pre-commit hooks, check out my earlier blog post on using pre-commit hooks for improving code style):
Fourth, update your pyproject.toml file to include commitizen, which references the current version of your code as well as other locations in your code where the version needs to be updated upon a commit (such as your setup.py file):
Finally, run pre-commit install --hook-type commit-msg to set up the commitizen pre-commit hook.
Now that we’ve installed and configured commitizen, let’s take a look at its use in your git workflow.
Let’s assume you’ve checked out a new (feature) branch and you’ve made some changes that you’d like to commit. Instead of using the conventional git commit '<commit-message>' command after adding (un)tracked files, we use the commitizen commit command (or cz c in short). Using this command will prompt a bunch of options:
Use the selection menu to classify the kinds of changes you’ve made (e.g. a bug fix, or a new feature), and add a commit message when prompted to do so. This will prefix the commit message with the selected code change classification (e.g. feat or fix). For example, if you’ve added a new feature, the commitizen-generated commit message may look as follows:
doc: update README
After you’ve made your commit and pushed your branch, registered a PR, and merged to master (or “main”), check out the master branch and run:
cz bump --check-consistency --changelog
This will check the consistency of the versions in your commitizen configuration (and code), and generate or update a changelog (see here for an example of a commitizen-based changelog). Subsequently, run the following commands to update the changelog and version references on your branch, and push the new version tag:
git pushgit push --tags
And that’s it — now you’re all set up for automated version and changelog bumps for your Python project based on your commit history. Thanks for reading!
P.s. if this all went a bit too fast, have a look at this repo I set up for a different blog post, where I’ve used commitizen for versioning.
Support my work: If you liked this article and you’d like to support my work, please consider becoming a paying Medium member via my referral page. The price of the subscription is the same if you sign up via my referral page, but I will receive part of your monthly membership fee.
If you liked this article, here are some other articles you may enjoy:
python.plainenglish.io
towardsdatascience.com
towardsdatascience.com
Please read this disclaimer carefully before relying on any of the content in my articles on Medium.com.
|
[
{
"code": null,
"e": 622,
"s": 172,
"text": "Tired of keeping track of whether your code changes warrant a minor or major version increment? Too busy to keep a neat and tidy changelog? Try using commitizen, a command-line utility that “forces” you to write commit messages following the Conventional commits standard (or a different, user-defined format). Once configured, commitizen will bump the semantic versioning of your code automatically based on your commits, and update your changelog."
},
{
"code": null,
"e": 708,
"s": 622,
"text": "Commitizen is configured in five simple steps. First, you need to install commitizen:"
},
{
"code": null,
"e": 731,
"s": 708,
"text": "pip install commitizen"
},
{
"code": null,
"e": 873,
"s": 731,
"text": "Second, add a reference to your code’s current version number to your __init__.py file, or add a separate __version__.py file as shown below:"
},
{
"code": null,
"e": 1089,
"s": 873,
"text": "Third, update your .pre-commit-config.yaml to include a pre-commit hook for commitizen (if you’re unfamiliar with pre-commit hooks, check out my earlier blog post on using pre-commit hooks for improving code style):"
},
{
"code": null,
"e": 1324,
"s": 1089,
"text": "Fourth, update your pyproject.toml file to include commitizen, which references the current version of your code as well as other locations in your code where the version needs to be updated upon a commit (such as your setup.py file):"
},
{
"code": null,
"e": 1421,
"s": 1324,
"text": "Finally, run pre-commit install --hook-type commit-msg to set up the commitizen pre-commit hook."
},
{
"code": null,
"e": 1524,
"s": 1421,
"text": "Now that we’ve installed and configured commitizen, let’s take a look at its use in your git workflow."
},
{
"code": null,
"e": 1847,
"s": 1524,
"text": "Let’s assume you’ve checked out a new (feature) branch and you’ve made some changes that you’d like to commit. Instead of using the conventional git commit '<commit-message>' command after adding (un)tracked files, we use the commitizen commit command (or cz c in short). Using this command will prompt a bunch of options:"
},
{
"code": null,
"e": 2206,
"s": 1847,
"text": "Use the selection menu to classify the kinds of changes you’ve made (e.g. a bug fix, or a new feature), and add a commit message when prompted to do so. This will prefix the commit message with the selected code change classification (e.g. feat or fix). For example, if you’ve added a new feature, the commitizen-generated commit message may look as follows:"
},
{
"code": null,
"e": 2225,
"s": 2206,
"text": "doc: update README"
},
{
"code": null,
"e": 2367,
"s": 2225,
"text": "After you’ve made your commit and pushed your branch, registered a PR, and merged to master (or “main”), check out the master branch and run:"
},
{
"code": null,
"e": 2407,
"s": 2367,
"text": "cz bump --check-consistency --changelog"
},
{
"code": null,
"e": 2728,
"s": 2407,
"text": "This will check the consistency of the versions in your commitizen configuration (and code), and generate or update a changelog (see here for an example of a commitizen-based changelog). Subsequently, run the following commands to update the changelog and version references on your branch, and push the new version tag:"
},
{
"code": null,
"e": 2752,
"s": 2728,
"text": "git pushgit push --tags"
},
{
"code": null,
"e": 2906,
"s": 2752,
"text": "And that’s it — now you’re all set up for automated version and changelog bumps for your Python project based on your commit history. Thanks for reading!"
},
{
"code": null,
"e": 3048,
"s": 2906,
"text": "P.s. if this all went a bit too fast, have a look at this repo I set up for a different blog post, where I’ve used commitizen for versioning."
},
{
"code": null,
"e": 3331,
"s": 3048,
"text": "Support my work: If you liked this article and you’d like to support my work, please consider becoming a paying Medium member via my referral page. The price of the subscription is the same if you sign up via my referral page, but I will receive part of your monthly membership fee."
},
{
"code": null,
"e": 3402,
"s": 3331,
"text": "If you liked this article, here are some other articles you may enjoy:"
},
{
"code": null,
"e": 3425,
"s": 3402,
"text": "python.plainenglish.io"
},
{
"code": null,
"e": 3448,
"s": 3425,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3471,
"s": 3448,
"text": "towardsdatascience.com"
}
] |
Neo4j - Database Backup and Restore
|
In Real-time applications, we should take backup of our application Database regularly so that we can restore to some working condition at any failure point.
This rule is applicable for both RDBMS and No SQL databases.
In this section, we are going to discuss about two important DBA tasks.
How to backup a Neo4j Database.
How to restore Neo4j Database to a specific backup.
NOTE:-
These steps are applicable to Windows Operating System only. We should use similar kind of commands to do the same steps in other Operating Systems.
Step 1 - Click on "Neo4j Community" as shown below
Windows "Start" button >> "All Programs" >> "Neo4j Community" >> "Neo4j Community"
By default, it selects c:\Users\[username]\Documents\Neo4j\default.graphdb. If you want, you can change your path to different directory. Here we have changed to our Neo4j Database folder
C:\Ne04j2.0db
Click on "Start" button.
Once the server is started, we can observe our Neo4j Database files are generated at specified directory
Before taking Database backup, first and foremost thing we should do is shutdown the Neo4j Database server.
Click on "Stop" Button to shutdown the server
Step 2 - Our Neo4j Database files are available at C:\Ne04j2.0db
Step 3 - Open command prompt
Step 4 - Create a folder "Neo4jDbBackup-01" at C:\Neo4j ( This may be any location in your file system)
mkdir C:\Neo4j\Neo4jDbBackup-01
It creates a new folder "Neo4jDbBackup-01" at specified file system location "C:\Neo4j\"
Step 5 - Type the below command and press Enter key
copy C:\Ne04j2.0db C:\Neo4j\Neo4jDbBackup-01
That means our files are copied to required destination folder. Access that folder and observe that folder has our database files.
Step 6 - Use any Windows compression/decompression tool like WinZip, 7 Zip, or WinRar to zip our Database folder.
Now our Neo4jDbBackup-01.zip file is created. If you have any memory constraints in your file system, then remove "Neo4jDbBackup-01" folder at "C:\Neo4j\"
Step 1 - Shutdown the database server. Please refer previous steps to shutdown the server.
Step 2 - Empty the current database folder
Step 3 - Use any Windows compression/decompression tool like WinZip, 7 Zip, or WinRar to unzip our backup folder.
Step 4 - Open command prompt and execute the following command
Copy C:\Neo4j\Neo4jDbBackup-01 C:\Ne04j2.0db
Step 5 - Now we can observe that our database folder contains working backup files
Step 6 - Start the server by clicking on "Start" button.
Now execute some MATCH + RETURN commands to verify whether we have restored our database properly or not
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2497,
"s": 2339,
"text": "In Real-time applications, we should take backup of our application Database regularly so that we can restore to some working condition at any failure point."
},
{
"code": null,
"e": 2558,
"s": 2497,
"text": "This rule is applicable for both RDBMS and No SQL databases."
},
{
"code": null,
"e": 2630,
"s": 2558,
"text": "In this section, we are going to discuss about two important DBA tasks."
},
{
"code": null,
"e": 2662,
"s": 2630,
"text": "How to backup a Neo4j Database."
},
{
"code": null,
"e": 2714,
"s": 2662,
"text": "How to restore Neo4j Database to a specific backup."
},
{
"code": null,
"e": 2721,
"s": 2714,
"text": "NOTE:-"
},
{
"code": null,
"e": 2870,
"s": 2721,
"text": "These steps are applicable to Windows Operating System only. We should use similar kind of commands to do the same steps in other Operating Systems."
},
{
"code": null,
"e": 2921,
"s": 2870,
"text": "Step 1 - Click on \"Neo4j Community\" as shown below"
},
{
"code": null,
"e": 3004,
"s": 2921,
"text": "Windows \"Start\" button >> \"All Programs\" >> \"Neo4j Community\" >> \"Neo4j Community\""
},
{
"code": null,
"e": 3192,
"s": 3004,
"text": "By default, it selects c:\\Users\\[username]\\Documents\\Neo4j\\default.graphdb. If you want, you can change your path to different directory. Here we have changed to our Neo4j Database folder"
},
{
"code": null,
"e": 3206,
"s": 3192,
"text": "C:\\Ne04j2.0db"
},
{
"code": null,
"e": 3231,
"s": 3206,
"text": "Click on \"Start\" button."
},
{
"code": null,
"e": 3336,
"s": 3231,
"text": "Once the server is started, we can observe our Neo4j Database files are generated at specified directory"
},
{
"code": null,
"e": 3444,
"s": 3336,
"text": "Before taking Database backup, first and foremost thing we should do is shutdown the Neo4j Database server."
},
{
"code": null,
"e": 3490,
"s": 3444,
"text": "Click on \"Stop\" Button to shutdown the server"
},
{
"code": null,
"e": 3555,
"s": 3490,
"text": "Step 2 - Our Neo4j Database files are available at C:\\Ne04j2.0db"
},
{
"code": null,
"e": 3584,
"s": 3555,
"text": "Step 3 - Open command prompt"
},
{
"code": null,
"e": 3689,
"s": 3584,
"text": "Step 4 - Create a folder \"Neo4jDbBackup-01\" at C:\\Neo4j ( This may be any location in your file system)"
},
{
"code": null,
"e": 3721,
"s": 3689,
"text": "mkdir C:\\Neo4j\\Neo4jDbBackup-01"
},
{
"code": null,
"e": 3810,
"s": 3721,
"text": "It creates a new folder \"Neo4jDbBackup-01\" at specified file system location \"C:\\Neo4j\\\""
},
{
"code": null,
"e": 3862,
"s": 3810,
"text": "Step 5 - Type the below command and press Enter key"
},
{
"code": null,
"e": 3907,
"s": 3862,
"text": "copy C:\\Ne04j2.0db C:\\Neo4j\\Neo4jDbBackup-01"
},
{
"code": null,
"e": 4038,
"s": 3907,
"text": "That means our files are copied to required destination folder. Access that folder and observe that folder has our database files."
},
{
"code": null,
"e": 4152,
"s": 4038,
"text": "Step 6 - Use any Windows compression/decompression tool like WinZip, 7 Zip, or WinRar to zip our Database folder."
},
{
"code": null,
"e": 4307,
"s": 4152,
"text": "Now our Neo4jDbBackup-01.zip file is created. If you have any memory constraints in your file system, then remove \"Neo4jDbBackup-01\" folder at \"C:\\Neo4j\\\""
},
{
"code": null,
"e": 4398,
"s": 4307,
"text": "Step 1 - Shutdown the database server. Please refer previous steps to shutdown the server."
},
{
"code": null,
"e": 4441,
"s": 4398,
"text": "Step 2 - Empty the current database folder"
},
{
"code": null,
"e": 4555,
"s": 4441,
"text": "Step 3 - Use any Windows compression/decompression tool like WinZip, 7 Zip, or WinRar to unzip our backup folder."
},
{
"code": null,
"e": 4618,
"s": 4555,
"text": "Step 4 - Open command prompt and execute the following command"
},
{
"code": null,
"e": 4663,
"s": 4618,
"text": "Copy C:\\Neo4j\\Neo4jDbBackup-01 C:\\Ne04j2.0db"
},
{
"code": null,
"e": 4746,
"s": 4663,
"text": "Step 5 - Now we can observe that our database folder contains working backup files"
},
{
"code": null,
"e": 4803,
"s": 4746,
"text": "Step 6 - Start the server by clicking on \"Start\" button."
},
{
"code": null,
"e": 4908,
"s": 4803,
"text": "Now execute some MATCH + RETURN commands to verify whether we have restored our database properly or not"
},
{
"code": null,
"e": 4915,
"s": 4908,
"text": " Print"
},
{
"code": null,
"e": 4926,
"s": 4915,
"text": " Add Notes"
}
] |
Bootstrap .modal("show") method
|
The modal(“show”) method opens a modal like below −
The modal is displayed using the modal(“show”) method as shown below −
$("#newModal").modal("show");
Let us see an example of modal(“show”) method −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
#button1 {
width: 140px;
padding: 20px;
bottom: 150px;
z-index: 9999;
font-size: 15px;
position: absolute;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<h2>Sample</h2>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
<button type="button" class="btn btn-default btn-lg" id="button1">Click to hide</button>
<div class="modal fade" id="newModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Sample Modal</h4>
</div>
<div class="modal-body">
<p>This is demo text.</p>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$("#newModal").modal("show");
$("#button1").click(function(){
$("#newModal").modal("hide");
});
});
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1114,
"s": 1062,
"text": "The modal(“show”) method opens a modal like below −"
},
{
"code": null,
"e": 1185,
"s": 1114,
"text": "The modal is displayed using the modal(“show”) method as shown below −"
},
{
"code": null,
"e": 1215,
"s": 1185,
"text": "$(\"#newModal\").modal(\"show\");"
},
{
"code": null,
"e": 1263,
"s": 1215,
"text": "Let us see an example of modal(“show”) method −"
},
{
"code": null,
"e": 1273,
"s": 1263,
"text": "Live Demo"
},
{
"code": null,
"e": 3093,
"s": 1273,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>\n <style>\n #button1 {\n width: 140px;\n padding: 20px;\n bottom: 150px;\n z-index: 9999;\n font-size: 15px;\n position: absolute;\n margin: 0 auto;\n }\n </style>\n </head>\n<body>\n <div class=\"container\">\n <h2>Sample</h2>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <button type=\"button\" class=\"btn btn-default btn-lg\" id=\"button1\">Click to hide</button>\n <div class=\"modal fade\" id=\"newModal\" role=\"dialog\">\n <div class=\"modal-dialog\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\">×</button>\n <h4 class=\"modal-title\">Sample Modal</h4>\n </div>\n <div class=\"modal-body\">\n <p>This is demo text.</p>\n </div>\n </div>\n </div>\n </div>\n</div>\n\n<script>\n $(document).ready(function(){\n $(\"#newModal\").modal(\"show\");\n $(\"#button1\").click(function(){\n $(\"#newModal\").modal(\"hide\");\n });\n });\n</script>\n\n</body>\n</html>"
}
] |
How do I list all files of a directory in Python?
|
os.listdir(my_path) will get you everything that's in the my_path directory - files and directories.
You can use it as follows:
>>> import os
>>> os.listdir('.')
['DLLs', 'Doc', 'etc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'Scripts', 'share', 'tcl', 'Tools', 'w9xpopen.exe']
If you want just files, you can filter it using isfile:
>>> import os
>>> file_list = [f for f in os.listdir('.') if os.path.isfile(os.path.join('.', f))]
>>> print file_list
['LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'w9xpopen.exe']
|
[
{
"code": null,
"e": 1163,
"s": 1062,
"text": "os.listdir(my_path) will get you everything that's in the my_path directory - files and directories."
},
{
"code": null,
"e": 1190,
"s": 1163,
"text": "You can use it as follows:"
},
{
"code": null,
"e": 1395,
"s": 1190,
"text": ">>> import os\n>>> os.listdir('.')\n['DLLs', 'Doc', 'etc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'Scripts', 'share', 'tcl', 'Tools', 'w9xpopen.exe']"
},
{
"code": null,
"e": 1451,
"s": 1395,
"text": "If you want just files, you can filter it using isfile:"
},
{
"code": null,
"e": 1657,
"s": 1451,
"text": ">>> import os\n>>> file_list = [f for f in os.listdir('.') if os.path.isfile(os.path.join('.', f))]\n>>> print file_list\n['LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'w9xpopen.exe']"
}
] |
Count of subarray that does not contain any subarray with sum 0 - GeeksforGeeks
|
15 Feb, 2022
Given an array arr, the task is to find the total number of subarrays of the given array which do not contain any subarray whose sum of elements is equal to zero. All the array elements are distinct.Examples:
Input: arr = {2, 4, -6} Output: 5 Explanation: There are 5 subarrays which do not contain any subarray whose elements sum is equal to zero: [2], [4], [-6], [2, 4], [4, -6]Input: arr = {10, -10, 10} Output: 3
Approach:
Firstly store all elements of array as sum of its previous element. Now take two pointers, increase second pointer and store the value in a map while a same element not encounter. If an element encounter which is already exist in map, this means there exist a subarray between two pointers whose elements sum is equal to 0. Now increase first pointer and remove the element from map while the two same elements exists. Store the answer in a variable and finally return it.
Firstly store all elements of array as sum of its previous element.
Now take two pointers, increase second pointer and store the value in a map while a same element not encounter.
If an element encounter which is already exist in map, this means there exist a subarray between two pointers whose elements sum is equal to 0.
Now increase first pointer and remove the element from map while the two same elements exists.
Store the answer in a variable and finally return it.
Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// C++ program to Count the no of subarray// which do not contain any subarray// whose sum of elements is equal to zero #include <bits/stdc++.h>using namespace std; // Function that print the number of// subarrays which do not contain any subarray// whose elements sum is equal to 0void numberOfSubarrays(int arr[], int n){ vector<int> v(n + 1); v[0] = 0; // Storing each element as sum // of its previous element for (int i = 0; i < n; i++) { v[i + 1] = v[i] + arr[i]; } map<int, int> mp; int begin = 0, end = 0, answer = 0; mp[0] = 1; while (begin < n) { while (end < n && mp.find(v[end + 1]) == mp.end()) { end++; mp[v[end]] = 1; } // Check if another same element found // this means a subarray exist between // end and begin whose sum // of elements is equal to 0 answer = answer + end - begin; // Erase beginning element from map mp.erase(v[begin]); // Increase begin begin++; } // Print the result cout << answer << endl;} // Driver Codeint main(){ int arr[] = { 2, 4, -6 }; int size = sizeof(arr) / sizeof(arr[0]); numberOfSubarrays(arr, size); return 0;}
// Java program to Count the no of subarray// which do not contain any subarray// whose sum of elements is equal to zeroimport java.util.*; class GFG{ // Function that print the number of// subarrays which do not contain any subarray// whose elements sum is equal to 0static void numberOfSubarrays(int arr[], int n){ int []v = new int[n + 1]; v[0] = 0; // Storing each element as sum // of its previous element for (int i = 0; i < n; i++) { v[i + 1] = v[i] + arr[i]; } HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>(); int begin = 0, end = 0, answer = 0; mp.put(0, 1); while (begin < n) { while (end < n && !mp.containsKey(v[end + 1])) { end++; mp.put(v[end], 1); } // Check if another same element found // this means a subarray exist between // end and begin whose sum // of elements is equal to 0 answer = answer + end - begin; // Erase beginning element from map mp.remove(v[begin]); // Increase begin begin++; } // Print the result System.out.print(answer +"\n");} // Driver Codepublic static void main(String[] args){ int arr[] = { 2, 4, -6 }; int size = arr.length; numberOfSubarrays(arr, size);}} // This code is contributed by sapnasingh4991
# Python 3 program to Count the no of subarray# which do not contain any subarray# whose sum of elements is equal to zero # Function that print the number of# subarrays which do not contain any subarray# whose elements sum is equal to 0def numberOfSubarrays(arr, n): v = [0]*(n + 1) # Storing each element as sum # of its previous element for i in range( n): v[i + 1] = v[i] + arr[i] mp = {} begin, end, answer = 0 , 0 , 0 mp[0] = 1 while (begin < n): while (end < n and (v[end + 1]) not in mp): end += 1 mp[v[end]] = 1 # Check if another same element found # this means a subarray exist between # end and begin whose sum # of elements is equal to 0 answer = answer + end - begin # Erase beginning element from map del mp[v[begin]] # Increase begin begin += 1 # Print the result print(answer) # Driver Codeif __name__ == "__main__": arr = [ 2, 4, -6 ] size = len(arr) numberOfSubarrays(arr, size) # This code is contributed by chitranayal
// C# program to Count the no of subarray// which do not contain any subarray// whose sum of elements is equal to zerousing System;using System.Collections.Generic; class GFG{ // Function that print the number of// subarrays which do not contain any subarray// whose elements sum is equal to 0static void numberOfSubarrays(int []arr, int n){ int []v = new int[n + 1]; v[0] = 0; // Storing each element as sum // of its previous element for (int i = 0; i < n; i++) { v[i + 1] = v[i] + arr[i]; } Dictionary<int,int> mp = new Dictionary<int,int>(); int begin = 0, end = 0, answer = 0; mp.Add(0, 1); while (begin < n) { while (end < n && !mp.ContainsKey(v[end + 1])) { end++; mp.Add(v[end], 1); } // Check if another same element found // this means a subarray exist between // end and begin whose sum // of elements is equal to 0 answer = answer + end - begin; // Erase beginning element from map mp.Remove(v[begin]); // Increase begin begin++; } // Print the result Console.Write(answer +"\n");} // Driver Codepublic static void Main(String[] args){ int []arr = { 2, 4, -6 }; int size = arr.Length; numberOfSubarrays(arr, size);}} // This code is contributed by Rajput-Ji
<script> // JavaScript program to Count the no of subarray// which do not contain any subarray// whose sum of elements is equal to zero // Function that print the number of// subarrays which do not contain any subarray// whose elements sum is equal to 0function numberOfSubarrays(arr, n){ let v = new Array(n + 1); v[0] = 0; // Storing each element as sum // of its previous element for (let i = 0; i < n; i++) { v[i + 1] = v[i] + arr[i]; } let mp = new Map(); let begin = 0, end = 0, answer = 0; mp.set(0, 1); while (begin < n) { while (end < n && !mp.has(v[end + 1])) { end++; mp.set(v[end], 1); } // Check if another same element found // this means a subarray exist between // end and begin whose sum // of elements is equal to 0 answer = answer + end - begin; // Erase beginning element from map mp.clear(); // Increase begin begin++; } // Print the result document.write(answer + "<br>");} // Driver Code let arr = [ 2, 4, -6 ];let size = arr.length; numberOfSubarrays(arr, size); // This code is contributed by _saurabh_jaiswal </script>
5
Time Complexity: O(N)
Auxiliary Space: O(N)
ukasp
sapnasingh4991
Rajput-Ji
Akanksha_Rai
_saurabh_jaiswal
bharani19797
rohitsingh07052
subarray
subarray-sum
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Linked List vs Array
Python | Using 2D arrays/lists the right way
Maximum and minimum of an array using minimum number of comparisons
Given an array of size n and a number k, find all elements that appear more than n/k times
|
[
{
"code": null,
"e": 24143,
"s": 24115,
"text": "\n15 Feb, 2022"
},
{
"code": null,
"e": 24354,
"s": 24143,
"text": "Given an array arr, the task is to find the total number of subarrays of the given array which do not contain any subarray whose sum of elements is equal to zero. All the array elements are distinct.Examples: "
},
{
"code": null,
"e": 24564,
"s": 24354,
"text": "Input: arr = {2, 4, -6} Output: 5 Explanation: There are 5 subarrays which do not contain any subarray whose elements sum is equal to zero: [2], [4], [-6], [2, 4], [4, -6]Input: arr = {10, -10, 10} Output: 3 "
},
{
"code": null,
"e": 24578,
"s": 24566,
"text": "Approach: "
},
{
"code": null,
"e": 25055,
"s": 24578,
"text": "Firstly store all elements of array as sum of its previous element. Now take two pointers, increase second pointer and store the value in a map while a same element not encounter. If an element encounter which is already exist in map, this means there exist a subarray between two pointers whose elements sum is equal to 0. Now increase first pointer and remove the element from map while the two same elements exists. Store the answer in a variable and finally return it."
},
{
"code": null,
"e": 25125,
"s": 25055,
"text": "Firstly store all elements of array as sum of its previous element. "
},
{
"code": null,
"e": 25239,
"s": 25125,
"text": "Now take two pointers, increase second pointer and store the value in a map while a same element not encounter. "
},
{
"code": null,
"e": 25385,
"s": 25239,
"text": "If an element encounter which is already exist in map, this means there exist a subarray between two pointers whose elements sum is equal to 0. "
},
{
"code": null,
"e": 25482,
"s": 25385,
"text": "Now increase first pointer and remove the element from map while the two same elements exists. "
},
{
"code": null,
"e": 25536,
"s": 25482,
"text": "Store the answer in a variable and finally return it."
},
{
"code": null,
"e": 25585,
"s": 25536,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 25589,
"s": 25585,
"text": "C++"
},
{
"code": null,
"e": 25594,
"s": 25589,
"text": "Java"
},
{
"code": null,
"e": 25602,
"s": 25594,
"text": "Python3"
},
{
"code": null,
"e": 25605,
"s": 25602,
"text": "C#"
},
{
"code": null,
"e": 25616,
"s": 25605,
"text": "Javascript"
},
{
"code": "// C++ program to Count the no of subarray// which do not contain any subarray// whose sum of elements is equal to zero #include <bits/stdc++.h>using namespace std; // Function that print the number of// subarrays which do not contain any subarray// whose elements sum is equal to 0void numberOfSubarrays(int arr[], int n){ vector<int> v(n + 1); v[0] = 0; // Storing each element as sum // of its previous element for (int i = 0; i < n; i++) { v[i + 1] = v[i] + arr[i]; } map<int, int> mp; int begin = 0, end = 0, answer = 0; mp[0] = 1; while (begin < n) { while (end < n && mp.find(v[end + 1]) == mp.end()) { end++; mp[v[end]] = 1; } // Check if another same element found // this means a subarray exist between // end and begin whose sum // of elements is equal to 0 answer = answer + end - begin; // Erase beginning element from map mp.erase(v[begin]); // Increase begin begin++; } // Print the result cout << answer << endl;} // Driver Codeint main(){ int arr[] = { 2, 4, -6 }; int size = sizeof(arr) / sizeof(arr[0]); numberOfSubarrays(arr, size); return 0;}",
"e": 26885,
"s": 25616,
"text": null
},
{
"code": "// Java program to Count the no of subarray// which do not contain any subarray// whose sum of elements is equal to zeroimport java.util.*; class GFG{ // Function that print the number of// subarrays which do not contain any subarray// whose elements sum is equal to 0static void numberOfSubarrays(int arr[], int n){ int []v = new int[n + 1]; v[0] = 0; // Storing each element as sum // of its previous element for (int i = 0; i < n; i++) { v[i + 1] = v[i] + arr[i]; } HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>(); int begin = 0, end = 0, answer = 0; mp.put(0, 1); while (begin < n) { while (end < n && !mp.containsKey(v[end + 1])) { end++; mp.put(v[end], 1); } // Check if another same element found // this means a subarray exist between // end and begin whose sum // of elements is equal to 0 answer = answer + end - begin; // Erase beginning element from map mp.remove(v[begin]); // Increase begin begin++; } // Print the result System.out.print(answer +\"\\n\");} // Driver Codepublic static void main(String[] args){ int arr[] = { 2, 4, -6 }; int size = arr.length; numberOfSubarrays(arr, size);}} // This code is contributed by sapnasingh4991",
"e": 28243,
"s": 26885,
"text": null
},
{
"code": "# Python 3 program to Count the no of subarray# which do not contain any subarray# whose sum of elements is equal to zero # Function that print the number of# subarrays which do not contain any subarray# whose elements sum is equal to 0def numberOfSubarrays(arr, n): v = [0]*(n + 1) # Storing each element as sum # of its previous element for i in range( n): v[i + 1] = v[i] + arr[i] mp = {} begin, end, answer = 0 , 0 , 0 mp[0] = 1 while (begin < n): while (end < n and (v[end + 1]) not in mp): end += 1 mp[v[end]] = 1 # Check if another same element found # this means a subarray exist between # end and begin whose sum # of elements is equal to 0 answer = answer + end - begin # Erase beginning element from map del mp[v[begin]] # Increase begin begin += 1 # Print the result print(answer) # Driver Codeif __name__ == \"__main__\": arr = [ 2, 4, -6 ] size = len(arr) numberOfSubarrays(arr, size) # This code is contributed by chitranayal",
"e": 29347,
"s": 28243,
"text": null
},
{
"code": "// C# program to Count the no of subarray// which do not contain any subarray// whose sum of elements is equal to zerousing System;using System.Collections.Generic; class GFG{ // Function that print the number of// subarrays which do not contain any subarray// whose elements sum is equal to 0static void numberOfSubarrays(int []arr, int n){ int []v = new int[n + 1]; v[0] = 0; // Storing each element as sum // of its previous element for (int i = 0; i < n; i++) { v[i + 1] = v[i] + arr[i]; } Dictionary<int,int> mp = new Dictionary<int,int>(); int begin = 0, end = 0, answer = 0; mp.Add(0, 1); while (begin < n) { while (end < n && !mp.ContainsKey(v[end + 1])) { end++; mp.Add(v[end], 1); } // Check if another same element found // this means a subarray exist between // end and begin whose sum // of elements is equal to 0 answer = answer + end - begin; // Erase beginning element from map mp.Remove(v[begin]); // Increase begin begin++; } // Print the result Console.Write(answer +\"\\n\");} // Driver Codepublic static void Main(String[] args){ int []arr = { 2, 4, -6 }; int size = arr.Length; numberOfSubarrays(arr, size);}} // This code is contributed by Rajput-Ji",
"e": 30726,
"s": 29347,
"text": null
},
{
"code": "<script> // JavaScript program to Count the no of subarray// which do not contain any subarray// whose sum of elements is equal to zero // Function that print the number of// subarrays which do not contain any subarray// whose elements sum is equal to 0function numberOfSubarrays(arr, n){ let v = new Array(n + 1); v[0] = 0; // Storing each element as sum // of its previous element for (let i = 0; i < n; i++) { v[i + 1] = v[i] + arr[i]; } let mp = new Map(); let begin = 0, end = 0, answer = 0; mp.set(0, 1); while (begin < n) { while (end < n && !mp.has(v[end + 1])) { end++; mp.set(v[end], 1); } // Check if another same element found // this means a subarray exist between // end and begin whose sum // of elements is equal to 0 answer = answer + end - begin; // Erase beginning element from map mp.clear(); // Increase begin begin++; } // Print the result document.write(answer + \"<br>\");} // Driver Code let arr = [ 2, 4, -6 ];let size = arr.length; numberOfSubarrays(arr, size); // This code is contributed by _saurabh_jaiswal </script>",
"e": 31926,
"s": 30726,
"text": null
},
{
"code": null,
"e": 31928,
"s": 31926,
"text": "5"
},
{
"code": null,
"e": 31952,
"s": 31930,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 31974,
"s": 31952,
"text": "Auxiliary Space: O(N)"
},
{
"code": null,
"e": 31980,
"s": 31974,
"text": "ukasp"
},
{
"code": null,
"e": 31995,
"s": 31980,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 32005,
"s": 31995,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 32018,
"s": 32005,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 32035,
"s": 32018,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 32048,
"s": 32035,
"text": "bharani19797"
},
{
"code": null,
"e": 32064,
"s": 32048,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 32073,
"s": 32064,
"text": "subarray"
},
{
"code": null,
"e": 32086,
"s": 32073,
"text": "subarray-sum"
},
{
"code": null,
"e": 32093,
"s": 32086,
"text": "Arrays"
},
{
"code": null,
"e": 32100,
"s": 32093,
"text": "Arrays"
},
{
"code": null,
"e": 32198,
"s": 32100,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32207,
"s": 32198,
"text": "Comments"
},
{
"code": null,
"e": 32220,
"s": 32207,
"text": "Old Comments"
},
{
"code": null,
"e": 32268,
"s": 32220,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 32312,
"s": 32268,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 32335,
"s": 32312,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 32367,
"s": 32335,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 32381,
"s": 32367,
"text": "Linear Search"
},
{
"code": null,
"e": 32466,
"s": 32381,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 32487,
"s": 32466,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 32532,
"s": 32487,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 32600,
"s": 32532,
"text": "Maximum and minimum of an array using minimum number of comparisons"
}
] |
Flipkart Interview Experience for SDE-I | 1 Year Experienced - GeeksforGeeks
|
20 Aug, 2021
Round 1:
Machine Coding – 30 mins discussion on problem statement, 3hrs to implement, another 1 – 1.5 hrs discussion on solution, with test cases.
Design Covid-19 Vaccination Booking System
Features include :
Onboarding states, districts, wards, vaccination centers, slots
Users registering themselves with unique documentation.
Proper Search functions to help user, find slots, centres, wards in city.
List bookings and center data.
The question was implementation heavy, we needed to make sure we take care of abrupt input and edge cases, and there were a lot of these cases coming up.
A similar kind of implementation-based question can be – https://workat.tech/machine-coding/practice/design-library-management-system-jgjrv8q8b136.
The inputs/commands were very similar to the one in the article.
Round 2(DSA): 45 Minutes
Given an array of positive and negative numbers. You have to find the maximum product of 3 numbershttps://practice.geeksforgeeks.org/problems/three-great-candidates0515/1.Input : [9, 1, 2, 3, 4, 5, -8, 10]
Output : 450 (10 * 9 * 5)
Input : [-9, 1, 2, 3, 4, 5, -8, 10]
Output : 720 (10 * -9 * -8)Solution:– Sort the array and the answer will be max(product of last 3 numbers OR product of first 2 numbers with last one)Time: O(n Log n)– Traverse the array and store the max 3 numbers and min 2 numbers in variables. Answer will be max(max1 * max2 * max3, max1 * min 1 * min2).Time: O(n)Given Flight Routes with a source, we need to find the destination. A destination is the airport which does not has a route to some other airport.There can me multiple airports which do not have a route to some other airport, but the destination airport should be reachable from the source.A destination airport will always exist.Input : [A,B] [B,C] [C,D] [E,F], Source = A
Output : D
A(source)->B->C->D
E->FNo route after D. F also does not have a route to another aiport, but F cannot be arrived from the source, so it cannot be the answer.Input : [A,B] [B,C] [C,D] [C,E] [E,D], Source = A
Output : D
A(source)-B-C - D
\ /
EThere is not route after D, so D will be the destination.Solution:Creating the graph, and then doing a DFS call from source till we find a node that has no children. That node will be the answer.Time – O(n), n is the number of airportsI used a hashmap to build the graph like adjacency list.There was discussion on other ways of building the graph that could be space optimised.Given a positive number N, generate the score for that number, where N can be represented as sum of 2 numbers A and B, and score is summation of all permutations of [Score(A) + Score(B)].A and B combined must be unique. (Ex : 1 & 3 is same as 3 & 1)Input : 3
Output : 3
Input : 5
Output : 14Solution:This is a 1D DP problem, where score of N can be calculated in a bottom up manner, by calculating the scores for the numbers less than N.Example :
1 => 1 (Base case)
2 : 1 + 1 => Score(1) + Score(1) = 2
3 : 1 + 2 => Score(1) + Score(2) = 3
4 : 1 + 3 => Score(1) + Score(3) = 4
2 + 2 => Score(2) + Score(2) = 4
= 4 + 4 = 8
5 : 1 + 4 => Score(1) + Score(4) = 9
: 2 + 3 => Score(2) + Score(3) = 5
= 9 + 5 = 14
6 : 1 + 5 => Score(1) + Score(5) = 15
: 2 + 4 => Score(2) + Score(4) = 10
: 3 + 3 => Score(3) + Score(3) = 6
= 15 + 10 + 6 = 31>We just needed make a 1D array from 1 to N, and traverse from 1 filling the values and finally return Score(N).Time: O(n^2)
Given an array of positive and negative numbers. You have to find the maximum product of 3 numbershttps://practice.geeksforgeeks.org/problems/three-great-candidates0515/1.Input : [9, 1, 2, 3, 4, 5, -8, 10]
Output : 450 (10 * 9 * 5)
Input : [-9, 1, 2, 3, 4, 5, -8, 10]
Output : 720 (10 * -9 * -8)Solution:– Sort the array and the answer will be max(product of last 3 numbers OR product of first 2 numbers with last one)Time: O(n Log n)– Traverse the array and store the max 3 numbers and min 2 numbers in variables. Answer will be max(max1 * max2 * max3, max1 * min 1 * min2).Time: O(n)
Input : [9, 1, 2, 3, 4, 5, -8, 10]
Output : 450 (10 * 9 * 5)
Input : [-9, 1, 2, 3, 4, 5, -8, 10]
Output : 720 (10 * -9 * -8)
Solution:
– Sort the array and the answer will be max(product of last 3 numbers OR product of first 2 numbers with last one)
Time: O(n Log n)
– Traverse the array and store the max 3 numbers and min 2 numbers in variables. Answer will be max(max1 * max2 * max3, max1 * min 1 * min2).
Time: O(n)
Given Flight Routes with a source, we need to find the destination. A destination is the airport which does not has a route to some other airport.There can me multiple airports which do not have a route to some other airport, but the destination airport should be reachable from the source.A destination airport will always exist.Input : [A,B] [B,C] [C,D] [E,F], Source = A
Output : D
A(source)->B->C->D
E->FNo route after D. F also does not have a route to another aiport, but F cannot be arrived from the source, so it cannot be the answer.Input : [A,B] [B,C] [C,D] [C,E] [E,D], Source = A
Output : D
A(source)-B-C - D
\ /
EThere is not route after D, so D will be the destination.Solution:Creating the graph, and then doing a DFS call from source till we find a node that has no children. That node will be the answer.Time – O(n), n is the number of airportsI used a hashmap to build the graph like adjacency list.There was discussion on other ways of building the graph that could be space optimised.
There can me multiple airports which do not have a route to some other airport, but the destination airport should be reachable from the source.
A destination airport will always exist.
Input : [A,B] [B,C] [C,D] [E,F], Source = A
Output : D
A(source)->B->C->D
E->F
No route after D. F also does not have a route to another aiport, but F cannot be arrived from the source, so it cannot be the answer.
Input : [A,B] [B,C] [C,D] [C,E] [E,D], Source = A
Output : D
A(source)-B-C - D
\ /
E
There is not route after D, so D will be the destination.
Solution:
Creating the graph, and then doing a DFS call from source till we find a node that has no children. That node will be the answer.
Time – O(n), n is the number of airports
I used a hashmap to build the graph like adjacency list.
There was discussion on other ways of building the graph that could be space optimised.
Given a positive number N, generate the score for that number, where N can be represented as sum of 2 numbers A and B, and score is summation of all permutations of [Score(A) + Score(B)].A and B combined must be unique. (Ex : 1 & 3 is same as 3 & 1)Input : 3
Output : 3
Input : 5
Output : 14Solution:This is a 1D DP problem, where score of N can be calculated in a bottom up manner, by calculating the scores for the numbers less than N.Example :
1 => 1 (Base case)
2 : 1 + 1 => Score(1) + Score(1) = 2
3 : 1 + 2 => Score(1) + Score(2) = 3
4 : 1 + 3 => Score(1) + Score(3) = 4
2 + 2 => Score(2) + Score(2) = 4
= 4 + 4 = 8
5 : 1 + 4 => Score(1) + Score(4) = 9
: 2 + 3 => Score(2) + Score(3) = 5
= 9 + 5 = 14
6 : 1 + 5 => Score(1) + Score(5) = 15
: 2 + 4 => Score(2) + Score(4) = 10
: 3 + 3 => Score(3) + Score(3) = 6
= 15 + 10 + 6 = 31>We just needed make a 1D array from 1 to N, and traverse from 1 filling the values and finally return Score(N).Time: O(n^2)
A and B combined must be unique. (Ex : 1 & 3 is same as 3 & 1)
Input : 3
Output : 3
Input : 5
Output : 14
Solution:
This is a 1D DP problem, where score of N can be calculated in a bottom up manner, by calculating the scores for the numbers less than N.
Example :
1 => 1 (Base case)
2 : 1 + 1 => Score(1) + Score(1) = 2
3 : 1 + 2 => Score(1) + Score(2) = 3
4 : 1 + 3 => Score(1) + Score(3) = 4
2 + 2 => Score(2) + Score(2) = 4
= 4 + 4 = 8
5 : 1 + 4 => Score(1) + Score(4) = 9
: 2 + 3 => Score(2) + Score(3) = 5
= 9 + 5 = 14
6 : 1 + 5 => Score(1) + Score(5) = 15
: 2 + 4 => Score(2) + Score(4) = 10
: 3 + 3 => Score(3) + Score(3) = 6
= 15 + 10 + 6 = 31
>We just needed make a 1D array from 1 to N, and traverse from 1 filling the values and finally return Score(N).
Time: O(n^2)
Some people had 2 DSA rounds, but my round went pretty well, so they cut down 1 round for me.
Although the questions seemed on the easy-mediumish side, but with 45 mins in hand out of which 10 mins were spent in intro and basic projects/roles discussion, solving 3 questions in about 30 mins made it a bit difficult.
Round 3(Hiring Manager/Cultural Fitment): 1 Hour
Asked me about the roles in previous org.Explain a very high level architecture of the things I work on.Choice of language/framework and reasons.Choice of DB (SQL / NoSQL) and why. (Deep Discussion)Caching Concepts with deep Discussion.Discussion on Projects.Situation when I proved myself more towards customer oriented.Situation when I had disagreements with team and how did I handle.Situation when I went out of the way to do something.Greatest Achievement till now for me.How to handle a situation when customer requirements are misaligned with business demands.Steps you take to show up team work.
Asked me about the roles in previous org.
Explain a very high level architecture of the things I work on.
Choice of language/framework and reasons.
Choice of DB (SQL / NoSQL) and why. (Deep Discussion)
Caching Concepts with deep Discussion.
Discussion on Projects.
Situation when I proved myself more towards customer oriented.
Situation when I had disagreements with team and how did I handle.
Situation when I went out of the way to do something.
Greatest Achievement till now for me.
How to handle a situation when customer requirements are misaligned with business demands.
Steps you take to show up team work.
Verdict: Selected
Be consistent and have patience, things will work and you will land where you want.
Flipkart
Marketing
Experienced
Interview Experiences
Flipkart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Infosys Interview Experience for Java Backend Developer (3-5 Years Experienced)
Paypal Interview Experience for SSE
Amazon Interview Experience for System Development Engineer (Exp - 6 months)
Walmart Interview Experience for SDE-III
Amazon Interview Questions
Microsoft Interview Experience for Internship (Via Engage)
Commonly Asked Java Programming Interview Questions | Set 2
Amazon Interview Experience for SDE-1 (On-Campus)
Amazon Interview Experience for SDE-1
|
[
{
"code": null,
"e": 25241,
"s": 25213,
"text": "\n20 Aug, 2021"
},
{
"code": null,
"e": 25250,
"s": 25241,
"text": "Round 1:"
},
{
"code": null,
"e": 25388,
"s": 25250,
"text": "Machine Coding – 30 mins discussion on problem statement, 3hrs to implement, another 1 – 1.5 hrs discussion on solution, with test cases."
},
{
"code": null,
"e": 25431,
"s": 25388,
"text": "Design Covid-19 Vaccination Booking System"
},
{
"code": null,
"e": 25450,
"s": 25431,
"text": "Features include :"
},
{
"code": null,
"e": 25514,
"s": 25450,
"text": "Onboarding states, districts, wards, vaccination centers, slots"
},
{
"code": null,
"e": 25570,
"s": 25514,
"text": "Users registering themselves with unique documentation."
},
{
"code": null,
"e": 25644,
"s": 25570,
"text": "Proper Search functions to help user, find slots, centres, wards in city."
},
{
"code": null,
"e": 25675,
"s": 25644,
"text": "List bookings and center data."
},
{
"code": null,
"e": 25829,
"s": 25675,
"text": "The question was implementation heavy, we needed to make sure we take care of abrupt input and edge cases, and there were a lot of these cases coming up."
},
{
"code": null,
"e": 25977,
"s": 25829,
"text": "A similar kind of implementation-based question can be – https://workat.tech/machine-coding/practice/design-library-management-system-jgjrv8q8b136."
},
{
"code": null,
"e": 26042,
"s": 25977,
"text": "The inputs/commands were very similar to the one in the article."
},
{
"code": null,
"e": 26067,
"s": 26042,
"text": "Round 2(DSA): 45 Minutes"
},
{
"code": null,
"e": 28650,
"s": 26067,
"text": "Given an array of positive and negative numbers. You have to find the maximum product of 3 numbershttps://practice.geeksforgeeks.org/problems/three-great-candidates0515/1.Input : [9, 1, 2, 3, 4, 5, -8, 10]\nOutput : 450 (10 * 9 * 5)\nInput : [-9, 1, 2, 3, 4, 5, -8, 10]\nOutput : 720 (10 * -9 * -8)Solution:– Sort the array and the answer will be max(product of last 3 numbers OR product of first 2 numbers with last one)Time: O(n Log n)– Traverse the array and store the max 3 numbers and min 2 numbers in variables. Answer will be max(max1 * max2 * max3, max1 * min 1 * min2).Time: O(n)Given Flight Routes with a source, we need to find the destination. A destination is the airport which does not has a route to some other airport.There can me multiple airports which do not have a route to some other airport, but the destination airport should be reachable from the source.A destination airport will always exist.Input : [A,B] [B,C] [C,D] [E,F], Source = A\nOutput : D\nA(source)->B->C->D\nE->FNo route after D. F also does not have a route to another aiport, but F cannot be arrived from the source, so it cannot be the answer.Input : [A,B] [B,C] [C,D] [C,E] [E,D], Source = A\nOutput : D\nA(source)-B-C - D\n \\ /\n EThere is not route after D, so D will be the destination.Solution:Creating the graph, and then doing a DFS call from source till we find a node that has no children. That node will be the answer.Time – O(n), n is the number of airportsI used a hashmap to build the graph like adjacency list.There was discussion on other ways of building the graph that could be space optimised.Given a positive number N, generate the score for that number, where N can be represented as sum of 2 numbers A and B, and score is summation of all permutations of [Score(A) + Score(B)].A and B combined must be unique. (Ex : 1 & 3 is same as 3 & 1)Input : 3\nOutput : 3\nInput : 5\nOutput : 14Solution:This is a 1D DP problem, where score of N can be calculated in a bottom up manner, by calculating the scores for the numbers less than N.Example :\n1 => 1 (Base case)\n2 : 1 + 1 => Score(1) + Score(1) = 2\n3 : 1 + 2 => Score(1) + Score(2) = 3\n4 : 1 + 3 => Score(1) + Score(3) = 4\n2 + 2 => Score(2) + Score(2) = 4\n= 4 + 4 = 8\n5 : 1 + 4 => Score(1) + Score(4) = 9\n : 2 + 3 => Score(2) + Score(3) = 5\n = 9 + 5 = 14\n6 : 1 + 5 => Score(1) + Score(5) = 15\n : 2 + 4 => Score(2) + Score(4) = 10\n : 3 + 3 => Score(3) + Score(3) = 6\n = 15 + 10 + 6 = 31>We just needed make a 1D array from 1 to N, and traverse from 1 filling the values and finally return Score(N).Time: O(n^2)"
},
{
"code": null,
"e": 29236,
"s": 28650,
"text": "Given an array of positive and negative numbers. You have to find the maximum product of 3 numbershttps://practice.geeksforgeeks.org/problems/three-great-candidates0515/1.Input : [9, 1, 2, 3, 4, 5, -8, 10]\nOutput : 450 (10 * 9 * 5)\nInput : [-9, 1, 2, 3, 4, 5, -8, 10]\nOutput : 720 (10 * -9 * -8)Solution:– Sort the array and the answer will be max(product of last 3 numbers OR product of first 2 numbers with last one)Time: O(n Log n)– Traverse the array and store the max 3 numbers and min 2 numbers in variables. Answer will be max(max1 * max2 * max3, max1 * min 1 * min2).Time: O(n)"
},
{
"code": null,
"e": 29361,
"s": 29236,
"text": "Input : [9, 1, 2, 3, 4, 5, -8, 10]\nOutput : 450 (10 * 9 * 5)\nInput : [-9, 1, 2, 3, 4, 5, -8, 10]\nOutput : 720 (10 * -9 * -8)"
},
{
"code": null,
"e": 29371,
"s": 29361,
"text": "Solution:"
},
{
"code": null,
"e": 29486,
"s": 29371,
"text": "– Sort the array and the answer will be max(product of last 3 numbers OR product of first 2 numbers with last one)"
},
{
"code": null,
"e": 29503,
"s": 29486,
"text": "Time: O(n Log n)"
},
{
"code": null,
"e": 29645,
"s": 29503,
"text": "– Traverse the array and store the max 3 numbers and min 2 numbers in variables. Answer will be max(max1 * max2 * max3, max1 * min 1 * min2)."
},
{
"code": null,
"e": 29656,
"s": 29645,
"text": "Time: O(n)"
},
{
"code": null,
"e": 30691,
"s": 29656,
"text": "Given Flight Routes with a source, we need to find the destination. A destination is the airport which does not has a route to some other airport.There can me multiple airports which do not have a route to some other airport, but the destination airport should be reachable from the source.A destination airport will always exist.Input : [A,B] [B,C] [C,D] [E,F], Source = A\nOutput : D\nA(source)->B->C->D\nE->FNo route after D. F also does not have a route to another aiport, but F cannot be arrived from the source, so it cannot be the answer.Input : [A,B] [B,C] [C,D] [C,E] [E,D], Source = A\nOutput : D\nA(source)-B-C - D\n \\ /\n EThere is not route after D, so D will be the destination.Solution:Creating the graph, and then doing a DFS call from source till we find a node that has no children. That node will be the answer.Time – O(n), n is the number of airportsI used a hashmap to build the graph like adjacency list.There was discussion on other ways of building the graph that could be space optimised."
},
{
"code": null,
"e": 30836,
"s": 30691,
"text": "There can me multiple airports which do not have a route to some other airport, but the destination airport should be reachable from the source."
},
{
"code": null,
"e": 30877,
"s": 30836,
"text": "A destination airport will always exist."
},
{
"code": null,
"e": 30956,
"s": 30877,
"text": "Input : [A,B] [B,C] [C,D] [E,F], Source = A\nOutput : D\nA(source)->B->C->D\nE->F"
},
{
"code": null,
"e": 31091,
"s": 30956,
"text": "No route after D. F also does not have a route to another aiport, but F cannot be arrived from the source, so it cannot be the answer."
},
{
"code": null,
"e": 31206,
"s": 31091,
"text": "Input : [A,B] [B,C] [C,D] [C,E] [E,D], Source = A\nOutput : D\nA(source)-B-C - D\n \\ /\n E"
},
{
"code": null,
"e": 31264,
"s": 31206,
"text": "There is not route after D, so D will be the destination."
},
{
"code": null,
"e": 31274,
"s": 31264,
"text": "Solution:"
},
{
"code": null,
"e": 31404,
"s": 31274,
"text": "Creating the graph, and then doing a DFS call from source till we find a node that has no children. That node will be the answer."
},
{
"code": null,
"e": 31445,
"s": 31404,
"text": "Time – O(n), n is the number of airports"
},
{
"code": null,
"e": 31502,
"s": 31445,
"text": "I used a hashmap to build the graph like adjacency list."
},
{
"code": null,
"e": 31590,
"s": 31502,
"text": "There was discussion on other ways of building the graph that could be space optimised."
},
{
"code": null,
"e": 32554,
"s": 31590,
"text": "Given a positive number N, generate the score for that number, where N can be represented as sum of 2 numbers A and B, and score is summation of all permutations of [Score(A) + Score(B)].A and B combined must be unique. (Ex : 1 & 3 is same as 3 & 1)Input : 3\nOutput : 3\nInput : 5\nOutput : 14Solution:This is a 1D DP problem, where score of N can be calculated in a bottom up manner, by calculating the scores for the numbers less than N.Example :\n1 => 1 (Base case)\n2 : 1 + 1 => Score(1) + Score(1) = 2\n3 : 1 + 2 => Score(1) + Score(2) = 3\n4 : 1 + 3 => Score(1) + Score(3) = 4\n2 + 2 => Score(2) + Score(2) = 4\n= 4 + 4 = 8\n5 : 1 + 4 => Score(1) + Score(4) = 9\n : 2 + 3 => Score(2) + Score(3) = 5\n = 9 + 5 = 14\n6 : 1 + 5 => Score(1) + Score(5) = 15\n : 2 + 4 => Score(2) + Score(4) = 10\n : 3 + 3 => Score(3) + Score(3) = 6\n = 15 + 10 + 6 = 31>We just needed make a 1D array from 1 to N, and traverse from 1 filling the values and finally return Score(N).Time: O(n^2)"
},
{
"code": null,
"e": 32617,
"s": 32554,
"text": "A and B combined must be unique. (Ex : 1 & 3 is same as 3 & 1)"
},
{
"code": null,
"e": 32660,
"s": 32617,
"text": "Input : 3\nOutput : 3\nInput : 5\nOutput : 14"
},
{
"code": null,
"e": 32670,
"s": 32660,
"text": "Solution:"
},
{
"code": null,
"e": 32808,
"s": 32670,
"text": "This is a 1D DP problem, where score of N can be calculated in a bottom up manner, by calculating the scores for the numbers less than N."
},
{
"code": null,
"e": 33211,
"s": 32808,
"text": "Example :\n1 => 1 (Base case)\n2 : 1 + 1 => Score(1) + Score(1) = 2\n3 : 1 + 2 => Score(1) + Score(2) = 3\n4 : 1 + 3 => Score(1) + Score(3) = 4\n2 + 2 => Score(2) + Score(2) = 4\n= 4 + 4 = 8\n5 : 1 + 4 => Score(1) + Score(4) = 9\n : 2 + 3 => Score(2) + Score(3) = 5\n = 9 + 5 = 14\n6 : 1 + 5 => Score(1) + Score(5) = 15\n : 2 + 4 => Score(2) + Score(4) = 10\n : 3 + 3 => Score(3) + Score(3) = 6\n = 15 + 10 + 6 = 31"
},
{
"code": null,
"e": 33324,
"s": 33211,
"text": ">We just needed make a 1D array from 1 to N, and traverse from 1 filling the values and finally return Score(N)."
},
{
"code": null,
"e": 33337,
"s": 33324,
"text": "Time: O(n^2)"
},
{
"code": null,
"e": 33431,
"s": 33337,
"text": "Some people had 2 DSA rounds, but my round went pretty well, so they cut down 1 round for me."
},
{
"code": null,
"e": 33654,
"s": 33431,
"text": "Although the questions seemed on the easy-mediumish side, but with 45 mins in hand out of which 10 mins were spent in intro and basic projects/roles discussion, solving 3 questions in about 30 mins made it a bit difficult."
},
{
"code": null,
"e": 33703,
"s": 33654,
"text": "Round 3(Hiring Manager/Cultural Fitment): 1 Hour"
},
{
"code": null,
"e": 34307,
"s": 33703,
"text": "Asked me about the roles in previous org.Explain a very high level architecture of the things I work on.Choice of language/framework and reasons.Choice of DB (SQL / NoSQL) and why. (Deep Discussion)Caching Concepts with deep Discussion.Discussion on Projects.Situation when I proved myself more towards customer oriented.Situation when I had disagreements with team and how did I handle.Situation when I went out of the way to do something.Greatest Achievement till now for me.How to handle a situation when customer requirements are misaligned with business demands.Steps you take to show up team work."
},
{
"code": null,
"e": 34349,
"s": 34307,
"text": "Asked me about the roles in previous org."
},
{
"code": null,
"e": 34413,
"s": 34349,
"text": "Explain a very high level architecture of the things I work on."
},
{
"code": null,
"e": 34455,
"s": 34413,
"text": "Choice of language/framework and reasons."
},
{
"code": null,
"e": 34509,
"s": 34455,
"text": "Choice of DB (SQL / NoSQL) and why. (Deep Discussion)"
},
{
"code": null,
"e": 34548,
"s": 34509,
"text": "Caching Concepts with deep Discussion."
},
{
"code": null,
"e": 34572,
"s": 34548,
"text": "Discussion on Projects."
},
{
"code": null,
"e": 34635,
"s": 34572,
"text": "Situation when I proved myself more towards customer oriented."
},
{
"code": null,
"e": 34702,
"s": 34635,
"text": "Situation when I had disagreements with team and how did I handle."
},
{
"code": null,
"e": 34756,
"s": 34702,
"text": "Situation when I went out of the way to do something."
},
{
"code": null,
"e": 34794,
"s": 34756,
"text": "Greatest Achievement till now for me."
},
{
"code": null,
"e": 34885,
"s": 34794,
"text": "How to handle a situation when customer requirements are misaligned with business demands."
},
{
"code": null,
"e": 34922,
"s": 34885,
"text": "Steps you take to show up team work."
},
{
"code": null,
"e": 34940,
"s": 34922,
"text": "Verdict: Selected"
},
{
"code": null,
"e": 35024,
"s": 34940,
"text": "Be consistent and have patience, things will work and you will land where you want."
},
{
"code": null,
"e": 35033,
"s": 35024,
"text": "Flipkart"
},
{
"code": null,
"e": 35043,
"s": 35033,
"text": "Marketing"
},
{
"code": null,
"e": 35055,
"s": 35043,
"text": "Experienced"
},
{
"code": null,
"e": 35077,
"s": 35055,
"text": "Interview Experiences"
},
{
"code": null,
"e": 35086,
"s": 35077,
"text": "Flipkart"
},
{
"code": null,
"e": 35184,
"s": 35086,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35193,
"s": 35184,
"text": "Comments"
},
{
"code": null,
"e": 35206,
"s": 35193,
"text": "Old Comments"
},
{
"code": null,
"e": 35271,
"s": 35206,
"text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022"
},
{
"code": null,
"e": 35351,
"s": 35271,
"text": "Infosys Interview Experience for Java Backend Developer (3-5 Years Experienced)"
},
{
"code": null,
"e": 35387,
"s": 35351,
"text": "Paypal Interview Experience for SSE"
},
{
"code": null,
"e": 35464,
"s": 35387,
"text": "Amazon Interview Experience for System Development Engineer (Exp - 6 months)"
},
{
"code": null,
"e": 35505,
"s": 35464,
"text": "Walmart Interview Experience for SDE-III"
},
{
"code": null,
"e": 35532,
"s": 35505,
"text": "Amazon Interview Questions"
},
{
"code": null,
"e": 35591,
"s": 35532,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 35651,
"s": 35591,
"text": "Commonly Asked Java Programming Interview Questions | Set 2"
},
{
"code": null,
"e": 35701,
"s": 35651,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
}
] |
Abstract Classes in PHP - GeeksforGeeks
|
19 Jul, 2019
Abstract classes are the classes in which at least one method is abstract. Unlike C++ abstract classes in PHP are declared with the help of abstract keyword. Use of abstract classes are that all base classes implementing this class should give implementation of abstract methods declared in parent class. An abstract class can contain abstract as well as non abstract methods.
<?php // Abstract class example in PHPabstract class base{ // This is abstract function abstract function printdata(); // This is not abstract function function pr() { echo "Base class"; }}?>
Following are some important facts about abstract classes in PHP.
Like Java, PHP also an instance of abstract class can not be created.Example:<?php // Abstract classabstract class Base { // This is abstract function abstract function printdata();}class Derived extends base { function printdata() { echo "Derived class"; }} // Uncommenting the following line will // cause compiler error as the line tries// to create an instance of abstract class. // $b = new Base(); $b1 = new Derived;$b1->printdata();?>Output:Derived class
Example:
<?php // Abstract classabstract class Base { // This is abstract function abstract function printdata();}class Derived extends base { function printdata() { echo "Derived class"; }} // Uncommenting the following line will // cause compiler error as the line tries// to create an instance of abstract class. // $b = new Base(); $b1 = new Derived;$b1->printdata();?>
Derived class
Like C++ or Java abstract class in PHP can contain constructor also.Example:<?php // Abstract classabstract class Base { function __construct() { echo "this is abstract class constructor "; } // This is abstract function abstract function printdata();}class Derived extends base { function __construct() { echo "\n Derived class constructor"; } function printdata() { echo "\n Derived class printdata function"; }}$b1 = new Derived;$b1->printdata();?>Output:Derived class constructor
Derived class printdata function
Example:
<?php // Abstract classabstract class Base { function __construct() { echo "this is abstract class constructor "; } // This is abstract function abstract function printdata();}class Derived extends base { function __construct() { echo "\n Derived class constructor"; } function printdata() { echo "\n Derived class printdata function"; }}$b1 = new Derived;$b1->printdata();?>
Derived class constructor
Derived class printdata function
Unlike Java, an abstract class can not be created which does not contains at least one abstract method in PHP. If we run the following example then it will display an error message.Example:<?php // example to understand that an abstract // class can not contain an method with// body in phpabstract class Base { abstract function printdata() { echo "Parent class printdata"; }}?>Runtime Errors:PHP Fatal error: Abstract function Base::printdata() cannot contain body
in /home/a7540402ade5337d505a779cf4797b38.php on line 7
Example:
<?php // example to understand that an abstract // class can not contain an method with// body in phpabstract class Base { abstract function printdata() { echo "Parent class printdata"; }}?>
Runtime Errors:
PHP Fatal error: Abstract function Base::printdata() cannot contain body
in /home/a7540402ade5337d505a779cf4797b38.php on line 7
Shivam_k
PHP-OOP
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to execute PHP code using command line ?
How to pop an alert message box using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 31040,
"s": 31012,
"text": "\n19 Jul, 2019"
},
{
"code": null,
"e": 31417,
"s": 31040,
"text": "Abstract classes are the classes in which at least one method is abstract. Unlike C++ abstract classes in PHP are declared with the help of abstract keyword. Use of abstract classes are that all base classes implementing this class should give implementation of abstract methods declared in parent class. An abstract class can contain abstract as well as non abstract methods."
},
{
"code": "<?php // Abstract class example in PHPabstract class base{ // This is abstract function abstract function printdata(); // This is not abstract function function pr() { echo \"Base class\"; }}?>",
"e": 31641,
"s": 31417,
"text": null
},
{
"code": null,
"e": 31707,
"s": 31641,
"text": "Following are some important facts about abstract classes in PHP."
},
{
"code": null,
"e": 32197,
"s": 31707,
"text": "Like Java, PHP also an instance of abstract class can not be created.Example:<?php // Abstract classabstract class Base { // This is abstract function abstract function printdata();}class Derived extends base { function printdata() { echo \"Derived class\"; }} // Uncommenting the following line will // cause compiler error as the line tries// to create an instance of abstract class. // $b = new Base(); $b1 = new Derived;$b1->printdata();?>Output:Derived class\n"
},
{
"code": null,
"e": 32206,
"s": 32197,
"text": "Example:"
},
{
"code": "<?php // Abstract classabstract class Base { // This is abstract function abstract function printdata();}class Derived extends base { function printdata() { echo \"Derived class\"; }} // Uncommenting the following line will // cause compiler error as the line tries// to create an instance of abstract class. // $b = new Base(); $b1 = new Derived;$b1->printdata();?>",
"e": 32598,
"s": 32206,
"text": null
},
{
"code": null,
"e": 32613,
"s": 32598,
"text": "Derived class\n"
},
{
"code": null,
"e": 33180,
"s": 32613,
"text": "Like C++ or Java abstract class in PHP can contain constructor also.Example:<?php // Abstract classabstract class Base { function __construct() { echo \"this is abstract class constructor \"; } // This is abstract function abstract function printdata();}class Derived extends base { function __construct() { echo \"\\n Derived class constructor\"; } function printdata() { echo \"\\n Derived class printdata function\"; }}$b1 = new Derived;$b1->printdata();?>Output:Derived class constructor\n Derived class printdata function\n"
},
{
"code": null,
"e": 33189,
"s": 33180,
"text": "Example:"
},
{
"code": "<?php // Abstract classabstract class Base { function __construct() { echo \"this is abstract class constructor \"; } // This is abstract function abstract function printdata();}class Derived extends base { function __construct() { echo \"\\n Derived class constructor\"; } function printdata() { echo \"\\n Derived class printdata function\"; }}$b1 = new Derived;$b1->printdata();?>",
"e": 33613,
"s": 33189,
"text": null
},
{
"code": null,
"e": 33674,
"s": 33613,
"text": "Derived class constructor\n Derived class printdata function\n"
},
{
"code": null,
"e": 34214,
"s": 33674,
"text": "Unlike Java, an abstract class can not be created which does not contains at least one abstract method in PHP. If we run the following example then it will display an error message.Example:<?php // example to understand that an abstract // class can not contain an method with// body in phpabstract class Base { abstract function printdata() { echo \"Parent class printdata\"; }}?>Runtime Errors:PHP Fatal error: Abstract function Base::printdata() cannot contain body \nin /home/a7540402ade5337d505a779cf4797b38.php on line 7\n"
},
{
"code": null,
"e": 34223,
"s": 34214,
"text": "Example:"
},
{
"code": "<?php // example to understand that an abstract // class can not contain an method with// body in phpabstract class Base { abstract function printdata() { echo \"Parent class printdata\"; }}?>",
"e": 34428,
"s": 34223,
"text": null
},
{
"code": null,
"e": 34444,
"s": 34428,
"text": "Runtime Errors:"
},
{
"code": null,
"e": 34576,
"s": 34444,
"text": "PHP Fatal error: Abstract function Base::printdata() cannot contain body \nin /home/a7540402ade5337d505a779cf4797b38.php on line 7\n"
},
{
"code": null,
"e": 34585,
"s": 34576,
"text": "Shivam_k"
},
{
"code": null,
"e": 34593,
"s": 34585,
"text": "PHP-OOP"
},
{
"code": null,
"e": 34597,
"s": 34593,
"text": "PHP"
},
{
"code": null,
"e": 34614,
"s": 34597,
"text": "Web Technologies"
},
{
"code": null,
"e": 34618,
"s": 34614,
"text": "PHP"
},
{
"code": null,
"e": 34716,
"s": 34618,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34725,
"s": 34716,
"text": "Comments"
},
{
"code": null,
"e": 34738,
"s": 34725,
"text": "Old Comments"
},
{
"code": null,
"e": 34788,
"s": 34738,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 34833,
"s": 34788,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 34877,
"s": 34833,
"text": "How to pop an alert message box using PHP ?"
},
{
"code": null,
"e": 34901,
"s": 34877,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 34941,
"s": 34901,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 34997,
"s": 34941,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 35030,
"s": 34997,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 35092,
"s": 35030,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 35135,
"s": 35092,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to send data to previous activity in Android?
|
This example demonstrate about How to send data to previous activity in Android
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:layout_margin = "16dp"
android:orientation = "vertical"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/text_view"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_centerInParent = "true"
android:layout_gravity = "center" />
<Button
android:id = "@+id/button"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_alignParentBottom = "true"
android:layout_gravity = "center"
android:layout_marginTop = "16dp"
android:text = "Get Data" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private final static int MY_REQUEST_CODE = 1;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivityForResult(intent, MY_REQUEST_CODE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode = = Activity.RESULT_OK) {
if (requestCode = = MY_REQUEST_CODE) {
if (data ! = null)
textView.setText(data.getStringExtra("value"));
}
}
}
}
Step 4 − Add the following code to res/layout/activity_second.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:layout_margin = "16dp"
android:orientation = "vertical"
tools:context = ".SecondActivity">
<EditText
android:id = "@+id/edit_text"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_centerInParent = "true"
android:layout_gravity = "center"
android:hint = "Enter something to return previous activity"
android:inputType = "text" />
<Button
android:id = "@+id/button"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_alignParentBottom = "true"
android:layout_gravity = "center"
android:layout_marginTop = "16dp"
android:text = "Done" />
</RelativeLayout>
Step 5 − Add the following code to src/SecondActivity.java
package com.example.myapplication;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
final EditText editText = findViewById(R.id.edit_text);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String value = editText.getText().toString().trim();
Intent intent = new Intent();
intent.putExtra("value", value);
setResult(RESULT_OK, intent);
finish();
}
});
}
}
Step 6 − 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">
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon = "@mipmap/ic_launcher_round"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<activity android:name = ".MainActivity">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name = ".SecondActivity"></activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code
|
[
{
"code": null,
"e": 1142,
"s": 1062,
"text": "This example demonstrate about How to send data to previous activity in Android"
},
{
"code": null,
"e": 1271,
"s": 1142,
"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": 1336,
"s": 1271,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2237,
"s": 1336,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<RelativeLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n android:orientation = \"vertical\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_centerInParent = \"true\"\n android:layout_gravity = \"center\" />\n <Button\n android:id = \"@+id/button\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_alignParentBottom = \"true\"\n android:layout_gravity = \"center\"\n android:layout_marginTop = \"16dp\"\n android:text = \"Get Data\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2294,
"s": 2237,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3715,
"s": 2294,
"text": "package com.example.myapplication;\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.support.annotation.Nullable;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n private final static int MY_REQUEST_CODE = 1;\n TextView textView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text_view);\n Button button = findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent intent = new Intent(MainActivity.this, SecondActivity.class);\n startActivityForResult(intent, MY_REQUEST_CODE);\n }\n });\n }\n @Override\n protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (resultCode = = Activity.RESULT_OK) {\n if (requestCode = = MY_REQUEST_CODE) {\n if (data ! = null)\n textView.setText(data.getStringExtra(\"value\"));\n }\n }\n }\n}"
},
{
"code": null,
"e": 3782,
"s": 3715,
"text": "Step 4 − Add the following code to res/layout/activity_second.xml."
},
{
"code": null,
"e": 4781,
"s": 3782,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<RelativeLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n android:orientation = \"vertical\"\n tools:context = \".SecondActivity\">\n <EditText\n android:id = \"@+id/edit_text\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_centerInParent = \"true\"\n android:layout_gravity = \"center\"\n android:hint = \"Enter something to return previous activity\"\n android:inputType = \"text\" />\n <Button\n android:id = \"@+id/button\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_alignParentBottom = \"true\"\n android:layout_gravity = \"center\"\n android:layout_marginTop = \"16dp\"\n android:text = \"Done\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 4840,
"s": 4781,
"text": "Step 5 − Add the following code to src/SecondActivity.java"
},
{
"code": null,
"e": 5833,
"s": 4840,
"text": "package com.example.myapplication;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\n\npublic class SecondActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_second);\n final EditText editText = findViewById(R.id.edit_text);\n Button button = findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String value = editText.getText().toString().trim();\n Intent intent = new Intent();\n intent.putExtra(\"value\", value);\n setResult(RESULT_OK, intent);\n finish();\n }\n });\n }\n}"
},
{
"code": null,
"e": 5888,
"s": 5833,
"text": "Step 6 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 6659,
"s": 5888,
"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 <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <activity android:name = \".SecondActivity\"></activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 7008,
"s": 6659,
"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": 7050,
"s": 7010,
"text": "Click here to download the project code"
}
] |
Python 3 - List sort() Method
|
The sort() method sorts objects of list, use compare function if given.
Following is the syntax for sort() method −
list.sort([func])
NA
This method does not return any value; it simply sorts the contents of the given list.
The following example shows the usage of sort() method.
#!/usr/bin/python3
list1 = ['physics', 'Biology', 'chemistry', 'maths']
list1.sort()
print ("list now : ", list1)
When we run above program, it produces the following result −
list now : ['Biology', 'chemistry', 'maths', 'physics']
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": 2412,
"s": 2340,
"text": "The sort() method sorts objects of list, use compare function if given."
},
{
"code": null,
"e": 2456,
"s": 2412,
"text": "Following is the syntax for sort() method −"
},
{
"code": null,
"e": 2475,
"s": 2456,
"text": "list.sort([func])\n"
},
{
"code": null,
"e": 2478,
"s": 2475,
"text": "NA"
},
{
"code": null,
"e": 2565,
"s": 2478,
"text": "This method does not return any value; it simply sorts the contents of the given list."
},
{
"code": null,
"e": 2621,
"s": 2565,
"text": "The following example shows the usage of sort() method."
},
{
"code": null,
"e": 2736,
"s": 2621,
"text": "#!/usr/bin/python3\n\nlist1 = ['physics', 'Biology', 'chemistry', 'maths']\nlist1.sort()\nprint (\"list now : \", list1)"
},
{
"code": null,
"e": 2798,
"s": 2736,
"text": "When we run above program, it produces the following result −"
},
{
"code": null,
"e": 2856,
"s": 2798,
"text": "list now : ['Biology', 'chemistry', 'maths', 'physics']\n"
},
{
"code": null,
"e": 2893,
"s": 2856,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 2909,
"s": 2893,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 2942,
"s": 2909,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2961,
"s": 2942,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 2996,
"s": 2961,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3018,
"s": 2996,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3052,
"s": 3018,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3080,
"s": 3052,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3115,
"s": 3080,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3129,
"s": 3115,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3162,
"s": 3129,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3179,
"s": 3162,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3186,
"s": 3179,
"text": " Print"
},
{
"code": null,
"e": 3197,
"s": 3186,
"text": " Add Notes"
}
] |
OpenCV - Distance Transformation
|
The distance transform operator generally takes binary images as inputs. In this operation, the gray level intensities of the points inside the foreground regions are changed to distance their respective distances from the closest 0 value (boundary).
You can apply distance transform in OpenCV using the method distanceTransform(). Following is the syntax of this method.
distanceTransform(src, dst, distanceType, maskSize)
This method accepts the following parameters −
src − An object of the class Mat representing the source (input) image.
src − An object of the class Mat representing the source (input) image.
dst − An object of the class Mat representing the destination (output) image.
dst − An object of the class Mat representing the destination (output) image.
distanceType − A variable of the type integer representing the type of the distance transformation to be applied.
distanceType − A variable of the type integer representing the type of the distance transformation to be applied.
maskSize − A variable of integer type representing the mask size to be used.
maskSize − A variable of integer type representing the mask size to be used.
The following program demonstrates how to perform distance transformation operation on a given image.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class DistanceTransform {
public static void main(String args[]) {
// Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
// Reading the Image from the file and storing it in to a Matrix object
String file ="E:/OpenCV/chap19/input.jpg";
Mat src = Imgcodecs.imread(file,0);
// Creating an empty matrix to store the results
Mat dst = new Mat();
Mat binary = new Mat();
// Converting the grayscale image to binary image
Imgproc.threshold(src, binary, 100, 255, Imgproc.THRESH_BINARY);
// Applying distance transform
Imgproc.distanceTransform(mat, dst, Imgproc.DIST_C, 3);
// Writing the image
Imgcodecs.imwrite("E:/OpenCV/chap19/distnceTransform.jpg", dst);
System.out.println("Image Processed");
}
}
Assume that following is the input image input.jpg specified in the above program.
On executing the program, you will get the following output −
Image Processed
If you open the specified path, you can observe the output image as follows −
In addition to the distance operation type DIST_C demonstrated in the previous example, OpenCV caters various other types of distance transform operations. All these types are represented by predefined static fields (fixed values) of Imgproc class.
You can choose the type of the distance transform operation you need, by passing its respective predefined value to the parameter named distanceType of the distanceTransform() method.
// Applying distance transform
Imgproc.distanceTransform(mat, dst, Imgproc.DIST_C, 3);
Following are the values representing various types of distanceTransform operations and their respective outputs.
70 Lectures
9 hours
Abhilash Nelson
41 Lectures
4 hours
Abhilash Nelson
20 Lectures
2 hours
Spotle Learn
12 Lectures
46 mins
Srikanth Guskra
19 Lectures
2 hours
Haithem Gasmi
67 Lectures
6.5 hours
Gianluca Mottola
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3255,
"s": 3004,
"text": "The distance transform operator generally takes binary images as inputs. In this operation, the gray level intensities of the points inside the foreground regions are changed to distance their respective distances from the closest 0 value (boundary)."
},
{
"code": null,
"e": 3376,
"s": 3255,
"text": "You can apply distance transform in OpenCV using the method distanceTransform(). Following is the syntax of this method."
},
{
"code": null,
"e": 3429,
"s": 3376,
"text": "distanceTransform(src, dst, distanceType, maskSize)\n"
},
{
"code": null,
"e": 3476,
"s": 3429,
"text": "This method accepts the following parameters −"
},
{
"code": null,
"e": 3548,
"s": 3476,
"text": "src − An object of the class Mat representing the source (input) image."
},
{
"code": null,
"e": 3620,
"s": 3548,
"text": "src − An object of the class Mat representing the source (input) image."
},
{
"code": null,
"e": 3698,
"s": 3620,
"text": "dst − An object of the class Mat representing the destination (output) image."
},
{
"code": null,
"e": 3776,
"s": 3698,
"text": "dst − An object of the class Mat representing the destination (output) image."
},
{
"code": null,
"e": 3890,
"s": 3776,
"text": "distanceType − A variable of the type integer representing the type of the distance transformation to be applied."
},
{
"code": null,
"e": 4004,
"s": 3890,
"text": "distanceType − A variable of the type integer representing the type of the distance transformation to be applied."
},
{
"code": null,
"e": 4081,
"s": 4004,
"text": "maskSize − A variable of integer type representing the mask size to be used."
},
{
"code": null,
"e": 4158,
"s": 4081,
"text": "maskSize − A variable of integer type representing the mask size to be used."
},
{
"code": null,
"e": 4260,
"s": 4158,
"text": "The following program demonstrates how to perform distance transformation operation on a given image."
},
{
"code": null,
"e": 5227,
"s": 4260,
"text": "import org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\n\npublic class DistanceTransform {\n public static void main(String args[]) {\n // Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n\n // Reading the Image from the file and storing it in to a Matrix object\n String file =\"E:/OpenCV/chap19/input.jpg\";\n Mat src = Imgcodecs.imread(file,0);\n\n // Creating an empty matrix to store the results\n Mat dst = new Mat();\n Mat binary = new Mat();\n\n // Converting the grayscale image to binary image\n Imgproc.threshold(src, binary, 100, 255, Imgproc.THRESH_BINARY);\n\n // Applying distance transform\n Imgproc.distanceTransform(mat, dst, Imgproc.DIST_C, 3);\n\n // Writing the image\n Imgcodecs.imwrite(\"E:/OpenCV/chap19/distnceTransform.jpg\", dst);\n\n System.out.println(\"Image Processed\");\n }\n}"
},
{
"code": null,
"e": 5310,
"s": 5227,
"text": "Assume that following is the input image input.jpg specified in the above program."
},
{
"code": null,
"e": 5372,
"s": 5310,
"text": "On executing the program, you will get the following output −"
},
{
"code": null,
"e": 5389,
"s": 5372,
"text": "Image Processed\n"
},
{
"code": null,
"e": 5467,
"s": 5389,
"text": "If you open the specified path, you can observe the output image as follows −"
},
{
"code": null,
"e": 5716,
"s": 5467,
"text": "In addition to the distance operation type DIST_C demonstrated in the previous example, OpenCV caters various other types of distance transform operations. All these types are represented by predefined static fields (fixed values) of Imgproc class."
},
{
"code": null,
"e": 5900,
"s": 5716,
"text": "You can choose the type of the distance transform operation you need, by passing its respective predefined value to the parameter named distanceType of the distanceTransform() method."
},
{
"code": null,
"e": 5989,
"s": 5900,
"text": "// Applying distance transform \nImgproc.distanceTransform(mat, dst, Imgproc.DIST_C, 3);\n"
},
{
"code": null,
"e": 6103,
"s": 5989,
"text": "Following are the values representing various types of distanceTransform operations and their respective outputs."
},
{
"code": null,
"e": 6136,
"s": 6103,
"text": "\n 70 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 6153,
"s": 6136,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6186,
"s": 6153,
"text": "\n 41 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6203,
"s": 6186,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6236,
"s": 6203,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6250,
"s": 6236,
"text": " Spotle Learn"
},
{
"code": null,
"e": 6282,
"s": 6250,
"text": "\n 12 Lectures \n 46 mins\n"
},
{
"code": null,
"e": 6299,
"s": 6282,
"text": " Srikanth Guskra"
},
{
"code": null,
"e": 6332,
"s": 6299,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6347,
"s": 6332,
"text": " Haithem Gasmi"
},
{
"code": null,
"e": 6382,
"s": 6347,
"text": "\n 67 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 6400,
"s": 6382,
"text": " Gianluca Mottola"
},
{
"code": null,
"e": 6407,
"s": 6400,
"text": " Print"
},
{
"code": null,
"e": 6418,
"s": 6407,
"text": " Add Notes"
}
] |
How to deploy Jupyter notebooks as components of a Kubeflow ML pipeline (Part 2) | by Lak Lakshmanan | Towards Data Science
|
In Part 1, I showed you how to create and deploy a Kubeflow ML pipeline using Docker components. In Part 2, I will show you how to make a Jupyter notebook a component of a Kubeflow ML pipeline. Where the Docker components are for the folks operationalizing machine learning models, being able to run a Jupyter notebook on arbitrary hardware is more suitable for data scientists.
I’ll assume that you already have a Kubeflow pipelines cluster up and running as explained in the previous article. Typically, the “ML Platform Team” (part of the IT department) would manage the cluster for use by a team of data scientists.
Note: When I wrote this article, you had to run a notebook on the cluster itself. Now, though, a much better way is to use AI Platform Notebooks and submit code to the cluster remotely. Follow the instructions in this README file, making sure to start a TensorFlow 1.10 Notebook VM. Skip this step, and start from Step 2.
From the Kubeflow pipelines user interface (http://localhost:8085/pipeline if you followed the instructions in the previous post), click on the link for Notebooks:
This will prompt you to start JupyterHub if this is the first time. Use your GCP username/password to login. Then, select the version of Tensorflow that you want:
I chose TensorFlow v1.10 on a cpu.
Then, open up a Terminal window and git clone my repo:
git clone https://github.com/GoogleCloudPlatform/data-science-on-gcp
Switch back to the Jupyter notebooks listing and navigate to data-science-on-gcp/updates/cloudml and open up flights_model.ipynb.
The actual TensorFlow code (See full notebook here: flights_model.ipynb) isn’t important, but I want you to notice a few things. One is that I developed this notebook mostly in Eager mode, for easy debugging:
if EAGER_MODE: dataset = load_dataset(TRAIN_DATA_PATTERN) for n, data in enumerate(dataset): numpy_data = {k: v.numpy() for k, v in data.items()} # .numpy() works only in eager mode print(numpy_data) if n>3: break
Then, I trained the model for a few steps and specified more steps if “not in develop mode”:
num_steps = 10 if DEVELOP_MODE else (1000000 // train_batch_size)
Finally, I deployed it to Cloud ML Engine as a web service:
gcloud ml-engine versions create ${MODEL_VERSION} --model ${MODEL_NAME} --origin ${MODEL_LOCATION} --runtime-version 1.10
and made sure that I could send JSON to the deployed model:
{"dep_delay": 14.0, "taxiout": 13.0, "distance": 319.0, "avg_dep_delay": 25.863039, "avg_arr_delay": 27.0, "carrier": "WN", "dep_lat": 32.84722, "dep_lon": -96.85167, "arr_lat": 31.9425, "arr_lon": -102.20194, "origin": "DAL", "dest": "MAF"}{"dep_delay": -9.0, "taxiout": 21.0, "distance": 301.0, "avg_dep_delay": 41.050808, "avg_arr_delay": -7.0, "carrier": "EV", "dep_lat": 29.984444, "dep_lon": -95.34139, "arr_lat": 27.544167, "arr_lon": -99.46167, "origin": "IAH", "dest": "LRD"}
to get back, for each instance the probability that the flight will be late.
So, I have a full-fledged notebook that does some ML workflow. Can I execute this as a component as part of a Kubeflow pipeline? Recall from Part 1 that all it takes for something to be a component is for it to be a self-contained container that takes a few parameters and writes outputs to files, either on the Kubeflow cluster or on Cloud Storage.
In order to deploy the flights_model notebook as a component:
I have a cell at the top of my notebook whose tag is “parameters”. In this cell, I define any variables that I will want to re-execute the notebook with. In particular, I set up a variable called DEVELOP_MODE. In develop mode, I will read small datasets; in not-develop-mode, I’ll train on the full dataset. Because I want you to be able to change them easily, I also make the PROJECT (to be billed) and the BUCKET (to store outputs) as parameters.
I then build a Docker image that is capable of executing my notebook. To execute a notebook, I will use the Python package papermill. My notebook uses Python3, gcloud and tensorflow. So my Dockerfile captures all those dependencies in the Dockerfile
FROM google/cloud-sdk:latestRUN apt-get update -y && apt-get install --no-install-recommends -y -q ca-certificates python3-dev python3-setuptools python3-pipRUN python3 -m pip install tensorflow==1.10 jupyter papermillCOPY run_notebook.sh ./ENTRYPOINT ["bash", "./run_notebook.sh"]
The entry point to the Docker image is run_notebook.sh which uses papermill to execute the notebook:
gsutil cp $IN_NB_GCS input.ipynbgsutil cp $PARAMS_GCS params.yamlpapermill input.ipynb output.ipynb -f params.yaml --log-outputgsutil cp output.ipynb $OUT_NB_GCS
Essentially, the script copies the notebook to be run from Google Cloud Storage to the Kubeflow pod, runs the notebook with papermill and copies the resulting output back to Google Cloud Storage.
But params.yaml? What’s params.yaml? Those are the configurable parameters to the notebook. For example, it could be:
---BUCKET: cloud-training-demos-mlPROJECT: cloud-training-demosDEVELOP_MODE: False
That’s it! When this Docker image is run, it will execute the supplied notebook and copy the output notebook (with plots plotted, models trained, etc.) to GCS.
The point of running the notebook as one step of the pipeline is so that it can be orchestrated and reused in other pipelines. But just to show you how it can be done, this is how you would create a pipeline that executes only this notebook:
import kfp.components as compimport kfp.dsl as dsl# a single-op pipeline that runs the flights pipeline on the pod@dsl.pipeline( name='FlightsPipeline', description='Trains, deploys flights model')def flights_pipeline( inputnb=dsl.PipelineParam('inputnb'), outputnb=dsl.PipelineParam('outputnb'), params=dsl.PipelineParam('params')): notebookop = dsl.ContainerOp( name='flightsmodel', image='gcr.io/cloud-training-demos/submitnotebook:latest', arguments=[ inputnb, outputnb, params ] )
Nothing fancy — I’m creating a container, telling it to use my image that has TensorFlow, papermill, etc. and giving it the input and output notebooks and params. As the pipeline runs, logs get streamed to the pipelines log, and will show up in Stackdriver:
In my GitHub repo, creating and deploying the pipeline is shown in launcher.ipynb.
If you haven’t do so already, please read and walk through Part 1 of how to create and deploy a Kubeflow ML pipeline using Docker images.
Try out this article on how to deploy a Jupyter notebook as a component in a Kubeflow pipeline:
Start a cluster as explained in Part 1On the cluster, open flights_model.ipynb, change the PROJECT and BUCKET to be something you own, and run the notebook, making sure it works.Open launcher.ipynb and walk through the steps of running flights_model.ipynb and as a Kubeflow pipelines component.
Start a cluster as explained in Part 1
On the cluster, open flights_model.ipynb, change the PROJECT and BUCKET to be something you own, and run the notebook, making sure it works.
Open launcher.ipynb and walk through the steps of running flights_model.ipynb and as a Kubeflow pipelines component.
The launcher notebook also includes the ability to launch the flights_model notebook on the Deep Learning VM, but ignore it for now — I’ll cover that in Part 3 of this series.
The notebook can be a unit of composability and reusability — but for this to happen, you have to take care to write small, single-purpose notebooks. What I did in this article — a huge, monolithic notebook — is not a good idea. The tradeoff is that if you use smaller notebooks, dependency tracking becomes difficult.
Use the Deep Learning VM for development and automation if you are a small team and don’t have anyone maintaining ML infrastructure like Kubeflow clusters for you. I will cover this in Part 3 of this series.
If you work in a large organization where a separate ML Platform team manages your ML infrastructure (i.e., a Kubeflow cluster), this article (Part 2) shows you how to develop in Jupyter notebooks and deploy to Kubeflow pipelines. (The IT team will probably help you with the Docker parts if you show them this article).
While notebooks will help you be agile, you will also be building up a lot of technical debt. Monolithic notebooks make reusability hard and single-purpose notebooks make it hard to track dependencies. Secondly, even though your logs will go to GCP’s logging platform (Stackdriver), they are probably unstructured cell output. This makes it hard to monitor the pipeline and react to failures. Plan, therefore, on moving mature code and models out of notebooks into separate pipeline components, each of which is a container. This is what I showed you in Part 1.
In other words, use Deep Learning VM for small teams, Jupyter components for experimental work, and container-ops for mature models
|
[
{
"code": null,
"e": 550,
"s": 171,
"text": "In Part 1, I showed you how to create and deploy a Kubeflow ML pipeline using Docker components. In Part 2, I will show you how to make a Jupyter notebook a component of a Kubeflow ML pipeline. Where the Docker components are for the folks operationalizing machine learning models, being able to run a Jupyter notebook on arbitrary hardware is more suitable for data scientists."
},
{
"code": null,
"e": 791,
"s": 550,
"text": "I’ll assume that you already have a Kubeflow pipelines cluster up and running as explained in the previous article. Typically, the “ML Platform Team” (part of the IT department) would manage the cluster for use by a team of data scientists."
},
{
"code": null,
"e": 1113,
"s": 791,
"text": "Note: When I wrote this article, you had to run a notebook on the cluster itself. Now, though, a much better way is to use AI Platform Notebooks and submit code to the cluster remotely. Follow the instructions in this README file, making sure to start a TensorFlow 1.10 Notebook VM. Skip this step, and start from Step 2."
},
{
"code": null,
"e": 1277,
"s": 1113,
"text": "From the Kubeflow pipelines user interface (http://localhost:8085/pipeline if you followed the instructions in the previous post), click on the link for Notebooks:"
},
{
"code": null,
"e": 1440,
"s": 1277,
"text": "This will prompt you to start JupyterHub if this is the first time. Use your GCP username/password to login. Then, select the version of Tensorflow that you want:"
},
{
"code": null,
"e": 1475,
"s": 1440,
"text": "I chose TensorFlow v1.10 on a cpu."
},
{
"code": null,
"e": 1530,
"s": 1475,
"text": "Then, open up a Terminal window and git clone my repo:"
},
{
"code": null,
"e": 1599,
"s": 1530,
"text": "git clone https://github.com/GoogleCloudPlatform/data-science-on-gcp"
},
{
"code": null,
"e": 1729,
"s": 1599,
"text": "Switch back to the Jupyter notebooks listing and navigate to data-science-on-gcp/updates/cloudml and open up flights_model.ipynb."
},
{
"code": null,
"e": 1938,
"s": 1729,
"text": "The actual TensorFlow code (See full notebook here: flights_model.ipynb) isn’t important, but I want you to notice a few things. One is that I developed this notebook mostly in Eager mode, for easy debugging:"
},
{
"code": null,
"e": 2173,
"s": 1938,
"text": "if EAGER_MODE: dataset = load_dataset(TRAIN_DATA_PATTERN) for n, data in enumerate(dataset): numpy_data = {k: v.numpy() for k, v in data.items()} # .numpy() works only in eager mode print(numpy_data) if n>3: break"
},
{
"code": null,
"e": 2266,
"s": 2173,
"text": "Then, I trained the model for a few steps and specified more steps if “not in develop mode”:"
},
{
"code": null,
"e": 2332,
"s": 2266,
"text": "num_steps = 10 if DEVELOP_MODE else (1000000 // train_batch_size)"
},
{
"code": null,
"e": 2392,
"s": 2332,
"text": "Finally, I deployed it to Cloud ML Engine as a web service:"
},
{
"code": null,
"e": 2514,
"s": 2392,
"text": "gcloud ml-engine versions create ${MODEL_VERSION} --model ${MODEL_NAME} --origin ${MODEL_LOCATION} --runtime-version 1.10"
},
{
"code": null,
"e": 2574,
"s": 2514,
"text": "and made sure that I could send JSON to the deployed model:"
},
{
"code": null,
"e": 3059,
"s": 2574,
"text": "{\"dep_delay\": 14.0, \"taxiout\": 13.0, \"distance\": 319.0, \"avg_dep_delay\": 25.863039, \"avg_arr_delay\": 27.0, \"carrier\": \"WN\", \"dep_lat\": 32.84722, \"dep_lon\": -96.85167, \"arr_lat\": 31.9425, \"arr_lon\": -102.20194, \"origin\": \"DAL\", \"dest\": \"MAF\"}{\"dep_delay\": -9.0, \"taxiout\": 21.0, \"distance\": 301.0, \"avg_dep_delay\": 41.050808, \"avg_arr_delay\": -7.0, \"carrier\": \"EV\", \"dep_lat\": 29.984444, \"dep_lon\": -95.34139, \"arr_lat\": 27.544167, \"arr_lon\": -99.46167, \"origin\": \"IAH\", \"dest\": \"LRD\"}"
},
{
"code": null,
"e": 3136,
"s": 3059,
"text": "to get back, for each instance the probability that the flight will be late."
},
{
"code": null,
"e": 3486,
"s": 3136,
"text": "So, I have a full-fledged notebook that does some ML workflow. Can I execute this as a component as part of a Kubeflow pipeline? Recall from Part 1 that all it takes for something to be a component is for it to be a self-contained container that takes a few parameters and writes outputs to files, either on the Kubeflow cluster or on Cloud Storage."
},
{
"code": null,
"e": 3548,
"s": 3486,
"text": "In order to deploy the flights_model notebook as a component:"
},
{
"code": null,
"e": 3997,
"s": 3548,
"text": "I have a cell at the top of my notebook whose tag is “parameters”. In this cell, I define any variables that I will want to re-execute the notebook with. In particular, I set up a variable called DEVELOP_MODE. In develop mode, I will read small datasets; in not-develop-mode, I’ll train on the full dataset. Because I want you to be able to change them easily, I also make the PROJECT (to be billed) and the BUCKET (to store outputs) as parameters."
},
{
"code": null,
"e": 4247,
"s": 3997,
"text": "I then build a Docker image that is capable of executing my notebook. To execute a notebook, I will use the Python package papermill. My notebook uses Python3, gcloud and tensorflow. So my Dockerfile captures all those dependencies in the Dockerfile"
},
{
"code": null,
"e": 4529,
"s": 4247,
"text": "FROM google/cloud-sdk:latestRUN apt-get update -y && apt-get install --no-install-recommends -y -q ca-certificates python3-dev python3-setuptools python3-pipRUN python3 -m pip install tensorflow==1.10 jupyter papermillCOPY run_notebook.sh ./ENTRYPOINT [\"bash\", \"./run_notebook.sh\"]"
},
{
"code": null,
"e": 4630,
"s": 4529,
"text": "The entry point to the Docker image is run_notebook.sh which uses papermill to execute the notebook:"
},
{
"code": null,
"e": 4793,
"s": 4630,
"text": "gsutil cp $IN_NB_GCS input.ipynbgsutil cp $PARAMS_GCS params.yamlpapermill input.ipynb output.ipynb -f params.yaml --log-outputgsutil cp output.ipynb $OUT_NB_GCS"
},
{
"code": null,
"e": 4989,
"s": 4793,
"text": "Essentially, the script copies the notebook to be run from Google Cloud Storage to the Kubeflow pod, runs the notebook with papermill and copies the resulting output back to Google Cloud Storage."
},
{
"code": null,
"e": 5107,
"s": 4989,
"text": "But params.yaml? What’s params.yaml? Those are the configurable parameters to the notebook. For example, it could be:"
},
{
"code": null,
"e": 5190,
"s": 5107,
"text": "---BUCKET: cloud-training-demos-mlPROJECT: cloud-training-demosDEVELOP_MODE: False"
},
{
"code": null,
"e": 5350,
"s": 5190,
"text": "That’s it! When this Docker image is run, it will execute the supplied notebook and copy the output notebook (with plots plotted, models trained, etc.) to GCS."
},
{
"code": null,
"e": 5592,
"s": 5350,
"text": "The point of running the notebook as one step of the pipeline is so that it can be orchestrated and reused in other pipelines. But just to show you how it can be done, this is how you would create a pipeline that executes only this notebook:"
},
{
"code": null,
"e": 6135,
"s": 5592,
"text": "import kfp.components as compimport kfp.dsl as dsl# a single-op pipeline that runs the flights pipeline on the pod@dsl.pipeline( name='FlightsPipeline', description='Trains, deploys flights model')def flights_pipeline( inputnb=dsl.PipelineParam('inputnb'), outputnb=dsl.PipelineParam('outputnb'), params=dsl.PipelineParam('params')): notebookop = dsl.ContainerOp( name='flightsmodel', image='gcr.io/cloud-training-demos/submitnotebook:latest', arguments=[ inputnb, outputnb, params ] )"
},
{
"code": null,
"e": 6393,
"s": 6135,
"text": "Nothing fancy — I’m creating a container, telling it to use my image that has TensorFlow, papermill, etc. and giving it the input and output notebooks and params. As the pipeline runs, logs get streamed to the pipelines log, and will show up in Stackdriver:"
},
{
"code": null,
"e": 6476,
"s": 6393,
"text": "In my GitHub repo, creating and deploying the pipeline is shown in launcher.ipynb."
},
{
"code": null,
"e": 6614,
"s": 6476,
"text": "If you haven’t do so already, please read and walk through Part 1 of how to create and deploy a Kubeflow ML pipeline using Docker images."
},
{
"code": null,
"e": 6710,
"s": 6614,
"text": "Try out this article on how to deploy a Jupyter notebook as a component in a Kubeflow pipeline:"
},
{
"code": null,
"e": 7005,
"s": 6710,
"text": "Start a cluster as explained in Part 1On the cluster, open flights_model.ipynb, change the PROJECT and BUCKET to be something you own, and run the notebook, making sure it works.Open launcher.ipynb and walk through the steps of running flights_model.ipynb and as a Kubeflow pipelines component."
},
{
"code": null,
"e": 7044,
"s": 7005,
"text": "Start a cluster as explained in Part 1"
},
{
"code": null,
"e": 7185,
"s": 7044,
"text": "On the cluster, open flights_model.ipynb, change the PROJECT and BUCKET to be something you own, and run the notebook, making sure it works."
},
{
"code": null,
"e": 7302,
"s": 7185,
"text": "Open launcher.ipynb and walk through the steps of running flights_model.ipynb and as a Kubeflow pipelines component."
},
{
"code": null,
"e": 7478,
"s": 7302,
"text": "The launcher notebook also includes the ability to launch the flights_model notebook on the Deep Learning VM, but ignore it for now — I’ll cover that in Part 3 of this series."
},
{
"code": null,
"e": 7797,
"s": 7478,
"text": "The notebook can be a unit of composability and reusability — but for this to happen, you have to take care to write small, single-purpose notebooks. What I did in this article — a huge, monolithic notebook — is not a good idea. The tradeoff is that if you use smaller notebooks, dependency tracking becomes difficult."
},
{
"code": null,
"e": 8005,
"s": 7797,
"text": "Use the Deep Learning VM for development and automation if you are a small team and don’t have anyone maintaining ML infrastructure like Kubeflow clusters for you. I will cover this in Part 3 of this series."
},
{
"code": null,
"e": 8326,
"s": 8005,
"text": "If you work in a large organization where a separate ML Platform team manages your ML infrastructure (i.e., a Kubeflow cluster), this article (Part 2) shows you how to develop in Jupyter notebooks and deploy to Kubeflow pipelines. (The IT team will probably help you with the Docker parts if you show them this article)."
},
{
"code": null,
"e": 8888,
"s": 8326,
"text": "While notebooks will help you be agile, you will also be building up a lot of technical debt. Monolithic notebooks make reusability hard and single-purpose notebooks make it hard to track dependencies. Secondly, even though your logs will go to GCP’s logging platform (Stackdriver), they are probably unstructured cell output. This makes it hard to monitor the pipeline and react to failures. Plan, therefore, on moving mature code and models out of notebooks into separate pipeline components, each of which is a container. This is what I showed you in Part 1."
}
] |
C# - nested switch Statements
|
It is possible to have a switch as part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise.
The syntax for a nested switch statement is as follows −
switch(ch1) {
case 'A':
Console.WriteLine("This A is part of outer switch" );
switch(ch2) {
case 'A':
Console.WriteLine("This A is part of inner switch" );
break;
case 'B': /* inner B case code */
}
break;
case 'B': /* outer B case code */
}
using System;
namespace DecisionMaking {
class Program {
static void Main(string[] args) {
int a = 100;
int b = 200;
switch (a) {
case 100:
Console.WriteLine("This is part of outer switch ");
switch (b) {
case 200:
Console.WriteLine("This is part of inner switch ");
break;
}
break;
}
Console.WriteLine("Exact value of a is : {0}", a);
Console.WriteLine("Exact value of b is : {0}", b);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
This is part of outer switch
This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2461,
"s": 2270,
"text": "It is possible to have a switch as part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise."
},
{
"code": null,
"e": 2519,
"s": 2461,
"text": "The syntax for a nested switch statement is as follows −"
},
{
"code": null,
"e": 2814,
"s": 2519,
"text": "switch(ch1) {\n case 'A':\n Console.WriteLine(\"This A is part of outer switch\" );\n \n switch(ch2) {\n case 'A':\n Console.WriteLine(\"This A is part of inner switch\" );\n break;\n case 'B': /* inner B case code */\n }\n break;\n case 'B': /* outer B case code */\n}\n"
},
{
"code": null,
"e": 3439,
"s": 2814,
"text": "using System;\n\nnamespace DecisionMaking {\n class Program {\n static void Main(string[] args) {\n int a = 100;\n int b = 200;\n \n switch (a) {\n case 100: \n Console.WriteLine(\"This is part of outer switch \");\n \n switch (b) {\n case 200:\n Console.WriteLine(\"This is part of inner switch \");\n break;\n }\n break;\n }\n Console.WriteLine(\"Exact value of a is : {0}\", a);\n Console.WriteLine(\"Exact value of b is : {0}\", b);\n Console.ReadLine();\n }\n }\n} "
},
{
"code": null,
"e": 3520,
"s": 3439,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3631,
"s": 3520,
"text": "This is part of outer switch\nThis is part of inner switch\nExact value of a is : 100\nExact value of b is : 200\n"
},
{
"code": null,
"e": 3668,
"s": 3631,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 3681,
"s": 3668,
"text": " Raja Biswas"
},
{
"code": null,
"e": 3715,
"s": 3681,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3733,
"s": 3715,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 3766,
"s": 3733,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3780,
"s": 3766,
"text": " Peter Jepson"
},
{
"code": null,
"e": 3817,
"s": 3780,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 3832,
"s": 3817,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 3867,
"s": 3832,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 3882,
"s": 3867,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3917,
"s": 3882,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3929,
"s": 3917,
"text": " Eric Frick"
},
{
"code": null,
"e": 3936,
"s": 3929,
"text": " Print"
},
{
"code": null,
"e": 3947,
"s": 3936,
"text": " Add Notes"
}
] |
Swift – Nested if-else Statement
|
28 Feb, 2022
In Swift, a situation comes when we have to check an if condition inside an if-else statement then a term comes named nested if-else statement. It means an if-else statement inside another if statement. Or in simple words first, there is an outer if statement, and inside it another if – else statement is present and such type of statement is known as nested if statement. We can use one if or else if statement inside another if or else if statements.
Syntax:
// Outer if condition
if (condition 1)
{
// inner if statement
if (condition 2)
{
// Statement 1
}
// inner else statement
else
{
// Statement 2
}
}
// Outer else statement
else
{
// inner if statement
if (condition 3)
{
// Statement 3
}
// inner else statement
else
{
// Statement 4
}
}
Here, if the outer condition1 is true, then it will check for inner condition 2. If inner condition is true then it will proceed to statement 1 otherwise statement 2 will proceed. Similarly in outer else part will execute.
Notes: We can add else and else if statements to the inner if statement whenever required. Also, we can nest multiple layers of if-else statements inside a if statement.
Flowchart:
Example 1:
Swift
// Swift program illustrate the use// of Nested if-else statement import Swiftvar a = 100var b = 200var c = 300 // outer if statementif (a > b) { // inner if statement if (a > c) { // Print statement 1 print("100 is Greater") } // inner else statement else { // Print statement 2 print("300 is Greater"); }} // outer else statementelse { // inner if statement if (b > c) { // Print statement 3 print("200 is Greater") } // inner else statement else { // Print statement 4 print("300 is Greater"); }}
Output:
300 is Greater
Explanation : In above example, First it will check for outer if condition. If outer if condition is true then it will check for inner if statement. If outer if statement is false it then will move to outer else part and so on. Here outer if condition is false. Next it will move to outer else part and check for inner if statement i.e. if b is greater than c ( b > c ). Here it evaluates false. Hence it will move to inner else part and prints statement 4.
Example 2 :
Swift
// Swift program illustrate the use of// Nested if-else-if statementimport Swift var number = 5 // outer if statementif (number >= 0) { // inner if statement if (number == 0) { // Print statement 1 print("Number is 0") } // inner else statement else { // Print statement 2 print("Number is greater than 0"); }} // outer else statementelse { // Print statement 3 print("Number is smaller than 0");}
Output :
Number is greater than 0
Explanation : Here we have declared a variable number with value 15. Then we have used if-else construct. If the outer if condition is true then and only then it will execute the inner if condition. In this example, the outer if condition is true hence the inner if block is processed. In the inner if condition, we again have a condition that checks if number is equals to 0 or not. When inner condition is true, then it will process the print statement 1 and If inner if statement is false then it will process the print statement 2. In this case, the inner if condition is false hence it will move to else part and prints statement 2 and the value is printed on the output screen.
nikhatkhan11
Picked
Swift-Control-Flow
Swift
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 482,
"s": 28,
"text": "In Swift, a situation comes when we have to check an if condition inside an if-else statement then a term comes named nested if-else statement. It means an if-else statement inside another if statement. Or in simple words first, there is an outer if statement, and inside it another if – else statement is present and such type of statement is known as nested if statement. We can use one if or else if statement inside another if or else if statements."
},
{
"code": null,
"e": 491,
"s": 482,
"text": "Syntax: "
},
{
"code": null,
"e": 889,
"s": 491,
"text": "// Outer if condition\nif (condition 1) \n{\n\n // inner if statement\n if (condition 2) \n {\n // Statement 1\n }\n // inner else statement\n else \n {\n // Statement 2\n }\n}\n\n// Outer else statement\nelse \n{\n\n // inner if statement\n if (condition 3) \n {\n // Statement 3\n }\n \n // inner else statement\n else \n {\n // Statement 4\n }\n}"
},
{
"code": null,
"e": 1112,
"s": 889,
"text": "Here, if the outer condition1 is true, then it will check for inner condition 2. If inner condition is true then it will proceed to statement 1 otherwise statement 2 will proceed. Similarly in outer else part will execute."
},
{
"code": null,
"e": 1282,
"s": 1112,
"text": "Notes: We can add else and else if statements to the inner if statement whenever required. Also, we can nest multiple layers of if-else statements inside a if statement."
},
{
"code": null,
"e": 1294,
"s": 1282,
"text": "Flowchart: "
},
{
"code": null,
"e": 1306,
"s": 1294,
"text": "Example 1: "
},
{
"code": null,
"e": 1312,
"s": 1306,
"text": "Swift"
},
{
"code": "// Swift program illustrate the use// of Nested if-else statement import Swiftvar a = 100var b = 200var c = 300 // outer if statementif (a > b) { // inner if statement if (a > c) { // Print statement 1 print(\"100 is Greater\") } // inner else statement else { // Print statement 2 print(\"300 is Greater\"); }} // outer else statementelse { // inner if statement if (b > c) { // Print statement 3 print(\"200 is Greater\") } // inner else statement else { // Print statement 4 print(\"300 is Greater\"); }}",
"e": 1885,
"s": 1312,
"text": null
},
{
"code": null,
"e": 1894,
"s": 1885,
"text": "Output: "
},
{
"code": null,
"e": 1910,
"s": 1894,
"text": "300 is Greater "
},
{
"code": null,
"e": 2368,
"s": 1910,
"text": "Explanation : In above example, First it will check for outer if condition. If outer if condition is true then it will check for inner if statement. If outer if statement is false it then will move to outer else part and so on. Here outer if condition is false. Next it will move to outer else part and check for inner if statement i.e. if b is greater than c ( b > c ). Here it evaluates false. Hence it will move to inner else part and prints statement 4."
},
{
"code": null,
"e": 2381,
"s": 2368,
"text": "Example 2 : "
},
{
"code": null,
"e": 2387,
"s": 2381,
"text": "Swift"
},
{
"code": "// Swift program illustrate the use of// Nested if-else-if statementimport Swift var number = 5 // outer if statementif (number >= 0) { // inner if statement if (number == 0) { // Print statement 1 print(\"Number is 0\") } // inner else statement else { // Print statement 2 print(\"Number is greater than 0\"); }} // outer else statementelse { // Print statement 3 print(\"Number is smaller than 0\");}",
"e": 2833,
"s": 2387,
"text": null
},
{
"code": null,
"e": 2843,
"s": 2833,
"text": "Output : "
},
{
"code": null,
"e": 2868,
"s": 2843,
"text": "Number is greater than 0"
},
{
"code": null,
"e": 3554,
"s": 2868,
"text": "Explanation : Here we have declared a variable number with value 15. Then we have used if-else construct. If the outer if condition is true then and only then it will execute the inner if condition. In this example, the outer if condition is true hence the inner if block is processed. In the inner if condition, we again have a condition that checks if number is equals to 0 or not. When inner condition is true, then it will process the print statement 1 and If inner if statement is false then it will process the print statement 2. In this case, the inner if condition is false hence it will move to else part and prints statement 2 and the value is printed on the output screen."
},
{
"code": null,
"e": 3567,
"s": 3554,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 3574,
"s": 3567,
"text": "Picked"
},
{
"code": null,
"e": 3593,
"s": 3574,
"text": "Swift-Control-Flow"
},
{
"code": null,
"e": 3599,
"s": 3593,
"text": "Swift"
}
] |
Java SimpleDateFormat | Set 1
|
08 Oct, 2021
SimpleDateFormat class helps in formatting and parsing of data. We can change date from one format to other. It allows to user to interpret string date format into a Date object. We can modify Date accordingly, we want.
Declaration :
public class SimpleDateFormat
extends DateFormat
Constructors :
SimpleDateFormat(String pattern_arg) : Constructs a Simple Date Format using the given pattern – pattern_arg, default date format symbols for the default FORMAT locale.
SimpleDateFormat(String pattern_arg, Locale locale_arg) : Constructs a Simple Date Format using the given pattern – pattern_arg, default date format symbols for the given FORMAT Locale – locale_arg.
SimpleDateFormat(String pattern_arg, DateFormatSymbols formatSymbols) : Constructs a SimpleDateFormat using the given pattern – pattern_arg and date format symbols.
Java Program illustrating SimpleDateFormat class
Java
// Java Program illustrating SimpleDateFormat classimport java.text.*;import java.util.*; public class NewClass{ public static void main(String[] args) { SimpleDateFormat geek = new SimpleDateFormat("dd / MM / yy"); // Creating instance of the System date Calendar c = Calendar.getInstance(); System.out.println("Present Date : " + c.getTime()); // Formatting Date according "dd / MM / yy" String formattedDate = geek.format(c.getTime()); System.out.println("Date formatted : "+formattedDate); }}
Output:
Present Date : Wed Jun 21 18:21:13 IST 2017
Date formatted : 21 / 06 / 17
Methods :
1. set2DigitYearStart() : java.text.SimpleDateFormat.set2DigitYearStart(Date starting_Date) parses the date and set the date in the range starting_Date to starting_Date + 100 years.
Syntax :
public void set2DigitYearStart(Date starting_Date)
Parameters :
starting_Date : Date is set in the range - starting_Date to starting_Date + 100 years
Return :
Returns void
Java
// Java Program illustrating// use of set2DigitYearStart() method import java.text.*;import java.util.Calendar; public class NewClass{ public static void main(String[] args) throws InterruptedException { SimpleDateFormat geek = new SimpleDateFormat("MM / dd / yy"); try { Calendar c = Calendar.getInstance(); c.setTime(geek.parse("10 / 27 / 16")); System.out.println("Initial Time : "+c.getTime()); // Setting 1916 instead of 2016 // Use of set2DigitYearStart() method geek.set2DigitYearStart(geek.parse("01 / 01 / 1900")); c.setTime(geek.parse("06 / 12 / 16")); System.out.println("New Time : "+c.getTime()); } catch (ParseException except) { except.printStackTrace(); } }}
Output :
Initial Time : Thu Oct 27 00:00:00 IST 2016
New Time : Mon Jun 12 00:00:00 IST 1916
2. get2DigitYearStart() : java.text.SimpleDateFormat.get2DigitYearStart() returns start of 100 year period that was set during parsing.
Syntax :
public void get2DigitYearStart()
Parameters :
-----
Return :
Returns start of 100 year period that was set during parsing.
Implementation :
Java
// Java Program illustrating// use of get2DigitYearStart() method import java.text.*;import java.util.Calendar; public class NewClass{ public static void main(String[] args) throws InterruptedException { SimpleDateFormat geek = new SimpleDateFormat("MM / dd / yy"); try { Calendar c = Calendar.getInstance(); c.setTime(geek.parse("10 / 27 / 16")); System.out.println("Initial Time : "+c.getTime()); // Setting 1916 instead of 2016 // Use of set2DigitYearStart() method geek.set2DigitYearStart(geek.parse("01 / 01 / 1900")); // Start Year is 1990. c.setTime(geek.parse("06 / 12 / 16")); System.out.println("New Time : "+c.getTime()); // Use of get2DigitYearStart() method to check start year c.setTime(geek.get2DigitYearStart()); System.out.println("START Year : "+c.get(Calendar.YEAR)); } catch (ParseException except) { except.printStackTrace(); } }}
Output :
Initial Time : Thu Oct 27 00:00:00 IST 2016
New Time : Mon Jun 12 00:00:00 IST 1916
START Year : 1900
3. toPattern() : java.text.SimpleDateFormat.toPattern() returns pattern of the Date format.
Syntax :
public String toPattern()
Parameters :
-----
Return :
Returns pattern of the Date format.
Java
// Java Program illustrating use of toPattern() method import java.text.*;import java.util.Calendar; public class NewClass{ public static void main(String[] args) throws InterruptedException { SimpleDateFormat geek = new SimpleDateFormat(); // Initializing Calendar object Calendar c = Calendar.getInstance(); // getting Current Date String dateToday = geek.format(c.getTime()); System.out.println("Current Date : "+dateToday); // Use of toPattern() method // Printing Date Pattern System.out.println("Date Pattern : "+geek.toPattern()); }}
Output :
Current Date : 6/21/17 6:24 PM
Date Pattern : M/d/yy h:mm a
4. parse() : java.text.SimpleDateFormat.parse() parses text from a string to form Date. It is specified by parse in class SimpleDateFormat.
Syntax :
public Date parse()
Parameters :
-----
Return :
Returns Date parsed from a string.
Java
// Java Program illustrating// use of parse() method import java.text.*;import java.util.Calendar; public class NewClass{ public static void main(String[] args) throws InterruptedException { SimpleDateFormat geek = new SimpleDateFormat("MM / dd / yy"); try { Calendar c = Calendar.getInstance(); // Use of .parse() method to parse Date From String 's' String s = "10 / 27 / 16" ; c.setTime(geek.parse(s)); System.out.println("Time parsed from String : "+c.getTime()); } catch (ParseException except) { except.printStackTrace(); } }}
Output :
Time parsed from String : Thu Oct 27 00:00:00 IST 2016
5. applyPattern() : java.text.SimpleDateFormat.applyPattern(String arg) is used to set a defined pattern to the Date Format.
Syntax :
public void applyPattern(String arg)
Parameters :
arg : defined pattern to be set to the Date Format.
Return :
Void
Implementation :
Java
// Java Program illustrating// use of applyPattern() method import java.text.*;import java.util.Calendar;public class NewClass{ public static void main(String[] args) throws InterruptedException { SimpleDateFormat geek = new SimpleDateFormat(); // Initializing calendar Object Calendar c = Calendar.getInstance(); // Using 'arg' pattern String arg = "dd / MM / yyyy HH:mm Z"; // Use of applyPattern() method to set date to 'arg' format geek.applyPattern(arg); // current date and time String currentdate = geek.format(c.getTime()); System.out.println("Current Date : "+currentdate); // Print the pattern being used System.out.println("Pattern applied : "+geek.toPattern()); }}
Output :
Current Date : 21 / 06 / 2017 18:25 +0530
Pattern applied : dd / MM / yyyy HH:mm Z
6. format() : java.text.SimpleDateFormat.format(Date arg) changes Date or Time to string.
Syntax :
public final String format(Date arg)
Parameters :
arg : Date to be formatted to String
Return :
Formatted String of Date
Java
// Java Program illustrating// use of format() method import java.text.*;import java.util.Calendar; public class NewClass{ public static void main(String[] args) throws InterruptedException { SimpleDateFormat geek = new SimpleDateFormat(); // Initializing calendar Object Calendar c = Calendar.getInstance(); System.out.println("Actual Date : "+c.getTime()); // Use of format() method to format Date to String String currentdate = geek.format(c.getTime()); System.out.println("Formatted Date to String : "+currentdate); }}
Output :
Actual Date : Wed Jun 21 18:25:50 IST 2017
Formatted Date to String : 6/21/17 6:25 PM
7. toLocalizedPattern() : java.text.SimpleDateFormat.toLocalizedPattern() returns Date pattern String of the Date Formatter.
Syntax :
public String toLocalizedPattern()
Parameters :
------
Return :
Date pattern String used in the formatter
Java
// Java Program illustrating// use of toLocalizedPattern() method import java.text.*;import java.util.Calendar; public class NewClass{ public static void main(String[] args) throws InterruptedException { // Date Formatter SimpleDateFormat geek = new SimpleDateFormat(); // Initializing calendar Object Calendar c = Calendar.getInstance(); System.out.println("Date : " + geek.format(c.getTime())); // Use of format() method to format Date to String System.out.println("Pattern in DateFormater 'geek' :" + geek.toLocalizedPattern()); }}
Output :
Date : 6/21/17 6:27 PM
Pattern in DateFormater 'geek' : M/d/yy h:mm a
Next: Java.text.SimpleDateFormat class | Set 2
This article is contributed by Mohit Gupta_OMG . 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.
anikakapoor
akshaysingh98088
simranarora5sos
varshagumber28
Java-Date-Time
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Queue Interface In Java
Object Oriented Programming (OOPs) Concept in Java
Stack Class in Java
Interfaces in Java
ArrayList in Java
HashMap in Java with Examples
Collections in Java
ChronoZonedDateTime isAfter() method in Java with Examples
Multidimensional Arrays in Java
Introduction to Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 248,
"s": 28,
"text": "SimpleDateFormat class helps in formatting and parsing of data. We can change date from one format to other. It allows to user to interpret string date format into a Date object. We can modify Date accordingly, we want."
},
{
"code": null,
"e": 263,
"s": 248,
"text": "Declaration : "
},
{
"code": null,
"e": 312,
"s": 263,
"text": "public class SimpleDateFormat\nextends DateFormat"
},
{
"code": null,
"e": 329,
"s": 312,
"text": "Constructors : "
},
{
"code": null,
"e": 498,
"s": 329,
"text": "SimpleDateFormat(String pattern_arg) : Constructs a Simple Date Format using the given pattern – pattern_arg, default date format symbols for the default FORMAT locale."
},
{
"code": null,
"e": 697,
"s": 498,
"text": "SimpleDateFormat(String pattern_arg, Locale locale_arg) : Constructs a Simple Date Format using the given pattern – pattern_arg, default date format symbols for the given FORMAT Locale – locale_arg."
},
{
"code": null,
"e": 862,
"s": 697,
"text": "SimpleDateFormat(String pattern_arg, DateFormatSymbols formatSymbols) : Constructs a SimpleDateFormat using the given pattern – pattern_arg and date format symbols."
},
{
"code": null,
"e": 913,
"s": 862,
"text": "Java Program illustrating SimpleDateFormat class "
},
{
"code": null,
"e": 918,
"s": 913,
"text": "Java"
},
{
"code": "// Java Program illustrating SimpleDateFormat classimport java.text.*;import java.util.*; public class NewClass{ public static void main(String[] args) { SimpleDateFormat geek = new SimpleDateFormat(\"dd / MM / yy\"); // Creating instance of the System date Calendar c = Calendar.getInstance(); System.out.println(\"Present Date : \" + c.getTime()); // Formatting Date according \"dd / MM / yy\" String formattedDate = geek.format(c.getTime()); System.out.println(\"Date formatted : \"+formattedDate); }}",
"e": 1476,
"s": 918,
"text": null
},
{
"code": null,
"e": 1485,
"s": 1476,
"text": "Output: "
},
{
"code": null,
"e": 1559,
"s": 1485,
"text": "Present Date : Wed Jun 21 18:21:13 IST 2017\nDate formatted : 21 / 06 / 17"
},
{
"code": null,
"e": 1571,
"s": 1559,
"text": "Methods : "
},
{
"code": null,
"e": 1754,
"s": 1571,
"text": "1. set2DigitYearStart() : java.text.SimpleDateFormat.set2DigitYearStart(Date starting_Date) parses the date and set the date in the range starting_Date to starting_Date + 100 years. "
},
{
"code": null,
"e": 1763,
"s": 1754,
"text": "Syntax :"
},
{
"code": null,
"e": 1936,
"s": 1763,
"text": "public void set2DigitYearStart(Date starting_Date)\nParameters :\nstarting_Date : Date is set in the range - starting_Date to starting_Date + 100 years\nReturn :\nReturns void"
},
{
"code": null,
"e": 1941,
"s": 1936,
"text": "Java"
},
{
"code": "// Java Program illustrating// use of set2DigitYearStart() method import java.text.*;import java.util.Calendar; public class NewClass{ public static void main(String[] args) throws InterruptedException { SimpleDateFormat geek = new SimpleDateFormat(\"MM / dd / yy\"); try { Calendar c = Calendar.getInstance(); c.setTime(geek.parse(\"10 / 27 / 16\")); System.out.println(\"Initial Time : \"+c.getTime()); // Setting 1916 instead of 2016 // Use of set2DigitYearStart() method geek.set2DigitYearStart(geek.parse(\"01 / 01 / 1900\")); c.setTime(geek.parse(\"06 / 12 / 16\")); System.out.println(\"New Time : \"+c.getTime()); } catch (ParseException except) { except.printStackTrace(); } }}",
"e": 2776,
"s": 1941,
"text": null
},
{
"code": null,
"e": 2786,
"s": 2776,
"text": "Output : "
},
{
"code": null,
"e": 2870,
"s": 2786,
"text": "Initial Time : Thu Oct 27 00:00:00 IST 2016\nNew Time : Mon Jun 12 00:00:00 IST 1916"
},
{
"code": null,
"e": 3007,
"s": 2870,
"text": "2. get2DigitYearStart() : java.text.SimpleDateFormat.get2DigitYearStart() returns start of 100 year period that was set during parsing. "
},
{
"code": null,
"e": 3016,
"s": 3007,
"text": "Syntax :"
},
{
"code": null,
"e": 3140,
"s": 3016,
"text": "public void get2DigitYearStart()\nParameters :\n-----\nReturn :\nReturns start of 100 year period that was set during parsing."
},
{
"code": null,
"e": 3158,
"s": 3140,
"text": "Implementation : "
},
{
"code": null,
"e": 3163,
"s": 3158,
"text": "Java"
},
{
"code": "// Java Program illustrating// use of get2DigitYearStart() method import java.text.*;import java.util.Calendar; public class NewClass{ public static void main(String[] args) throws InterruptedException { SimpleDateFormat geek = new SimpleDateFormat(\"MM / dd / yy\"); try { Calendar c = Calendar.getInstance(); c.setTime(geek.parse(\"10 / 27 / 16\")); System.out.println(\"Initial Time : \"+c.getTime()); // Setting 1916 instead of 2016 // Use of set2DigitYearStart() method geek.set2DigitYearStart(geek.parse(\"01 / 01 / 1900\")); // Start Year is 1990. c.setTime(geek.parse(\"06 / 12 / 16\")); System.out.println(\"New Time : \"+c.getTime()); // Use of get2DigitYearStart() method to check start year c.setTime(geek.get2DigitYearStart()); System.out.println(\"START Year : \"+c.get(Calendar.YEAR)); } catch (ParseException except) { except.printStackTrace(); } }}",
"e": 4266,
"s": 3163,
"text": null
},
{
"code": null,
"e": 4276,
"s": 4266,
"text": "Output : "
},
{
"code": null,
"e": 4378,
"s": 4276,
"text": "Initial Time : Thu Oct 27 00:00:00 IST 2016\nNew Time : Mon Jun 12 00:00:00 IST 1916\nSTART Year : 1900"
},
{
"code": null,
"e": 4471,
"s": 4378,
"text": "3. toPattern() : java.text.SimpleDateFormat.toPattern() returns pattern of the Date format. "
},
{
"code": null,
"e": 4480,
"s": 4471,
"text": "Syntax :"
},
{
"code": null,
"e": 4571,
"s": 4480,
"text": "public String toPattern()\nParameters :\n-----\nReturn :\nReturns pattern of the Date format."
},
{
"code": null,
"e": 4576,
"s": 4571,
"text": "Java"
},
{
"code": "// Java Program illustrating use of toPattern() method import java.text.*;import java.util.Calendar; public class NewClass{ public static void main(String[] args) throws InterruptedException { SimpleDateFormat geek = new SimpleDateFormat(); // Initializing Calendar object Calendar c = Calendar.getInstance(); // getting Current Date String dateToday = geek.format(c.getTime()); System.out.println(\"Current Date : \"+dateToday); // Use of toPattern() method // Printing Date Pattern System.out.println(\"Date Pattern : \"+geek.toPattern()); }}",
"e": 5194,
"s": 4576,
"text": null
},
{
"code": null,
"e": 5204,
"s": 5194,
"text": "Output : "
},
{
"code": null,
"e": 5264,
"s": 5204,
"text": "Current Date : 6/21/17 6:24 PM\nDate Pattern : M/d/yy h:mm a"
},
{
"code": null,
"e": 5405,
"s": 5264,
"text": "4. parse() : java.text.SimpleDateFormat.parse() parses text from a string to form Date. It is specified by parse in class SimpleDateFormat. "
},
{
"code": null,
"e": 5414,
"s": 5405,
"text": "Syntax :"
},
{
"code": null,
"e": 5498,
"s": 5414,
"text": "public Date parse()\nParameters :\n-----\nReturn :\nReturns Date parsed from a string."
},
{
"code": null,
"e": 5503,
"s": 5498,
"text": "Java"
},
{
"code": "// Java Program illustrating// use of parse() method import java.text.*;import java.util.Calendar; public class NewClass{ public static void main(String[] args) throws InterruptedException { SimpleDateFormat geek = new SimpleDateFormat(\"MM / dd / yy\"); try { Calendar c = Calendar.getInstance(); // Use of .parse() method to parse Date From String 's' String s = \"10 / 27 / 16\" ; c.setTime(geek.parse(s)); System.out.println(\"Time parsed from String : \"+c.getTime()); } catch (ParseException except) { except.printStackTrace(); } }}",
"e": 6174,
"s": 5503,
"text": null
},
{
"code": null,
"e": 6184,
"s": 6174,
"text": "Output : "
},
{
"code": null,
"e": 6239,
"s": 6184,
"text": "Time parsed from String : Thu Oct 27 00:00:00 IST 2016"
},
{
"code": null,
"e": 6365,
"s": 6239,
"text": "5. applyPattern() : java.text.SimpleDateFormat.applyPattern(String arg) is used to set a defined pattern to the Date Format. "
},
{
"code": null,
"e": 6374,
"s": 6365,
"text": "Syntax :"
},
{
"code": null,
"e": 6491,
"s": 6374,
"text": "public void applyPattern(String arg)\nParameters :\narg : defined pattern to be set to the Date Format.\nReturn :\nVoid"
},
{
"code": null,
"e": 6509,
"s": 6491,
"text": "Implementation : "
},
{
"code": null,
"e": 6514,
"s": 6509,
"text": "Java"
},
{
"code": "// Java Program illustrating// use of applyPattern() method import java.text.*;import java.util.Calendar;public class NewClass{ public static void main(String[] args) throws InterruptedException { SimpleDateFormat geek = new SimpleDateFormat(); // Initializing calendar Object Calendar c = Calendar.getInstance(); // Using 'arg' pattern String arg = \"dd / MM / yyyy HH:mm Z\"; // Use of applyPattern() method to set date to 'arg' format geek.applyPattern(arg); // current date and time String currentdate = geek.format(c.getTime()); System.out.println(\"Current Date : \"+currentdate); // Print the pattern being used System.out.println(\"Pattern applied : \"+geek.toPattern()); }}",
"e": 7289,
"s": 6514,
"text": null
},
{
"code": null,
"e": 7299,
"s": 7289,
"text": "Output : "
},
{
"code": null,
"e": 7382,
"s": 7299,
"text": "Current Date : 21 / 06 / 2017 18:25 +0530\nPattern applied : dd / MM / yyyy HH:mm Z"
},
{
"code": null,
"e": 7472,
"s": 7382,
"text": "6. format() : java.text.SimpleDateFormat.format(Date arg) changes Date or Time to string."
},
{
"code": null,
"e": 7482,
"s": 7472,
"text": " Syntax :"
},
{
"code": null,
"e": 7604,
"s": 7482,
"text": "public final String format(Date arg)\nParameters :\narg : Date to be formatted to String\nReturn :\nFormatted String of Date"
},
{
"code": null,
"e": 7609,
"s": 7604,
"text": "Java"
},
{
"code": "// Java Program illustrating// use of format() method import java.text.*;import java.util.Calendar; public class NewClass{ public static void main(String[] args) throws InterruptedException { SimpleDateFormat geek = new SimpleDateFormat(); // Initializing calendar Object Calendar c = Calendar.getInstance(); System.out.println(\"Actual Date : \"+c.getTime()); // Use of format() method to format Date to String String currentdate = geek.format(c.getTime()); System.out.println(\"Formatted Date to String : \"+currentdate); }}",
"e": 8202,
"s": 7609,
"text": null
},
{
"code": null,
"e": 8212,
"s": 8202,
"text": "Output : "
},
{
"code": null,
"e": 8298,
"s": 8212,
"text": "Actual Date : Wed Jun 21 18:25:50 IST 2017\nFormatted Date to String : 6/21/17 6:25 PM"
},
{
"code": null,
"e": 8424,
"s": 8298,
"text": "7. toLocalizedPattern() : java.text.SimpleDateFormat.toLocalizedPattern() returns Date pattern String of the Date Formatter. "
},
{
"code": null,
"e": 8433,
"s": 8424,
"text": "Syntax :"
},
{
"code": null,
"e": 8540,
"s": 8433,
"text": "public String toLocalizedPattern()\nParameters :\n------\nReturn :\nDate pattern String used in the formatter"
},
{
"code": null,
"e": 8545,
"s": 8540,
"text": "Java"
},
{
"code": "// Java Program illustrating// use of toLocalizedPattern() method import java.text.*;import java.util.Calendar; public class NewClass{ public static void main(String[] args) throws InterruptedException { // Date Formatter SimpleDateFormat geek = new SimpleDateFormat(); // Initializing calendar Object Calendar c = Calendar.getInstance(); System.out.println(\"Date : \" + geek.format(c.getTime())); // Use of format() method to format Date to String System.out.println(\"Pattern in DateFormater 'geek' :\" + geek.toLocalizedPattern()); }}",
"e": 9178,
"s": 8545,
"text": null
},
{
"code": null,
"e": 9188,
"s": 9178,
"text": "Output : "
},
{
"code": null,
"e": 9258,
"s": 9188,
"text": "Date : 6/21/17 6:27 PM\nPattern in DateFormater 'geek' : M/d/yy h:mm a"
},
{
"code": null,
"e": 9306,
"s": 9258,
"text": "Next: Java.text.SimpleDateFormat class | Set 2 "
},
{
"code": null,
"e": 9731,
"s": 9306,
"text": "This article is contributed by Mohit Gupta_OMG . 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": 9743,
"s": 9731,
"text": "anikakapoor"
},
{
"code": null,
"e": 9760,
"s": 9743,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 9776,
"s": 9760,
"text": "simranarora5sos"
},
{
"code": null,
"e": 9791,
"s": 9776,
"text": "varshagumber28"
},
{
"code": null,
"e": 9806,
"s": 9791,
"text": "Java-Date-Time"
},
{
"code": null,
"e": 9824,
"s": 9806,
"text": "Java-lang package"
},
{
"code": null,
"e": 9829,
"s": 9824,
"text": "Java"
},
{
"code": null,
"e": 9834,
"s": 9829,
"text": "Java"
},
{
"code": null,
"e": 9932,
"s": 9834,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9956,
"s": 9932,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 10007,
"s": 9956,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 10027,
"s": 10007,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 10046,
"s": 10027,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 10064,
"s": 10046,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 10094,
"s": 10064,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 10114,
"s": 10094,
"text": "Collections in Java"
},
{
"code": null,
"e": 10173,
"s": 10114,
"text": "ChronoZonedDateTime isAfter() method in Java with Examples"
},
{
"code": null,
"e": 10205,
"s": 10173,
"text": "Multidimensional Arrays in Java"
}
] |
How to Fix java.util.NoSuchElementException in Java?
|
03 Mar, 2022
An unexpected, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exceptions are caused by our program and these are recoverable. Suppose if our program requirement is to read data from the remote file locating in the U.S.A. At runtime, if a remote file is not available then we will get RuntimeException saying fileNotFoundException. If fileNotFoundException occurs we can provide the local file to the program to read and continue the rest of the program normally.
There are mainly two types of exception in java as follows:
1. Checked Exception: The exception which is checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exceptions then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get the compile-time error. Examples of checked exceptions are ClassNotFoundException, IOException, SQLException, etc.
2. Unchecked Exception: The exceptions which are not checked by the compiler, whether programmer handling or not such type of exception are called an unchecked exception. Examples of unchecked Exceptions are ArithmeticException, ArrayStoreException, etc.
Whether the exception is checked or unchecked every exception occurs at run time only if there is no chance of occurring any exception at compile time.
NoSuchElementException:
It is the child class of RuntimeException and hence it is an unchecked exception. This exception is rise automatically by JVM and given by the accessors methods of Enumeration, Iterator or Tokenizer such as next() or nextElement() or nextToken() when we are trying to access the content of an array, collection, or any other object and if these objects are empty or if we are trying to get next element after reaching the end of an object then we will get java.util.NoSuchElementException.
In the below example we are trying to access a HashMap by using the accessor method next() of the Iterator class but as the HashMap is empty we will be going to get NoSuchElementException.
Example 1:
Java
// Java program to demonstrate the occurrence of// NoSuchElementException // import required packagesimport java.io.*;import java.lang.*;import java.util.*; // driver classclass Geek { // main method public static void main(String[] args) { // creating an hashmap object HashMap<Integer, Integer> map = new HashMap<>(); // creating an iterator Iterator itr = map.keySet().iterator(); // trying to access the element itr.next(); }}
Example 2: Here we are trying to access the element of an empty vector object through an enumerator.
Java
// Java program to demonstrate the occurrence of// NoSuchElementException // import required packages import java.io.*;import java.lang.*;import java.util.*; // driver classclass Geek { // main method public static void main(String[] args) { // creating an vector object Vector<Integer> v = new Vector<>(); // creating an enumerator Enumeration enumerator = v.elements(); // trying to access the element enumerator.nextElement(); }}
How to solve this error?
Almost all the classes whose accessor methods give NoSuchElementException contains their respective method to check whether the object contains more elements or not. So in order to avoid this NoSuchElementException we need to always call,
Iterator.hasNext() or
Enumeration.hasMoreElements() or
hasMoreToken() method before calling next( ) or nextElement or nextToken() method.
Below is the implementation of the above statement :
Example 1:
Java
// Java program to remove the occurrence of// NoSuchElementException by using hasNext() // import required packagesimport java.io.*;import java.lang.*;import java.util.*; // driver classclass Geek { // main method public static void main(String[] args) { // creating an hashmap object HashMap<Integer, Integer> map = new HashMap<>(); // creating an iterator Iterator itr = map.keySet().iterator(); // checking the map object using .hasNext() // method if it has elements to access // or not before accessing the map using // .next() method while (itr.hasNext()) System.out.println(itr.next()); }}
Output:
Example 2:
Java
// Java program to remove the occurrence of// NoSuchElementException by using hasMoreElements() // import required packagesimport java.io.*;import java.lang.*;import java.util.*; // driver classclass Geek { // main method public static void main(String[] args) { // creating an vector object Vector<Integer> v = new Vector<>(); // creating an enumerator Enumeration enumerator = v.elements(); // Checking the vector object using // hasMorelements method if it has elements // to access or not before accessing the vector // using .nextElement() method while (enumerator.hasMoreElements()) System.out.println(enumerator.nextElement()); }}
Output:
arorakashish0911
avtarkumar719
Java-Exceptions
Picked
Technical Scripter 2020
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Mar, 2022"
},
{
"code": null,
"e": 541,
"s": 28,
"text": "An unexpected, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exceptions are caused by our program and these are recoverable. Suppose if our program requirement is to read data from the remote file locating in the U.S.A. At runtime, if a remote file is not available then we will get RuntimeException saying fileNotFoundException. If fileNotFoundException occurs we can provide the local file to the program to read and continue the rest of the program normally."
},
{
"code": null,
"e": 601,
"s": 541,
"text": "There are mainly two types of exception in java as follows:"
},
{
"code": null,
"e": 1051,
"s": 601,
"text": "1. Checked Exception: The exception which is checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exceptions then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get the compile-time error. Examples of checked exceptions are ClassNotFoundException, IOException, SQLException, etc."
},
{
"code": null,
"e": 1306,
"s": 1051,
"text": "2. Unchecked Exception: The exceptions which are not checked by the compiler, whether programmer handling or not such type of exception are called an unchecked exception. Examples of unchecked Exceptions are ArithmeticException, ArrayStoreException, etc."
},
{
"code": null,
"e": 1458,
"s": 1306,
"text": "Whether the exception is checked or unchecked every exception occurs at run time only if there is no chance of occurring any exception at compile time."
},
{
"code": null,
"e": 1482,
"s": 1458,
"text": "NoSuchElementException:"
},
{
"code": null,
"e": 1972,
"s": 1482,
"text": "It is the child class of RuntimeException and hence it is an unchecked exception. This exception is rise automatically by JVM and given by the accessors methods of Enumeration, Iterator or Tokenizer such as next() or nextElement() or nextToken() when we are trying to access the content of an array, collection, or any other object and if these objects are empty or if we are trying to get next element after reaching the end of an object then we will get java.util.NoSuchElementException."
},
{
"code": null,
"e": 2161,
"s": 1972,
"text": "In the below example we are trying to access a HashMap by using the accessor method next() of the Iterator class but as the HashMap is empty we will be going to get NoSuchElementException."
},
{
"code": null,
"e": 2172,
"s": 2161,
"text": "Example 1:"
},
{
"code": null,
"e": 2177,
"s": 2172,
"text": "Java"
},
{
"code": "// Java program to demonstrate the occurrence of// NoSuchElementException // import required packagesimport java.io.*;import java.lang.*;import java.util.*; // driver classclass Geek { // main method public static void main(String[] args) { // creating an hashmap object HashMap<Integer, Integer> map = new HashMap<>(); // creating an iterator Iterator itr = map.keySet().iterator(); // trying to access the element itr.next(); }}",
"e": 2679,
"s": 2177,
"text": null
},
{
"code": null,
"e": 2785,
"s": 2684,
"text": "Example 2: Here we are trying to access the element of an empty vector object through an enumerator."
},
{
"code": null,
"e": 2792,
"s": 2787,
"text": "Java"
},
{
"code": "// Java program to demonstrate the occurrence of// NoSuchElementException // import required packages import java.io.*;import java.lang.*;import java.util.*; // driver classclass Geek { // main method public static void main(String[] args) { // creating an vector object Vector<Integer> v = new Vector<>(); // creating an enumerator Enumeration enumerator = v.elements(); // trying to access the element enumerator.nextElement(); }}",
"e": 3296,
"s": 2792,
"text": null
},
{
"code": null,
"e": 3326,
"s": 3301,
"text": "How to solve this error?"
},
{
"code": null,
"e": 3567,
"s": 3328,
"text": "Almost all the classes whose accessor methods give NoSuchElementException contains their respective method to check whether the object contains more elements or not. So in order to avoid this NoSuchElementException we need to always call,"
},
{
"code": null,
"e": 3591,
"s": 3569,
"text": "Iterator.hasNext() or"
},
{
"code": null,
"e": 3624,
"s": 3591,
"text": "Enumeration.hasMoreElements() or"
},
{
"code": null,
"e": 3707,
"s": 3624,
"text": "hasMoreToken() method before calling next( ) or nextElement or nextToken() method."
},
{
"code": null,
"e": 3762,
"s": 3709,
"text": "Below is the implementation of the above statement :"
},
{
"code": null,
"e": 3775,
"s": 3764,
"text": "Example 1:"
},
{
"code": null,
"e": 3782,
"s": 3777,
"text": "Java"
},
{
"code": "// Java program to remove the occurrence of// NoSuchElementException by using hasNext() // import required packagesimport java.io.*;import java.lang.*;import java.util.*; // driver classclass Geek { // main method public static void main(String[] args) { // creating an hashmap object HashMap<Integer, Integer> map = new HashMap<>(); // creating an iterator Iterator itr = map.keySet().iterator(); // checking the map object using .hasNext() // method if it has elements to access // or not before accessing the map using // .next() method while (itr.hasNext()) System.out.println(itr.next()); }}",
"e": 4482,
"s": 3782,
"text": null
},
{
"code": null,
"e": 4490,
"s": 4482,
"text": "Output:"
},
{
"code": null,
"e": 4502,
"s": 4490,
"text": " Example 2:"
},
{
"code": null,
"e": 4507,
"s": 4502,
"text": "Java"
},
{
"code": "// Java program to remove the occurrence of// NoSuchElementException by using hasMoreElements() // import required packagesimport java.io.*;import java.lang.*;import java.util.*; // driver classclass Geek { // main method public static void main(String[] args) { // creating an vector object Vector<Integer> v = new Vector<>(); // creating an enumerator Enumeration enumerator = v.elements(); // Checking the vector object using // hasMorelements method if it has elements // to access or not before accessing the vector // using .nextElement() method while (enumerator.hasMoreElements()) System.out.println(enumerator.nextElement()); }}",
"e": 5248,
"s": 4507,
"text": null
},
{
"code": null,
"e": 5256,
"s": 5248,
"text": "Output:"
},
{
"code": null,
"e": 5273,
"s": 5256,
"text": "arorakashish0911"
},
{
"code": null,
"e": 5287,
"s": 5273,
"text": "avtarkumar719"
},
{
"code": null,
"e": 5303,
"s": 5287,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 5310,
"s": 5303,
"text": "Picked"
},
{
"code": null,
"e": 5334,
"s": 5310,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 5339,
"s": 5334,
"text": "Java"
},
{
"code": null,
"e": 5358,
"s": 5339,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5363,
"s": 5358,
"text": "Java"
},
{
"code": null,
"e": 5461,
"s": 5363,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5512,
"s": 5461,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 5543,
"s": 5512,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 5562,
"s": 5543,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 5592,
"s": 5562,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 5607,
"s": 5592,
"text": "Stream In Java"
},
{
"code": null,
"e": 5625,
"s": 5607,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 5645,
"s": 5625,
"text": "Collections in Java"
},
{
"code": null,
"e": 5669,
"s": 5645,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 5701,
"s": 5669,
"text": "Multidimensional Arrays in Java"
}
] |
How to create tabs containing different content in HTML ?
|
06 Aug, 2021
Tabs are used to navigate and display different content around the website. We use tabs to manage space and to make the website more attractive.
Approach:
In the body tag create some tabs under the div tag with a Custom-Data-Attribute that holds the id of the content.
Create another div tag to store the content of the tab with a specific id.
Specify data attributes for each content tag to display only one tab content at a time.
Using JavaScript we can display the content of the tag using its id.
In this article, we have created three tabs Tab-1, Tab-2 and Tab-3. When we click on any specific tab it will display the content of that tab.
Note: For CSS, refer to code under the style tag and for JavaScript refer to code under the script tag.
Example: In this example, we will create tabs containing different content.
HTML
<!DOCTYPE html><html lang="en"> <head> <style> body { background: rgb(140, 214, 30); } [data-tab-info] { display: none; } .active[data-tab-info] { display: block; } .tab-content { font-size: 30px; font-family: sans-serif; font-weight: bold; color: rgb(82, 75, 75); } .tabs { font-size: 40px; color: rgb(255, 255, 255); display: flex; margin: 0; } .tabs span { background: rgb(28, 145, 38); padding: 10px; border: 1px solid rgb(255, 255, 255); } .tabs span:hover { background: rgb(29, 185, 112); cursor: pointer; color: black; } </style></head> <body> <div class="tabs"> <span data-tab-value="#tab_1">Tab-1</span> <span data-tab-value="#tab_2">Tab-2</span> <span data-tab-value="#tab_3">Tab-3</span> </div> <div class="tab-content"> <div class="tabs__tab active" id="tab_1" data-tab-info> <p>Welcome to GeeksforGeek.</p> </div> <div class="tabs__tab" id="tab_2" data-tab-info> <p>Hello Everyone.</p> </div> <div class="tabs__tab" id="tab_3" data-tab-info> <p>Learn cool stuff.</p> </div> </div> <script type="text/javascript"> const tabs = document.querySelectorAll('[data-tab-value]') const tabInfos = document.querySelectorAll('[data-tab-info]') tabs.forEach(tab => { tab.addEventListener('click', () => { const target = document .querySelector(tab.dataset.tabValue); tabInfos.forEach(tabInfo => { tabInfo.classList.remove('active') }) target.classList.add('active'); }) }) </script></body> </html>
Output:When we click on Tab-1 it is showing the content of Tab-1 same with Tab-2 and Tab-3.
CSS-Properties
CSS-Questions
HTML-Attributes
HTML-Questions
JavaScript-Methods
JavaScript-Questions
Picked
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Aug, 2021"
},
{
"code": null,
"e": 198,
"s": 52,
"text": "Tabs are used to navigate and display different content around the website. We use tabs to manage space and to make the website more attractive. "
},
{
"code": null,
"e": 208,
"s": 198,
"text": "Approach:"
},
{
"code": null,
"e": 324,
"s": 208,
"text": "In the body tag create some tabs under the div tag with a Custom-Data-Attribute that holds the id of the content. "
},
{
"code": null,
"e": 400,
"s": 324,
"text": " Create another div tag to store the content of the tab with a specific id."
},
{
"code": null,
"e": 489,
"s": 400,
"text": " Specify data attributes for each content tag to display only one tab content at a time."
},
{
"code": null,
"e": 558,
"s": 489,
"text": "Using JavaScript we can display the content of the tag using its id."
},
{
"code": null,
"e": 701,
"s": 558,
"text": "In this article, we have created three tabs Tab-1, Tab-2 and Tab-3. When we click on any specific tab it will display the content of that tab."
},
{
"code": null,
"e": 805,
"s": 701,
"text": "Note: For CSS, refer to code under the style tag and for JavaScript refer to code under the script tag."
},
{
"code": null,
"e": 883,
"s": 807,
"text": "Example: In this example, we will create tabs containing different content."
},
{
"code": null,
"e": 888,
"s": 883,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> body { background: rgb(140, 214, 30); } [data-tab-info] { display: none; } .active[data-tab-info] { display: block; } .tab-content { font-size: 30px; font-family: sans-serif; font-weight: bold; color: rgb(82, 75, 75); } .tabs { font-size: 40px; color: rgb(255, 255, 255); display: flex; margin: 0; } .tabs span { background: rgb(28, 145, 38); padding: 10px; border: 1px solid rgb(255, 255, 255); } .tabs span:hover { background: rgb(29, 185, 112); cursor: pointer; color: black; } </style></head> <body> <div class=\"tabs\"> <span data-tab-value=\"#tab_1\">Tab-1</span> <span data-tab-value=\"#tab_2\">Tab-2</span> <span data-tab-value=\"#tab_3\">Tab-3</span> </div> <div class=\"tab-content\"> <div class=\"tabs__tab active\" id=\"tab_1\" data-tab-info> <p>Welcome to GeeksforGeek.</p> </div> <div class=\"tabs__tab\" id=\"tab_2\" data-tab-info> <p>Hello Everyone.</p> </div> <div class=\"tabs__tab\" id=\"tab_3\" data-tab-info> <p>Learn cool stuff.</p> </div> </div> <script type=\"text/javascript\"> const tabs = document.querySelectorAll('[data-tab-value]') const tabInfos = document.querySelectorAll('[data-tab-info]') tabs.forEach(tab => { tab.addEventListener('click', () => { const target = document .querySelector(tab.dataset.tabValue); tabInfos.forEach(tabInfo => { tabInfo.classList.remove('active') }) target.classList.add('active'); }) }) </script></body> </html>",
"e": 2916,
"s": 888,
"text": null
},
{
"code": null,
"e": 3008,
"s": 2916,
"text": "Output:When we click on Tab-1 it is showing the content of Tab-1 same with Tab-2 and Tab-3."
},
{
"code": null,
"e": 3023,
"s": 3008,
"text": "CSS-Properties"
},
{
"code": null,
"e": 3037,
"s": 3023,
"text": "CSS-Questions"
},
{
"code": null,
"e": 3053,
"s": 3037,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 3068,
"s": 3053,
"text": "HTML-Questions"
},
{
"code": null,
"e": 3087,
"s": 3068,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 3108,
"s": 3087,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 3115,
"s": 3108,
"text": "Picked"
},
{
"code": null,
"e": 3119,
"s": 3115,
"text": "CSS"
},
{
"code": null,
"e": 3124,
"s": 3119,
"text": "HTML"
},
{
"code": null,
"e": 3135,
"s": 3124,
"text": "JavaScript"
},
{
"code": null,
"e": 3152,
"s": 3135,
"text": "Web Technologies"
},
{
"code": null,
"e": 3157,
"s": 3152,
"text": "HTML"
},
{
"code": null,
"e": 3255,
"s": 3157,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3294,
"s": 3255,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3333,
"s": 3294,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 3372,
"s": 3333,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 3401,
"s": 3372,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 3438,
"s": 3401,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 3462,
"s": 3438,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3515,
"s": 3462,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 3575,
"s": 3515,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 3636,
"s": 3575,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
How to use a not:first-child selector in CSS?
|
04 Dec, 2018
This selector is used to select every element which is not the first-child of its parent element. It is represented as an argument in the form of :not(first-child) element.
Syntax:
:not( element ) {
// CSS property
}
Example:
<!DOCTYPE html><html> <head> <title>not first child selector</title> <style> h1 { color:green; } div ul:not(:first-child) { background-color: green; color:white; font-style:italic; font-weight:bold; width:60%; margin-left:100px; } h1, h2 { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>not:first-child selector </h2> <div> <ul style="margin-left:100px"> <li>gfg</li> <li>geeks</li> <li>sudo</li> </ul> <ul> <li>Bca</li> <li>Mca</li> <li>B.Tech</li> </ul> </div> </body></html>
OutputExplanation: The above example shows that a <div> is a container Tag. It contains <ul> Tag so it selects all child elements of <div> tag except its first-child.
Supported Browsers: The browser supported by :not:(first-child) selectors are listed below:
Apple Safari 3.1
Google Chrome 4.0
Firefox 3.0
Opera 9.6
Internet Explorer 7.0
CSS-Misc
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 225,
"s": 52,
"text": "This selector is used to select every element which is not the first-child of its parent element. It is represented as an argument in the form of :not(first-child) element."
},
{
"code": null,
"e": 233,
"s": 225,
"text": "Syntax:"
},
{
"code": null,
"e": 273,
"s": 233,
"text": ":not( element ) {\n // CSS property\n} \n"
},
{
"code": null,
"e": 282,
"s": 273,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>not first child selector</title> <style> h1 { color:green; } div ul:not(:first-child) { background-color: green; color:white; font-style:italic; font-weight:bold; width:60%; margin-left:100px; } h1, h2 { text-align:center; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>not:first-child selector </h2> <div> <ul style=\"margin-left:100px\"> <li>gfg</li> <li>geeks</li> <li>sudo</li> </ul> <ul> <li>Bca</li> <li>Mca</li> <li>B.Tech</li> </ul> </div> </body></html> ",
"e": 1182,
"s": 282,
"text": null
},
{
"code": null,
"e": 1349,
"s": 1182,
"text": "OutputExplanation: The above example shows that a <div> is a container Tag. It contains <ul> Tag so it selects all child elements of <div> tag except its first-child."
},
{
"code": null,
"e": 1441,
"s": 1349,
"text": "Supported Browsers: The browser supported by :not:(first-child) selectors are listed below:"
},
{
"code": null,
"e": 1458,
"s": 1441,
"text": "Apple Safari 3.1"
},
{
"code": null,
"e": 1476,
"s": 1458,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 1488,
"s": 1476,
"text": "Firefox 3.0"
},
{
"code": null,
"e": 1498,
"s": 1488,
"text": "Opera 9.6"
},
{
"code": null,
"e": 1520,
"s": 1498,
"text": "Internet Explorer 7.0"
},
{
"code": null,
"e": 1529,
"s": 1520,
"text": "CSS-Misc"
},
{
"code": null,
"e": 1536,
"s": 1529,
"text": "Picked"
},
{
"code": null,
"e": 1540,
"s": 1536,
"text": "CSS"
},
{
"code": null,
"e": 1545,
"s": 1540,
"text": "HTML"
},
{
"code": null,
"e": 1562,
"s": 1545,
"text": "Web Technologies"
},
{
"code": null,
"e": 1567,
"s": 1562,
"text": "HTML"
}
] |
Node.js fs.Dirent.isDirectory() Method
|
19 Jan, 2022
The fs.Dirent.isDirectory() method is an inbuilt application programming interface of class fs.Dirent within File System module which is used to check if the particular dirent describes a Directory or not.
Syntax:
const dirent.isDirectory()
Parameter: This method does not accept any parameter.Return Value: This method returns true if the particular dirent describes Directory otherwise false.
Below programs illustrates the use of fs.dirent.isDirectory() method in Node.js:
Example 1: Filename: index.js
Javascript
// Node.js program to demonstrate the// dirent.isDirectory() methodconst fs = require('fs'); // Initiating async functionasync function stop(path) { // Creating and initiating directory's // underlying resource handle const dir = await fs.promises.opendir(path); // Synchronously reading the directory's // underlying resource handle using // readSync() method for(var i = 0 ; i <= 3 ; i ++ ) { // Checking if the particular dirent // is Directory or not by using // isDirectory() method const value = (dir.readSync()).isDirectory(); // Display the result console.log(dir.readSync()); console.log(value); }} // Catching errorstop('./').catch(console.error);
Run index.js file using the following command:
node index.js
Output:
Dirent { name: 'cert.cer', [Symbol(type)]: 1 }
false
Dirent { name: 'certificate1.cer', [Symbol(type)]: 1 }
false
Dirent { name: 'filename.txt', [Symbol(type)]: 1 }
true
Dirent { name: 'GFG.java', [Symbol(type)]: 1 }
false
Example 2: Filename: index.js
Javascript
// node.js program to demonstrate the// dirent.isDirectory() methodconst fs = require('fs'); // Initiating async functionasync function stop(path) { let dir = null; try { // Creating and initiating directory's // underlying resource handle dir = await fs.promises.opendir( new URL('file:///F:/java/')); // Using readSync() method for(var i = 0 ; i <= 3 ; i ++ ) { // Checking if the particular dirent // is Directory or not by using // isDirectory() method const value = (dir.readSync()).isDirectory(); // Display the result console.log(dir.readSync()); console.log(value); } } finally { if (dir) { // Display the result console.log("dir is closed successfully"); // Synchronously closeSyncing the directory's // underlying resource handle const promise = dir.closeSync(); } }} // Catching errorstop('./').catch(console.error);
Run index.js file using the following command:
node index.js
Output:
Dirent { name: 'cert.cer', [Symbol(type)]: 1 }
false
Dirent { name: 'certificate1.cer', [Symbol(type)]: 1 }
false
Dirent { name: 'features', [Symbol(type)]: 2 }
false
Dirent { name: 'GFG.class', [Symbol(type)]: 1 }
false
dir is closed successfully
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_dirent_isdirectory
kalrap615
sooda367
sweetyty
Node.js-fs-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 234,
"s": 28,
"text": "The fs.Dirent.isDirectory() method is an inbuilt application programming interface of class fs.Dirent within File System module which is used to check if the particular dirent describes a Directory or not."
},
{
"code": null,
"e": 243,
"s": 234,
"text": "Syntax: "
},
{
"code": null,
"e": 270,
"s": 243,
"text": "const dirent.isDirectory()"
},
{
"code": null,
"e": 424,
"s": 270,
"text": "Parameter: This method does not accept any parameter.Return Value: This method returns true if the particular dirent describes Directory otherwise false."
},
{
"code": null,
"e": 505,
"s": 424,
"text": "Below programs illustrates the use of fs.dirent.isDirectory() method in Node.js:"
},
{
"code": null,
"e": 536,
"s": 505,
"text": "Example 1: Filename: index.js "
},
{
"code": null,
"e": 547,
"s": 536,
"text": "Javascript"
},
{
"code": "// Node.js program to demonstrate the// dirent.isDirectory() methodconst fs = require('fs'); // Initiating async functionasync function stop(path) { // Creating and initiating directory's // underlying resource handle const dir = await fs.promises.opendir(path); // Synchronously reading the directory's // underlying resource handle using // readSync() method for(var i = 0 ; i <= 3 ; i ++ ) { // Checking if the particular dirent // is Directory or not by using // isDirectory() method const value = (dir.readSync()).isDirectory(); // Display the result console.log(dir.readSync()); console.log(value); }} // Catching errorstop('./').catch(console.error);",
"e": 1240,
"s": 547,
"text": null
},
{
"code": null,
"e": 1288,
"s": 1240,
"text": "Run index.js file using the following command: "
},
{
"code": null,
"e": 1302,
"s": 1288,
"text": "node index.js"
},
{
"code": null,
"e": 1312,
"s": 1302,
"text": "Output: "
},
{
"code": null,
"e": 1535,
"s": 1312,
"text": "Dirent { name: 'cert.cer', [Symbol(type)]: 1 }\nfalse\nDirent { name: 'certificate1.cer', [Symbol(type)]: 1 }\nfalse\nDirent { name: 'filename.txt', [Symbol(type)]: 1 }\ntrue\nDirent { name: 'GFG.java', [Symbol(type)]: 1 }\nfalse"
},
{
"code": null,
"e": 1566,
"s": 1535,
"text": "Example 2: Filename: index.js "
},
{
"code": null,
"e": 1577,
"s": 1566,
"text": "Javascript"
},
{
"code": "// node.js program to demonstrate the// dirent.isDirectory() methodconst fs = require('fs'); // Initiating async functionasync function stop(path) { let dir = null; try { // Creating and initiating directory's // underlying resource handle dir = await fs.promises.opendir( new URL('file:///F:/java/')); // Using readSync() method for(var i = 0 ; i <= 3 ; i ++ ) { // Checking if the particular dirent // is Directory or not by using // isDirectory() method const value = (dir.readSync()).isDirectory(); // Display the result console.log(dir.readSync()); console.log(value); } } finally { if (dir) { // Display the result console.log(\"dir is closed successfully\"); // Synchronously closeSyncing the directory's // underlying resource handle const promise = dir.closeSync(); } }} // Catching errorstop('./').catch(console.error);",
"e": 2494,
"s": 1577,
"text": null
},
{
"code": null,
"e": 2542,
"s": 2494,
"text": "Run index.js file using the following command: "
},
{
"code": null,
"e": 2556,
"s": 2542,
"text": "node index.js"
},
{
"code": null,
"e": 2566,
"s": 2556,
"text": "Output: "
},
{
"code": null,
"e": 2814,
"s": 2566,
"text": "Dirent { name: 'cert.cer', [Symbol(type)]: 1 }\nfalse\nDirent { name: 'certificate1.cer', [Symbol(type)]: 1 }\nfalse\nDirent { name: 'features', [Symbol(type)]: 2 }\nfalse\nDirent { name: 'GFG.class', [Symbol(type)]: 1 }\nfalse\ndir is closed successfully"
},
{
"code": null,
"e": 2902,
"s": 2814,
"text": "Reference: https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_dirent_isdirectory "
},
{
"code": null,
"e": 2912,
"s": 2902,
"text": "kalrap615"
},
{
"code": null,
"e": 2921,
"s": 2912,
"text": "sooda367"
},
{
"code": null,
"e": 2930,
"s": 2921,
"text": "sweetyty"
},
{
"code": null,
"e": 2948,
"s": 2930,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 2956,
"s": 2948,
"text": "Node.js"
},
{
"code": null,
"e": 2973,
"s": 2956,
"text": "Web Technologies"
}
] |
CSS | page-break-inside Property
|
23 Jan, 2019
The page-break-inside property in CSS is used to specify how the page breaks inside the element to which it is applied while printing. It inserts a page break or sometimes it used to avoid page break inside an element while printing.
Syntax:
page-break-inside: auto|avoid|initial|inherit
Property Values:
auto: It is the default value. This value represents the page break automatically.Syntax:page-break-inside: auto;
Syntax:
page-break-inside: auto;
avoid: It avoids a page break inside the element.Syntax:page-break-inside: avoid;
page-break-inside: avoid;
initial: It sets the page-break-inside property to its default value.Syntax:page-break-inside: initial;
page-break-inside: initial;
inherits: The page-break-inside property is inherited from its parent.Syntax:page-break-inside: inherits;
page-break-inside: inherits;
Note: This property is mostly used to print a document.
Print Media Query:
@media print {
img {
display: block;
page-break-inside: avoid;
}
}
Example 1: This example use page-break-inside property value to avoid.
<!DOCTYPE html><html> <head> <title> CSS page-break-inside property </title> <style type="text/css"> @media print { ul { page-break-inside: avoid; } } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS page-break-inside property</h2> <br><br><br> <img src = "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png" alt = "" /> <br><br><br><br> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> <br><br><br> <img src = "https://media.geeksforgeeks.org/wp-content/uploads/interview-preparation-2.png" alt = "" /> <ul> <li>Data Structure</li> <li>Algorithms</li> <li>C Programming</li> <li>C++ Programming</li> <li>Java Programming</li> <li>Python Programming</li> <li>PHP Programming</li> <li>Operating System</li> <li>Computer Networks</li> <li>DBMS</li> <li>SQL</li> <li>TOC</li> </ul></body> </html>
Output:Print Preview:
Example 2: This example use page-break-inside property value to none.
<!DOCTYPE html><html> <head> <title> CSS page-break-inside property </title> <style type="text/css"> @media print { ul { page-break-inside: none; } } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS page-break-inside property</h2> <br><br><br> <img src = "https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png" alt = "" /> <br><br><br><br> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> <br><br><br> <img src = "https://media.geeksforgeeks.org/wp-content/uploads/interview-preparation-2.png" alt = "" /> <ul> <li>Data Structure</li> <li>Algorithms</li> <li>C Programming</li> <li>C++ Programming</li> <li>Java Programming</li> <li>Python Programming</li> <li>PHP Programming</li> <li>Operating System</li> <li>Computer Networks</li> <li>DBMS</li> <li>SQL</li> <li>TOC</li> </ul></body> </html>
Output:Print Preview:
Supported Browsers: The browser supported by page-break-inside property are listed below:
Google Chrome 1.0
Internet Explorer 8.0
Firefox 19.0
Safari 1.3
Opera 7.0
CSS-Properties
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Jan, 2019"
},
{
"code": null,
"e": 262,
"s": 28,
"text": "The page-break-inside property in CSS is used to specify how the page breaks inside the element to which it is applied while printing. It inserts a page break or sometimes it used to avoid page break inside an element while printing."
},
{
"code": null,
"e": 270,
"s": 262,
"text": "Syntax:"
},
{
"code": null,
"e": 316,
"s": 270,
"text": "page-break-inside: auto|avoid|initial|inherit"
},
{
"code": null,
"e": 333,
"s": 316,
"text": "Property Values:"
},
{
"code": null,
"e": 447,
"s": 333,
"text": "auto: It is the default value. This value represents the page break automatically.Syntax:page-break-inside: auto;"
},
{
"code": null,
"e": 455,
"s": 447,
"text": "Syntax:"
},
{
"code": null,
"e": 480,
"s": 455,
"text": "page-break-inside: auto;"
},
{
"code": null,
"e": 562,
"s": 480,
"text": "avoid: It avoids a page break inside the element.Syntax:page-break-inside: avoid;"
},
{
"code": null,
"e": 588,
"s": 562,
"text": "page-break-inside: avoid;"
},
{
"code": null,
"e": 692,
"s": 588,
"text": "initial: It sets the page-break-inside property to its default value.Syntax:page-break-inside: initial;"
},
{
"code": null,
"e": 720,
"s": 692,
"text": "page-break-inside: initial;"
},
{
"code": null,
"e": 826,
"s": 720,
"text": "inherits: The page-break-inside property is inherited from its parent.Syntax:page-break-inside: inherits;"
},
{
"code": null,
"e": 855,
"s": 826,
"text": "page-break-inside: inherits;"
},
{
"code": null,
"e": 911,
"s": 855,
"text": "Note: This property is mostly used to print a document."
},
{
"code": null,
"e": 930,
"s": 911,
"text": "Print Media Query:"
},
{
"code": null,
"e": 1021,
"s": 930,
"text": "@media print {\n img {\n display: block;\n page-break-inside: avoid;\n }\n}"
},
{
"code": null,
"e": 1092,
"s": 1021,
"text": "Example 1: This example use page-break-inside property value to avoid."
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS page-break-inside property </title> <style type=\"text/css\"> @media print { ul { page-break-inside: avoid; } } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS page-break-inside property</h2> <br><br><br> <img src = \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png\" alt = \"\" /> <br><br><br><br> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> <br><br><br> <img src = \"https://media.geeksforgeeks.org/wp-content/uploads/interview-preparation-2.png\" alt = \"\" /> <ul> <li>Data Structure</li> <li>Algorithms</li> <li>C Programming</li> <li>C++ Programming</li> <li>Java Programming</li> <li>Python Programming</li> <li>PHP Programming</li> <li>Operating System</li> <li>Computer Networks</li> <li>DBMS</li> <li>SQL</li> <li>TOC</li> </ul></body> </html> ",
"e": 2474,
"s": 1092,
"text": null
},
{
"code": null,
"e": 2496,
"s": 2474,
"text": "Output:Print Preview:"
},
{
"code": null,
"e": 2566,
"s": 2496,
"text": "Example 2: This example use page-break-inside property value to none."
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS page-break-inside property </title> <style type=\"text/css\"> @media print { ul { page-break-inside: none; } } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>CSS page-break-inside property</h2> <br><br><br> <img src = \"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png\" alt = \"\" /> <br><br><br><br> <p> Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> <br><br><br> <img src = \"https://media.geeksforgeeks.org/wp-content/uploads/interview-preparation-2.png\" alt = \"\" /> <ul> <li>Data Structure</li> <li>Algorithms</li> <li>C Programming</li> <li>C++ Programming</li> <li>Java Programming</li> <li>Python Programming</li> <li>PHP Programming</li> <li>Operating System</li> <li>Computer Networks</li> <li>DBMS</li> <li>SQL</li> <li>TOC</li> </ul></body> </html> ",
"e": 3947,
"s": 2566,
"text": null
},
{
"code": null,
"e": 3969,
"s": 3947,
"text": "Output:Print Preview:"
},
{
"code": null,
"e": 4059,
"s": 3969,
"text": "Supported Browsers: The browser supported by page-break-inside property are listed below:"
},
{
"code": null,
"e": 4077,
"s": 4059,
"text": "Google Chrome 1.0"
},
{
"code": null,
"e": 4099,
"s": 4077,
"text": "Internet Explorer 8.0"
},
{
"code": null,
"e": 4112,
"s": 4099,
"text": "Firefox 19.0"
},
{
"code": null,
"e": 4123,
"s": 4112,
"text": "Safari 1.3"
},
{
"code": null,
"e": 4133,
"s": 4123,
"text": "Opera 7.0"
},
{
"code": null,
"e": 4148,
"s": 4133,
"text": "CSS-Properties"
},
{
"code": null,
"e": 4155,
"s": 4148,
"text": "Picked"
},
{
"code": null,
"e": 4159,
"s": 4155,
"text": "CSS"
},
{
"code": null,
"e": 4176,
"s": 4159,
"text": "Web Technologies"
},
{
"code": null,
"e": 4274,
"s": 4176,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4322,
"s": 4274,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 4384,
"s": 4322,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4434,
"s": 4384,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 4492,
"s": 4434,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 4542,
"s": 4492,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 4575,
"s": 4542,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4637,
"s": 4575,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4698,
"s": 4637,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4748,
"s": 4698,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Fixed (or static) Partitioning in Operating System in C++
|
In this tutorial, we are going to learn about the fixed partitioning in the operating system.
Fixed partitioning is one to manage the memory in operating system. It's an old technique. It divides the memory into equal blocks. The size of each block is predefined and can not be changed.
The memory is used for the contiguous processes.
Let's see the sample program that allocates memory based on the process size.
Live Demo
#include<iostream>
using namespace std;
int main() {
int blockNumber = 5, processesNumber = 3;
int blockSize[5] = {4, 4, 4, 4, 4}, processSize[3] = {1, 2, 3};
int flags[5], allocation[5];
for(int i = 0; i < 5; i++) {
flags[i] = 0;
allocation[i] = -1;
}
// allocating the blocks to processes
for(int i = 0; i < processesNumber; i++) {
for(int j = 0; j < blockNumber; j++) {
if(flags[j] == 0 && blockSize[j] >= processSize[i]) {
allocation[j] = i;
flags[j] = 1;
break;
}
}
}
for (int i = 0; i < blockNumber; i++) {
if (flags[i] == 1) {
cout << "Process " << processSize[allocation[i]] << " is allocated" << endl;
}
}
return 0;
}
If you execute the above program, then you will get the following result.
Process 1 is allocated
Process 2 is allocated
Process 3 is allocated
If you have any queries in the tutorial, mention them in the comment section.
|
[
{
"code": null,
"e": 1281,
"s": 1187,
"text": "In this tutorial, we are going to learn about the fixed partitioning in the operating system."
},
{
"code": null,
"e": 1474,
"s": 1281,
"text": "Fixed partitioning is one to manage the memory in operating system. It's an old technique. It divides the memory into equal blocks. The size of each block is predefined and can not be changed."
},
{
"code": null,
"e": 1523,
"s": 1474,
"text": "The memory is used for the contiguous processes."
},
{
"code": null,
"e": 1601,
"s": 1523,
"text": "Let's see the sample program that allocates memory based on the process size."
},
{
"code": null,
"e": 1612,
"s": 1601,
"text": " Live Demo"
},
{
"code": null,
"e": 2371,
"s": 1612,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n int blockNumber = 5, processesNumber = 3;\n int blockSize[5] = {4, 4, 4, 4, 4}, processSize[3] = {1, 2, 3};\n int flags[5], allocation[5];\n for(int i = 0; i < 5; i++) {\n flags[i] = 0;\n allocation[i] = -1;\n }\n // allocating the blocks to processes\n for(int i = 0; i < processesNumber; i++) {\n for(int j = 0; j < blockNumber; j++) {\n if(flags[j] == 0 && blockSize[j] >= processSize[i]) {\n allocation[j] = i;\n flags[j] = 1;\n break;\n }\n }\n }\n for (int i = 0; i < blockNumber; i++) {\n if (flags[i] == 1) {\n cout << \"Process \" << processSize[allocation[i]] << \" is allocated\" << endl;\n }\n }\n return 0;\n}"
},
{
"code": null,
"e": 2445,
"s": 2371,
"text": "If you execute the above program, then you will get the following result."
},
{
"code": null,
"e": 2514,
"s": 2445,
"text": "Process 1 is allocated\nProcess 2 is allocated\nProcess 3 is allocated"
},
{
"code": null,
"e": 2592,
"s": 2514,
"text": "If you have any queries in the tutorial, mention them in the comment section."
}
] |
How to create dictionary and add key–value pairs dynamically?
|
28 May, 2020
In this article, we will discuss how we can create a dictionary in JavaScript and add key-value pairs in it. Actually there is no ‘dictionary’ type in JavaScript but we can create key-value pairs by using JavaScript Objects. Create a new JavaScript Object which will act as dictionary.
Syntax: Key can be a string , integer. If you just write key1 or any number, it will treat as a string.
var dict = { key1 : value1 ,
key2 : value2 ,
....
};
Create empty dictionaryvar dict = {};
var dict = {};
Adding Key-Value Pairs in Dictionarydict[new_key] = new_value;orIf new_key is already present in the dictionary then the value of this will be updated to new_value.dict.new_key = new_value;
dict[new_key] = new_value;
orIf new_key is already present in the dictionary then the value of this will be updated to new_value.
dict.new_key = new_value;
Accessing Key-Value Pairsvar value = dict[key];orvar value = dict.key;
var value = dict[key];
or
var value = dict.key;
Iterating the whole dictionaryfor(var key in dict) {
console.log(key + " : " + dict[key]);
}
for(var key in dict) {
console.log(key + " : " + dict[key]);
}
Example:
HTML
<!DOCTYPE html><html> <head> <title>Dictionary in Javascript</title> </head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <p> var dict = { <br /> "geek" : 1 , <br /> "for" : "2", <br /> "geeks" : 3.5 <br /> }; <br /> </p> <button onClick="fun()"> Add new Key-Value Pairs </button> <p id="demo"></p> <!-- Script to create dictionary and add key-value pairs --> <script> function fun() { var dict = { geek: 1, for: "2", geeks: 3.5, }; dict.new_geeks = "new_value"; dict["another_new_geeks"] = "another_value"; var to_show = "var dict = { <br>"; for (var key in dict) { to_show += '"' + key + '" : ' + dict[key] + "<br>"; } to_show += " }; <br>"; document.getElementById("demo") .innerHTML = to_show; } </script> </body></html>
Output:
JavaScript-Misc
Picked
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 340,
"s": 53,
"text": "In this article, we will discuss how we can create a dictionary in JavaScript and add key-value pairs in it. Actually there is no ‘dictionary’ type in JavaScript but we can create key-value pairs by using JavaScript Objects. Create a new JavaScript Object which will act as dictionary."
},
{
"code": null,
"e": 444,
"s": 340,
"text": "Syntax: Key can be a string , integer. If you just write key1 or any number, it will treat as a string."
},
{
"code": null,
"e": 538,
"s": 444,
"text": "var dict = { key1 : value1 , \n key2 : value2 , \n .... \n };\n"
},
{
"code": null,
"e": 576,
"s": 538,
"text": "Create empty dictionaryvar dict = {};"
},
{
"code": null,
"e": 591,
"s": 576,
"text": "var dict = {};"
},
{
"code": null,
"e": 781,
"s": 591,
"text": "Adding Key-Value Pairs in Dictionarydict[new_key] = new_value;orIf new_key is already present in the dictionary then the value of this will be updated to new_value.dict.new_key = new_value;"
},
{
"code": null,
"e": 808,
"s": 781,
"text": "dict[new_key] = new_value;"
},
{
"code": null,
"e": 911,
"s": 808,
"text": "orIf new_key is already present in the dictionary then the value of this will be updated to new_value."
},
{
"code": null,
"e": 937,
"s": 911,
"text": "dict.new_key = new_value;"
},
{
"code": null,
"e": 1008,
"s": 937,
"text": "Accessing Key-Value Pairsvar value = dict[key];orvar value = dict.key;"
},
{
"code": null,
"e": 1031,
"s": 1008,
"text": "var value = dict[key];"
},
{
"code": null,
"e": 1034,
"s": 1031,
"text": "or"
},
{
"code": null,
"e": 1056,
"s": 1034,
"text": "var value = dict.key;"
},
{
"code": null,
"e": 1153,
"s": 1056,
"text": "Iterating the whole dictionaryfor(var key in dict) {\n console.log(key + \" : \" + dict[key]);\n}\n"
},
{
"code": null,
"e": 1220,
"s": 1153,
"text": "for(var key in dict) {\n console.log(key + \" : \" + dict[key]);\n}\n"
},
{
"code": null,
"e": 1229,
"s": 1220,
"text": "Example:"
},
{
"code": null,
"e": 1234,
"s": 1229,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Dictionary in Javascript</title> </head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <p> var dict = { <br /> \"geek\" : 1 , <br /> \"for\" : \"2\", <br /> \"geeks\" : 3.5 <br /> }; <br /> </p> <button onClick=\"fun()\"> Add new Key-Value Pairs </button> <p id=\"demo\"></p> <!-- Script to create dictionary and add key-value pairs --> <script> function fun() { var dict = { geek: 1, for: \"2\", geeks: 3.5, }; dict.new_geeks = \"new_value\"; dict[\"another_new_geeks\"] = \"another_value\"; var to_show = \"var dict = { <br>\"; for (var key in dict) { to_show += '\"' + key + '\" : ' + dict[key] + \"<br>\"; } to_show += \" }; <br>\"; document.getElementById(\"demo\") .innerHTML = to_show; } </script> </body></html> ",
"e": 2502,
"s": 1234,
"text": null
},
{
"code": null,
"e": 2510,
"s": 2502,
"text": "Output:"
},
{
"code": null,
"e": 2526,
"s": 2510,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2533,
"s": 2526,
"text": "Picked"
},
{
"code": null,
"e": 2544,
"s": 2533,
"text": "JavaScript"
}
] |
C# Program to Check all Items of a Float Array is Greater than 5.0 using LINQ
|
06 Dec, 2021
Given a float array, now our task is to check if all the elements present in the float array are greater than 5.0. So we use the All() method of LINQ. This method is used to check if all the elements in the given sequence satisfy the given condition. It will return true if all the elements of the specified sequence pass the test in the given predicate, otherwise, it will return false. So to solve the given problem we use the following query:
result = nums.All(element => element > 5.0F);
Here, the result is a boolean type variable that stores the final result, nums is the array of float, and the All() method contains the condition which checks each element present in the given array satisfy the condition or not. Here if all the elements of the array fulfill the given condition then this statement “nums.All(element => element > 5.0F)” will return true. If any of the elements does not fulfill the given condition then it will return false.
Example:
Input : [6.0, 7.89, 8.9, 89.5, 13.3]
Output : true
Input : [2.0, 1.89, 2.9, 89.5, 13.3]
Output : false
Example 1:
C#
// C# program to check if all the items of a // Float Array is greater than 5.0using System;using System.Linq; class geeks{ static void Main(string[] args){ // Creating a float array float[] nums = { 1.2f, 30.3f, 5.6f, 7.0f, 10.1f }; bool result; // Checking the given array contains all the // elements that are greate than 5.0 result = nums.All(element => element > 5.0F); if (result == true) { Console.Write("Elements in the array are greater than 5"); } else { Console.Write("Elements in the array are not greater than 5"); }}}
Output:
Elements in the array are not greater than 5
Example 2:
C#
// C# program to check if all the items of a // Float Array is greater than 5.0using System;using System.Linq; class geeks{ static void Main(string[] args){ // Creating a float array float[] nums1 = { 1.2f, 30.3f, 3.6f, 7.0f, 10.1f }; float[] nums2 = { 6.2f, 10.3f, 9.6f, 19.0f, 20.1f }; bool result1, result2; // Checking the given array contains all the // elements that are greate than 5.0 result1 = nums1.All(element => element > 5.0F); result2 = nums2.All(element => element > 5.0F); // Displaying the final result Console.WriteLine("Is nums1 contain all the elements " + "greater than 5.0f: " + result1); Console.WriteLine("Is nums2 contain all the elements " + "greater than 5.0f: " + result2);}}
Output:
Is nums1 contain all the elements greater than 5.0f: False
Is nums2 contain all the elements greater than 5.0f: True
CSharp LINQ
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
C# | .NET Framework (Basic Architecture and Component Stack)
Convert String to Character Array in C#
Program to Print a New Line in C#
Socket Programming in C#
Getting a Month Name Using Month Number in C#
Program to find absolute value of a given number
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Dec, 2021"
},
{
"code": null,
"e": 474,
"s": 28,
"text": "Given a float array, now our task is to check if all the elements present in the float array are greater than 5.0. So we use the All() method of LINQ. This method is used to check if all the elements in the given sequence satisfy the given condition. It will return true if all the elements of the specified sequence pass the test in the given predicate, otherwise, it will return false. So to solve the given problem we use the following query:"
},
{
"code": null,
"e": 520,
"s": 474,
"text": "result = nums.All(element => element > 5.0F);"
},
{
"code": null,
"e": 978,
"s": 520,
"text": "Here, the result is a boolean type variable that stores the final result, nums is the array of float, and the All() method contains the condition which checks each element present in the given array satisfy the condition or not. Here if all the elements of the array fulfill the given condition then this statement “nums.All(element => element > 5.0F)” will return true. If any of the elements does not fulfill the given condition then it will return false."
},
{
"code": null,
"e": 988,
"s": 978,
"text": "Example: "
},
{
"code": null,
"e": 1095,
"s": 988,
"text": "Input : [6.0, 7.89, 8.9, 89.5, 13.3]\nOutput : true\n \nInput : [2.0, 1.89, 2.9, 89.5, 13.3]\nOutput : false"
},
{
"code": null,
"e": 1106,
"s": 1095,
"text": "Example 1:"
},
{
"code": null,
"e": 1109,
"s": 1106,
"text": "C#"
},
{
"code": "// C# program to check if all the items of a // Float Array is greater than 5.0using System;using System.Linq; class geeks{ static void Main(string[] args){ // Creating a float array float[] nums = { 1.2f, 30.3f, 5.6f, 7.0f, 10.1f }; bool result; // Checking the given array contains all the // elements that are greate than 5.0 result = nums.All(element => element > 5.0F); if (result == true) { Console.Write(\"Elements in the array are greater than 5\"); } else { Console.Write(\"Elements in the array are not greater than 5\"); }}}",
"e": 1721,
"s": 1109,
"text": null
},
{
"code": null,
"e": 1729,
"s": 1721,
"text": "Output:"
},
{
"code": null,
"e": 1774,
"s": 1729,
"text": "Elements in the array are not greater than 5"
},
{
"code": null,
"e": 1785,
"s": 1774,
"text": "Example 2:"
},
{
"code": null,
"e": 1788,
"s": 1785,
"text": "C#"
},
{
"code": "// C# program to check if all the items of a // Float Array is greater than 5.0using System;using System.Linq; class geeks{ static void Main(string[] args){ // Creating a float array float[] nums1 = { 1.2f, 30.3f, 3.6f, 7.0f, 10.1f }; float[] nums2 = { 6.2f, 10.3f, 9.6f, 19.0f, 20.1f }; bool result1, result2; // Checking the given array contains all the // elements that are greate than 5.0 result1 = nums1.All(element => element > 5.0F); result2 = nums2.All(element => element > 5.0F); // Displaying the final result Console.WriteLine(\"Is nums1 contain all the elements \" + \"greater than 5.0f: \" + result1); Console.WriteLine(\"Is nums2 contain all the elements \" + \"greater than 5.0f: \" + result2);}}",
"e": 2599,
"s": 1788,
"text": null
},
{
"code": null,
"e": 2607,
"s": 2599,
"text": "Output:"
},
{
"code": null,
"e": 2724,
"s": 2607,
"text": "Is nums1 contain all the elements greater than 5.0f: False\nIs nums2 contain all the elements greater than 5.0f: True"
},
{
"code": null,
"e": 2736,
"s": 2724,
"text": "CSharp LINQ"
},
{
"code": null,
"e": 2743,
"s": 2736,
"text": "Picked"
},
{
"code": null,
"e": 2746,
"s": 2743,
"text": "C#"
},
{
"code": null,
"e": 2758,
"s": 2746,
"text": "C# Programs"
},
{
"code": null,
"e": 2856,
"s": 2758,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2899,
"s": 2856,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 2948,
"s": 2899,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 2971,
"s": 2948,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 2987,
"s": 2971,
"text": "C# | List Class"
},
{
"code": null,
"e": 3048,
"s": 2987,
"text": "C# | .NET Framework (Basic Architecture and Component Stack)"
},
{
"code": null,
"e": 3088,
"s": 3048,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 3122,
"s": 3088,
"text": "Program to Print a New Line in C#"
},
{
"code": null,
"e": 3147,
"s": 3122,
"text": "Socket Programming in C#"
},
{
"code": null,
"e": 3193,
"s": 3147,
"text": "Getting a Month Name Using Month Number in C#"
}
] |
groupadd command in Linux with examples
|
28 Feb, 2022
Groups in Linux refer to the user groups. In Linux, there can be many users of a single system, (normal user can take uid from 1000 to 60000, and one root user (uid 0) and 999 system users (uid 1 to 999)). In a scenario where there are many users, there might be some privileges that some users have and some don’t, and it becomes difficult to manage all the permissions at the individual user level. So using groups, we can group together a number of users, and set privileges and permissions for the entire group. groupadd command is used to create a new user group.
Syntax:
groupadd [option] group_name
Example:
sudo groupadd developers
Note:
Every new group created is registered in the file “/etc/group“. To verify that the group has been created, enter the command
sudo tail /etc/group
Output:
Output:
The file shows group information in the following format:
group_name : password : group-id : list-of-members
Options:
-f, –force : This option forces the command to silently abort if the group with given already exists. If this option is used with the -g or –gid option and the group id given already exists, the command forcefully ignores the given group id and creates a new and unique group id.
-g, –gid GID : This option is used to provide a group id (numeric) to the new group, and it should be non-negative and unique unless explicitly created to be non-unique (using -o option). If this option is not used, the default id is assigned, which is greater than every other group already present.
-h, –help : Display help message and exit.
-K, –key KEY=VALUE : Overrides /etc/login.defs defaults (GID_MIN, GID_MAX and others). Multiple -K options can be specified. GID_MIN and GID_MAX are the parameters set in /etc/login.defs which defines the minimum and maximum values that a group id can take. Example:
Example:
groupadd -K GID_MIN=500 -K GID_MAX=700
-o, –non-unique : This option permits to add a group with a non-unique GID.
-p, –password PASSWORD : The encrypted password, as returned by crypt(3). The default is to disable the password. This password is visible to the users. You should make sure the password respects the system’s password policy. The group passwords are stored in “/etc/gshadow” file.
-r, –system : Create a system group. The numeric identifiers of new system groups are chosen in the SYS_GID_MIN-SYS_GID_MAX range, defined in login.defs, instead of GID_MIN and GID_MAX.
-R, –root CHROOT_DIR : Apply changes in the CHROOT_DIR directory and use the configuration files from the CHROOT_DIR directory.
Important Points:
To add a new user into the group, the group is mentioned using -g option in the command useradd.
sudo useradd -g developers new_user
To add an existing user to a group, use the usermod command
usermod -g developers existing_user
KrishnaBirla
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 598,
"s": 28,
"text": "Groups in Linux refer to the user groups. In Linux, there can be many users of a single system, (normal user can take uid from 1000 to 60000, and one root user (uid 0) and 999 system users (uid 1 to 999)). In a scenario where there are many users, there might be some privileges that some users have and some don’t, and it becomes difficult to manage all the permissions at the individual user level. So using groups, we can group together a number of users, and set privileges and permissions for the entire group. groupadd command is used to create a new user group. "
},
{
"code": null,
"e": 608,
"s": 598,
"text": "Syntax: "
},
{
"code": null,
"e": 638,
"s": 608,
"text": "groupadd [option] group_name "
},
{
"code": null,
"e": 649,
"s": 638,
"text": "Example: "
},
{
"code": null,
"e": 675,
"s": 649,
"text": "sudo groupadd developers "
},
{
"code": null,
"e": 682,
"s": 675,
"text": "Note: "
},
{
"code": null,
"e": 811,
"s": 684,
"text": "Every new group created is registered in the file “/etc/group“. To verify that the group has been created, enter the command "
},
{
"code": null,
"e": 834,
"s": 813,
"text": "sudo tail /etc/group"
},
{
"code": null,
"e": 844,
"s": 834,
"text": "Output: "
},
{
"code": null,
"e": 853,
"s": 844,
"text": "Output: "
},
{
"code": null,
"e": 915,
"s": 855,
"text": "The file shows group information in the following format: "
},
{
"code": null,
"e": 968,
"s": 917,
"text": "group_name : password : group-id : list-of-members"
},
{
"code": null,
"e": 978,
"s": 968,
"text": "Options: "
},
{
"code": null,
"e": 1262,
"s": 980,
"text": "-f, –force : This option forces the command to silently abort if the group with given already exists. If this option is used with the -g or –gid option and the group id given already exists, the command forcefully ignores the given group id and creates a new and unique group id. "
},
{
"code": null,
"e": 1565,
"s": 1264,
"text": "-g, –gid GID : This option is used to provide a group id (numeric) to the new group, and it should be non-negative and unique unless explicitly created to be non-unique (using -o option). If this option is not used, the default id is assigned, which is greater than every other group already present."
},
{
"code": null,
"e": 1608,
"s": 1565,
"text": "-h, –help : Display help message and exit."
},
{
"code": null,
"e": 1877,
"s": 1608,
"text": "-K, –key KEY=VALUE : Overrides /etc/login.defs defaults (GID_MIN, GID_MAX and others). Multiple -K options can be specified. GID_MIN and GID_MAX are the parameters set in /etc/login.defs which defines the minimum and maximum values that a group id can take. Example: "
},
{
"code": null,
"e": 1887,
"s": 1877,
"text": "Example: "
},
{
"code": null,
"e": 1929,
"s": 1889,
"text": " groupadd -K GID_MIN=500 -K GID_MAX=700"
},
{
"code": null,
"e": 2009,
"s": 1933,
"text": "-o, –non-unique : This option permits to add a group with a non-unique GID."
},
{
"code": null,
"e": 2290,
"s": 2009,
"text": "-p, –password PASSWORD : The encrypted password, as returned by crypt(3). The default is to disable the password. This password is visible to the users. You should make sure the password respects the system’s password policy. The group passwords are stored in “/etc/gshadow” file."
},
{
"code": null,
"e": 2476,
"s": 2290,
"text": "-r, –system : Create a system group. The numeric identifiers of new system groups are chosen in the SYS_GID_MIN-SYS_GID_MAX range, defined in login.defs, instead of GID_MIN and GID_MAX."
},
{
"code": null,
"e": 2604,
"s": 2476,
"text": "-R, –root CHROOT_DIR : Apply changes in the CHROOT_DIR directory and use the configuration files from the CHROOT_DIR directory."
},
{
"code": null,
"e": 2624,
"s": 2604,
"text": "Important Points: "
},
{
"code": null,
"e": 2723,
"s": 2624,
"text": "To add a new user into the group, the group is mentioned using -g option in the command useradd. "
},
{
"code": null,
"e": 2762,
"s": 2725,
"text": "sudo useradd -g developers new_user "
},
{
"code": null,
"e": 2824,
"s": 2762,
"text": "To add an existing user to a group, use the usermod command "
},
{
"code": null,
"e": 2863,
"s": 2826,
"text": "usermod -g developers existing_user "
},
{
"code": null,
"e": 2882,
"s": 2869,
"text": "KrishnaBirla"
},
{
"code": null,
"e": 2896,
"s": 2882,
"text": "linux-command"
},
{
"code": null,
"e": 2918,
"s": 2896,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 2925,
"s": 2918,
"text": "Picked"
},
{
"code": null,
"e": 2936,
"s": 2925,
"text": "Linux-Unix"
}
] |
Decision Making in C / C++ (if , if..else, Nested if, if-else-if )
|
30 Jun, 2021
There come situations in real life when we need to make some decisions and based on these decisions, we decide what should we do next. Similar situations arise in programming also where we need to make some decisions and based on these decisions we will execute the next block of code. For example, in C if x occurs then execute y else execute z. There can also be multiple conditions like in C if x occurs then execute p, else if condition y occurs execute q, else execute r. This condition of C else-if is one of the many ways of importing multiple conditions.
Decision-making statements in programming languages decide the direction of the flow of program execution. Decision-making statements available in C or C++ are:
if statementif..else statementsnested if statementsif-else-if ladderswitch statementsJump Statements: breakcontinuegotoreturn
if statement
if..else statements
nested if statements
if-else-if ladder
switch statements
Jump Statements: breakcontinuegotoreturn
breakcontinuegotoreturn
break
continue
goto
return
if statement in C/C++
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not. Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. C if statement accepts boolean values – if the value is true then it will execute the block of statements below it otherwise not. If we do not provide the curly braces ‘{‘ and ‘}’ after if(condition) then by default if statement will consider the first immediately below statement to be inside its block. Example:
if(condition)
statement1;
statement2;
// Here if the condition is true, if block
// will consider only statement1 to be inside
// its block.
Flowchart
C
C++
// C program to illustrate If statement#include <stdio.h> int main() { int i = 10; if (i > 15) { printf("10 is less than 15"); } printf("I am Not in if");}
// C++ program to illustrate If statement#include<iostream>using namespace std; int main() { int i = 10; if (i > 15) { cout<<"10 is less than 15"; } cout<<"I am Not in if"; }
I am Not in if
As the condition present in the if statement is false. So, the block below the if statement is not executed.
if-else in C/C++
The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the C else statement. We can use the else statement with if statement to execute a block of code when the condition is false. Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Flowchart:
Example:
C
C++
// C program to illustrate If statement#include <stdio.h> int main() { int i = 20; if (i < 15){ printf("i is smaller than 15"); } else{ printf("i is greater than 15"); } return 0; }
// C++ program to illustrate if-else statement#include<iostream>using namespace std; int main() { int i = 20; if (i < 15) cout<<"i is smaller than 15"; else cout<<"i is greater than 15"; return 0; }
i is greater than 15
The block of code following the else statement is executed as the condition present in the if statement is false.
nested-if in C/C++
A nested if in C is an if statement that is the target of another if statement. Nested if statements mean an if statement inside another if statement. Yes, both C and C++ allow us to nested if statements within if statements, i.e, we can place an if statement inside another if statement. Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Flowchart
Example:
C
C++
// C program to illustrate nested-if statement#include <stdio.h> int main() { int i = 10; if (i == 10) { // First if statement if (i < 15) printf("i is smaller than 15\n"); // Nested - if statement // Will only be executed if statement above // is true if (i < 12) printf("i is smaller than 12 too\n"); else printf("i is greater than 15"); } return 0;}
// C++ program to illustrate nested-if statement#include <iostream>using namespace std; int main(){ int i = 10; if (i == 10) { // First if statement if (i < 15) cout<<"i is smaller than 15\n"; // Nested - if statement // Will only be executed if statement above // is true if (i < 12) cout<<"i is smaller than 12 too\n"; else cout<<"i is greater than 15"; } return 0;}
i is smaller than 15
i is smaller than 12 too
if-else-if ladder in C/C++
Here, a user can decide among multiple options. The C if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions are true, then the final else statement will be executed. Syntax:
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
Example:
C
C++
// C program to illustrate nested-if statement#include <stdio.h> int main() { int i = 20; if (i == 10) printf("i is 10"); else if (i == 15) printf("i is 15"); else if (i == 20) printf("i is 20"); else printf("i is not present");}
// C++ program to illustrate if-else-if ladder#include<iostream>using namespace std; int main(){ int i = 20; if (i == 10) cout<<"i is 10"; else if (i == 15) cout<<"i is 15"; else if (i == 20) cout<<"i is 20"; else cout<<"i is not present";}
i is 20
Jump Statements in C/C++
These statements are used in C orC++ for the unconditional flow of control throughout the functions in a program. They support four types of jump statements:
C break: This loop control statement is used to terminate the loop. As soon as the break statement is encountered from within a loop, the loop iterations stop there, and control returns from the loop immediately to the first statement after the loop. Syntax:
C break: This loop control statement is used to terminate the loop. As soon as the break statement is encountered from within a loop, the loop iterations stop there, and control returns from the loop immediately to the first statement after the loop. Syntax:
break;
Basically, break statements are used in situations when we are not sure about the actual number of iterations for the loop or we want to terminate the loop based on some condition.
Basically, break statements are used in situations when we are not sure about the actual number of iterations for the loop or we want to terminate the loop based on some condition.
Example:
Example:
C
C++
// C program to illustrate// Linear Search #include <stdio.h> void findElement(int arr[], int size, int key){ // loop to traverse array and search for key for (int i = 0; i < size; i++) { if (arr[i] == key) { printf("Element found at position: %d", (i + 1)); break; } }} int main() { int arr[] = { 1, 2, 3, 4, 5, 6 }; // no of elements int n = 6; // key to be searched int key = 3; // Calling function to find the key findElement(arr, n, key); return 0;}
// CPP program to illustrate// Linear Search#include <iostream>using namespace std; void findElement(int arr[], int size, int key){ // loop to traverse array and search for key for (int i = 0; i < size; i++) { if (arr[i] == key) { cout << "Element found at position: " << (i + 1); break; } }} // Driver program to test above functionint main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = 6; // no of elements int key = 3; // key to be searched // Calling function to find the key findElement(arr, n, key); return 0;}
Element found at position: 3
C continues: This loop control statement is just like the break statement. The continue statement is opposite to that of the break statement, instead of terminating the loop, it forces to execute the next iteration of the loop. As the name suggests the continue statement forces the loop to continue or execute the next iteration. When the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped and the next iteration of the loop will begin. Syntax:
C continues: This loop control statement is just like the break statement. The continue statement is opposite to that of the break statement, instead of terminating the loop, it forces to execute the next iteration of the loop. As the name suggests the continue statement forces the loop to continue or execute the next iteration. When the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped and the next iteration of the loop will begin. Syntax:
continue;
Example:
Example:
C
C++
// C program to explain the use// of continue statement#include <stdio.h> int main() { // loop from 1 to 10 for (int i = 1; i <= 10; i++) { // If i is equals to 6, // continue to next iteration // without printing if (i == 6) continue; else // otherwise print the value of i printf("%d ", i); } return 0;}
// C++ program to explain the use// of continue statement #include <iostream>using namespace std; int main(){ // loop from 1 to 10 for (int i = 1; i <= 10; i++) { // If i is equals to 6, // continue to next iteration // without printing if (i == 6) continue; else // otherwise print the value of i cout << i << " "; } return 0;}
1 2 3 4 5 7 8 9 10
If you create a variable in if-else in C/C++, it will be local to that if/else block only. You can use global variables inside the if/else block. If the name of the variable you created in if/else is as same as any global variable then priority will be given to `local variable`.
C++
C
#include<iostream>using namespace std; int main(){ int gfg=0; // local variable for main cout<<"Before if-else block "<<gfg<<endl; if(1){ int gfg = 100; // new local variable of if block cout<<"if block "<<gfg<<endl; } cout<<"After if block "<<gfg<<endl; return 0;}/* Before if-else block 0 if block 100 After if block 0*/
#include <stdio.h> int main() { int gfg=0; // local variable for main printf("Before if-else block %d\n",gfg); if(1){ int gfg = 100; // new local variable of if block printf("if block %d\n",gfg); } printf("After if block %d",gfg); return 0;}
C goto: The goto statement in C/C++ also referred to as unconditional jump statement can be used to jump from one point to another within a function. Syntax:
C goto: The goto statement in C/C++ also referred to as unconditional jump statement can be used to jump from one point to another within a function. Syntax:
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a label. Here label is a user-defined identifier that indicates the target statement. The statement immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also appear before the ‘goto label;’ statement in the above syntax.
In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a label. Here label is a user-defined identifier that indicates the target statement. The statement immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also appear before the ‘goto label;’ statement in the above syntax.
Below are some examples of how to use goto statement:Examples:
Below are some examples of how to use goto statement:Examples:
C
C++
// C program to print numbers// from 1 to 10 using goto statement#include <stdio.h> // function to print numbers from 1 to 10void printNumbers(){ int n = 1;label: printf("%d ",n); n++; if (n <= 10) goto label;} // Driver program to test above functionint main() { printNumbers(); return 0;}
// C++ program to print numbers// from 1 to 10 using goto statement#include <iostream>using namespace std; // function to print numbers from 1 to 10void printNumbers(){ int n = 1;label: cout << n << " "; n++; if (n <= 10) goto label;} // Driver program to test above functionint main(){ printNumbers(); return 0;}
1 2 3 4 5 6 7 8 9 10
C return: The return in C or C++ returns the flow of the execution to the function from where it is called. This statement does not mandatorily need any conditional statements. As soon as the statement is executed, the flow of the program stops immediately and return the control from where it was called. The return statement may or may not return anything for a void function, but for a non-void function, a return value is must be returned. Syntax:
C return: The return in C or C++ returns the flow of the execution to the function from where it is called. This statement does not mandatorily need any conditional statements. As soon as the statement is executed, the flow of the program stops immediately and return the control from where it was called. The return statement may or may not return anything for a void function, but for a non-void function, a return value is must be returned. Syntax:
return[expression];
Example:
Example:
C
C++
// C code to illustrate return// statement#include <stdio.h> // non-void return type// function to calculate sumint SUM(int a, int b){ int s1 = a + b; return s1;} // returns void// function to printvoid Print(int s2){ printf("The sum is %d", s2); return;} int main(){ int num1 = 10; int num2 = 10; int sum_of = SUM(num1, num2); Print(sum_of); return 0;}
// C++ code to illustrate return// statement#include <iostream>using namespace std; // non-void return type// function to calculate sumint SUM(int a, int b){ int s1 = a + b; return s1;} // returns void// function to printvoid Print(int s2){ cout << "The sum is "<< s2; return;} int main(){ int num1 = 10; int num2 = 10; int sum_of = SUM(num1, num2); Print(sum_of); return 0;}
The sum is 20
?list=PLqM7alHXFySGg6GSRmE2INI4k8fPH5qVB
chaudhary_19
akshaypawar4
pranitkharat143
C Basics
CBSE - Class 11
CPP-Basics
school-programming
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vector in C++ STL
Initialize a vector in C++ (7 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
unordered_map in C++ STL
Python Dictionary
Reverse a string in Java
Introduction To PYTHON
Interfaces in Java
Types of Operating Systems
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 617,
"s": 52,
"text": "There come situations in real life when we need to make some decisions and based on these decisions, we decide what should we do next. Similar situations arise in programming also where we need to make some decisions and based on these decisions we will execute the next block of code. For example, in C if x occurs then execute y else execute z. There can also be multiple conditions like in C if x occurs then execute p, else if condition y occurs execute q, else execute r. This condition of C else-if is one of the many ways of importing multiple conditions. "
},
{
"code": null,
"e": 780,
"s": 617,
"text": "Decision-making statements in programming languages decide the direction of the flow of program execution. Decision-making statements available in C or C++ are: "
},
{
"code": null,
"e": 906,
"s": 780,
"text": "if statementif..else statementsnested if statementsif-else-if ladderswitch statementsJump Statements: breakcontinuegotoreturn"
},
{
"code": null,
"e": 919,
"s": 906,
"text": "if statement"
},
{
"code": null,
"e": 939,
"s": 919,
"text": "if..else statements"
},
{
"code": null,
"e": 960,
"s": 939,
"text": "nested if statements"
},
{
"code": null,
"e": 978,
"s": 960,
"text": "if-else-if ladder"
},
{
"code": null,
"e": 996,
"s": 978,
"text": "switch statements"
},
{
"code": null,
"e": 1037,
"s": 996,
"text": "Jump Statements: breakcontinuegotoreturn"
},
{
"code": null,
"e": 1061,
"s": 1037,
"text": "breakcontinuegotoreturn"
},
{
"code": null,
"e": 1067,
"s": 1061,
"text": "break"
},
{
"code": null,
"e": 1076,
"s": 1067,
"text": "continue"
},
{
"code": null,
"e": 1081,
"s": 1076,
"text": "goto"
},
{
"code": null,
"e": 1088,
"s": 1081,
"text": "return"
},
{
"code": null,
"e": 1112,
"s": 1090,
"text": "if statement in C/C++"
},
{
"code": null,
"e": 1121,
"s": 1112,
"text": "Chapters"
},
{
"code": null,
"e": 1148,
"s": 1121,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1198,
"s": 1148,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1221,
"s": 1198,
"text": "captions off, selected"
},
{
"code": null,
"e": 1229,
"s": 1221,
"text": "English"
},
{
"code": null,
"e": 1253,
"s": 1229,
"text": "This is a modal window."
},
{
"code": null,
"e": 1322,
"s": 1253,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1344,
"s": 1322,
"text": "End of dialog window."
},
{
"code": null,
"e": 1597,
"s": 1344,
"text": "if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not. Syntax: "
},
{
"code": null,
"e": 1671,
"s": 1597,
"text": "if(condition) \n{\n // Statements to execute if\n // condition is true\n}"
},
{
"code": null,
"e": 2054,
"s": 1671,
"text": "Here, the condition after evaluation will be either true or false. C if statement accepts boolean values – if the value is true then it will execute the block of statements below it otherwise not. If we do not provide the curly braces ‘{‘ and ‘}’ after if(condition) then by default if statement will consider the first immediately below statement to be inside its block. Example: "
},
{
"code": null,
"e": 2204,
"s": 2054,
"text": "if(condition)\n statement1;\n statement2;\n\n// Here if the condition is true, if block \n// will consider only statement1 to be inside \n// its block."
},
{
"code": null,
"e": 2216,
"s": 2204,
"text": "Flowchart "
},
{
"code": null,
"e": 2220,
"s": 2218,
"text": "C"
},
{
"code": null,
"e": 2224,
"s": 2220,
"text": "C++"
},
{
"code": "// C program to illustrate If statement#include <stdio.h> int main() { int i = 10; if (i > 15) { printf(\"10 is less than 15\"); } printf(\"I am Not in if\");}",
"e": 2409,
"s": 2224,
"text": null
},
{
"code": "// C++ program to illustrate If statement#include<iostream>using namespace std; int main() { int i = 10; if (i > 15) { cout<<\"10 is less than 15\"; } cout<<\"I am Not in if\"; }",
"e": 2652,
"s": 2409,
"text": null
},
{
"code": null,
"e": 2667,
"s": 2652,
"text": "I am Not in if"
},
{
"code": null,
"e": 2779,
"s": 2669,
"text": "As the condition present in the if statement is false. So, the block below the if statement is not executed. "
},
{
"code": null,
"e": 2796,
"s": 2779,
"text": "if-else in C/C++"
},
{
"code": null,
"e": 3149,
"s": 2796,
"text": "The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the C else statement. We can use the else statement with if statement to execute a block of code when the condition is false. Syntax: "
},
{
"code": null,
"e": 3288,
"s": 3149,
"text": "if (condition)\n{\n // Executes this block if\n // condition is true\n}\nelse\n{\n // Executes this block if\n // condition is false\n}"
},
{
"code": null,
"e": 3301,
"s": 3288,
"text": "Flowchart: "
},
{
"code": null,
"e": 3311,
"s": 3301,
"text": "Example: "
},
{
"code": null,
"e": 3313,
"s": 3311,
"text": "C"
},
{
"code": null,
"e": 3317,
"s": 3313,
"text": "C++"
},
{
"code": "// C program to illustrate If statement#include <stdio.h> int main() { int i = 20; if (i < 15){ printf(\"i is smaller than 15\"); } else{ printf(\"i is greater than 15\"); } return 0; }",
"e": 3555,
"s": 3317,
"text": null
},
{
"code": "// C++ program to illustrate if-else statement#include<iostream>using namespace std; int main() { int i = 20; if (i < 15) cout<<\"i is smaller than 15\"; else cout<<\"i is greater than 15\"; return 0; }",
"e": 3818,
"s": 3555,
"text": null
},
{
"code": null,
"e": 3839,
"s": 3818,
"text": "i is greater than 15"
},
{
"code": null,
"e": 3956,
"s": 3841,
"text": "The block of code following the else statement is executed as the condition present in the if statement is false. "
},
{
"code": null,
"e": 3975,
"s": 3956,
"text": "nested-if in C/C++"
},
{
"code": null,
"e": 4274,
"s": 3975,
"text": "A nested if in C is an if statement that is the target of another if statement. Nested if statements mean an if statement inside another if statement. Yes, both C and C++ allow us to nested if statements within if statements, i.e, we can place an if statement inside another if statement. Syntax: "
},
{
"code": null,
"e": 4406,
"s": 4274,
"text": "if (condition1) \n{\n // Executes when condition1 is true\n if (condition2) \n {\n // Executes when condition2 is true\n }\n}"
},
{
"code": null,
"e": 4418,
"s": 4406,
"text": "Flowchart "
},
{
"code": null,
"e": 4429,
"s": 4418,
"text": "Example: "
},
{
"code": null,
"e": 4431,
"s": 4429,
"text": "C"
},
{
"code": null,
"e": 4435,
"s": 4431,
"text": "C++"
},
{
"code": "// C program to illustrate nested-if statement#include <stdio.h> int main() { int i = 10; if (i == 10) { // First if statement if (i < 15) printf(\"i is smaller than 15\\n\"); // Nested - if statement // Will only be executed if statement above // is true if (i < 12) printf(\"i is smaller than 12 too\\n\"); else printf(\"i is greater than 15\"); } return 0;}",
"e": 4887,
"s": 4435,
"text": null
},
{
"code": "// C++ program to illustrate nested-if statement#include <iostream>using namespace std; int main(){ int i = 10; if (i == 10) { // First if statement if (i < 15) cout<<\"i is smaller than 15\\n\"; // Nested - if statement // Will only be executed if statement above // is true if (i < 12) cout<<\"i is smaller than 12 too\\n\"; else cout<<\"i is greater than 15\"; } return 0;}",
"e": 5355,
"s": 4887,
"text": null
},
{
"code": null,
"e": 5401,
"s": 5355,
"text": "i is smaller than 15\ni is smaller than 12 too"
},
{
"code": null,
"e": 5430,
"s": 5403,
"text": "if-else-if ladder in C/C++"
},
{
"code": null,
"e": 5786,
"s": 5430,
"text": "Here, a user can decide among multiple options. The C if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions are true, then the final else statement will be executed. Syntax: "
},
{
"code": null,
"e": 5875,
"s": 5786,
"text": "if (condition)\n statement;\nelse if (condition)\n statement;\n.\n.\nelse\n statement;"
},
{
"code": null,
"e": 5888,
"s": 5877,
"text": "Example: "
},
{
"code": null,
"e": 5890,
"s": 5888,
"text": "C"
},
{
"code": null,
"e": 5894,
"s": 5890,
"text": "C++"
},
{
"code": "// C program to illustrate nested-if statement#include <stdio.h> int main() { int i = 20; if (i == 10) printf(\"i is 10\"); else if (i == 15) printf(\"i is 15\"); else if (i == 20) printf(\"i is 20\"); else printf(\"i is not present\");}",
"e": 6169,
"s": 5894,
"text": null
},
{
"code": "// C++ program to illustrate if-else-if ladder#include<iostream>using namespace std; int main(){ int i = 20; if (i == 10) cout<<\"i is 10\"; else if (i == 15) cout<<\"i is 15\"; else if (i == 20) cout<<\"i is 20\"; else cout<<\"i is not present\";}",
"e": 6455,
"s": 6169,
"text": null
},
{
"code": null,
"e": 6463,
"s": 6455,
"text": "i is 20"
},
{
"code": null,
"e": 6490,
"s": 6465,
"text": "Jump Statements in C/C++"
},
{
"code": null,
"e": 6649,
"s": 6490,
"text": "These statements are used in C orC++ for the unconditional flow of control throughout the functions in a program. They support four types of jump statements: "
},
{
"code": null,
"e": 6910,
"s": 6649,
"text": "C break: This loop control statement is used to terminate the loop. As soon as the break statement is encountered from within a loop, the loop iterations stop there, and control returns from the loop immediately to the first statement after the loop. Syntax: "
},
{
"code": null,
"e": 7171,
"s": 6910,
"text": "C break: This loop control statement is used to terminate the loop. As soon as the break statement is encountered from within a loop, the loop iterations stop there, and control returns from the loop immediately to the first statement after the loop. Syntax: "
},
{
"code": null,
"e": 7178,
"s": 7171,
"text": "break;"
},
{
"code": null,
"e": 7361,
"s": 7178,
"text": "Basically, break statements are used in situations when we are not sure about the actual number of iterations for the loop or we want to terminate the loop based on some condition. "
},
{
"code": null,
"e": 7544,
"s": 7361,
"text": "Basically, break statements are used in situations when we are not sure about the actual number of iterations for the loop or we want to terminate the loop based on some condition. "
},
{
"code": null,
"e": 7555,
"s": 7544,
"text": "Example: "
},
{
"code": null,
"e": 7566,
"s": 7555,
"text": "Example: "
},
{
"code": null,
"e": 7568,
"s": 7566,
"text": "C"
},
{
"code": null,
"e": 7572,
"s": 7568,
"text": "C++"
},
{
"code": "// C program to illustrate// Linear Search #include <stdio.h> void findElement(int arr[], int size, int key){ // loop to traverse array and search for key for (int i = 0; i < size; i++) { if (arr[i] == key) { printf(\"Element found at position: %d\", (i + 1)); break; } }} int main() { int arr[] = { 1, 2, 3, 4, 5, 6 }; // no of elements int n = 6; // key to be searched int key = 3; // Calling function to find the key findElement(arr, n, key); return 0;}",
"e": 8109,
"s": 7572,
"text": null
},
{
"code": "// CPP program to illustrate// Linear Search#include <iostream>using namespace std; void findElement(int arr[], int size, int key){ // loop to traverse array and search for key for (int i = 0; i < size; i++) { if (arr[i] == key) { cout << \"Element found at position: \" << (i + 1); break; } }} // Driver program to test above functionint main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = 6; // no of elements int key = 3; // key to be searched // Calling function to find the key findElement(arr, n, key); return 0;}",
"e": 8690,
"s": 8109,
"text": null
},
{
"code": null,
"e": 8723,
"s": 8694,
"text": "Element found at position: 3"
},
{
"code": null,
"e": 9241,
"s": 8725,
"text": " C continues: This loop control statement is just like the break statement. The continue statement is opposite to that of the break statement, instead of terminating the loop, it forces to execute the next iteration of the loop. As the name suggests the continue statement forces the loop to continue or execute the next iteration. When the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped and the next iteration of the loop will begin. Syntax: "
},
{
"code": null,
"e": 9758,
"s": 9243,
"text": "C continues: This loop control statement is just like the break statement. The continue statement is opposite to that of the break statement, instead of terminating the loop, it forces to execute the next iteration of the loop. As the name suggests the continue statement forces the loop to continue or execute the next iteration. When the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped and the next iteration of the loop will begin. Syntax: "
},
{
"code": null,
"e": 9768,
"s": 9758,
"text": "continue;"
},
{
"code": null,
"e": 9783,
"s": 9772,
"text": "Example: "
},
{
"code": null,
"e": 9794,
"s": 9783,
"text": "Example: "
},
{
"code": null,
"e": 9796,
"s": 9794,
"text": "C"
},
{
"code": null,
"e": 9800,
"s": 9796,
"text": "C++"
},
{
"code": "// C program to explain the use// of continue statement#include <stdio.h> int main() { // loop from 1 to 10 for (int i = 1; i <= 10; i++) { // If i is equals to 6, // continue to next iteration // without printing if (i == 6) continue; else // otherwise print the value of i printf(\"%d \", i); } return 0;}",
"e": 10189,
"s": 9800,
"text": null
},
{
"code": "// C++ program to explain the use// of continue statement #include <iostream>using namespace std; int main(){ // loop from 1 to 10 for (int i = 1; i <= 10; i++) { // If i is equals to 6, // continue to next iteration // without printing if (i == 6) continue; else // otherwise print the value of i cout << i << \" \"; } return 0;}",
"e": 10601,
"s": 10189,
"text": null
},
{
"code": null,
"e": 10624,
"s": 10605,
"text": "1 2 3 4 5 7 8 9 10"
},
{
"code": null,
"e": 10911,
"s": 10630,
"text": "If you create a variable in if-else in C/C++, it will be local to that if/else block only. You can use global variables inside the if/else block. If the name of the variable you created in if/else is as same as any global variable then priority will be given to `local variable`. "
},
{
"code": null,
"e": 10915,
"s": 10911,
"text": "C++"
},
{
"code": null,
"e": 10917,
"s": 10915,
"text": "C"
},
{
"code": "#include<iostream>using namespace std; int main(){ int gfg=0; // local variable for main cout<<\"Before if-else block \"<<gfg<<endl; if(1){ int gfg = 100; // new local variable of if block cout<<\"if block \"<<gfg<<endl; } cout<<\"After if block \"<<gfg<<endl; return 0;}/* Before if-else block 0 if block 100 After if block 0*/",
"e": 11281,
"s": 10917,
"text": null
},
{
"code": "#include <stdio.h> int main() { int gfg=0; // local variable for main printf(\"Before if-else block %d\\n\",gfg); if(1){ int gfg = 100; // new local variable of if block printf(\"if block %d\\n\",gfg); } printf(\"After if block %d\",gfg); return 0;}",
"e": 11556,
"s": 11281,
"text": null
},
{
"code": null,
"e": 11716,
"s": 11556,
"text": "C goto: The goto statement in C/C++ also referred to as unconditional jump statement can be used to jump from one point to another within a function. Syntax: "
},
{
"code": null,
"e": 11876,
"s": 11716,
"text": "C goto: The goto statement in C/C++ also referred to as unconditional jump statement can be used to jump from one point to another within a function. Syntax: "
},
{
"code": null,
"e": 12047,
"s": 11876,
"text": "Syntax1 | Syntax2\n----------------------------\ngoto label; | label: \n. | .\n. | .\n. | .\nlabel: | goto label;"
},
{
"code": null,
"e": 12399,
"s": 12047,
"text": "In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a label. Here label is a user-defined identifier that indicates the target statement. The statement immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also appear before the ‘goto label;’ statement in the above syntax. "
},
{
"code": null,
"e": 12751,
"s": 12399,
"text": "In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a label. Here label is a user-defined identifier that indicates the target statement. The statement immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also appear before the ‘goto label;’ statement in the above syntax. "
},
{
"code": null,
"e": 12816,
"s": 12751,
"text": "Below are some examples of how to use goto statement:Examples: "
},
{
"code": null,
"e": 12881,
"s": 12816,
"text": "Below are some examples of how to use goto statement:Examples: "
},
{
"code": null,
"e": 12883,
"s": 12881,
"text": "C"
},
{
"code": null,
"e": 12887,
"s": 12883,
"text": "C++"
},
{
"code": "// C program to print numbers// from 1 to 10 using goto statement#include <stdio.h> // function to print numbers from 1 to 10void printNumbers(){ int n = 1;label: printf(\"%d \",n); n++; if (n <= 10) goto label;} // Driver program to test above functionint main() { printNumbers(); return 0;}",
"e": 13203,
"s": 12887,
"text": null
},
{
"code": "// C++ program to print numbers// from 1 to 10 using goto statement#include <iostream>using namespace std; // function to print numbers from 1 to 10void printNumbers(){ int n = 1;label: cout << n << \" \"; n++; if (n <= 10) goto label;} // Driver program to test above functionint main(){ printNumbers(); return 0;}",
"e": 13542,
"s": 13203,
"text": null
},
{
"code": null,
"e": 13567,
"s": 13546,
"text": "1 2 3 4 5 6 7 8 9 10"
},
{
"code": null,
"e": 14024,
"s": 13569,
"text": " C return: The return in C or C++ returns the flow of the execution to the function from where it is called. This statement does not mandatorily need any conditional statements. As soon as the statement is executed, the flow of the program stops immediately and return the control from where it was called. The return statement may or may not return anything for a void function, but for a non-void function, a return value is must be returned. Syntax: "
},
{
"code": null,
"e": 14480,
"s": 14026,
"text": "C return: The return in C or C++ returns the flow of the execution to the function from where it is called. This statement does not mandatorily need any conditional statements. As soon as the statement is executed, the flow of the program stops immediately and return the control from where it was called. The return statement may or may not return anything for a void function, but for a non-void function, a return value is must be returned. Syntax: "
},
{
"code": null,
"e": 14500,
"s": 14480,
"text": "return[expression];"
},
{
"code": null,
"e": 14511,
"s": 14500,
"text": "Example: "
},
{
"code": null,
"e": 14522,
"s": 14511,
"text": "Example: "
},
{
"code": null,
"e": 14524,
"s": 14522,
"text": "C"
},
{
"code": null,
"e": 14528,
"s": 14524,
"text": "C++"
},
{
"code": "// C code to illustrate return// statement#include <stdio.h> // non-void return type// function to calculate sumint SUM(int a, int b){ int s1 = a + b; return s1;} // returns void// function to printvoid Print(int s2){ printf(\"The sum is %d\", s2); return;} int main(){ int num1 = 10; int num2 = 10; int sum_of = SUM(num1, num2); Print(sum_of); return 0;}",
"e": 14909,
"s": 14528,
"text": null
},
{
"code": "// C++ code to illustrate return// statement#include <iostream>using namespace std; // non-void return type// function to calculate sumint SUM(int a, int b){ int s1 = a + b; return s1;} // returns void// function to printvoid Print(int s2){ cout << \"The sum is \"<< s2; return;} int main(){ int num1 = 10; int num2 = 10; int sum_of = SUM(num1, num2); Print(sum_of); return 0;}",
"e": 15312,
"s": 14909,
"text": null
},
{
"code": null,
"e": 15330,
"s": 15316,
"text": "The sum is 20"
},
{
"code": null,
"e": 15381,
"s": 15338,
"text": "?list=PLqM7alHXFySGg6GSRmE2INI4k8fPH5qVB "
},
{
"code": null,
"e": 15396,
"s": 15383,
"text": "chaudhary_19"
},
{
"code": null,
"e": 15409,
"s": 15396,
"text": "akshaypawar4"
},
{
"code": null,
"e": 15425,
"s": 15409,
"text": "pranitkharat143"
},
{
"code": null,
"e": 15434,
"s": 15425,
"text": "C Basics"
},
{
"code": null,
"e": 15450,
"s": 15434,
"text": "CBSE - Class 11"
},
{
"code": null,
"e": 15461,
"s": 15450,
"text": "CPP-Basics"
},
{
"code": null,
"e": 15480,
"s": 15461,
"text": "school-programming"
},
{
"code": null,
"e": 15484,
"s": 15480,
"text": "C++"
},
{
"code": null,
"e": 15503,
"s": 15484,
"text": "School Programming"
},
{
"code": null,
"e": 15507,
"s": 15503,
"text": "CPP"
},
{
"code": null,
"e": 15605,
"s": 15507,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15623,
"s": 15605,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 15669,
"s": 15623,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 15692,
"s": 15669,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 15719,
"s": 15692,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 15744,
"s": 15719,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 15762,
"s": 15744,
"text": "Python Dictionary"
},
{
"code": null,
"e": 15787,
"s": 15762,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 15810,
"s": 15787,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 15829,
"s": 15810,
"text": "Interfaces in Java"
}
] |
Python - Tuples
|
A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also. For example −
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing −
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there is only one value −
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −
#!/usr/bin/python
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];
When the above code is executed, it produces the following result −
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates −
#!/usr/bin/python
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;
When the above code is executed, it produces the following result −
(12, 34.56, 'abc', 'xyz')
Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement. For example −
#!/usr/bin/python
tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : ";
print tup;
This produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more −
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined
Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings in the prior chapter −
Because tuples are sequences, indexing and slicing work the same way for tuples as they do for strings. Assuming following input −
L = ('spam', 'Spam', 'SPAM!')
Any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these short examples −
#!/usr/bin/python
print 'abc', -4.24e93, 18+6.6j, 'xyz';
x, y = 1, 2;
print "Value of x , y : ", x,y;
When the above code is executed, it produces the following result −
abc -4.24e+93 (18+6.6j) xyz
Value of x , y : 1 2
Python includes the following tuple functions −
Compares elements of both tuples.
Gives the total length of the tuple.
Returns item from the tuple with max value.
Returns item from the tuple with min value.
Converts a list into tuple.
|
[
{
"code": null,
"e": 2632,
"s": 2378,
"text": "A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets."
},
{
"code": null,
"e": 2799,
"s": 2632,
"text": "Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also. For example −"
},
{
"code": null,
"e": 2897,
"s": 2799,
"text": "tup1 = ('physics', 'chemistry', 1997, 2000);\ntup2 = (1, 2, 3, 4, 5 );\ntup3 = \"a\", \"b\", \"c\", \"d\";\n"
},
{
"code": null,
"e": 2964,
"s": 2897,
"text": "The empty tuple is written as two parentheses containing nothing −"
},
{
"code": null,
"e": 2976,
"s": 2964,
"text": "tup1 = ();\n"
},
{
"code": null,
"e": 3086,
"s": 2976,
"text": "To write a tuple containing a single value you have to include a comma, even though there is only one value −"
},
{
"code": null,
"e": 3101,
"s": 3086,
"text": "tup1 = (50,);\n"
},
{
"code": null,
"e": 3197,
"s": 3101,
"text": "Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on."
},
{
"code": null,
"e": 3347,
"s": 3197,
"text": "To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −"
},
{
"code": null,
"e": 3502,
"s": 3347,
"text": "#!/usr/bin/python\n\ntup1 = ('physics', 'chemistry', 1997, 2000);\ntup2 = (1, 2, 3, 4, 5, 6, 7 );\nprint \"tup1[0]: \", tup1[0];\nprint \"tup2[1:5]: \", tup2[1:5];"
},
{
"code": null,
"e": 3571,
"s": 3502,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3615,
"s": 3571,
"text": "tup1[0]: physics\ntup2[1:5]: [2, 3, 4, 5]\n"
},
{
"code": null,
"e": 3816,
"s": 3615,
"text": "Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates −"
},
{
"code": null,
"e": 4013,
"s": 3816,
"text": "#!/usr/bin/python\n\ntup1 = (12, 34.56);\ntup2 = ('abc', 'xyz');\n\n# Following action is not valid for tuples\n# tup1[0] = 100;\n\n# So let's create a new tuple as follows\ntup3 = tup1 + tup2;\nprint tup3;"
},
{
"code": null,
"e": 4081,
"s": 4013,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 4108,
"s": 4081,
"text": "(12, 34.56, 'abc', 'xyz')\n"
},
{
"code": null,
"e": 4270,
"s": 4108,
"text": "Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded."
},
{
"code": null,
"e": 4350,
"s": 4270,
"text": "To explicitly remove an entire tuple, just use the del statement. For example −"
},
{
"code": null,
"e": 4475,
"s": 4350,
"text": "#!/usr/bin/python\n\ntup = ('physics', 'chemistry', 1997, 2000);\nprint tup;\ndel tup;\nprint \"After deleting tup : \";\nprint tup;"
},
{
"code": null,
"e": 4599,
"s": 4475,
"text": "This produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more −"
},
{
"code": null,
"e": 4786,
"s": 4599,
"text": "('physics', 'chemistry', 1997, 2000)\nAfter deleting tup :\nTraceback (most recent call last):\n File \"test.py\", line 9, in <module>\n print tup;\nNameError: name 'tup' is not defined\n"
},
{
"code": null,
"e": 4947,
"s": 4786,
"text": "Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string."
},
{
"code": null,
"e": 5055,
"s": 4947,
"text": "In fact, tuples respond to all of the general sequence operations we used on strings in the prior chapter −"
},
{
"code": null,
"e": 5186,
"s": 5055,
"text": "Because tuples are sequences, indexing and slicing work the same way for tuples as they do for strings. Assuming following input −"
},
{
"code": null,
"e": 5216,
"s": 5186,
"text": "L = ('spam', 'Spam', 'SPAM!')"
},
{
"code": null,
"e": 5415,
"s": 5218,
"text": "Any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these short examples −"
},
{
"code": null,
"e": 5518,
"s": 5415,
"text": "#!/usr/bin/python\n\nprint 'abc', -4.24e93, 18+6.6j, 'xyz';\nx, y = 1, 2;\nprint \"Value of x , y : \", x,y;"
},
{
"code": null,
"e": 5586,
"s": 5518,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 5636,
"s": 5586,
"text": "abc -4.24e+93 (18+6.6j) xyz\nValue of x , y : 1 2\n"
},
{
"code": null,
"e": 5684,
"s": 5636,
"text": "Python includes the following tuple functions −"
},
{
"code": null,
"e": 5718,
"s": 5684,
"text": "Compares elements of both tuples."
},
{
"code": null,
"e": 5755,
"s": 5718,
"text": "Gives the total length of the tuple."
},
{
"code": null,
"e": 5799,
"s": 5755,
"text": "Returns item from the tuple with max value."
},
{
"code": null,
"e": 5843,
"s": 5799,
"text": "Returns item from the tuple with min value."
}
] |
Python program to check if the list contains three consecutive common numbers in Python
|
17 Aug, 2020
Our task is to print the element which occurs 3 consecutive times in a Python list.
Example :
Input : [4, 5, 5, 5, 3, 8]
Output : 5
Input : [1, 1, 1, 64, 23, 64, 22, 22, 22]
Output : 1, 22
Approach :
Create a list.Create a loop for range size – 2.Check if the element is equal to the next element.Again check if the next element is equal to the next element.If both conditions are satisfied then print the element.
Create a list.
Create a loop for range size – 2.
Check if the element is equal to the next element.
Again check if the next element is equal to the next element.
If both conditions are satisfied then print the element.
Example 1 : Only one occurrence of a 3 consecutively occurring element.
# creating the arrayarr = [4, 5, 5, 5, 3, 8] # size of the listsize = len(arr) # looping till length - 2for i in range(size - 2): # checking the conditions if arr[i] == arr[i + 1] and arr[i + 1] == arr[i + 2]: # printing the element as the # conditions are satisfied print(arr[i])
Output :
5
Example 2 : Multiple occurrences of 3 consecutively occurring elements.
# creating the arrayarr = [1, 1, 1, 64, 23, 64, 22, 22, 22] # size of the listsize = len(arr) # looping till length - 2for i in range(size - 2): # checking the conditions if arr[i] == arr[i + 1] and arr[i + 1] == arr[i + 2]: # printing the element as the # conditions are satisfied print(arr[i])
Output :
1
22
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Aug, 2020"
},
{
"code": null,
"e": 138,
"s": 54,
"text": "Our task is to print the element which occurs 3 consecutive times in a Python list."
},
{
"code": null,
"e": 148,
"s": 138,
"text": "Example :"
},
{
"code": null,
"e": 247,
"s": 148,
"text": "Input : [4, 5, 5, 5, 3, 8]\n\nOutput : 5\n\nInput : [1, 1, 1, 64, 23, 64, 22, 22, 22]\n\nOutput : 1, 22\n"
},
{
"code": null,
"e": 258,
"s": 247,
"text": "Approach :"
},
{
"code": null,
"e": 473,
"s": 258,
"text": "Create a list.Create a loop for range size – 2.Check if the element is equal to the next element.Again check if the next element is equal to the next element.If both conditions are satisfied then print the element."
},
{
"code": null,
"e": 488,
"s": 473,
"text": "Create a list."
},
{
"code": null,
"e": 522,
"s": 488,
"text": "Create a loop for range size – 2."
},
{
"code": null,
"e": 573,
"s": 522,
"text": "Check if the element is equal to the next element."
},
{
"code": null,
"e": 635,
"s": 573,
"text": "Again check if the next element is equal to the next element."
},
{
"code": null,
"e": 692,
"s": 635,
"text": "If both conditions are satisfied then print the element."
},
{
"code": null,
"e": 764,
"s": 692,
"text": "Example 1 : Only one occurrence of a 3 consecutively occurring element."
},
{
"code": "# creating the arrayarr = [4, 5, 5, 5, 3, 8] # size of the listsize = len(arr) # looping till length - 2for i in range(size - 2): # checking the conditions if arr[i] == arr[i + 1] and arr[i + 1] == arr[i + 2]: # printing the element as the # conditions are satisfied print(arr[i])",
"e": 1080,
"s": 764,
"text": null
},
{
"code": null,
"e": 1089,
"s": 1080,
"text": "Output :"
},
{
"code": null,
"e": 1091,
"s": 1089,
"text": "5"
},
{
"code": null,
"e": 1163,
"s": 1091,
"text": "Example 2 : Multiple occurrences of 3 consecutively occurring elements."
},
{
"code": "# creating the arrayarr = [1, 1, 1, 64, 23, 64, 22, 22, 22] # size of the listsize = len(arr) # looping till length - 2for i in range(size - 2): # checking the conditions if arr[i] == arr[i + 1] and arr[i + 1] == arr[i + 2]: # printing the element as the # conditions are satisfied print(arr[i])",
"e": 1494,
"s": 1163,
"text": null
},
{
"code": null,
"e": 1503,
"s": 1494,
"text": "Output :"
},
{
"code": null,
"e": 1509,
"s": 1503,
"text": "1\n22\n"
},
{
"code": null,
"e": 1530,
"s": 1509,
"text": "Python list-programs"
},
{
"code": null,
"e": 1542,
"s": 1530,
"text": "python-list"
},
{
"code": null,
"e": 1549,
"s": 1542,
"text": "Python"
},
{
"code": null,
"e": 1565,
"s": 1549,
"text": "Python Programs"
},
{
"code": null,
"e": 1577,
"s": 1565,
"text": "python-list"
},
{
"code": null,
"e": 1675,
"s": 1577,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1693,
"s": 1675,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1735,
"s": 1693,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1757,
"s": 1735,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1792,
"s": 1757,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1818,
"s": 1792,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1861,
"s": 1818,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 1883,
"s": 1861,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1922,
"s": 1883,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1960,
"s": 1922,
"text": "Python | Convert a list to dictionary"
}
] |
Python – Read blob object in python using wand library
|
07 Sep, 2021
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is used to store media files like images, video and audio files. Due to its ability to store multimedia files it takes a huge disk space. Also length of BLOB may go upto 2, 147, 483, 647 characters. BLOB provides fast multimedia transfer. To get blob file from image :
with open('image_path') as f:
image_blob = f.read()
To read image from blob in Wand :
with Image(blob=image_binary) as img:
\\other code
Input Image :
Code :
Python3
# import required librariesfrom __future__ import print_function # import Image from wand.image modulefrom wand.image import Image # open image using file handlingwith open('koala.jpeg') as f: # get blob from image file image_blob = f.read() # read image using wand from blob filewith Image(blob = image_binary) as img: # get height of image print('height =', img.height) # get width of image print('width =', img.width)
Output :
height = 300
width = 400
anikaseth98
Python-wand
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 644,
"s": 28,
"text": "BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is used to store media files like images, video and audio files. Due to its ability to store multimedia files it takes a huge disk space. Also length of BLOB may go upto 2, 147, 483, 647 characters. BLOB provides fast multimedia transfer. To get blob file from image : "
},
{
"code": null,
"e": 705,
"s": 644,
"text": " with open('image_path') as f:\n image_blob = f.read()"
},
{
"code": null,
"e": 741,
"s": 705,
"text": "To read image from blob in Wand : "
},
{
"code": null,
"e": 796,
"s": 741,
"text": "with Image(blob=image_binary) as img:\n \\\\other code"
},
{
"code": null,
"e": 812,
"s": 796,
"text": "Input Image : "
},
{
"code": null,
"e": 821,
"s": 812,
"text": "Code : "
},
{
"code": null,
"e": 829,
"s": 821,
"text": "Python3"
},
{
"code": "# import required librariesfrom __future__ import print_function # import Image from wand.image modulefrom wand.image import Image # open image using file handlingwith open('koala.jpeg') as f: # get blob from image file image_blob = f.read() # read image using wand from blob filewith Image(blob = image_binary) as img: # get height of image print('height =', img.height) # get width of image print('width =', img.width)",
"e": 1271,
"s": 829,
"text": null
},
{
"code": null,
"e": 1282,
"s": 1271,
"text": "Output : "
},
{
"code": null,
"e": 1307,
"s": 1282,
"text": "height = 300\nwidth = 400"
},
{
"code": null,
"e": 1321,
"s": 1309,
"text": "anikaseth98"
},
{
"code": null,
"e": 1333,
"s": 1321,
"text": "Python-wand"
},
{
"code": null,
"e": 1340,
"s": 1333,
"text": "Python"
},
{
"code": null,
"e": 1438,
"s": 1340,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1470,
"s": 1438,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1497,
"s": 1470,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1528,
"s": 1497,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1551,
"s": 1528,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1572,
"s": 1551,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1628,
"s": 1572,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1670,
"s": 1628,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1712,
"s": 1670,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1751,
"s": 1712,
"text": "Python | Get unique values from a list"
}
] |
HTML DOM querySelector() Method
|
20 Nov, 2021
The querySelector() method in HTML is used to return the first element that matches a specified CSS selector(s) in the document.
Note: The querySelector() method only returns the first element that matches the specified selectors. To return all the matches, use the querySelectorAll() method.
Syntax:
element.querySelector(selectors);
Selectors are the required field. It Specifies one or more CSS selectors to match the element. These selectors are used to select HTML elements based on their id, classes, types, etc. In the case of multiple selectors, a comma is used to separate each selector. The element which occurs first in the document is the returned element. If the selector matches an id( which should be unique on each page), which is used several times in the document then it will return the first matching element.
Return value :- This method is used to return the first element that matches a specified CSS selector(s) in the document.
Example: This example describes the use of the DOM querySelector() method to select the very first matching element for the specific selector.
HTML
<!DOCTYPE html><html> <head> <title>DOM querySelector() Method</title></head> <body style="text-align: center;"> <h1 style="color: green;">GeeksforGeeks</h1> <h2>querySelector() Method</h2> <div id="gfg"> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p> </div> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var x = document.getElementById("gfg"); x.querySelector("p").style.backgroundColor = "Green"; x.querySelector("p").style.color = "white"; } </script></body> </html>
Output:
DOM querySelector() Method
Supported Browsers: The browser supported by querySelector() method are listed below:
Google Chrome 4.0
Internet Explorer 8.0
Microsoft Edge
Firefox 3.5
Opera 10.0
Safari 3.2
simranarora5sos
bhaskargeeksforgeeks
chhabradhanvi
HTML-DOM
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Nov, 2021"
},
{
"code": null,
"e": 183,
"s": 54,
"text": "The querySelector() method in HTML is used to return the first element that matches a specified CSS selector(s) in the document."
},
{
"code": null,
"e": 347,
"s": 183,
"text": "Note: The querySelector() method only returns the first element that matches the specified selectors. To return all the matches, use the querySelectorAll() method."
},
{
"code": null,
"e": 355,
"s": 347,
"text": "Syntax:"
},
{
"code": null,
"e": 389,
"s": 355,
"text": "element.querySelector(selectors);"
},
{
"code": null,
"e": 884,
"s": 389,
"text": "Selectors are the required field. It Specifies one or more CSS selectors to match the element. These selectors are used to select HTML elements based on their id, classes, types, etc. In the case of multiple selectors, a comma is used to separate each selector. The element which occurs first in the document is the returned element. If the selector matches an id( which should be unique on each page), which is used several times in the document then it will return the first matching element."
},
{
"code": null,
"e": 1007,
"s": 884,
"text": "Return value :- This method is used to return the first element that matches a specified CSS selector(s) in the document."
},
{
"code": null,
"e": 1150,
"s": 1007,
"text": "Example: This example describes the use of the DOM querySelector() method to select the very first matching element for the specific selector."
},
{
"code": null,
"e": 1155,
"s": 1150,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>DOM querySelector() Method</title></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <h2>querySelector() Method</h2> <div id=\"gfg\"> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p> </div> <button onclick=\"myFunction()\">Try it</button> <script> function myFunction() { var x = document.getElementById(\"gfg\"); x.querySelector(\"p\").style.backgroundColor = \"Green\"; x.querySelector(\"p\").style.color = \"white\"; } </script></body> </html>",
"e": 1737,
"s": 1155,
"text": null
},
{
"code": null,
"e": 1745,
"s": 1737,
"text": "Output:"
},
{
"code": null,
"e": 1772,
"s": 1745,
"text": "DOM querySelector() Method"
},
{
"code": null,
"e": 1858,
"s": 1772,
"text": "Supported Browsers: The browser supported by querySelector() method are listed below:"
},
{
"code": null,
"e": 1876,
"s": 1858,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 1898,
"s": 1876,
"text": "Internet Explorer 8.0"
},
{
"code": null,
"e": 1913,
"s": 1898,
"text": "Microsoft Edge"
},
{
"code": null,
"e": 1925,
"s": 1913,
"text": "Firefox 3.5"
},
{
"code": null,
"e": 1936,
"s": 1925,
"text": "Opera 10.0"
},
{
"code": null,
"e": 1947,
"s": 1936,
"text": "Safari 3.2"
},
{
"code": null,
"e": 1963,
"s": 1947,
"text": "simranarora5sos"
},
{
"code": null,
"e": 1984,
"s": 1963,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 1998,
"s": 1984,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 2007,
"s": 1998,
"text": "HTML-DOM"
},
{
"code": null,
"e": 2014,
"s": 2007,
"text": "Picked"
},
{
"code": null,
"e": 2019,
"s": 2014,
"text": "HTML"
},
{
"code": null,
"e": 2036,
"s": 2019,
"text": "Web Technologies"
},
{
"code": null,
"e": 2041,
"s": 2036,
"text": "HTML"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.