title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
How to Build a Sticky Notes Application in Android Studio? - GeeksforGeeks
|
15 Jun, 2021
We as humans tend to forget some small but important things, and to resolve this we try to write those things up and paste them somewhere, we often have eyes on. And in this digital era, the things we are most likely to see are laptop, computer, or mobile phone screens. For this, we all have once used the Sticky Notes on Windows or Stickies on Mac, today in this article we would be discussing how we can build such an application for Android.
Now, if we think of something that is sticky i.e. which sticks to the screen, in Android, the component which comes to our mind is the Home screen Widgets. Home Screen Widgets are the best interactive components that stick to the screen and can be resized in any manner. We would be creating an application that also has its own widget. We will first write some text in the main application and save that into a file in memory. At the very moment, we will update the widget with text that the user just saved. And Horray! Our Sticky note is ready.
Here one thing to note is that in Android views are also called Widgets, so to avoid confusion we use the term Home Screen Widgets. These are the broadcast receivers that provide interactive components. They usually show some sort of information and encourage the user to interact with it. For example, it may display time, weather, or emails and once you click on them the main application hosting them would start. Widgets use RemoteViews to build its user interface. With the same permissions as the original application, a RemoteView may be run by another method. As a consequence, the widget runs with the permissions of the application that created it. A Widget’s user interface is determined by a broadcast receiver. This receiver inflates its layout into a RemoteView object.
YouTubeGeeksforGeeks502K subscribersHow to Make a Sticky Notes Android App? | 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 / 52:29•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=qfzdZoEiZFQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
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 AndroidManifest.xml file
Add the user permissions for reading and write the file from storage. Also, in order to register the widget, we have to create a broadcast receiver with an intent filter.
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.notes"> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <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/Theme.Notes"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- To register a widget, you create a broadcast receiver with an intent filter for the android.appwidget.action.APPWIDGET_UPDATE action--> <receiver android:name=".AppWidget" android:label="StickyNotes"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <!-- This metadata contains the configuration of your widget, the resource attribute contains the layout of your widget as it will be seen in the list of widgets --> <meta-data android:name="android.appwidget.provider" android:resource="@xml/new_app_widget_info" /> </receiver> </application> </manifest>
Step 3: Creating a Widget
Follow the steps mentioned in this article Create a Basic Widget of an Android App to add the Widget to your project. The file new_app_widget_info.xml contains code that determines the look of our widget as it would appear in the Widgets list.
Step 4: Working with the AppWidget Class
This class will be formed in the previous step. Go to the AppWidget.java file and refer to the following code. Below is the code for the AppWidget.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.app.PendingIntent;import android.appwidget.AppWidgetManager;import android.appwidget.AppWidgetProvider;import android.content.Context;import android.content.Intent;import android.widget.RemoteViews; // Implementation of App Widget functionalitypublic class AppWidget extends AppWidgetProvider { // Create an Intent to launch activity @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // Perform this loop procedure for each App Widget // that belongs to this provider for (int appWidgetId : appWidgetIds) { // Create an Intent to launch MainActivity Intent launchActivity = new Intent(context, MainActivity.class); // Attaching a Pending Intent // to trigger it when // application is not alive PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, launchActivity, 0); // Get the layout for the App Widget and attach // an on-click listener to the button RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.new_app_widget); remoteViews.setOnClickPendingIntent(R.id.appwidget_text, pendingIntent); // Tell the AppWidgetManager to perform an // update on the current app widget appWidgetManager.updateAppWidget(appWidgetId, remoteViews); } }}
Step 5: Creating the StickyNote Class
This is a helper class that provides the functionality of saving, updating, and retrieving the contents to and from the file. Go to the StickyNote .java file and refer to the following code. Below is the code for the StickyNote .java file. Comments are added inside the code to understand the code in more detail.
Java
import android.content.Context; import java.io.BufferedReader;import java.io.File;import java.io.FileOutputStream;import java.io.FileReader;import java.io.IOException; import static android.content.Context.MODE_PRIVATE; class StickyNote { // this function will return // the content from the text // file(if any) String getStick(Context context) { // get the file from path File fileEvents = new File(context.getFilesDir().getPath() + "/gfg.txt"); // create a StringBuilder to store the text from file StringBuilder text = new StringBuilder(); try { // use the BufferedReader // to Read the file // efficiently BufferedReader br = new BufferedReader(new FileReader(fileEvents)); String line; // read a single line at a time // append newline character after each line while ((line = br.readLine()) != null) { text.append(line); text.append('\n'); } // close the BufferedReader br.close(); } catch (IOException e) { e.printStackTrace(); } // finally return the // string i.e. the retrieved data // from file return text.toString(); } // this function saves the new // content in the file if it // exists or will create a new one void setStick(String textToBeSaved, Context context) { String text = textToBeSaved; // create the FileOutputStream // to efficiently write the file FileOutputStream fos = null; try { // get the file from storage fos = context.getApplicationContext().openFileOutput("gfg.txt", MODE_PRIVATE); // write to the file at once fos.write(text.getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }}
Step 6: 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.appwidget.AppWidgetManager;import android.content.ComponentName;import android.widget.EditText;import android.widget.RemoteViews;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { EditText mEditText; // creating a new note StickyNote note = new StickyNote(); @Override protected void onCreate(android.os.Bundle savedInstanceState) { setContentView(R.layout.activity_main); super.onCreate(savedInstanceState); // getting the reference of the EditText mEditText = findViewById(R.id.editText); // retrieve the text from the saved file in // memory(if any) and set it to the edittext mEditText.setText(note.getStick(this)); } // function to update the // Widget(Sticky Note) every time // user saves the note public void updateWidget() { // the AppWidgetManager helps // us to manage all the // widgets from this app AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this); // the RemoteViews class allows us to inflate a // layout resource file hierarchy and provides some // basic operations for modifying the content of the // inflated hierarchy RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.new_app_widget); // by using ComponentName class we can get specific // application component and to identify the // component we pass the package name and the class // name inside of that package ComponentName thisWidget = new ComponentName(this, AppWidget.class); // update the text of the textview of the widget remoteViews.setTextViewText(R.id.appwidget_text, mEditText.getText().toString()); // finally us the AppWidgetManager instance to // update all the widgets appWidgetManager.updateAppWidget(thisWidget, remoteViews); } // this function saves // the current status // of the EditText public void saveButton(android.view.View v) { // update the content of file stored in the memory note.setStick(mEditText.getText().toString(), this); updateWidget(); Toast.makeText(this, "Updated Successfully!!", Toast.LENGTH_SHORT).show(); }}
Step 7: Layout file of our Widget
Since we only want our widget to hold the text, we just add the TextView in the layout resource file which would be updated from time to time.
XML
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/widgetLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FDD835" android:orientation="horizontal" android:padding="8dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/appwidget_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Text" android:textColor="#ffffff" android:textSize="20sp" tools:layout_editor_absoluteX="1dp" tools:layout_editor_absoluteY="1dp" /> </LinearLayout> </FrameLayout>
Output:
Github Project Link
For all the drawable resource files please refer to the following GitHub kink: https://github.com/raghavtilak/StickyNotes
You can add functionality to change the appearance of the Widget, like the text style, background color, transparency, width, etc.You can make some UI improvements.You can create multiple Sticky Notes, by saving the data into the database and fetching the same.Also, you can try adding some different views to the Widget.
You can add functionality to change the appearance of the Widget, like the text style, background color, transparency, width, etc.
You can make some UI improvements.
You can create multiple Sticky Notes, by saving the data into the database and fetching the same.
Also, you can try adding some different views to the Widget.
Android-Studio
Picked
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
Android Listview in Java with Example
How to Change the Background Color After Clicking the Button in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
|
[
{
"code": null,
"e": 25142,
"s": 25114,
"text": "\n15 Jun, 2021"
},
{
"code": null,
"e": 25589,
"s": 25142,
"text": "We as humans tend to forget some small but important things, and to resolve this we try to write those things up and paste them somewhere, we often have eyes on. And in this digital era, the things we are most likely to see are laptop, computer, or mobile phone screens. For this, we all have once used the Sticky Notes on Windows or Stickies on Mac, today in this article we would be discussing how we can build such an application for Android. "
},
{
"code": null,
"e": 26137,
"s": 25589,
"text": "Now, if we think of something that is sticky i.e. which sticks to the screen, in Android, the component which comes to our mind is the Home screen Widgets. Home Screen Widgets are the best interactive components that stick to the screen and can be resized in any manner. We would be creating an application that also has its own widget. We will first write some text in the main application and save that into a file in memory. At the very moment, we will update the widget with text that the user just saved. And Horray! Our Sticky note is ready."
},
{
"code": null,
"e": 26921,
"s": 26137,
"text": "Here one thing to note is that in Android views are also called Widgets, so to avoid confusion we use the term Home Screen Widgets. These are the broadcast receivers that provide interactive components. They usually show some sort of information and encourage the user to interact with it. For example, it may display time, weather, or emails and once you click on them the main application hosting them would start. Widgets use RemoteViews to build its user interface. With the same permissions as the original application, a RemoteView may be run by another method. As a consequence, the widget runs with the permissions of the application that created it. A Widget’s user interface is determined by a broadcast receiver. This receiver inflates its layout into a RemoteView object."
},
{
"code": null,
"e": 27760,
"s": 26921,
"text": "YouTubeGeeksforGeeks502K subscribersHow to Make a Sticky Notes Android App? | 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 / 52:29•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=qfzdZoEiZFQ\" 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": 27789,
"s": 27760,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 27951,
"s": 27789,
"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": 28001,
"s": 27951,
"text": "Step 2: Working with the AndroidManifest.xml file"
},
{
"code": null,
"e": 28174,
"s": 28001,
"text": "Add the user permissions for reading and write the file from storage. Also, in order to register the widget, we have to create a broadcast receiver with an intent filter. "
},
{
"code": null,
"e": 28178,
"s": 28174,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.notes\"> <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" /> <uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\" /> <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/Theme.Notes\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> <!-- To register a widget, you create a broadcast receiver with an intent filter for the android.appwidget.action.APPWIDGET_UPDATE action--> <receiver android:name=\".AppWidget\" android:label=\"StickyNotes\"> <intent-filter> <action android:name=\"android.appwidget.action.APPWIDGET_UPDATE\" /> </intent-filter> <!-- This metadata contains the configuration of your widget, the resource attribute contains the layout of your widget as it will be seen in the list of widgets --> <meta-data android:name=\"android.appwidget.provider\" android:resource=\"@xml/new_app_widget_info\" /> </receiver> </application> </manifest>",
"e": 29807,
"s": 28178,
"text": null
},
{
"code": null,
"e": 29835,
"s": 29807,
"text": "Step 3: Creating a Widget "
},
{
"code": null,
"e": 30079,
"s": 29835,
"text": "Follow the steps mentioned in this article Create a Basic Widget of an Android App to add the Widget to your project. The file new_app_widget_info.xml contains code that determines the look of our widget as it would appear in the Widgets list."
},
{
"code": null,
"e": 30120,
"s": 30079,
"text": "Step 4: Working with the AppWidget Class"
},
{
"code": null,
"e": 30352,
"s": 30120,
"text": "This class will be formed in the previous step. Go to the AppWidget.java file and refer to the following code. Below is the code for the AppWidget.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 30357,
"s": 30352,
"text": "Java"
},
{
"code": "import android.app.PendingIntent;import android.appwidget.AppWidgetManager;import android.appwidget.AppWidgetProvider;import android.content.Context;import android.content.Intent;import android.widget.RemoteViews; // Implementation of App Widget functionalitypublic class AppWidget extends AppWidgetProvider { // Create an Intent to launch activity @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // Perform this loop procedure for each App Widget // that belongs to this provider for (int appWidgetId : appWidgetIds) { // Create an Intent to launch MainActivity Intent launchActivity = new Intent(context, MainActivity.class); // Attaching a Pending Intent // to trigger it when // application is not alive PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, launchActivity, 0); // Get the layout for the App Widget and attach // an on-click listener to the button RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.new_app_widget); remoteViews.setOnClickPendingIntent(R.id.appwidget_text, pendingIntent); // Tell the AppWidgetManager to perform an // update on the current app widget appWidgetManager.updateAppWidget(appWidgetId, remoteViews); } }}",
"e": 31840,
"s": 30357,
"text": null
},
{
"code": null,
"e": 31878,
"s": 31840,
"text": "Step 5: Creating the StickyNote Class"
},
{
"code": null,
"e": 32193,
"s": 31878,
"text": "This is a helper class that provides the functionality of saving, updating, and retrieving the contents to and from the file. Go to the StickyNote .java file and refer to the following code. Below is the code for the StickyNote .java file. Comments are added inside the code to understand the code in more detail. "
},
{
"code": null,
"e": 32198,
"s": 32193,
"text": "Java"
},
{
"code": "import android.content.Context; import java.io.BufferedReader;import java.io.File;import java.io.FileOutputStream;import java.io.FileReader;import java.io.IOException; import static android.content.Context.MODE_PRIVATE; class StickyNote { // this function will return // the content from the text // file(if any) String getStick(Context context) { // get the file from path File fileEvents = new File(context.getFilesDir().getPath() + \"/gfg.txt\"); // create a StringBuilder to store the text from file StringBuilder text = new StringBuilder(); try { // use the BufferedReader // to Read the file // efficiently BufferedReader br = new BufferedReader(new FileReader(fileEvents)); String line; // read a single line at a time // append newline character after each line while ((line = br.readLine()) != null) { text.append(line); text.append('\\n'); } // close the BufferedReader br.close(); } catch (IOException e) { e.printStackTrace(); } // finally return the // string i.e. the retrieved data // from file return text.toString(); } // this function saves the new // content in the file if it // exists or will create a new one void setStick(String textToBeSaved, Context context) { String text = textToBeSaved; // create the FileOutputStream // to efficiently write the file FileOutputStream fos = null; try { // get the file from storage fos = context.getApplicationContext().openFileOutput(\"gfg.txt\", MODE_PRIVATE); // write to the file at once fos.write(text.getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }}",
"e": 34408,
"s": 32198,
"text": null
},
{
"code": null,
"e": 34456,
"s": 34408,
"text": "Step 6: Working with the MainActivity.java file"
},
{
"code": null,
"e": 34646,
"s": 34456,
"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": 34651,
"s": 34646,
"text": "Java"
},
{
"code": "import android.appwidget.AppWidgetManager;import android.content.ComponentName;import android.widget.EditText;import android.widget.RemoteViews;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { EditText mEditText; // creating a new note StickyNote note = new StickyNote(); @Override protected void onCreate(android.os.Bundle savedInstanceState) { setContentView(R.layout.activity_main); super.onCreate(savedInstanceState); // getting the reference of the EditText mEditText = findViewById(R.id.editText); // retrieve the text from the saved file in // memory(if any) and set it to the edittext mEditText.setText(note.getStick(this)); } // function to update the // Widget(Sticky Note) every time // user saves the note public void updateWidget() { // the AppWidgetManager helps // us to manage all the // widgets from this app AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this); // the RemoteViews class allows us to inflate a // layout resource file hierarchy and provides some // basic operations for modifying the content of the // inflated hierarchy RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.new_app_widget); // by using ComponentName class we can get specific // application component and to identify the // component we pass the package name and the class // name inside of that package ComponentName thisWidget = new ComponentName(this, AppWidget.class); // update the text of the textview of the widget remoteViews.setTextViewText(R.id.appwidget_text, mEditText.getText().toString()); // finally us the AppWidgetManager instance to // update all the widgets appWidgetManager.updateAppWidget(thisWidget, remoteViews); } // this function saves // the current status // of the EditText public void saveButton(android.view.View v) { // update the content of file stored in the memory note.setStick(mEditText.getText().toString(), this); updateWidget(); Toast.makeText(this, \"Updated Successfully!!\", Toast.LENGTH_SHORT).show(); }}",
"e": 37046,
"s": 34651,
"text": null
},
{
"code": null,
"e": 37080,
"s": 37046,
"text": "Step 7: Layout file of our Widget"
},
{
"code": null,
"e": 37224,
"s": 37080,
"text": "Since we only want our widget to hold the text, we just add the TextView in the layout resource file which would be updated from time to time. "
},
{
"code": null,
"e": 37228,
"s": 37224,
"text": "XML"
},
{
"code": "<FrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/widgetLayout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#FDD835\" android:orientation=\"horizontal\" android:padding=\"8dp\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <TextView android:id=\"@+id/appwidget_text\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Text\" android:textColor=\"#ffffff\" android:textSize=\"20sp\" tools:layout_editor_absoluteX=\"1dp\" tools:layout_editor_absoluteY=\"1dp\" /> </LinearLayout> </FrameLayout>",
"e": 38123,
"s": 37228,
"text": null
},
{
"code": null,
"e": 38131,
"s": 38123,
"text": "Output:"
},
{
"code": null,
"e": 38151,
"s": 38131,
"text": "Github Project Link"
},
{
"code": null,
"e": 38273,
"s": 38151,
"text": "For all the drawable resource files please refer to the following GitHub kink: https://github.com/raghavtilak/StickyNotes"
},
{
"code": null,
"e": 38595,
"s": 38273,
"text": "You can add functionality to change the appearance of the Widget, like the text style, background color, transparency, width, etc.You can make some UI improvements.You can create multiple Sticky Notes, by saving the data into the database and fetching the same.Also, you can try adding some different views to the Widget."
},
{
"code": null,
"e": 38726,
"s": 38595,
"text": "You can add functionality to change the appearance of the Widget, like the text style, background color, transparency, width, etc."
},
{
"code": null,
"e": 38761,
"s": 38726,
"text": "You can make some UI improvements."
},
{
"code": null,
"e": 38859,
"s": 38761,
"text": "You can create multiple Sticky Notes, by saving the data into the database and fetching the same."
},
{
"code": null,
"e": 38920,
"s": 38859,
"text": "Also, you can try adding some different views to the Widget."
},
{
"code": null,
"e": 38935,
"s": 38920,
"text": "Android-Studio"
},
{
"code": null,
"e": 38942,
"s": 38935,
"text": "Picked"
},
{
"code": null,
"e": 38950,
"s": 38942,
"text": "Android"
},
{
"code": null,
"e": 38955,
"s": 38950,
"text": "Java"
},
{
"code": null,
"e": 38960,
"s": 38955,
"text": "Java"
},
{
"code": null,
"e": 38968,
"s": 38960,
"text": "Android"
},
{
"code": null,
"e": 39066,
"s": 38968,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39105,
"s": 39066,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 39155,
"s": 39105,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 39197,
"s": 39155,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 39235,
"s": 39197,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 39308,
"s": 39235,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 39323,
"s": 39308,
"text": "Arrays in Java"
},
{
"code": null,
"e": 39367,
"s": 39323,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 39389,
"s": 39367,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 39425,
"s": 39389,
"text": "Arrays.sort() in Java with examples"
}
] |
MySQL Client Programs
|
There are 7 client programs, which are listed below −
mysql
mysql
mysqladmin
mysqladmin
mysqlcheck
mysqlcheck
mysqldump
mysqldump
mysqlimportmysqlpump
mysqlimportmysqlpump
mysqlshow
mysqlshow
mysqlslap
mysqlslap
Let us understand the MySQL client programs in brief −
The mysql is a simple SQL shell that has input line editing capabilities. It supports interactive and noninteractive usage. When it is used interactively, query results are presented in an ASCII-table format.
It can be invoked from the prompt of the user’s command interpreter. It has been demonstrated below −
shell> mysql db_name
The mysqladmin is a client that helps perform administrative operations. It can also be used to check the server's configuration and current status, to create and drop databases, and much more.
The mysqlcheck client performs table maintenance. It checks, repairs, optimizes, or analyses tables.
Every table is locked and hence unavailable to other sessions when it is being processed. But for check operations, the table is locked with a READ lock only.
The mysqldump client utility helps performs logical backups, thereby producing a set of SQL statements which can be executed to reproduce the original database object definitions and table data. It dumps one or more MySQL databases for backup or transfer to another SQL server.
The mysqldump command also generates output in CSV, other delimited text, or XML format. The utility mysqldump requires at least the SELECT privilege for dumped tables, SHOW VIEW for dumped views, TRIGGER for dumped triggers, LOCK TABLES if the --single-transaction option is not used, and PROCESS if --no-tablespaces option is not used.
The mysqlimport client comes with a command-line interface that helps with the LOAD DATA SQL statement. Most options to mysqlimport respond directly to clauses of LOAD DATA syntax
Let us understand the features of mysqlpump −
Parallel processing of databases, as well as that of objects within databases, thereby helping speed up the dump process.
Parallel processing of databases, as well as that of objects within databases, thereby helping speed up the dump process.
It provides better control over which databases and database objects (tables, stored programs, user accounts) need to be dumped
It provides better control over which databases and database objects (tables, stored programs, user accounts) need to be dumped
Dumping of user accounts as account-management statements (CREATE USER, GRANT)
instead of as inserts into the mysql system database
Dumping of user accounts as account-management statements (CREATE USER, GRANT)
instead of as inserts into the mysql system database
The mysqlshow client can be used to see what databases exist, their tables, or a table's columns or indexes. It provides a command-line interface for several SQL SHOW statements.
The mysqlslap utility is a diagnostic program that has designed to emulate client load for a MySQL server and report the timing of every stage. It works as though multiple clients are accessing the server.
|
[
{
"code": null,
"e": 1116,
"s": 1062,
"text": "There are 7 client programs, which are listed below −"
},
{
"code": null,
"e": 1122,
"s": 1116,
"text": "mysql"
},
{
"code": null,
"e": 1128,
"s": 1122,
"text": "mysql"
},
{
"code": null,
"e": 1139,
"s": 1128,
"text": "mysqladmin"
},
{
"code": null,
"e": 1150,
"s": 1139,
"text": "mysqladmin"
},
{
"code": null,
"e": 1161,
"s": 1150,
"text": "mysqlcheck"
},
{
"code": null,
"e": 1172,
"s": 1161,
"text": "mysqlcheck"
},
{
"code": null,
"e": 1182,
"s": 1172,
"text": "mysqldump"
},
{
"code": null,
"e": 1192,
"s": 1182,
"text": "mysqldump"
},
{
"code": null,
"e": 1213,
"s": 1192,
"text": "mysqlimportmysqlpump"
},
{
"code": null,
"e": 1234,
"s": 1213,
"text": "mysqlimportmysqlpump"
},
{
"code": null,
"e": 1244,
"s": 1234,
"text": "mysqlshow"
},
{
"code": null,
"e": 1254,
"s": 1244,
"text": "mysqlshow"
},
{
"code": null,
"e": 1264,
"s": 1254,
"text": "mysqlslap"
},
{
"code": null,
"e": 1274,
"s": 1264,
"text": "mysqlslap"
},
{
"code": null,
"e": 1329,
"s": 1274,
"text": "Let us understand the MySQL client programs in brief −"
},
{
"code": null,
"e": 1538,
"s": 1329,
"text": "The mysql is a simple SQL shell that has input line editing capabilities. It supports interactive and noninteractive usage. When it is used interactively, query results are presented in an ASCII-table format."
},
{
"code": null,
"e": 1640,
"s": 1538,
"text": "It can be invoked from the prompt of the user’s command interpreter. It has been demonstrated below −"
},
{
"code": null,
"e": 1661,
"s": 1640,
"text": "shell> mysql db_name"
},
{
"code": null,
"e": 1855,
"s": 1661,
"text": "The mysqladmin is a client that helps perform administrative operations. It can also be used to check the server's configuration and current status, to create and drop databases, and much more."
},
{
"code": null,
"e": 1956,
"s": 1855,
"text": "The mysqlcheck client performs table maintenance. It checks, repairs, optimizes, or analyses tables."
},
{
"code": null,
"e": 2115,
"s": 1956,
"text": "Every table is locked and hence unavailable to other sessions when it is being processed. But for check operations, the table is locked with a READ lock only."
},
{
"code": null,
"e": 2393,
"s": 2115,
"text": "The mysqldump client utility helps performs logical backups, thereby producing a set of SQL statements which can be executed to reproduce the original database object definitions and table data. It dumps one or more MySQL databases for backup or transfer to another SQL server."
},
{
"code": null,
"e": 2731,
"s": 2393,
"text": "The mysqldump command also generates output in CSV, other delimited text, or XML format. The utility mysqldump requires at least the SELECT privilege for dumped tables, SHOW VIEW for dumped views, TRIGGER for dumped triggers, LOCK TABLES if the --single-transaction option is not used, and PROCESS if --no-tablespaces option is not used."
},
{
"code": null,
"e": 2911,
"s": 2731,
"text": "The mysqlimport client comes with a command-line interface that helps with the LOAD DATA SQL statement. Most options to mysqlimport respond directly to clauses of LOAD DATA syntax"
},
{
"code": null,
"e": 2957,
"s": 2911,
"text": "Let us understand the features of mysqlpump −"
},
{
"code": null,
"e": 3079,
"s": 2957,
"text": "Parallel processing of databases, as well as that of objects within databases, thereby helping speed up the dump process."
},
{
"code": null,
"e": 3201,
"s": 3079,
"text": "Parallel processing of databases, as well as that of objects within databases, thereby helping speed up the dump process."
},
{
"code": null,
"e": 3329,
"s": 3201,
"text": "It provides better control over which databases and database objects (tables, stored programs, user accounts) need to be dumped"
},
{
"code": null,
"e": 3457,
"s": 3329,
"text": "It provides better control over which databases and database objects (tables, stored programs, user accounts) need to be dumped"
},
{
"code": null,
"e": 3589,
"s": 3457,
"text": "Dumping of user accounts as account-management statements (CREATE USER, GRANT)\ninstead of as inserts into the mysql system database"
},
{
"code": null,
"e": 3721,
"s": 3589,
"text": "Dumping of user accounts as account-management statements (CREATE USER, GRANT)\ninstead of as inserts into the mysql system database"
},
{
"code": null,
"e": 3900,
"s": 3721,
"text": "The mysqlshow client can be used to see what databases exist, their tables, or a table's columns or indexes. It provides a command-line interface for several SQL SHOW statements."
},
{
"code": null,
"e": 4106,
"s": 3900,
"text": "The mysqlslap utility is a diagnostic program that has designed to emulate client load for a MySQL server and report the timing of every stage. It works as though multiple clients are accessing the server."
}
] |
PostgreSQL – DATE_TRUNC Function
|
01 Feb, 2021
In PostgreSQL, DATE_TRUNC Function is used to truncate a timestamp type or interval type with specific and high level of precision.
Syntax: date_trunc('datepart', field)
The datepart argument in the above syntax is used to truncate one of the field,below listed field type:
millennium
century
decade
year
quarter
month
week
day
hour
minute
second
milliseconds
microseconds
The field argument holds either a TIMESTAMP type value or an INTERVAL type value to truncate. It can also be an expression that returns one of the above mentioned type. The date_trunc function generally returns a TIMESTAMP type value or an INTERVAL type value.
Example 1:
The following statement truncates a TIMESTAMP value to hour date part:
SELECT DATE_TRUNC('hour', TIMESTAMP '2020-03-17 02:09:30');
Output:
Example 2:
The below query counts the number of rentals by staff per year from the rental table of the sample database, ie, dvdrental:
SELECT
staff_id,
date_trunc('year', rental_date) y,
COUNT (rental_id) rental
FROM
rental
GROUP BY
staff_id, y
ORDER BY
staff_id
Output:
PostgreSQL-Date-function
PostgreSQL-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Feb, 2021"
},
{
"code": null,
"e": 160,
"s": 28,
"text": "In PostgreSQL, DATE_TRUNC Function is used to truncate a timestamp type or interval type with specific and high level of precision."
},
{
"code": null,
"e": 199,
"s": 160,
"text": "Syntax: date_trunc('datepart', field)\n"
},
{
"code": null,
"e": 303,
"s": 199,
"text": "The datepart argument in the above syntax is used to truncate one of the field,below listed field type:"
},
{
"code": null,
"e": 314,
"s": 303,
"text": "millennium"
},
{
"code": null,
"e": 322,
"s": 314,
"text": "century"
},
{
"code": null,
"e": 329,
"s": 322,
"text": "decade"
},
{
"code": null,
"e": 334,
"s": 329,
"text": "year"
},
{
"code": null,
"e": 342,
"s": 334,
"text": "quarter"
},
{
"code": null,
"e": 348,
"s": 342,
"text": "month"
},
{
"code": null,
"e": 353,
"s": 348,
"text": "week"
},
{
"code": null,
"e": 357,
"s": 353,
"text": "day"
},
{
"code": null,
"e": 362,
"s": 357,
"text": "hour"
},
{
"code": null,
"e": 369,
"s": 362,
"text": "minute"
},
{
"code": null,
"e": 376,
"s": 369,
"text": "second"
},
{
"code": null,
"e": 389,
"s": 376,
"text": "milliseconds"
},
{
"code": null,
"e": 402,
"s": 389,
"text": "microseconds"
},
{
"code": null,
"e": 663,
"s": 402,
"text": "The field argument holds either a TIMESTAMP type value or an INTERVAL type value to truncate. It can also be an expression that returns one of the above mentioned type. The date_trunc function generally returns a TIMESTAMP type value or an INTERVAL type value."
},
{
"code": null,
"e": 674,
"s": 663,
"text": "Example 1:"
},
{
"code": null,
"e": 745,
"s": 674,
"text": "The following statement truncates a TIMESTAMP value to hour date part:"
},
{
"code": null,
"e": 806,
"s": 745,
"text": "SELECT DATE_TRUNC('hour', TIMESTAMP '2020-03-17 02:09:30');\n"
},
{
"code": null,
"e": 814,
"s": 806,
"text": "Output:"
},
{
"code": null,
"e": 825,
"s": 814,
"text": "Example 2:"
},
{
"code": null,
"e": 949,
"s": 825,
"text": "The below query counts the number of rentals by staff per year from the rental table of the sample database, ie, dvdrental:"
},
{
"code": null,
"e": 1102,
"s": 949,
"text": "SELECT\n staff_id,\n date_trunc('year', rental_date) y,\n COUNT (rental_id) rental\nFROM\n rental\nGROUP BY\n staff_id, y\nORDER BY\n staff_id\n"
},
{
"code": null,
"e": 1110,
"s": 1102,
"text": "Output:"
},
{
"code": null,
"e": 1135,
"s": 1110,
"text": "PostgreSQL-Date-function"
},
{
"code": null,
"e": 1155,
"s": 1135,
"text": "PostgreSQL-function"
},
{
"code": null,
"e": 1166,
"s": 1155,
"text": "PostgreSQL"
}
] |
Python | Remove punctuation from string
|
30 Jun, 2021
Many times while working with Python strings, we have a problem in which we need to remove certain characters from strings. This can have application in data preprocessing in the Data Science domain and also in day-day programming. Let’s discuss certain ways in which we can perform this task.
Method #1 : Using loop + punctuation string
This is the brute way in which this task can be performed. In this, we check for the punctuations using a raw string which contain punctuations and then we construct string removing those punctuations.
Python3
# Python3 code to demonstrate working of# Removing punctuations in string# Using loop + punctuation string # initializing stringtest_str = "Gfg, is best : for ! Geeks ;" # printing original stringprint("The original string is : " + test_str) # initializing punctuations stringpunc = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' # Removing punctuations in string# Using loop + punctuation stringfor ele in test_str: if ele in punc: test_str = test_str.replace(ele, "") # printing resultprint("The string after punctuation filter : " + test_str)
The original string is : Gfg, is best : for ! Geeks ;
The string after punctuation filter : Gfg is best for Geeks
Method #2 : Using regex
The part of replacing with punctuation can also be performed using regex. In this, we replace all punctuation with an empty string using a certain regex.
Python3
# Python3 code to demonstrate working of# Removing punctuations in string# Using regeximport re # initializing stringtest_str = "Gfg, is best : for ! Geeks ;" # printing original stringprint("The original string is : " + test_str) # Removing punctuations in string# Using regexres = re.sub(r'[^\w\s]', '', test_str) # printing resultprint("The string after punctuation filter : " + res)
The original string is : Gfg, is best : for ! Geeks ;
The string after punctuation filter : Gfg is best for Geeks
amiableabhishekkumar
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 348,
"s": 53,
"text": "Many times while working with Python strings, we have a problem in which we need to remove certain characters from strings. This can have application in data preprocessing in the Data Science domain and also in day-day programming. Let’s discuss certain ways in which we can perform this task. "
},
{
"code": null,
"e": 393,
"s": 348,
"text": "Method #1 : Using loop + punctuation string "
},
{
"code": null,
"e": 596,
"s": 393,
"text": "This is the brute way in which this task can be performed. In this, we check for the punctuations using a raw string which contain punctuations and then we construct string removing those punctuations. "
},
{
"code": null,
"e": 604,
"s": 596,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Removing punctuations in string# Using loop + punctuation string # initializing stringtest_str = \"Gfg, is best : for ! Geeks ;\" # printing original stringprint(\"The original string is : \" + test_str) # initializing punctuations stringpunc = '''!()-[]{};:'\"\\,<>./?@#$%^&*_~''' # Removing punctuations in string# Using loop + punctuation stringfor ele in test_str: if ele in punc: test_str = test_str.replace(ele, \"\") # printing resultprint(\"The string after punctuation filter : \" + test_str)",
"e": 1148,
"s": 604,
"text": null
},
{
"code": null,
"e": 1265,
"s": 1148,
"text": "The original string is : Gfg, is best : for ! Geeks ;\nThe string after punctuation filter : Gfg is best for Geeks "
},
{
"code": null,
"e": 1293,
"s": 1267,
"text": " Method #2 : Using regex "
},
{
"code": null,
"e": 1448,
"s": 1293,
"text": "The part of replacing with punctuation can also be performed using regex. In this, we replace all punctuation with an empty string using a certain regex. "
},
{
"code": null,
"e": 1456,
"s": 1448,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Removing punctuations in string# Using regeximport re # initializing stringtest_str = \"Gfg, is best : for ! Geeks ;\" # printing original stringprint(\"The original string is : \" + test_str) # Removing punctuations in string# Using regexres = re.sub(r'[^\\w\\s]', '', test_str) # printing resultprint(\"The string after punctuation filter : \" + res)",
"e": 1843,
"s": 1456,
"text": null
},
{
"code": null,
"e": 1960,
"s": 1843,
"text": "The original string is : Gfg, is best : for ! Geeks ;\nThe string after punctuation filter : Gfg is best for Geeks "
},
{
"code": null,
"e": 1983,
"s": 1962,
"text": "amiableabhishekkumar"
},
{
"code": null,
"e": 2006,
"s": 1983,
"text": "Python string-programs"
},
{
"code": null,
"e": 2013,
"s": 2006,
"text": "Python"
},
{
"code": null,
"e": 2029,
"s": 2013,
"text": "Python Programs"
},
{
"code": null,
"e": 2127,
"s": 2029,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2145,
"s": 2127,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2187,
"s": 2145,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2209,
"s": 2187,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2241,
"s": 2209,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2267,
"s": 2241,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2289,
"s": 2267,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2328,
"s": 2289,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2366,
"s": 2328,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2403,
"s": 2366,
"text": "Python Program for Fibonacci numbers"
}
] |
How to count unique values inside a list
|
25 Jan, 2022
There are several methods for finding or counting unique items inside a list in Python. Here we’ll discuss 3 methods.
Method 1:
The first method is the brute force approach. This method is not very much efficient as it takes more time and space. In this method, we take an empty array and a count variable(set to be zero). We traverse from the start and check the items. If the item is not in the empty list(as it has taken empty) then we will add it to the empty list and increase the counter by 1. While traveling if the item is in the taken list(empty list) we will not count it.
Example:
Python3
# taking an input listinput_list = [1, 2, 2, 5, 8, 4, 4, 8] # taking an input listl1 = [] # taking an countercount = 0 # traversing the arrayfor item in input_list: if item not in l1: count += 1 l1.append(item) # printing the outputprint("No of unique items are:", count)
Output:
No of unique items are: 5
Method 2:
In this method, we will use a function name Counter. The module collections have this function. Using the Counter function we will create a dictionary. The keys of the dictionary will be the unique items and the values will be the number of that key present in the list. We will create a list using the keys, the length of the list will be our answer.
Python3
# importing Counter modulefrom collections import Counter input_list = [1, 2, 2, 5, 8, 4, 4, 8] # creating a list with the keysitems = Counter(input_list).keys()print("No of unique items in the list are:", len(items))
Output:
No of unique items in the list are: 5
If we print the length of the dictionary created using Counter will also give us the result. But this method is more understandable.
Method 3:
In this method, we will convert our list to set. As sets don’t contain any duplicate items then printing the length of the set will give us the total number of unique items.
Python3
input_list = [1, 2, 2, 5, 8, 4, 4, 8] # converting our list to setnew_set = set(input_list)print("No of unique items in the list are:", len(new_set))
Output:
No of unique items in the list are: 5
sagartomar9927
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n25 Jan, 2022"
},
{
"code": null,
"e": 171,
"s": 53,
"text": "There are several methods for finding or counting unique items inside a list in Python. Here we’ll discuss 3 methods."
},
{
"code": null,
"e": 182,
"s": 171,
"text": "Method 1: "
},
{
"code": null,
"e": 638,
"s": 182,
"text": "The first method is the brute force approach. This method is not very much efficient as it takes more time and space. In this method, we take an empty array and a count variable(set to be zero). We traverse from the start and check the items. If the item is not in the empty list(as it has taken empty) then we will add it to the empty list and increase the counter by 1. While traveling if the item is in the taken list(empty list) we will not count it. "
},
{
"code": null,
"e": 649,
"s": 638,
"text": "Example: "
},
{
"code": null,
"e": 657,
"s": 649,
"text": "Python3"
},
{
"code": "# taking an input listinput_list = [1, 2, 2, 5, 8, 4, 4, 8] # taking an input listl1 = [] # taking an countercount = 0 # traversing the arrayfor item in input_list: if item not in l1: count += 1 l1.append(item) # printing the outputprint(\"No of unique items are:\", count)",
"e": 946,
"s": 657,
"text": null
},
{
"code": null,
"e": 954,
"s": 946,
"text": "Output:"
},
{
"code": null,
"e": 980,
"s": 954,
"text": "No of unique items are: 5"
},
{
"code": null,
"e": 990,
"s": 980,
"text": "Method 2:"
},
{
"code": null,
"e": 1343,
"s": 990,
"text": "In this method, we will use a function name Counter. The module collections have this function. Using the Counter function we will create a dictionary. The keys of the dictionary will be the unique items and the values will be the number of that key present in the list. We will create a list using the keys, the length of the list will be our answer."
},
{
"code": null,
"e": 1351,
"s": 1343,
"text": "Python3"
},
{
"code": "# importing Counter modulefrom collections import Counter input_list = [1, 2, 2, 5, 8, 4, 4, 8] # creating a list with the keysitems = Counter(input_list).keys()print(\"No of unique items in the list are:\", len(items))",
"e": 1570,
"s": 1351,
"text": null
},
{
"code": null,
"e": 1578,
"s": 1570,
"text": "Output:"
},
{
"code": null,
"e": 1616,
"s": 1578,
"text": "No of unique items in the list are: 5"
},
{
"code": null,
"e": 1749,
"s": 1616,
"text": "If we print the length of the dictionary created using Counter will also give us the result. But this method is more understandable."
},
{
"code": null,
"e": 1759,
"s": 1749,
"text": "Method 3:"
},
{
"code": null,
"e": 1933,
"s": 1759,
"text": "In this method, we will convert our list to set. As sets don’t contain any duplicate items then printing the length of the set will give us the total number of unique items."
},
{
"code": null,
"e": 1941,
"s": 1933,
"text": "Python3"
},
{
"code": "input_list = [1, 2, 2, 5, 8, 4, 4, 8] # converting our list to setnew_set = set(input_list)print(\"No of unique items in the list are:\", len(new_set))",
"e": 2091,
"s": 1941,
"text": null
},
{
"code": null,
"e": 2099,
"s": 2091,
"text": "Output:"
},
{
"code": null,
"e": 2137,
"s": 2099,
"text": "No of unique items in the list are: 5"
},
{
"code": null,
"e": 2152,
"s": 2137,
"text": "sagartomar9927"
},
{
"code": null,
"e": 2173,
"s": 2152,
"text": "Python list-programs"
},
{
"code": null,
"e": 2185,
"s": 2173,
"text": "python-list"
},
{
"code": null,
"e": 2192,
"s": 2185,
"text": "Python"
},
{
"code": null,
"e": 2204,
"s": 2192,
"text": "python-list"
}
] |
Random Walk (Implementation in Python)
|
06 Nov, 2021
Introduction A random walk is a mathematical object, known as a stochastic or random process, that describes a path that consists of a succession of random steps on some mathematical space such as the integers. An elementary example of a random walk is the random walk on the integer number line, which starts at 0 and at each step moves +1 or -1 with equal probability. Other examples include the path traced by a molecule as it travels in a liquid or a gas, the search path of a foraging animal, the price of a fluctuating stock and the financial status of a gambler can all be approximated by random walk models, even though they may not be truly random in reality. As illustrated by those examples, random walks have applications to many scientific fields including ecology, psychology, computer science, physics, chemistry, biology as well as economics. Random walks explain the observed behaviors of many processes in these fields and thus serve as a fundamental model for the recorded stochastic activity. As a more mathematical application, the value of pi can be approximated by the usage of random walk in the agent-based modeling environment.
Enough with the boring theory. Let’s take a break while getting some knowledge of the code. So, to code out the random walk we will basically require some libraries in python some to do maths, and some others to plot the curve.
Libraries Required
matplotlib It’s an external library that helps you to plot the curve. To install this library type the following code in your cmd.
pip install matplotlib
It would be enough to get you through the installation.
numpy It’s also an external library in python it helps you to work with arrays and matrices. To install the library type the following code in cmd.
pip install numpy
random It’s a built-in library of python we will use to generate random points.
One-dimensional random walk An elementary example of a random walk is the random walk on the integer number line, which starts at 0 and at each step moves +1 or ? 1 with equal probability.
So let’s try to implement the 1-D random walk in python.
Python3
# Python code for 1-D random walk.import randomimport numpy as npimport matplotlib.pyplot as plt # Probability to move up or downprob = [0.05, 0.95] # statically defining the starting positionstart = 2 positions = [start] # creating the random pointsrr = np.random.random(1000)downp = rr < prob[0]upp = rr > prob[1] for idownp, iupp in zip(downp, upp): down = idownp and positions[-1] > 1 up = iupp and positions[-1] < 4 positions.append(positions[-1] - down + up) # plotting down the graph of the random walk in 1Dplt.plot(positions)plt.show()
Output:
Higher dimensions In higher dimensions, the set of randomly walked points has interesting geometric properties. In fact, one gets a discrete fractal, that is, a set that exhibits stochastic self-similarity on large scales. On small scales, one can observe “jaggedness” resulting from the grid on which the walk is performed. Two books of Lawler referenced below are good sources on this topic. The trajectory of a random walk is the collection of points visited, considered as a set with disregard to when the walk arrived at the point. In one dimension, the trajectory is simply all points between the minimum height and the maximum height the walk achieved (both are, on average, on the order of ? n).
Let’s try to create a random walk in 2D.
Python3
# Python code for 2D random walk.import numpyimport pylabimport random # defining the number of stepsn = 100000 #creating two array for containing x and y coordinate#of size equals to the number of size and filled up with 0'sx = numpy.zeros(n)y = numpy.zeros(n) # filling the coordinates with random variablesfor i in range(1, n): val = random.randint(1, 4) if val == 1: x[i] = x[i - 1] + 1 y[i] = y[i - 1] elif val == 2: x[i] = x[i - 1] - 1 y[i] = y[i - 1] elif val == 3: x[i] = x[i - 1] y[i] = y[i - 1] + 1 else: x[i] = x[i - 1] y[i] = y[i - 1] - 1 # plotting stuff:pylab.title("Random Walk ($n = " + str(n) + "$ steps)")pylab.plot(x, y)pylab.savefig("rand_walk"+str(n)+".png",bbox_inches="tight",dpi=600)pylab.show()
Output:
Applications
In computer networks, random walks can model the number of transmission packets buffered at a server.In population genetics, a random walk describes the statistical properties of genetic drift.In image segmentation, random walks are used to determine the labels (i.e., “object” or “background”) to associate with each pixel.In brain research, random walks and reinforced random walks are used to model cascades of neuron firing in the brain.Random walks have also been used to sample massive online graphs such as online social networks.
In computer networks, random walks can model the number of transmission packets buffered at a server.
In population genetics, a random walk describes the statistical properties of genetic drift.
In image segmentation, random walks are used to determine the labels (i.e., “object” or “background”) to associate with each pixel.
In brain research, random walks and reinforced random walks are used to model cascades of neuron firing in the brain.
Random walks have also been used to sample massive online graphs such as online social networks.
References 1. Wikipedia – Random Walk 2. Stackoverflow – Random Walk 1D 3. matplotlib documentationThis article is contributed by Subhajit Saha. 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.
reenadevi98412200
Python
Randomized
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Nov, 2021"
},
{
"code": null,
"e": 1208,
"s": 54,
"text": "Introduction A random walk is a mathematical object, known as a stochastic or random process, that describes a path that consists of a succession of random steps on some mathematical space such as the integers. An elementary example of a random walk is the random walk on the integer number line, which starts at 0 and at each step moves +1 or -1 with equal probability. Other examples include the path traced by a molecule as it travels in a liquid or a gas, the search path of a foraging animal, the price of a fluctuating stock and the financial status of a gambler can all be approximated by random walk models, even though they may not be truly random in reality. As illustrated by those examples, random walks have applications to many scientific fields including ecology, psychology, computer science, physics, chemistry, biology as well as economics. Random walks explain the observed behaviors of many processes in these fields and thus serve as a fundamental model for the recorded stochastic activity. As a more mathematical application, the value of pi can be approximated by the usage of random walk in the agent-based modeling environment."
},
{
"code": null,
"e": 1436,
"s": 1208,
"text": "Enough with the boring theory. Let’s take a break while getting some knowledge of the code. So, to code out the random walk we will basically require some libraries in python some to do maths, and some others to plot the curve."
},
{
"code": null,
"e": 1455,
"s": 1436,
"text": "Libraries Required"
},
{
"code": null,
"e": 1587,
"s": 1455,
"text": "matplotlib It’s an external library that helps you to plot the curve. To install this library type the following code in your cmd. "
},
{
"code": null,
"e": 1610,
"s": 1587,
"text": "pip install matplotlib"
},
{
"code": null,
"e": 1666,
"s": 1610,
"text": "It would be enough to get you through the installation."
},
{
"code": null,
"e": 1815,
"s": 1666,
"text": "numpy It’s also an external library in python it helps you to work with arrays and matrices. To install the library type the following code in cmd. "
},
{
"code": null,
"e": 1833,
"s": 1815,
"text": "pip install numpy"
},
{
"code": null,
"e": 1913,
"s": 1833,
"text": "random It’s a built-in library of python we will use to generate random points."
},
{
"code": null,
"e": 2103,
"s": 1913,
"text": "One-dimensional random walk An elementary example of a random walk is the random walk on the integer number line, which starts at 0 and at each step moves +1 or ? 1 with equal probability. "
},
{
"code": null,
"e": 2160,
"s": 2103,
"text": "So let’s try to implement the 1-D random walk in python."
},
{
"code": null,
"e": 2168,
"s": 2160,
"text": "Python3"
},
{
"code": "# Python code for 1-D random walk.import randomimport numpy as npimport matplotlib.pyplot as plt # Probability to move up or downprob = [0.05, 0.95] # statically defining the starting positionstart = 2 positions = [start] # creating the random pointsrr = np.random.random(1000)downp = rr < prob[0]upp = rr > prob[1] for idownp, iupp in zip(downp, upp): down = idownp and positions[-1] > 1 up = iupp and positions[-1] < 4 positions.append(positions[-1] - down + up) # plotting down the graph of the random walk in 1Dplt.plot(positions)plt.show()",
"e": 2724,
"s": 2168,
"text": null
},
{
"code": null,
"e": 2733,
"s": 2724,
"text": "Output: "
},
{
"code": null,
"e": 3438,
"s": 2733,
"text": "Higher dimensions In higher dimensions, the set of randomly walked points has interesting geometric properties. In fact, one gets a discrete fractal, that is, a set that exhibits stochastic self-similarity on large scales. On small scales, one can observe “jaggedness” resulting from the grid on which the walk is performed. Two books of Lawler referenced below are good sources on this topic. The trajectory of a random walk is the collection of points visited, considered as a set with disregard to when the walk arrived at the point. In one dimension, the trajectory is simply all points between the minimum height and the maximum height the walk achieved (both are, on average, on the order of ? n). "
},
{
"code": null,
"e": 3480,
"s": 3438,
"text": "Let’s try to create a random walk in 2D. "
},
{
"code": null,
"e": 3488,
"s": 3480,
"text": "Python3"
},
{
"code": "# Python code for 2D random walk.import numpyimport pylabimport random # defining the number of stepsn = 100000 #creating two array for containing x and y coordinate#of size equals to the number of size and filled up with 0'sx = numpy.zeros(n)y = numpy.zeros(n) # filling the coordinates with random variablesfor i in range(1, n): val = random.randint(1, 4) if val == 1: x[i] = x[i - 1] + 1 y[i] = y[i - 1] elif val == 2: x[i] = x[i - 1] - 1 y[i] = y[i - 1] elif val == 3: x[i] = x[i - 1] y[i] = y[i - 1] + 1 else: x[i] = x[i - 1] y[i] = y[i - 1] - 1 # plotting stuff:pylab.title(\"Random Walk ($n = \" + str(n) + \"$ steps)\")pylab.plot(x, y)pylab.savefig(\"rand_walk\"+str(n)+\".png\",bbox_inches=\"tight\",dpi=600)pylab.show()",
"e": 4284,
"s": 3488,
"text": null
},
{
"code": null,
"e": 4293,
"s": 4284,
"text": "Output: "
},
{
"code": null,
"e": 4307,
"s": 4293,
"text": "Applications "
},
{
"code": null,
"e": 4845,
"s": 4307,
"text": "In computer networks, random walks can model the number of transmission packets buffered at a server.In population genetics, a random walk describes the statistical properties of genetic drift.In image segmentation, random walks are used to determine the labels (i.e., “object” or “background”) to associate with each pixel.In brain research, random walks and reinforced random walks are used to model cascades of neuron firing in the brain.Random walks have also been used to sample massive online graphs such as online social networks."
},
{
"code": null,
"e": 4947,
"s": 4845,
"text": "In computer networks, random walks can model the number of transmission packets buffered at a server."
},
{
"code": null,
"e": 5040,
"s": 4947,
"text": "In population genetics, a random walk describes the statistical properties of genetic drift."
},
{
"code": null,
"e": 5172,
"s": 5040,
"text": "In image segmentation, random walks are used to determine the labels (i.e., “object” or “background”) to associate with each pixel."
},
{
"code": null,
"e": 5290,
"s": 5172,
"text": "In brain research, random walks and reinforced random walks are used to model cascades of neuron firing in the brain."
},
{
"code": null,
"e": 5387,
"s": 5290,
"text": "Random walks have also been used to sample massive online graphs such as online social networks."
},
{
"code": null,
"e": 5908,
"s": 5387,
"text": "References 1. Wikipedia – Random Walk 2. Stackoverflow – Random Walk 1D 3. matplotlib documentationThis article is contributed by Subhajit Saha. 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": 5926,
"s": 5908,
"text": "reenadevi98412200"
},
{
"code": null,
"e": 5933,
"s": 5926,
"text": "Python"
},
{
"code": null,
"e": 5944,
"s": 5933,
"text": "Randomized"
}
] |
Search for an element in a Mountain Array
|
31 May, 2021
Given a mountain array arr[] and an integer X, the task is to find the smallest index of X in the given array. If no such index is found, print -1.
Examples:
Input: arr = {1, 2, 3, 4, 5, 3, 1}, X = 3Output: 2Explanation: The smallest index of X(= 3) in the array is 2. Therefore, the required output is 2.
Input: arr[] = {0, 1, 2, 4, 2, 1}, X = 3Output: -1Explanation: Since 3 does not exist in the array, the required output is -1.
Naive Approach: The simplest approach is to traverse the array and check if the element in the current index is equal to X or not. If found to be true, then print that index.
Time Complexity: O(N)Auxiliary Space: O(1)
Efficient Approach: The optimal idea to solve this problem is to use Binary Search. Follow the steps below to solve this problem:
Find the peak index from the mountain array.
Based on the obtained peak index, the partition array into two parts. It searches for its left side first using Binary search, followed by its right. It is known that the left side of the peak element is sorted in ascending order and the right side is sorted in descending order.
Search in the left mountain array.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// CPP program for the above approach#include<bits/stdc++.h>using namespace std; // Function to find the index of// the peak element in the arrayint findPeak(vector<int> arr){ // Stores left most index in which // the peak element can be found int left = 0; // Stores right most index in which // the peak element can be found int right = arr.size() - 1; while (left < right) { // Stores mid of left and right int mid = left + (right - left) / 2; // If element at mid is less than // element at (mid + 1) if (arr[mid] < arr[mid + 1]) { // Update left left = mid + 1; } else { // Update right right = mid; } } return left;} // Function to perform binary search in an// a subarray if elements of the subarray// are in an ascending orderint BS(int X, int left, int right, vector<int> arr){ while (left <= right) { // Stores mid of left and right int mid = left + (right - left) / 2; // If X found at mid if (arr[mid] == X) { return mid; } // If X is greater than mid else if (X > arr[mid]) { // Update left left = mid + 1; } else { // Update right right = mid - 1; } } return -1;} // Function to perform binary search in an// a subarray if elements of the subarray// are in an ascending orderint reverseBS(int X, int left, int right, vector<int> arr){ while (left <= right) { // Stores mid of left and right int mid = left + (right - left) / 2; // If X found at mid if (arr[mid] == X) { return mid; } else if (X > arr[mid]) { // Update right right = mid - 1; } else { // Update left left = mid + 1; } } return -1;} // Function to find the smallest index of Xvoid findInMA(int X, vector<int> mountainArr){ // Stores index of peak element in array int peakIndex = findPeak(mountainArr); // Stores index of X in the array int res = -1; // If X greater than or equal to first element // of array and less than the peak element if (X >= mountainArr[0] && X <= mountainArr[peakIndex]) { // Update res res = BS(X, 0, peakIndex, mountainArr); } // If element not found on // left side of peak element if (res == -1) { // Update res res = reverseBS(X, peakIndex + 1, mountainArr.size() - 1, mountainArr); } // Print res cout<<res<<endl;} // Driver Codeint main(){ // Given X int X = 3; // Given array vector<int> list{1, 2, 3, 4, 5, 3, 1}; // Function Call findInMA(X, list);} // This code is contributed by bgangwar59.
// Java program for the above approach import java.io.*;import java.util.*; class GFG { // Function to find the index of // the peak element in the array public static int findPeak( ArrayList<Integer> arr) { // Stores left most index in which // the peak element can be found int left = 0; // Stores right most index in which // the peak element can be found int right = arr.size() - 1; while (left < right) { // Stores mid of left and right int mid = left + (right - left) / 2; // If element at mid is less than // element at (mid + 1) if (arr.get(mid) < arr.get(mid + 1)) { // Update left left = mid + 1; } else { // Update right right = mid; } } return left; } // Function to perform binary search in an // a subarray if elements of the subarray // are in an ascending order static int BS(int X, int left, int right, ArrayList<Integer> arr) { while (left <= right) { // Stores mid of left and right int mid = left + (right - left) / 2; // If X found at mid if (arr.get(mid) == X) { return mid; } // If X is greater than mid else if (X > arr.get(mid)) { // Update left left = mid + 1; } else { // Update right right = mid - 1; } } return -1; } // Function to perform binary search in an // a subarray if elements of the subarray // are in an ascending order static int reverseBS(int X, int left, int right, ArrayList<Integer> arr) { while (left <= right) { // Stores mid of left and right int mid = left + (right - left) / 2; // If X found at mid if (arr.get(mid) == X) { return mid; } else if (X > arr.get(mid)) { // Update right right = mid - 1; } else { // Update left left = mid + 1; } } return -1; } // Function to find the smallest index of X static void findInMA(int X, ArrayList<Integer> mountainArr) { // Stores index of peak element in array int peakIndex = findPeak(mountainArr); // Stores index of X in the array int res = -1; // If X greater than or equal to first element // of array and less than the peak element if (X >= mountainArr.get(0) && X <= mountainArr.get(peakIndex)) { // Update res res = BS(X, 0, peakIndex, mountainArr); } // If element not found on // left side of peak element if (res == -1) { // Update res res = reverseBS(X, peakIndex + 1, mountainArr.size() - 1, mountainArr); } // Print res System.out.println(res); } // Driver Code public static void main(String[] args) { // Given X int X = 3; // Given array ArrayList<Integer> list = new ArrayList<>( Arrays.asList(1, 2, 3, 4, 5, 3, 1)); // Function Call findInMA(X, list); }}
# Python3 program for the above approach # Function to find the index of# the peak element in the arraydef findPeak(arr): # Stores left most index in which # the peak element can be found left = 0 # Stores right most index in which # the peak element can be found right = len(arr) - 1 while (left < right): # Stores mid of left and right mid = left + (right - left) // 2 # If element at mid is less than # element at(mid + 1) if (arr[mid] < arr[(mid + 1)]): # Update left left = mid + 1 else: # Update right right = mid return left # Function to perform binary search in an# a subarray if elements of the subarray# are in an ascending orderdef BS(X, left, right, arr): while (left <= right): # Stores mid of left and right mid = left + (right - left) // 2 # If X found at mid if (arr[mid] == X): return mid # If X is greater than mid elif (X > arr[mid]): # Update left left = mid + 1 else: # Update right right = mid - 1 return -1 # Function to perform binary search in an# a subarray if elements of the subarray# are in an ascending orderdef reverseBS(X, left, right, arr): while (left <= right): # Stores mid of left and right mid = left + (right - left) // 2 # If X found at mid if (arr[mid] == X): return mid elif (X > arr[mid]): # Update right right = mid - 1 else: # Update left left = mid + 1 return -1 # Function to find the smallest index of Xdef findInMA(X, mountainArr): # Stores index of peak element in array peakIndex = findPeak(mountainArr) # Stores index of X in the array res = -1 # If X greater than or equal to first element # of array and less than the peak element if (X >= mountainArr[0] and X <= mountainArr[peakIndex]): # Update res res = BS(X, 0, peakIndex, mountainArr) # If element not found on # left side of peak element if (res == -1): # Update res res = reverseBS(X, peakIndex + 1, mountainArr.size() - 1, mountainArr) # Print res print(res) # Driver Codeif __name__ == "__main__": # Given X X = 3 # Given array arr = [ 1, 2, 3, 4, 5, 3, 1 ] # Function Call findInMA(X, arr) # This code is contributed by chitranayal
// C# program for the above approachusing System;using System.Collections.Generic;using System.Linq;class GFG{ // Function to find the index of // the peak element in the array public static int findPeak(List<int> arr) { // Stores left most index in which // the peak element can be found int left = 0; // Stores right most index in which // the peak element can be found int right = arr.Count - 1; while (left < right) { // Stores mid of left and right int mid = left + (right - left) / 2; // If element at mid is less than // element at (mid + 1) if (arr[mid] < arr[(mid + 1)]) { // Update left left = mid + 1; } else { // Update right right = mid; } } return left; } // Function to perform binary search in an // a subarray if elements of the subarray // are in an ascending order static int BS(int X, int left, int right, List<int> arr) { while (left <= right) { // Stores mid of left and right int mid = left + (right - left) / 2; // If X found at mid if (arr[(mid)] == X) { return mid; } // If X is greater than mid else if (X > arr[mid]) { // Update left left = mid + 1; } else { // Update right right = mid - 1; } } return -1; } // Function to perform binary search in an // a subarray if elements of the subarray // are in an ascending order static int reverseBS(int X, int left, int right, List<int> arr) { while (left <= right) { // Stores mid of left and right int mid = left + (right - left) / 2; // If X found at mid if (arr[mid] == X) { return mid; } else if (X > arr[mid]) { // Update right right = mid - 1; } else { // Update left left = mid + 1; } } return -1; } // Function to find the smallest index of X static void findInMA(int X, List<int> mountainArr) { // Stores index of peak element in array int peakIndex = findPeak(mountainArr); // Stores index of X in the array int res = -1; // If X greater than or equal to first element // of array and less than the peak element if (X >= mountainArr[0] && X <= mountainArr[peakIndex]) { // Update res res = BS(X, 0, peakIndex, mountainArr); } // If element not found on // left side of peak element if (res == -1) { // Update res res = reverseBS(X, peakIndex + 1, mountainArr.Count - 1, mountainArr); } // Print res Console.WriteLine(res); } // Driver Code public static void Main( ) { // Given X int X = 3; // Given array List<int> list = new List<int>(){1, 2, 3, 4, 5, 3, 1}; // Function Call findInMA(X, list); }} // This code is contributed by code_hunt.
<script> // Javascript program for the above approach // Function to find the index of// the peak element in the arrayfunction findPeak(arr){ // Stores left most index in which // the peak element can be found var left = 0; // Stores right most index in which // the peak element can be found var right = arr.length - 1; while (left < right) { // Stores mid of left and right var mid = left + parseInt((right - left) / 2); // If element at mid is less than // element at (mid + 1) if (arr[mid] < arr[mid + 1]) { // Update left left = mid + 1; } else { // Update right right = mid; } } return left;} // Function to perform binary search in an// a subarray if elements of the subarray// are in an ascending orderfunction BS(X, left, right, arr){ while (left <= right) { // Stores mid of left and right var mid = left + parseInt((right - left) / 2); // If X found at mid if (arr[mid] == X) { return mid; } // If X is greater than mid else if (X > arr[mid]) { // Update left left = mid + 1; } else { // Update right right = mid - 1; } } return -1;} // Function to perform binary search in an// a subarray if elements of the subarray// are in an ascending orderfunction reverseBS(X, left, right, arr){ while (left <= right) { // Stores mid of left and right var mid = left + parseInt((right - left) / 2); // If X found at mid if (arr[mid] == X) { return mid; } else if (X > arr[mid]) { // Update right right = mid - 1; } else { // Update left left = mid + 1; } } return -1;} // Function to find the smallest index of Xfunction findInMA(X, mountainArr){ // Stores index of peak element in array var peakIndex = findPeak(mountainArr); // Stores index of X in the array var res = -1; // If X greater than or equal to first element // of array and less than the peak element if (X >= mountainArr[0] && X <= mountainArr[peakIndex]) { // Update res res = BS(X, 0, peakIndex, mountainArr); } // If element not found on // left side of peak element if (res == -1) { // Update res res = reverseBS(X, peakIndex + 1, mountainArr.length - 1, mountainArr); } // Print res document.write( res + "<br>");} // Driver Code// Given Xvar X = 3;// Given arrayvar list = [1, 2, 3, 4, 5, 3, 1];// Function CallfindInMA(X, list); </script>
2
Time Complexity: O(Log(N))Auxiliary Space: O(1)
code_hunt
ukasp
bgangwar59
importantly
Algorithms-Divide and Conquer
Binary Search
Arrays
Divide and Conquer
Searching
Sorting
Arrays
Searching
Divide and Conquer
Sorting
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Merge Sort
QuickSort
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Count Inversions in an array | Set 1 (Using Merge Sort)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 200,
"s": 52,
"text": "Given a mountain array arr[] and an integer X, the task is to find the smallest index of X in the given array. If no such index is found, print -1."
},
{
"code": null,
"e": 210,
"s": 200,
"text": "Examples:"
},
{
"code": null,
"e": 358,
"s": 210,
"text": "Input: arr = {1, 2, 3, 4, 5, 3, 1}, X = 3Output: 2Explanation: The smallest index of X(= 3) in the array is 2. Therefore, the required output is 2."
},
{
"code": null,
"e": 485,
"s": 358,
"text": "Input: arr[] = {0, 1, 2, 4, 2, 1}, X = 3Output: -1Explanation: Since 3 does not exist in the array, the required output is -1."
},
{
"code": null,
"e": 661,
"s": 485,
"text": "Naive Approach: The simplest approach is to traverse the array and check if the element in the current index is equal to X or not. If found to be true, then print that index. "
},
{
"code": null,
"e": 704,
"s": 661,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 834,
"s": 704,
"text": "Efficient Approach: The optimal idea to solve this problem is to use Binary Search. Follow the steps below to solve this problem:"
},
{
"code": null,
"e": 879,
"s": 834,
"text": "Find the peak index from the mountain array."
},
{
"code": null,
"e": 1159,
"s": 879,
"text": "Based on the obtained peak index, the partition array into two parts. It searches for its left side first using Binary search, followed by its right. It is known that the left side of the peak element is sorted in ascending order and the right side is sorted in descending order."
},
{
"code": null,
"e": 1194,
"s": 1159,
"text": "Search in the left mountain array."
},
{
"code": null,
"e": 1245,
"s": 1194,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1249,
"s": 1245,
"text": "C++"
},
{
"code": null,
"e": 1254,
"s": 1249,
"text": "Java"
},
{
"code": null,
"e": 1262,
"s": 1254,
"text": "Python3"
},
{
"code": null,
"e": 1265,
"s": 1262,
"text": "C#"
},
{
"code": null,
"e": 1276,
"s": 1265,
"text": "Javascript"
},
{
"code": "// CPP program for the above approach#include<bits/stdc++.h>using namespace std; // Function to find the index of// the peak element in the arrayint findPeak(vector<int> arr){ // Stores left most index in which // the peak element can be found int left = 0; // Stores right most index in which // the peak element can be found int right = arr.size() - 1; while (left < right) { // Stores mid of left and right int mid = left + (right - left) / 2; // If element at mid is less than // element at (mid + 1) if (arr[mid] < arr[mid + 1]) { // Update left left = mid + 1; } else { // Update right right = mid; } } return left;} // Function to perform binary search in an// a subarray if elements of the subarray// are in an ascending orderint BS(int X, int left, int right, vector<int> arr){ while (left <= right) { // Stores mid of left and right int mid = left + (right - left) / 2; // If X found at mid if (arr[mid] == X) { return mid; } // If X is greater than mid else if (X > arr[mid]) { // Update left left = mid + 1; } else { // Update right right = mid - 1; } } return -1;} // Function to perform binary search in an// a subarray if elements of the subarray// are in an ascending orderint reverseBS(int X, int left, int right, vector<int> arr){ while (left <= right) { // Stores mid of left and right int mid = left + (right - left) / 2; // If X found at mid if (arr[mid] == X) { return mid; } else if (X > arr[mid]) { // Update right right = mid - 1; } else { // Update left left = mid + 1; } } return -1;} // Function to find the smallest index of Xvoid findInMA(int X, vector<int> mountainArr){ // Stores index of peak element in array int peakIndex = findPeak(mountainArr); // Stores index of X in the array int res = -1; // If X greater than or equal to first element // of array and less than the peak element if (X >= mountainArr[0] && X <= mountainArr[peakIndex]) { // Update res res = BS(X, 0, peakIndex, mountainArr); } // If element not found on // left side of peak element if (res == -1) { // Update res res = reverseBS(X, peakIndex + 1, mountainArr.size() - 1, mountainArr); } // Print res cout<<res<<endl;} // Driver Codeint main(){ // Given X int X = 3; // Given array vector<int> list{1, 2, 3, 4, 5, 3, 1}; // Function Call findInMA(X, list);} // This code is contributed by bgangwar59.",
"e": 3882,
"s": 1276,
"text": null
},
{
"code": "// Java program for the above approach import java.io.*;import java.util.*; class GFG { // Function to find the index of // the peak element in the array public static int findPeak( ArrayList<Integer> arr) { // Stores left most index in which // the peak element can be found int left = 0; // Stores right most index in which // the peak element can be found int right = arr.size() - 1; while (left < right) { // Stores mid of left and right int mid = left + (right - left) / 2; // If element at mid is less than // element at (mid + 1) if (arr.get(mid) < arr.get(mid + 1)) { // Update left left = mid + 1; } else { // Update right right = mid; } } return left; } // Function to perform binary search in an // a subarray if elements of the subarray // are in an ascending order static int BS(int X, int left, int right, ArrayList<Integer> arr) { while (left <= right) { // Stores mid of left and right int mid = left + (right - left) / 2; // If X found at mid if (arr.get(mid) == X) { return mid; } // If X is greater than mid else if (X > arr.get(mid)) { // Update left left = mid + 1; } else { // Update right right = mid - 1; } } return -1; } // Function to perform binary search in an // a subarray if elements of the subarray // are in an ascending order static int reverseBS(int X, int left, int right, ArrayList<Integer> arr) { while (left <= right) { // Stores mid of left and right int mid = left + (right - left) / 2; // If X found at mid if (arr.get(mid) == X) { return mid; } else if (X > arr.get(mid)) { // Update right right = mid - 1; } else { // Update left left = mid + 1; } } return -1; } // Function to find the smallest index of X static void findInMA(int X, ArrayList<Integer> mountainArr) { // Stores index of peak element in array int peakIndex = findPeak(mountainArr); // Stores index of X in the array int res = -1; // If X greater than or equal to first element // of array and less than the peak element if (X >= mountainArr.get(0) && X <= mountainArr.get(peakIndex)) { // Update res res = BS(X, 0, peakIndex, mountainArr); } // If element not found on // left side of peak element if (res == -1) { // Update res res = reverseBS(X, peakIndex + 1, mountainArr.size() - 1, mountainArr); } // Print res System.out.println(res); } // Driver Code public static void main(String[] args) { // Given X int X = 3; // Given array ArrayList<Integer> list = new ArrayList<>( Arrays.asList(1, 2, 3, 4, 5, 3, 1)); // Function Call findInMA(X, list); }}",
"e": 7402,
"s": 3882,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the index of# the peak element in the arraydef findPeak(arr): # Stores left most index in which # the peak element can be found left = 0 # Stores right most index in which # the peak element can be found right = len(arr) - 1 while (left < right): # Stores mid of left and right mid = left + (right - left) // 2 # If element at mid is less than # element at(mid + 1) if (arr[mid] < arr[(mid + 1)]): # Update left left = mid + 1 else: # Update right right = mid return left # Function to perform binary search in an# a subarray if elements of the subarray# are in an ascending orderdef BS(X, left, right, arr): while (left <= right): # Stores mid of left and right mid = left + (right - left) // 2 # If X found at mid if (arr[mid] == X): return mid # If X is greater than mid elif (X > arr[mid]): # Update left left = mid + 1 else: # Update right right = mid - 1 return -1 # Function to perform binary search in an# a subarray if elements of the subarray# are in an ascending orderdef reverseBS(X, left, right, arr): while (left <= right): # Stores mid of left and right mid = left + (right - left) // 2 # If X found at mid if (arr[mid] == X): return mid elif (X > arr[mid]): # Update right right = mid - 1 else: # Update left left = mid + 1 return -1 # Function to find the smallest index of Xdef findInMA(X, mountainArr): # Stores index of peak element in array peakIndex = findPeak(mountainArr) # Stores index of X in the array res = -1 # If X greater than or equal to first element # of array and less than the peak element if (X >= mountainArr[0] and X <= mountainArr[peakIndex]): # Update res res = BS(X, 0, peakIndex, mountainArr) # If element not found on # left side of peak element if (res == -1): # Update res res = reverseBS(X, peakIndex + 1, mountainArr.size() - 1, mountainArr) # Print res print(res) # Driver Codeif __name__ == \"__main__\": # Given X X = 3 # Given array arr = [ 1, 2, 3, 4, 5, 3, 1 ] # Function Call findInMA(X, arr) # This code is contributed by chitranayal",
"e": 9983,
"s": 7402,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;using System.Linq;class GFG{ // Function to find the index of // the peak element in the array public static int findPeak(List<int> arr) { // Stores left most index in which // the peak element can be found int left = 0; // Stores right most index in which // the peak element can be found int right = arr.Count - 1; while (left < right) { // Stores mid of left and right int mid = left + (right - left) / 2; // If element at mid is less than // element at (mid + 1) if (arr[mid] < arr[(mid + 1)]) { // Update left left = mid + 1; } else { // Update right right = mid; } } return left; } // Function to perform binary search in an // a subarray if elements of the subarray // are in an ascending order static int BS(int X, int left, int right, List<int> arr) { while (left <= right) { // Stores mid of left and right int mid = left + (right - left) / 2; // If X found at mid if (arr[(mid)] == X) { return mid; } // If X is greater than mid else if (X > arr[mid]) { // Update left left = mid + 1; } else { // Update right right = mid - 1; } } return -1; } // Function to perform binary search in an // a subarray if elements of the subarray // are in an ascending order static int reverseBS(int X, int left, int right, List<int> arr) { while (left <= right) { // Stores mid of left and right int mid = left + (right - left) / 2; // If X found at mid if (arr[mid] == X) { return mid; } else if (X > arr[mid]) { // Update right right = mid - 1; } else { // Update left left = mid + 1; } } return -1; } // Function to find the smallest index of X static void findInMA(int X, List<int> mountainArr) { // Stores index of peak element in array int peakIndex = findPeak(mountainArr); // Stores index of X in the array int res = -1; // If X greater than or equal to first element // of array and less than the peak element if (X >= mountainArr[0] && X <= mountainArr[peakIndex]) { // Update res res = BS(X, 0, peakIndex, mountainArr); } // If element not found on // left side of peak element if (res == -1) { // Update res res = reverseBS(X, peakIndex + 1, mountainArr.Count - 1, mountainArr); } // Print res Console.WriteLine(res); } // Driver Code public static void Main( ) { // Given X int X = 3; // Given array List<int> list = new List<int>(){1, 2, 3, 4, 5, 3, 1}; // Function Call findInMA(X, list); }} // This code is contributed by code_hunt.",
"e": 13567,
"s": 9983,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find the index of// the peak element in the arrayfunction findPeak(arr){ // Stores left most index in which // the peak element can be found var left = 0; // Stores right most index in which // the peak element can be found var right = arr.length - 1; while (left < right) { // Stores mid of left and right var mid = left + parseInt((right - left) / 2); // If element at mid is less than // element at (mid + 1) if (arr[mid] < arr[mid + 1]) { // Update left left = mid + 1; } else { // Update right right = mid; } } return left;} // Function to perform binary search in an// a subarray if elements of the subarray// are in an ascending orderfunction BS(X, left, right, arr){ while (left <= right) { // Stores mid of left and right var mid = left + parseInt((right - left) / 2); // If X found at mid if (arr[mid] == X) { return mid; } // If X is greater than mid else if (X > arr[mid]) { // Update left left = mid + 1; } else { // Update right right = mid - 1; } } return -1;} // Function to perform binary search in an// a subarray if elements of the subarray// are in an ascending orderfunction reverseBS(X, left, right, arr){ while (left <= right) { // Stores mid of left and right var mid = left + parseInt((right - left) / 2); // If X found at mid if (arr[mid] == X) { return mid; } else if (X > arr[mid]) { // Update right right = mid - 1; } else { // Update left left = mid + 1; } } return -1;} // Function to find the smallest index of Xfunction findInMA(X, mountainArr){ // Stores index of peak element in array var peakIndex = findPeak(mountainArr); // Stores index of X in the array var res = -1; // If X greater than or equal to first element // of array and less than the peak element if (X >= mountainArr[0] && X <= mountainArr[peakIndex]) { // Update res res = BS(X, 0, peakIndex, mountainArr); } // If element not found on // left side of peak element if (res == -1) { // Update res res = reverseBS(X, peakIndex + 1, mountainArr.length - 1, mountainArr); } // Print res document.write( res + \"<br>\");} // Driver Code// Given Xvar X = 3;// Given arrayvar list = [1, 2, 3, 4, 5, 3, 1];// Function CallfindInMA(X, list); </script>",
"e": 16062,
"s": 13567,
"text": null
},
{
"code": null,
"e": 16064,
"s": 16062,
"text": "2"
},
{
"code": null,
"e": 16114,
"s": 16066,
"text": "Time Complexity: O(Log(N))Auxiliary Space: O(1)"
},
{
"code": null,
"e": 16124,
"s": 16114,
"text": "code_hunt"
},
{
"code": null,
"e": 16130,
"s": 16124,
"text": "ukasp"
},
{
"code": null,
"e": 16141,
"s": 16130,
"text": "bgangwar59"
},
{
"code": null,
"e": 16153,
"s": 16141,
"text": "importantly"
},
{
"code": null,
"e": 16183,
"s": 16153,
"text": "Algorithms-Divide and Conquer"
},
{
"code": null,
"e": 16197,
"s": 16183,
"text": "Binary Search"
},
{
"code": null,
"e": 16204,
"s": 16197,
"text": "Arrays"
},
{
"code": null,
"e": 16223,
"s": 16204,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 16233,
"s": 16223,
"text": "Searching"
},
{
"code": null,
"e": 16241,
"s": 16233,
"text": "Sorting"
},
{
"code": null,
"e": 16248,
"s": 16241,
"text": "Arrays"
},
{
"code": null,
"e": 16258,
"s": 16248,
"text": "Searching"
},
{
"code": null,
"e": 16277,
"s": 16258,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 16285,
"s": 16277,
"text": "Sorting"
},
{
"code": null,
"e": 16299,
"s": 16285,
"text": "Binary Search"
},
{
"code": null,
"e": 16397,
"s": 16299,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16465,
"s": 16397,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 16509,
"s": 16465,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 16541,
"s": 16509,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 16589,
"s": 16541,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 16603,
"s": 16589,
"text": "Linear Search"
},
{
"code": null,
"e": 16614,
"s": 16603,
"text": "Merge Sort"
},
{
"code": null,
"e": 16624,
"s": 16614,
"text": "QuickSort"
},
{
"code": null,
"e": 16638,
"s": 16624,
"text": "Binary Search"
},
{
"code": null,
"e": 16706,
"s": 16638,
"text": "Maximum and minimum of an array using minimum number of comparisons"
}
] |
Maximum difference of zeros and ones in binary string
|
04 Jul, 2022
Given a binary string of 0s and 1s. The task is to find the length of the substring which is having a maximum difference between the number of 0s and the number of 1s (number of 0s – number of 1s). In case of all 1s print -1.
Examples:
Input : S = "11000010001"
Output : 6
From index 2 to index 9, there are 7
0s and 1 1s, so number of 0s - number
of 1s is 6.
Input : S = "1111"
Output : -1
The idea is to use Dynamic Programming to solve the problem. Before that, we will convert given binary string into an integer array of value 1s and -1s, say arr[]. That can be easily done by traversing the given binary string and if i-th index contain ‘0‘ make -1 in corresponding position in array. Similarly, if i-th index contain ‘1’, make 1 in the array.
Now, at each index i we need to make decision whether to take it or skip it. So, declare a 2D array of size n x 2, where n is the length of the given binary string, say dp[n][2].
dp[i][0] define the maximum value upto
index i, when we skip the i-th
index element.
dp[i][1] define the maximum value upto
index i after taking the i-th
index element.
Therefore, we can derive dp[i][] as:
dp[i][0] = max(dp[i+1][0], dp[i+1][1] + arr[i])
dp[i][1] = max(dp[i+1][1] + arr[i], 0)
For all ones, we check this case explicitly.
C++
Java
Python3
C#
Javascript
// CPP Program to find the length of// substring with maximum difference of// zeroes and ones in binary string.#include <bits/stdc++.h>#define MAX 100using namespace std; // Return true if there all 1sbool allones(string s, int n){ // Checking each index is 1 or not. int co = 0; for (int i = 0; i < s.size(); i++) co += (s[i] == '1'); return (co == n);} // Find the length of substring with maximum// difference of zeroes and ones in binary// stringint findlength(int arr[], string s, int n, int ind, int st, int dp[][3]){ // If string is over. if (ind >= n) return 0; // If the state is already calculated. if (dp[ind][st] != -1) return dp[ind][st]; if (st == 0) return dp[ind][st] = max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), findlength(arr, s, n, ind + 1, 0, dp)); else return dp[ind][st] = max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), 0);} // Returns length of substring which is// having maximum difference of number// of 0s and number of 1sint maxLen(string s, int n){ // If all 1s return -1. if (allones(s, n)) return -1; // Else find the length. int arr[MAX] = { 0 }; for (int i = 0; i < n; i++) arr[i] = (s[i] == '0' ? 1 : -1); int dp[MAX][3]; memset(dp, -1, sizeof dp); return findlength(arr, s, n, 0, 0, dp);} // Driven Programint main(){ string s = "11000010001"; int n = 11; cout << maxLen(s, n) << endl; return 0;}
// Java Program to find the length of// substring with maximum difference of// zeroes and ones in binary string.import java.util.Arrays; class GFG{static final int MAX=100; // Return true if there all 1sstatic boolean allones(String s, int n){ // Checking each index is 0 or not. int co = 0; for (int i = 0; i < s.length(); i++) if(s.charAt(i) == '1') co +=1; return (co == n);} // Find the length of substring with maximum// difference of zeroes and ones in binary// stringstatic int findlength(int arr[], String s, int n, int ind, int st, int dp[][]){ // If string is over. if (ind >= n) return 0; // If the state is already calculated. if (dp[ind][st] != -1) return dp[ind][st]; if (st == 0) return dp[ind][st] = Math.max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), findlength(arr, s, n, ind + 1, 0, dp)); else return dp[ind][st] = Math.max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), 0);} // Returns length of substring which is// having maximum difference of number// of 0s and number of 1sstatic int maxLen(String s, int n){ // If all 1s return -1. if (allones(s, n)) return -1; // Else find the length. int arr[] = new int[MAX]; for (int i = 0; i < n; i++) arr[i] = (s.charAt(i) == '0' ? 1 : -1); int dp[][] = new int[MAX][3]; for (int[] row : dp) Arrays.fill(row, -1); return findlength(arr, s, n, 0, 0, dp);} // Driver codepublic static void main (String[] args){ String s = "11000010001"; int n = 11; System.out.println(maxLen(s, n));}} // This code is contributed by Anant Agarwal.
# Python Program to find the length of# substring with maximum difference of# zeroes and ones in binary string.MAX = 100 # Return true if there all 1sdef allones(s, n): # Checking each index # is 0 or not. co = 0 for i in s: co += 1 if i == '1' else 0 return co == n # Find the length of substring with# maximum difference of zeroes and# ones in binary stringdef findlength(arr, s, n, ind, st, dp): # If string is over if ind >= n: return 0 # If the state is already calculated. if dp[ind][st] != -1: return dp[ind][st] if not st: dp[ind][st] = max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), (findlength(arr, s, n, ind + 1, 0, dp))) else: dp[ind][st] = max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), 0) return dp[ind][st] # Returns length of substring which is# having maximum difference of number# of 0s and number of 1sdef maxLen(s, n): # If all 1s return -1. if allones(s, n): return -1 # Else find the length. arr = [0] * MAX for i in range(n): arr[i] = 1 if s[i] == '0' else -1 dp = [[-1] * 3 for _ in range(MAX)] return findlength(arr, s, n, 0, 0, dp) # Driven Programs = "11000010001"n = 11print(maxLen(s, n)) # This code is contributed by Ansu Kumari.
// C# Program to find the length of// substring with maximum difference of// zeroes and ones in binary string.using System; class GFG{ static int MAX = 100; // Return true if there all 1s public static bool allones(string s, int n) { // Checking each index is 0 or not. int co = 0; for (int i = 0; i < s.Length; i++) co += (s[i] == '1' ? 1 : 0); return (co == n); } // Find the length of substring with maximum // difference of zeroes and ones in binary // string public static int findlength(int[] arr, string s, int n, int ind, int st, int[,] dp) { // If string is over. if (ind >= n) return 0; // If the state is already calculated. if (dp[ind,st] != -1) return dp[ind,st]; if (st == 0) return dp[ind,st] = Math.Max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), findlength(arr, s, n, ind + 1, 0, dp)); else return dp[ind,st] = Math.Max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), 0); } // Returns length of substring which is // having maximum difference of number // of 0s and number of 1s public static int maxLen(string s, int n) { // If all 1s return -1. if (allones(s, n)) return -1; // Else find the length. int[] arr = new int[MAX]; for (int i = 0; i < n; i++) arr[i] = (s[i] == '0' ? 1 : -1); int[,] dp = new int[MAX,3]; for(int i = 0; i < MAX; i++) for(int j = 0; j < 3; j++) dp[i,j] = -1; return findlength(arr, s, n, 0, 0, dp); } // Driven Program static void Main() { string s = "11000010001"; int n = 11; Console.Write(maxLen(s, n)); } // This code is contributed by DrRoot_}
<script> // Javascript Program to find the length of// substring with maximum difference of// zeroes and ones in binary string.var MAX = 100; // Return true if there all 1sfunction allones( s, n){ // Checking each index is 0 or not. var co = 0; for (var i = 0; i < s.length; i++) co += (s[i] == '1'); return (co == n);} // Find the length of substring with maximum// difference of zeroes and ones in binary// stringfunction findlength(arr, s, n, ind, st, dp){ // If string is over. if (ind >= n) return 0; // If the state is already calculated. if (dp[ind][st] != -1) return dp[ind][st]; if (st == 0) return dp[ind][st] = Math.max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), findlength(arr, s, n, ind + 1, 0, dp)); else return dp[ind][st] = Math.max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), 0);} // Returns length of substring which is// having maximum difference of number// of 0s and number of 1sfunction maxLen( s, n){ // If all 1s return -1. if (allones(s, n)) return -1; // Else find the length. var arr = Array(MAX).fill(0); for (var i = 0; i < n; i++) arr[i] = (s[i] == '0' ? 1 : -1); var dp = Array.from(Array(MAX), ()=> Array(3).fill(-1)); return findlength(arr, s, n, 0, 0, dp);} // Driven Programvar s = "11000010001";var n = 11;document.write( maxLen(s, n)); </script>
Output:
6
Time Complexity: O(2*len(s)), Auxiliary Space: O(len(s))
Maximum difference of zeros and ones in binary string | Set 2 (O(n) time)
DrRoot_
rrrtnx
prophet1999
amank2854
binary-string
Kadane
Dynamic Programming
Strings
Strings
Dynamic Programming
Kadane
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 280,
"s": 54,
"text": "Given a binary string of 0s and 1s. The task is to find the length of the substring which is having a maximum difference between the number of 0s and the number of 1s (number of 0s – number of 1s). In case of all 1s print -1."
},
{
"code": null,
"e": 291,
"s": 280,
"text": "Examples: "
},
{
"code": null,
"e": 415,
"s": 291,
"text": "Input : S = \"11000010001\"\nOutput : 6\nFrom index 2 to index 9, there are 7\n0s and 1 1s, so number of 0s - number\nof 1s is 6."
},
{
"code": null,
"e": 446,
"s": 415,
"text": "Input : S = \"1111\"\nOutput : -1"
},
{
"code": null,
"e": 806,
"s": 446,
"text": "The idea is to use Dynamic Programming to solve the problem. Before that, we will convert given binary string into an integer array of value 1s and -1s, say arr[]. That can be easily done by traversing the given binary string and if i-th index contain ‘0‘ make -1 in corresponding position in array. Similarly, if i-th index contain ‘1’, make 1 in the array. "
},
{
"code": null,
"e": 986,
"s": 806,
"text": "Now, at each index i we need to make decision whether to take it or skip it. So, declare a 2D array of size n x 2, where n is the length of the given binary string, say dp[n][2]. "
},
{
"code": null,
"e": 1318,
"s": 986,
"text": "dp[i][0] define the maximum value upto \n index i, when we skip the i-th\n index element.\ndp[i][1] define the maximum value upto \n index i after taking the i-th\n index element.\n\nTherefore, we can derive dp[i][] as:\ndp[i][0] = max(dp[i+1][0], dp[i+1][1] + arr[i])\ndp[i][1] = max(dp[i+1][1] + arr[i], 0)"
},
{
"code": null,
"e": 1363,
"s": 1318,
"text": "For all ones, we check this case explicitly."
},
{
"code": null,
"e": 1367,
"s": 1363,
"text": "C++"
},
{
"code": null,
"e": 1372,
"s": 1367,
"text": "Java"
},
{
"code": null,
"e": 1380,
"s": 1372,
"text": "Python3"
},
{
"code": null,
"e": 1383,
"s": 1380,
"text": "C#"
},
{
"code": null,
"e": 1394,
"s": 1383,
"text": "Javascript"
},
{
"code": "// CPP Program to find the length of// substring with maximum difference of// zeroes and ones in binary string.#include <bits/stdc++.h>#define MAX 100using namespace std; // Return true if there all 1sbool allones(string s, int n){ // Checking each index is 1 or not. int co = 0; for (int i = 0; i < s.size(); i++) co += (s[i] == '1'); return (co == n);} // Find the length of substring with maximum// difference of zeroes and ones in binary// stringint findlength(int arr[], string s, int n, int ind, int st, int dp[][3]){ // If string is over. if (ind >= n) return 0; // If the state is already calculated. if (dp[ind][st] != -1) return dp[ind][st]; if (st == 0) return dp[ind][st] = max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), findlength(arr, s, n, ind + 1, 0, dp)); else return dp[ind][st] = max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), 0);} // Returns length of substring which is// having maximum difference of number// of 0s and number of 1sint maxLen(string s, int n){ // If all 1s return -1. if (allones(s, n)) return -1; // Else find the length. int arr[MAX] = { 0 }; for (int i = 0; i < n; i++) arr[i] = (s[i] == '0' ? 1 : -1); int dp[MAX][3]; memset(dp, -1, sizeof dp); return findlength(arr, s, n, 0, 0, dp);} // Driven Programint main(){ string s = \"11000010001\"; int n = 11; cout << maxLen(s, n) << endl; return 0;}",
"e": 3069,
"s": 1394,
"text": null
},
{
"code": "// Java Program to find the length of// substring with maximum difference of// zeroes and ones in binary string.import java.util.Arrays; class GFG{static final int MAX=100; // Return true if there all 1sstatic boolean allones(String s, int n){ // Checking each index is 0 or not. int co = 0; for (int i = 0; i < s.length(); i++) if(s.charAt(i) == '1') co +=1; return (co == n);} // Find the length of substring with maximum// difference of zeroes and ones in binary// stringstatic int findlength(int arr[], String s, int n, int ind, int st, int dp[][]){ // If string is over. if (ind >= n) return 0; // If the state is already calculated. if (dp[ind][st] != -1) return dp[ind][st]; if (st == 0) return dp[ind][st] = Math.max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), findlength(arr, s, n, ind + 1, 0, dp)); else return dp[ind][st] = Math.max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), 0);} // Returns length of substring which is// having maximum difference of number// of 0s and number of 1sstatic int maxLen(String s, int n){ // If all 1s return -1. if (allones(s, n)) return -1; // Else find the length. int arr[] = new int[MAX]; for (int i = 0; i < n; i++) arr[i] = (s.charAt(i) == '0' ? 1 : -1); int dp[][] = new int[MAX][3]; for (int[] row : dp) Arrays.fill(row, -1); return findlength(arr, s, n, 0, 0, dp);} // Driver codepublic static void main (String[] args){ String s = \"11000010001\"; int n = 11; System.out.println(maxLen(s, n));}} // This code is contributed by Anant Agarwal.",
"e": 4920,
"s": 3069,
"text": null
},
{
"code": "# Python Program to find the length of# substring with maximum difference of# zeroes and ones in binary string.MAX = 100 # Return true if there all 1sdef allones(s, n): # Checking each index # is 0 or not. co = 0 for i in s: co += 1 if i == '1' else 0 return co == n # Find the length of substring with# maximum difference of zeroes and# ones in binary stringdef findlength(arr, s, n, ind, st, dp): # If string is over if ind >= n: return 0 # If the state is already calculated. if dp[ind][st] != -1: return dp[ind][st] if not st: dp[ind][st] = max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), (findlength(arr, s, n, ind + 1, 0, dp))) else: dp[ind][st] = max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), 0) return dp[ind][st] # Returns length of substring which is# having maximum difference of number# of 0s and number of 1sdef maxLen(s, n): # If all 1s return -1. if allones(s, n): return -1 # Else find the length. arr = [0] * MAX for i in range(n): arr[i] = 1 if s[i] == '0' else -1 dp = [[-1] * 3 for _ in range(MAX)] return findlength(arr, s, n, 0, 0, dp) # Driven Programs = \"11000010001\"n = 11print(maxLen(s, n)) # This code is contributed by Ansu Kumari.",
"e": 6264,
"s": 4920,
"text": null
},
{
"code": "// C# Program to find the length of// substring with maximum difference of// zeroes and ones in binary string.using System; class GFG{ static int MAX = 100; // Return true if there all 1s public static bool allones(string s, int n) { // Checking each index is 0 or not. int co = 0; for (int i = 0; i < s.Length; i++) co += (s[i] == '1' ? 1 : 0); return (co == n); } // Find the length of substring with maximum // difference of zeroes and ones in binary // string public static int findlength(int[] arr, string s, int n, int ind, int st, int[,] dp) { // If string is over. if (ind >= n) return 0; // If the state is already calculated. if (dp[ind,st] != -1) return dp[ind,st]; if (st == 0) return dp[ind,st] = Math.Max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), findlength(arr, s, n, ind + 1, 0, dp)); else return dp[ind,st] = Math.Max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), 0); } // Returns length of substring which is // having maximum difference of number // of 0s and number of 1s public static int maxLen(string s, int n) { // If all 1s return -1. if (allones(s, n)) return -1; // Else find the length. int[] arr = new int[MAX]; for (int i = 0; i < n; i++) arr[i] = (s[i] == '0' ? 1 : -1); int[,] dp = new int[MAX,3]; for(int i = 0; i < MAX; i++) for(int j = 0; j < 3; j++) dp[i,j] = -1; return findlength(arr, s, n, 0, 0, dp); } // Driven Program static void Main() { string s = \"11000010001\"; int n = 11; Console.Write(maxLen(s, n)); } // This code is contributed by DrRoot_}",
"e": 8203,
"s": 6264,
"text": null
},
{
"code": "<script> // Javascript Program to find the length of// substring with maximum difference of// zeroes and ones in binary string.var MAX = 100; // Return true if there all 1sfunction allones( s, n){ // Checking each index is 0 or not. var co = 0; for (var i = 0; i < s.length; i++) co += (s[i] == '1'); return (co == n);} // Find the length of substring with maximum// difference of zeroes and ones in binary// stringfunction findlength(arr, s, n, ind, st, dp){ // If string is over. if (ind >= n) return 0; // If the state is already calculated. if (dp[ind][st] != -1) return dp[ind][st]; if (st == 0) return dp[ind][st] = Math.max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), findlength(arr, s, n, ind + 1, 0, dp)); else return dp[ind][st] = Math.max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), 0);} // Returns length of substring which is// having maximum difference of number// of 0s and number of 1sfunction maxLen( s, n){ // If all 1s return -1. if (allones(s, n)) return -1; // Else find the length. var arr = Array(MAX).fill(0); for (var i = 0; i < n; i++) arr[i] = (s[i] == '0' ? 1 : -1); var dp = Array.from(Array(MAX), ()=> Array(3).fill(-1)); return findlength(arr, s, n, 0, 0, dp);} // Driven Programvar s = \"11000010001\";var n = 11;document.write( maxLen(s, n)); </script>",
"e": 9638,
"s": 8203,
"text": null
},
{
"code": null,
"e": 9647,
"s": 9638,
"text": "Output: "
},
{
"code": null,
"e": 9649,
"s": 9647,
"text": "6"
},
{
"code": null,
"e": 9706,
"s": 9649,
"text": "Time Complexity: O(2*len(s)), Auxiliary Space: O(len(s))"
},
{
"code": null,
"e": 9780,
"s": 9706,
"text": "Maximum difference of zeros and ones in binary string | Set 2 (O(n) time)"
},
{
"code": null,
"e": 9788,
"s": 9780,
"text": "DrRoot_"
},
{
"code": null,
"e": 9795,
"s": 9788,
"text": "rrrtnx"
},
{
"code": null,
"e": 9807,
"s": 9795,
"text": "prophet1999"
},
{
"code": null,
"e": 9817,
"s": 9807,
"text": "amank2854"
},
{
"code": null,
"e": 9831,
"s": 9817,
"text": "binary-string"
},
{
"code": null,
"e": 9838,
"s": 9831,
"text": "Kadane"
},
{
"code": null,
"e": 9858,
"s": 9838,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 9866,
"s": 9858,
"text": "Strings"
},
{
"code": null,
"e": 9874,
"s": 9866,
"text": "Strings"
},
{
"code": null,
"e": 9894,
"s": 9874,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 9901,
"s": 9894,
"text": "Kadane"
}
] |
Practice Questions for Recursion | Set 7 - GeeksforGeeks
|
13 May, 2022
Question 1 Predict the output of the following program. What does the following fun() do in general?
C++
C
Java
Python3
C#
Javascript
#include <iostream>using namespace std; int fun(int n, int* fp){ int t, f; if (n <= 2) { *fp = 1; return 1; } t = fun(n - 1, fp); f = t + *fp; *fp = t; return f;} int main(){ int x = 15; cout << fun(5, &x) << endl; return 0;}
#include <stdio.h> int fun(int n, int* fp){ int t, f; if (n <= 2) { *fp = 1; return 1; } t = fun(n - 1, fp); f = t + *fp; *fp = t; return f;} int main(){ int x = 15; printf("%d\n", fun(5, &x)); return 0;}
import java.io.*; class GFG { static int fp = 15; static int fun(int n) { int t, f; if (n <= 2) { fp = 1; return 1; } t = fun(n - 1); f = t + fp; fp = t; return f; } public static void main(String[] args) { System.out.println(fun(5)); }}// This code is contributed by shubhamsingh10
fp = 15 def fun(n): global fp if (n <= 2): fp = 1 return 1 t = fun(n - 1) f = t + fp fp = t return f # Driver code print(fun(5)) # This code is contributed by shubhamsingh10
using System; class GFG { static int fp = 15; static int fun(int n) { int t, f; if (n <= 2) { fp = 1; return 1; } t = fun(n - 1); f = t + fp; fp = t; return f; } static public void Main() { Console.Write(fun(5)); }}// This code is contributed by shubhamsingh10
<script>//Javascript Implementationvar fp = 15;function fun( n ){ var t, f; if ( n <= 2 ) { fp = 1; return 1; } t = fun ( n - 1 ); f = t + fp; fp = t; return f;} // Driver Code document.write(fun(5)); // This code is contributed by shubhamsingh10 </script>
5
The program calculates n-th Fibonacci Number. The statement t = fun ( n-1, fp ) gives the (n-1)th Fibonacci number and *fp is used to store the (n-2)th Fibonacci Number. The initial value of *fp (which is 15 in the above program) doesn’t matter. The following recursion tree shows all steps from 1 to 10, for the execution of fun(5, &x).
(1) fun(5, fp)
/ \
(2) fun(4, fp) (8) t = 3, f = 5, *fp = 3
/ \
(3) fun(3, fp) (7) t = 2, f = 3, *fp = 2
/ \
(4) fun(2, fp) (6) t = 1, f = 2, *fp = 1
/
(5) *fp = 1
Question 2: Predict the output of the following program.
C++
C
Java
Python3
C#
Javascript
#include <iostream>using namespace std;void fun(int n){ if (n > 0) { fun(n - 1); cout << n << " "; fun(n - 1); }} int main(){ fun(4); return 0;} // This code is contributed by shubhamsingh10
#include <stdio.h> void fun(int n){ if (n > 0) { fun(n - 1); printf("%d ", n); fun(n - 1); }} int main(){ fun(4); return 0;}
import java.util.*; class GFG { static void fun(int n) { if (n > 0) { fun(n - 1); System.out.print(n + " "); fun(n - 1); } } public static void main(String[] args) { fun(4); }}// This code is contributed by Shubhamsingh10
def fun(n): if(n > 0): fun(n - 1) print(n, end=" ") fun(n - 1) # driver code fun(4) # This code is contributed by shubhamsingh10
using System; class GFG { static void fun(int n) { if (n > 0) { fun(n - 1); Console.Write(n + " "); fun(n - 1); } } static public void Main() { fun(4); }} // This code is contributed by shubhamsingh10
<script>function fun(n){ if(n > 0) fun(n - 1); document.write(n+" ") fun(n - 1);} // driver codefun(4) // This code is contributed by bobby.</script>
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
fun(4)
/
fun(3), print(4), fun(3) [fun(3) prints 1 2 1 3 1 2 1]
/
fun(2), print(3), fun(2) [fun(2) prints 1 2 1]
/
fun(1), print(2), fun(1) [fun(1) prints 1]
/
fun(0), print(1), fun(0) [fun(0) does nothing]
Please write comments if you find any of the answers/codes incorrect, or you want to share more information/questions about the topics discussed above.
Akanksha_Rai
SHUBHAMSINGH10
gottumukkalabobby
parth01
dhruvdalal442002
harendrakumar123
Misc
Recursion
Misc
Recursion
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to write Regular Expressions?
Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
Association Rule
Recursive Functions
Activation Functions
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Program for Tower of Hanoi
Backtracking | Introduction
Print all possible combinations of r elements in a given array of size n
|
[
{
"code": null,
"e": 26303,
"s": 26275,
"text": "\n13 May, 2022"
},
{
"code": null,
"e": 26405,
"s": 26303,
"text": "Question 1 Predict the output of the following program. What does the following fun() do in general? "
},
{
"code": null,
"e": 26409,
"s": 26405,
"text": "C++"
},
{
"code": null,
"e": 26411,
"s": 26409,
"text": "C"
},
{
"code": null,
"e": 26416,
"s": 26411,
"text": "Java"
},
{
"code": null,
"e": 26424,
"s": 26416,
"text": "Python3"
},
{
"code": null,
"e": 26427,
"s": 26424,
"text": "C#"
},
{
"code": null,
"e": 26438,
"s": 26427,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; int fun(int n, int* fp){ int t, f; if (n <= 2) { *fp = 1; return 1; } t = fun(n - 1, fp); f = t + *fp; *fp = t; return f;} int main(){ int x = 15; cout << fun(5, &x) << endl; return 0;}",
"e": 26709,
"s": 26438,
"text": null
},
{
"code": "#include <stdio.h> int fun(int n, int* fp){ int t, f; if (n <= 2) { *fp = 1; return 1; } t = fun(n - 1, fp); f = t + *fp; *fp = t; return f;} int main(){ int x = 15; printf(\"%d\\n\", fun(5, &x)); return 0;}",
"e": 26960,
"s": 26709,
"text": null
},
{
"code": "import java.io.*; class GFG { static int fp = 15; static int fun(int n) { int t, f; if (n <= 2) { fp = 1; return 1; } t = fun(n - 1); f = t + fp; fp = t; return f; } public static void main(String[] args) { System.out.println(fun(5)); }}// This code is contributed by shubhamsingh10",
"e": 27343,
"s": 26960,
"text": null
},
{
"code": "fp = 15 def fun(n): global fp if (n <= 2): fp = 1 return 1 t = fun(n - 1) f = t + fp fp = t return f # Driver code print(fun(5)) # This code is contributed by shubhamsingh10",
"e": 27552,
"s": 27343,
"text": null
},
{
"code": "using System; class GFG { static int fp = 15; static int fun(int n) { int t, f; if (n <= 2) { fp = 1; return 1; } t = fun(n - 1); f = t + fp; fp = t; return f; } static public void Main() { Console.Write(fun(5)); }}// This code is contributed by shubhamsingh10",
"e": 27901,
"s": 27552,
"text": null
},
{
"code": "<script>//Javascript Implementationvar fp = 15;function fun( n ){ var t, f; if ( n <= 2 ) { fp = 1; return 1; } t = fun ( n - 1 ); f = t + fp; fp = t; return f;} // Driver Code document.write(fun(5)); // This code is contributed by shubhamsingh10 </script>",
"e": 28198,
"s": 27901,
"text": null
},
{
"code": null,
"e": 28200,
"s": 28198,
"text": "5"
},
{
"code": null,
"e": 28539,
"s": 28200,
"text": "The program calculates n-th Fibonacci Number. The statement t = fun ( n-1, fp ) gives the (n-1)th Fibonacci number and *fp is used to store the (n-2)th Fibonacci Number. The initial value of *fp (which is 15 in the above program) doesn’t matter. The following recursion tree shows all steps from 1 to 10, for the execution of fun(5, &x). "
},
{
"code": null,
"e": 28926,
"s": 28539,
"text": " (1) fun(5, fp)\n / \\\n (2) fun(4, fp) (8) t = 3, f = 5, *fp = 3\n / \\\n (3) fun(3, fp) (7) t = 2, f = 3, *fp = 2\n / \\\n (4) fun(2, fp) (6) t = 1, f = 2, *fp = 1\n / \n (5) *fp = 1 "
},
{
"code": null,
"e": 28984,
"s": 28926,
"text": "Question 2: Predict the output of the following program. "
},
{
"code": null,
"e": 28988,
"s": 28984,
"text": "C++"
},
{
"code": null,
"e": 28990,
"s": 28988,
"text": "C"
},
{
"code": null,
"e": 28995,
"s": 28990,
"text": "Java"
},
{
"code": null,
"e": 29003,
"s": 28995,
"text": "Python3"
},
{
"code": null,
"e": 29006,
"s": 29003,
"text": "C#"
},
{
"code": null,
"e": 29017,
"s": 29006,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std;void fun(int n){ if (n > 0) { fun(n - 1); cout << n << \" \"; fun(n - 1); }} int main(){ fun(4); return 0;} // This code is contributed by shubhamsingh10",
"e": 29241,
"s": 29017,
"text": null
},
{
"code": "#include <stdio.h> void fun(int n){ if (n > 0) { fun(n - 1); printf(\"%d \", n); fun(n - 1); }} int main(){ fun(4); return 0;}",
"e": 29399,
"s": 29241,
"text": null
},
{
"code": "import java.util.*; class GFG { static void fun(int n) { if (n > 0) { fun(n - 1); System.out.print(n + \" \"); fun(n - 1); } } public static void main(String[] args) { fun(4); }}// This code is contributed by Shubhamsingh10",
"e": 29681,
"s": 29399,
"text": null
},
{
"code": "def fun(n): if(n > 0): fun(n - 1) print(n, end=\" \") fun(n - 1) # driver code fun(4) # This code is contributed by shubhamsingh10",
"e": 29836,
"s": 29681,
"text": null
},
{
"code": "using System; class GFG { static void fun(int n) { if (n > 0) { fun(n - 1); Console.Write(n + \" \"); fun(n - 1); } } static public void Main() { fun(4); }} // This code is contributed by shubhamsingh10",
"e": 30097,
"s": 29836,
"text": null
},
{
"code": "<script>function fun(n){ if(n > 0) fun(n - 1); document.write(n+\" \") fun(n - 1);} // driver codefun(4) // This code is contributed by bobby.</script>",
"e": 30271,
"s": 30097,
"text": null
},
{
"code": null,
"e": 30302,
"s": 30271,
"text": "1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 "
},
{
"code": null,
"e": 30622,
"s": 30304,
"text": " fun(4)\n /\n fun(3), print(4), fun(3) [fun(3) prints 1 2 1 3 1 2 1]\n /\n fun(2), print(3), fun(2) [fun(2) prints 1 2 1]\n /\n fun(1), print(2), fun(1) [fun(1) prints 1]\n /\n fun(0), print(1), fun(0) [fun(0) does nothing]"
},
{
"code": null,
"e": 30775,
"s": 30622,
"text": "Please write comments if you find any of the answers/codes incorrect, or you want to share more information/questions about the topics discussed above. "
},
{
"code": null,
"e": 30788,
"s": 30775,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 30803,
"s": 30788,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 30821,
"s": 30803,
"text": "gottumukkalabobby"
},
{
"code": null,
"e": 30829,
"s": 30821,
"text": "parth01"
},
{
"code": null,
"e": 30846,
"s": 30829,
"text": "dhruvdalal442002"
},
{
"code": null,
"e": 30863,
"s": 30846,
"text": "harendrakumar123"
},
{
"code": null,
"e": 30868,
"s": 30863,
"text": "Misc"
},
{
"code": null,
"e": 30878,
"s": 30868,
"text": "Recursion"
},
{
"code": null,
"e": 30883,
"s": 30878,
"text": "Misc"
},
{
"code": null,
"e": 30893,
"s": 30883,
"text": "Recursion"
},
{
"code": null,
"e": 30898,
"s": 30893,
"text": "Misc"
},
{
"code": null,
"e": 30996,
"s": 30898,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31030,
"s": 30996,
"text": "How to write Regular Expressions?"
},
{
"code": null,
"e": 31111,
"s": 31030,
"text": "Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)"
},
{
"code": null,
"e": 31128,
"s": 31111,
"text": "Association Rule"
},
{
"code": null,
"e": 31148,
"s": 31128,
"text": "Recursive Functions"
},
{
"code": null,
"e": 31169,
"s": 31148,
"text": "Activation Functions"
},
{
"code": null,
"e": 31229,
"s": 31169,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31314,
"s": 31229,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 31341,
"s": 31314,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 31369,
"s": 31341,
"text": "Backtracking | Introduction"
}
] |
MongoDB Python | Insert and Update Data - GeeksforGeeks
|
20 Mar, 2020
Prerequisites : MongoDB Python BasicsWe would first understand how to insert a document/entry in a collection of a database. Then we would work on how to update an existing document in MongoDB using pymongo library in python. The update commands helps us to update the query data inserted already in MongoDB database collection.
Insert data
We would first insert data in MongoDB.
Step 1 – Establishing Connection: Port number Default: 27017conn = MongoClient(‘localhost’, port-number)If using default port-number i.e. 27017. Alternate connection method:conn = MongoClient()
conn = MongoClient(‘localhost’, port-number)
If using default port-number i.e. 27017. Alternate connection method:
conn = MongoClient()
Step 2 – Create Database or Switch to Existing Database:db = conn.dabasenameCreate a collection or Switch to existing collection:collection = db.collection_name
db = conn.dabasename
Create a collection or Switch to existing collection:
collection = db.collection_name
Step 3 – Insert : To Insert Data create a dictionary object and insert data in database. Method used to insert data: insert_one() or insert_many()After insert to find the documents inside a collection we use find() command. The find() method issues a query to retrieve data from a collection in MongoDB. All queries in MongoDB have the scope of a single collection.Note : ObjectId is different for every entry in database collection.Let us understand insert of data with help on code:-# Python code to illustrate# inserting data in MongoDBfrom pymongo import MongoClient try: conn = MongoClient() print("Connected successfully!!!")except: print("Could not connect to MongoDB") # databasedb = conn.database # Created or Switched to collection names: my_gfg_collectioncollection = db.my_gfg_collection emp_rec1 = { "name":"Mr.Geek", "eid":24, "location":"delhi" }emp_rec2 = { "name":"Mr.Shaurya", "eid":14, "location":"delhi" } # Insert Datarec_id1 = collection.insert_one(emp_rec1)rec_id2 = collection.insert_one(emp_rec2) print("Data inserted with record ids",rec_id1," ",rec_id2) # Printing the data insertedcursor = collection.find()for record in cursor: print(record)Output:Connected successfully!!!
Data inserted with record ids
{'_id': ObjectId('5a02227b37b8552becf5ed2a'),
'name': 'Mr.Geek', 'eid': 24, 'location': 'delhi'}
{'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name':
'Mr.Shaurya', 'eid': 14, 'location': 'delhi'}
insert_one() or insert_many()
After insert to find the documents inside a collection we use find() command. The find() method issues a query to retrieve data from a collection in MongoDB. All queries in MongoDB have the scope of a single collection.Note : ObjectId is different for every entry in database collection.Let us understand insert of data with help on code:-
# Python code to illustrate# inserting data in MongoDBfrom pymongo import MongoClient try: conn = MongoClient() print("Connected successfully!!!")except: print("Could not connect to MongoDB") # databasedb = conn.database # Created or Switched to collection names: my_gfg_collectioncollection = db.my_gfg_collection emp_rec1 = { "name":"Mr.Geek", "eid":24, "location":"delhi" }emp_rec2 = { "name":"Mr.Shaurya", "eid":14, "location":"delhi" } # Insert Datarec_id1 = collection.insert_one(emp_rec1)rec_id2 = collection.insert_one(emp_rec2) print("Data inserted with record ids",rec_id1," ",rec_id2) # Printing the data insertedcursor = collection.find()for record in cursor: print(record)
Output:
Connected successfully!!!
Data inserted with record ids
{'_id': ObjectId('5a02227b37b8552becf5ed2a'),
'name': 'Mr.Geek', 'eid': 24, 'location': 'delhi'}
{'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name':
'Mr.Shaurya', 'eid': 14, 'location': 'delhi'}
Updating data in MongoDB
Methods used: update_one() and update_many()Parameters passed:+ a filter document to match the documents to update+ an update document to specify the modification to perform+ an optional upsert parameter
After inserting Data in MongoDB let’s Update the Data of employee with id:24
# Python code to illustrate# updating data in MongoDB# with Data of employee with id:24from pymongo import MongoClient try: conn = MongoClient() print("Connected successfully!!!")except: print("Could not connect to MongoDB") # databasedb = conn.database # Created or Switched to collection names: my_gfg_collectioncollection = db.my_gfg_collection # update all the employee data whose eid is 24result = collection.update_many( {"eid":24}, { "$set":{ "name":"Mr.Geeksforgeeks" }, "$currentDate":{"lastModified":True} } ) print("Data updated with id",result) # Print the new recordcursor = collection.find()for record in cursor: print(record)
Output:
Connected successfully!!!
Data updated with id
{'_id': ObjectId('5a02227b37b8552becf5ed2a'),
'name': 'Mr.Geeksforgeeks', 'eid': 24, 'location':
'delhi', 'lastModified': datetime.datetime(2017, 11, 7, 21, 19, 9, 698000)}
{'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name':
'Mr.Shaurya', 'eid': 14, 'location': 'delhi'}
To find number of documents or entries in collection the are updated use.
print(result.matched_count)
Here output would be 1.
Python-mongoDB
Computer Organization & Architecture
GBlog
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Logical and Physical Address in Operating System
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Memory Hierarchy Design and its Characteristics
Computer Organization | RISC and CISC
Direct Access Media (DMA) Controller in Computer Architecture
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
DSA Sheet by Love Babbar
Socket Programming in C/C++
GET and POST requests using Python
Must Do Coding Questions for Product Based Companies
|
[
{
"code": null,
"e": 25395,
"s": 25367,
"text": "\n20 Mar, 2020"
},
{
"code": null,
"e": 25724,
"s": 25395,
"text": "Prerequisites : MongoDB Python BasicsWe would first understand how to insert a document/entry in a collection of a database. Then we would work on how to update an existing document in MongoDB using pymongo library in python. The update commands helps us to update the query data inserted already in MongoDB database collection."
},
{
"code": null,
"e": 25736,
"s": 25724,
"text": "Insert data"
},
{
"code": null,
"e": 25775,
"s": 25736,
"text": "We would first insert data in MongoDB."
},
{
"code": null,
"e": 25969,
"s": 25775,
"text": "Step 1 – Establishing Connection: Port number Default: 27017conn = MongoClient(‘localhost’, port-number)If using default port-number i.e. 27017. Alternate connection method:conn = MongoClient()"
},
{
"code": null,
"e": 26014,
"s": 25969,
"text": "conn = MongoClient(‘localhost’, port-number)"
},
{
"code": null,
"e": 26084,
"s": 26014,
"text": "If using default port-number i.e. 27017. Alternate connection method:"
},
{
"code": null,
"e": 26105,
"s": 26084,
"text": "conn = MongoClient()"
},
{
"code": null,
"e": 26266,
"s": 26105,
"text": "Step 2 – Create Database or Switch to Existing Database:db = conn.dabasenameCreate a collection or Switch to existing collection:collection = db.collection_name"
},
{
"code": null,
"e": 26287,
"s": 26266,
"text": "db = conn.dabasename"
},
{
"code": null,
"e": 26341,
"s": 26287,
"text": "Create a collection or Switch to existing collection:"
},
{
"code": null,
"e": 26373,
"s": 26341,
"text": "collection = db.collection_name"
},
{
"code": null,
"e": 27886,
"s": 26373,
"text": "Step 3 – Insert : To Insert Data create a dictionary object and insert data in database. Method used to insert data: insert_one() or insert_many()After insert to find the documents inside a collection we use find() command. The find() method issues a query to retrieve data from a collection in MongoDB. All queries in MongoDB have the scope of a single collection.Note : ObjectId is different for every entry in database collection.Let us understand insert of data with help on code:-# Python code to illustrate# inserting data in MongoDBfrom pymongo import MongoClient try: conn = MongoClient() print(\"Connected successfully!!!\")except: print(\"Could not connect to MongoDB\") # databasedb = conn.database # Created or Switched to collection names: my_gfg_collectioncollection = db.my_gfg_collection emp_rec1 = { \"name\":\"Mr.Geek\", \"eid\":24, \"location\":\"delhi\" }emp_rec2 = { \"name\":\"Mr.Shaurya\", \"eid\":14, \"location\":\"delhi\" } # Insert Datarec_id1 = collection.insert_one(emp_rec1)rec_id2 = collection.insert_one(emp_rec2) print(\"Data inserted with record ids\",rec_id1,\" \",rec_id2) # Printing the data insertedcursor = collection.find()for record in cursor: print(record)Output:Connected successfully!!!\nData inserted with record ids \n{'_id': ObjectId('5a02227b37b8552becf5ed2a'), \n'name': 'Mr.Geek', 'eid': 24, 'location': 'delhi'}\n{'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name':\n'Mr.Shaurya', 'eid': 14, 'location': 'delhi'}\n"
},
{
"code": null,
"e": 27917,
"s": 27886,
"text": " insert_one() or insert_many()"
},
{
"code": null,
"e": 28257,
"s": 27917,
"text": "After insert to find the documents inside a collection we use find() command. The find() method issues a query to retrieve data from a collection in MongoDB. All queries in MongoDB have the scope of a single collection.Note : ObjectId is different for every entry in database collection.Let us understand insert of data with help on code:-"
},
{
"code": "# Python code to illustrate# inserting data in MongoDBfrom pymongo import MongoClient try: conn = MongoClient() print(\"Connected successfully!!!\")except: print(\"Could not connect to MongoDB\") # databasedb = conn.database # Created or Switched to collection names: my_gfg_collectioncollection = db.my_gfg_collection emp_rec1 = { \"name\":\"Mr.Geek\", \"eid\":24, \"location\":\"delhi\" }emp_rec2 = { \"name\":\"Mr.Shaurya\", \"eid\":14, \"location\":\"delhi\" } # Insert Datarec_id1 = collection.insert_one(emp_rec1)rec_id2 = collection.insert_one(emp_rec2) print(\"Data inserted with record ids\",rec_id1,\" \",rec_id2) # Printing the data insertedcursor = collection.find()for record in cursor: print(record)",
"e": 29020,
"s": 28257,
"text": null
},
{
"code": null,
"e": 29028,
"s": 29020,
"text": "Output:"
},
{
"code": null,
"e": 29287,
"s": 29028,
"text": "Connected successfully!!!\nData inserted with record ids \n{'_id': ObjectId('5a02227b37b8552becf5ed2a'), \n'name': 'Mr.Geek', 'eid': 24, 'location': 'delhi'}\n{'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name':\n'Mr.Shaurya', 'eid': 14, 'location': 'delhi'}\n"
},
{
"code": null,
"e": 29312,
"s": 29287,
"text": "Updating data in MongoDB"
},
{
"code": null,
"e": 29516,
"s": 29312,
"text": "Methods used: update_one() and update_many()Parameters passed:+ a filter document to match the documents to update+ an update document to specify the modification to perform+ an optional upsert parameter"
},
{
"code": null,
"e": 29593,
"s": 29516,
"text": "After inserting Data in MongoDB let’s Update the Data of employee with id:24"
},
{
"code": "# Python code to illustrate# updating data in MongoDB# with Data of employee with id:24from pymongo import MongoClient try: conn = MongoClient() print(\"Connected successfully!!!\")except: print(\"Could not connect to MongoDB\") # databasedb = conn.database # Created or Switched to collection names: my_gfg_collectioncollection = db.my_gfg_collection # update all the employee data whose eid is 24result = collection.update_many( {\"eid\":24}, { \"$set\":{ \"name\":\"Mr.Geeksforgeeks\" }, \"$currentDate\":{\"lastModified\":True} } ) print(\"Data updated with id\",result) # Print the new recordcursor = collection.find()for record in cursor: print(record)",
"e": 30388,
"s": 29593,
"text": null
},
{
"code": null,
"e": 30396,
"s": 30388,
"text": "Output:"
},
{
"code": null,
"e": 30721,
"s": 30396,
"text": "Connected successfully!!!\nData updated with id \n{'_id': ObjectId('5a02227b37b8552becf5ed2a'), \n'name': 'Mr.Geeksforgeeks', 'eid': 24, 'location': \n'delhi', 'lastModified': datetime.datetime(2017, 11, 7, 21, 19, 9, 698000)}\n{'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name': \n'Mr.Shaurya', 'eid': 14, 'location': 'delhi'}\n"
},
{
"code": null,
"e": 30795,
"s": 30721,
"text": "To find number of documents or entries in collection the are updated use."
},
{
"code": null,
"e": 30825,
"s": 30795,
"text": " print(result.matched_count) "
},
{
"code": null,
"e": 30849,
"s": 30825,
"text": "Here output would be 1."
},
{
"code": null,
"e": 30864,
"s": 30849,
"text": "Python-mongoDB"
},
{
"code": null,
"e": 30901,
"s": 30864,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 30907,
"s": 30901,
"text": "GBlog"
},
{
"code": null,
"e": 30914,
"s": 30907,
"text": "Python"
},
{
"code": null,
"e": 30933,
"s": 30914,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31031,
"s": 30933,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31080,
"s": 31031,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 31175,
"s": 31080,
"text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)"
},
{
"code": null,
"e": 31223,
"s": 31175,
"text": "Memory Hierarchy Design and its Characteristics"
},
{
"code": null,
"e": 31261,
"s": 31223,
"text": "Computer Organization | RISC and CISC"
},
{
"code": null,
"e": 31323,
"s": 31261,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 31397,
"s": 31323,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 31422,
"s": 31397,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 31450,
"s": 31422,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 31485,
"s": 31450,
"text": "GET and POST requests using Python"
}
] |
How to add Matplotlib graph in Kivy ? - GeeksforGeeks
|
05 Apr, 2021
In this article, we will discuss how to add matplotlib graph in the kivy app.
Import matplotlib pyplot
Import numpy
Import FigureCanvas KivyAgg
Import kivy app
Import kivy builder
Create App class
Return builder string
Run an instance of the class
Below is the Implementation.
Python3
# importing pyplot for graph plottingfrom matplotlib import pyplot as plt # importing numpyimport numpy as npfrom kivy.garden.matplotlib import FigureCanvasKivyAgg # importing kivyappfrom kivy.app import App # importing kivy builderfrom kivy.lang import Builder # this is the main class which will # render the whole applicationclass uiApp(App): def build(self): self.str = Builder.load_string(""" BoxLayout: layout:layout BoxLayout: id:layout """) signal = [7, 89.6, 45.-56.34] signal = np.array(signal) # this will plot the signal on graph plt.plot(signal) # setting x label plt.xlabel('Time(s)') # setting y label plt.ylabel('signal (norm)') plt.grid(True, color='lightgray') # adding plot to kivy boxlayout self.str.layout.add_widget(FigureCanvasKivyAgg(plt.gcf())) return self.str # running the applicationuiApp().run()
Output:
Note: When you run the below code this may throw the error given below
What you have to do is open the file given in the white box by clicking on file while holding ctrl key and comment line underlined by green color in that file and hit save now you will be able to run it!!
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25561,
"s": 25533,
"text": "\n05 Apr, 2021"
},
{
"code": null,
"e": 25639,
"s": 25561,
"text": "In this article, we will discuss how to add matplotlib graph in the kivy app."
},
{
"code": null,
"e": 25664,
"s": 25639,
"text": "Import matplotlib pyplot"
},
{
"code": null,
"e": 25677,
"s": 25664,
"text": "Import numpy"
},
{
"code": null,
"e": 25705,
"s": 25677,
"text": "Import FigureCanvas KivyAgg"
},
{
"code": null,
"e": 25721,
"s": 25705,
"text": "Import kivy app"
},
{
"code": null,
"e": 25741,
"s": 25721,
"text": "Import kivy builder"
},
{
"code": null,
"e": 25758,
"s": 25741,
"text": "Create App class"
},
{
"code": null,
"e": 25780,
"s": 25758,
"text": "Return builder string"
},
{
"code": null,
"e": 25809,
"s": 25780,
"text": "Run an instance of the class"
},
{
"code": null,
"e": 25838,
"s": 25809,
"text": "Below is the Implementation."
},
{
"code": null,
"e": 25846,
"s": 25838,
"text": "Python3"
},
{
"code": "# importing pyplot for graph plottingfrom matplotlib import pyplot as plt # importing numpyimport numpy as npfrom kivy.garden.matplotlib import FigureCanvasKivyAgg # importing kivyappfrom kivy.app import App # importing kivy builderfrom kivy.lang import Builder # this is the main class which will # render the whole applicationclass uiApp(App): def build(self): self.str = Builder.load_string(\"\"\" BoxLayout: layout:layout BoxLayout: id:layout \"\"\") signal = [7, 89.6, 45.-56.34] signal = np.array(signal) # this will plot the signal on graph plt.plot(signal) # setting x label plt.xlabel('Time(s)') # setting y label plt.ylabel('signal (norm)') plt.grid(True, color='lightgray') # adding plot to kivy boxlayout self.str.layout.add_widget(FigureCanvasKivyAgg(plt.gcf())) return self.str # running the applicationuiApp().run()",
"e": 26884,
"s": 25846,
"text": null
},
{
"code": null,
"e": 26892,
"s": 26884,
"text": "Output:"
},
{
"code": null,
"e": 26963,
"s": 26892,
"text": "Note: When you run the below code this may throw the error given below"
},
{
"code": null,
"e": 27168,
"s": 26963,
"text": "What you have to do is open the file given in the white box by clicking on file while holding ctrl key and comment line underlined by green color in that file and hit save now you will be able to run it!!"
},
{
"code": null,
"e": 27180,
"s": 27168,
"text": "Python-kivy"
},
{
"code": null,
"e": 27187,
"s": 27180,
"text": "Python"
},
{
"code": null,
"e": 27285,
"s": 27187,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27317,
"s": 27285,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27359,
"s": 27317,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27401,
"s": 27359,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27428,
"s": 27401,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27484,
"s": 27428,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27506,
"s": 27484,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27545,
"s": 27506,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27576,
"s": 27545,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27605,
"s": 27576,
"text": "Create a directory in Python"
}
] |
Minimum number of elements to add to make median equals x - GeeksforGeeks
|
26 Mar, 2021
A median in an array with the length of n is an element which occupies position number (n+1)/2 after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.
Examples :
Input : 3 10
10 20 30
Output : 1
In the first sample we can add number 9
to array (10, 20, 30). The resulting array
(9, 10, 20, 30) will have a median in
position (4+1)/2 = 2, that is, 10
Input : 3 4
1 2 3
Output : 4
In the second sample you should add numbers
4, 5, 5, 5. The resulting array has median
equal to 4.
First Approach:- The approach is to add one more number x to the array until the median of the array equals to x. Below is the implementation of the above approach:-
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find minimum number// of elements needs to add to the// array so that its median equals x.#include <bits/stdc++.h>using namespace std; // Returns count of elements to be// added to make median x. This function// assumes that a[] has enough extra space.int minNumber(int a[], int n, int x){ // to sort the array in increasing order. sort(a, a + n); int k; for (k = 0; a[(n - 1) / 2] != x; k++) { a[n++] = x; sort(a, a + n); } return k;} // Driver codemain(){ int x = 10; int a[6] = { 10, 20, 30 }; int n = 3; cout << minNumber(a, n, x) << endl; return 0;}
// Java program to find minimum number// of elements needs to add to the// array so that its median equals x.import java.util.Arrays; class GFG{ // Returns count of elements to be// added to make median x. This function// assumes that a[] has enough extra space.static int minNumber(int a[], int n, int x){ // to sort the array in increasing order. Arrays.sort(a); int k; for (k = 0; a[(n) / 2] != x; k++) { a[n++] = x; Arrays.sort(a); } return k;} // Driver codepublic static void main(String[] args){ int x = 10; int a[] = { 10, 20, 30 }; int n = 3; System.out.println(minNumber(a, n-1, x));}} // This code has been contributed by 29AjayKumar
# Python3 program to find minimum number# of elements needs to add to the# array so that its median equals x. # Returns count of elements to be added # to make median x. This function# assumes that a[] has enough extra space.def minNumber(a, n, x): # to sort the array in increasing order. a.sort(reverse = False) k = 0 while(a[int((n - 1) / 2)] != x): a[n - 1] = x n += 1 a.sort(reverse = False) k += 1 return k # Driver codeif __name__ == '__main__': x = 10 a = [10, 20, 30] n = 3 print(minNumber(a, n, x)) # This code is contributed by# Surendra_Gangwar
// C# program to find minimum number// of elements needs to add to the// array so that its median equals x.using System; class GFG{ // Returns count of elements to be// added to make median x. This function// assumes that a[] has enough extra space.static int minNumber(int []a, int n, int x){ // to sort the array in increasing order. Array.Sort(a); int k; for (k = 0; a[(n) / 2] != x; k++) { a[n++] = x; Array.Sort(a); } return k;} // Driver codepublic static void Main(String[] args){ int x = 10; int []a = { 10, 20, 30 }; int n = 3; Console.WriteLine(minNumber(a, n-1, x));}} // This code contributed by Rajput-Ji
<?php// PHP program to find minimum// number of elements needs to// add to the array so that its// median equals x. // Returns count of elements// to be added to make median// x. This function assumes// that a[] has enough extra space.function minNumber($a, $n, $x){ // to sort the array in // increasing order. sort($a); $k; for ($k = 0; $a[($n - 1) / 2] != $x; $k++) { $a[$n++] = $x; sort($a); } return $k;} // Driver code$x = 10;$a = array (10, 20, 30);$n = 3;echo minNumber($a, $n, $x),"\n"; // This code is contributed by ajit?>
<script> // Javascript program to find minimum number // of elements needs to add to the // array so that its median equals x. // Returns count of elements to be // added to make median x. This function // assumes that a[] has enough extra space. function minNumber(a, n, x) { // to sort the array in increasing order. a.sort(); let k; for (k = 0; a[parseInt((n - 1) / 2, 10)] != x; k++) { a[n++] = x; a.sort(); } return k; } let x = 10; let a = [ 10, 20, 30 ]; let n = 3; document.write(minNumber(a, n, x)); // This code is contributed by mukesh07.</script>
Output :
1
Time complexity : O(knLogn)
Second Approach:- Better approach is to count all the elements equal to x(that is e), greater than x(that is h) and smaller than x(that is l). And then – if l is greater than h then, the ans will be (l – h) + 1 – e; And if h is greater than l then, ans will be (h – l – 1) + 1 – e;We can use Hoare’s partition scheme to count smaller, equal and greater elements.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find minimum number of// elements to add so that its median// equals x.#include <bits/stdc++.h>using namespace std; int minNumber(int a[], int n, int x){ int l = 0, h = 0, e = 0; for (int i = 0; i < n; i++) { // no. of elements equals to x, // that is, e. if (a[i] == x) e++; // no. of elements greater than x, // that is, h. else if (a[i] > x) h++; // no. of elements smaller than x, // that is, l. else if (a[i] < x) l++; } int ans = 0; if (l > h) ans = l - h; else if (l < h) ans = h - l - 1; // subtract the no. of elements // that are equal to x. return ans + 1 - e;} // Driver codeint main(){ int x = 10; int a[] = { 10, 20, 30 }; int n = sizeof(a) / sizeof(a[0]); cout << minNumber(a, n, x) << endl; return 0;}
// Java program to find minimum number// of elements to add so that its// median equals x.import java.util.*;import java.lang.*; class GFG { public static int minNumber(int a[], int n, int x) { int l = 0, h = 0, e = 0; for (int i = 0; i < n; i++) { // no. of elements equals to // x, that is, e. if (a[i] == x) e++; // no. of elements greater // than x, that is, h. else if (a[i] > x) h++; // no. of elements smaller // than x, that is, l. else if (a[i] < x) l++; } int ans = 0; if (l > h) ans = l - h; else if (l < h) ans = h - l - 1; // subtract the no. of elements // that are equal to x. return ans + 1 - e; } // Driven Program public static void main(String[] args) { int x = 10; int a[] = { 10, 20, 30 }; int n = a.length; System.out.println( minNumber(a, n, x)); }} // This code is contributed by// Prasad Kshirsagar
# Python3 program to find minimum number# of elements to add so that its median# equals x. def minNumber (a, n, x): l = 0 h = 0 e = 0 for i in range(n): # no. of elements equals to x, # that is, e. if a[i] == x: e+=1 # no. of elements greater than x, # that is, h. elif a[i] > x: h+=1 # no. of elements smaller than x, # that is, l. elif a[i] < x: l+=1 ans = 0; if l > h: ans = l - h elif l < h: ans = h - l - 1; # subtract the no. of elements # that are equal to x. return ans + 1 - e # Driver codex = 10a = [10, 20, 30]n = len(a)print(minNumber(a, n, x)) # This code is contributed# by "Abhishek Sharma 44"
// C# program to find minimum// number of elements to add// so that its median equals x.using System; class GFG{public static int minNumber(int []a, int n, int x){ int l = 0, h = 0, e = 0; for (int i = 0; i < n; i++) { // no. of elements // equals to x, // that is, e. if (a[i] == x) e++; // no. of elements // greater than x, // that is, h. else if (a[i] > x) h++; // no. of elements smaller // than x, that is, l. else if (a[i] < x) l++; } int ans = 0; if (l > h) ans = l - h; else if (l < h) ans = h - l - 1; // subtract the no. // of elements that // are equal to x. return ans + 1 - e;} // Driver Codepublic static void Main(){ int x = 10; int []a = {10, 20, 30}; int n = a.Length; Console.WriteLine( minNumber(a, n, x));}} // This code is contributed// by anuj_67.
<?php// PHP program to find minimum// number of elements to add so // that its median equals x. function minNumber($a, $n, $x){ $l = 0; $h = 0; $e = 0; for ($i = 0; $i < $n; $i++) { // no. of elements equals // to x, that is, e. if ($a[$i] == $x) $e++; // no. of elements greater // than x, that is, h. else if ($a[$i] > $x) $h++; // no. of elements smaller // than x, that is, l. else if ($a[$i] < $x) $l++; } $ans = 0; if ($l > $h) $ans = $l - $h; else if ($l < $h) $ans = $h - $l - 1; // subtract the no. of elements // that are equal to x. return $ans + 1 - $e;} // Driver code$x = 10;$a = array (10, 20, 30);$n = sizeof($a) ;echo minNumber($a, $n, $x), "\n"; // This code is contributed by jit_t?>
<script> // Javascript program to find minimum number// of elements to add so that its median// equals x.function minNumber(a, n, x){ let l = 0, h = 0, e = 0; for(let i = 0; i < n; i++) { // No. of elements equals to x, // that is, e. if (a[i] == x) e++; // No. of elements greater than x, // that is, h. else if (a[i] > x) h++; // No. of elements smaller than x, // that is, l. else if (a[i] < x) l++; } let ans = 0; if (l > h) ans = l - h; else if (l < h) ans = h - l - 1; // Subtract the no. of elements // that are equal to x. return ans + 1 - e;} // Driver codelet x = 10;let a = [ 10, 20, 30 ];let n = a.length; document.write(minNumber(a, n, x)); // This code is contributed by suresh07 </script>
Output :
1
Time complexity : O(n)
This article is contributed by Sagar Shukla. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Prasad_Kshirsagar
jit_t
vt_m
SURENDRA_GANGWAR
29AjayKumar
Rajput-Ji
mukesh07
suresh07
median-finding
Order-Statistics
statistical-algorithms
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HeapSort
std::sort() in C++ STL
Time Complexities of all Sorting Algorithms
Radix Sort
Merge two sorted arrays
Chocolate Distribution Problem
Count Inversions in an array | Set 1 (Using Merge Sort)
Sort an array of 0s, 1s and 2s
k largest(or smallest) elements in an array
Python Program for Bubble Sort
|
[
{
"code": null,
"e": 26523,
"s": 26495,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 26833,
"s": 26523,
"text": "A median in an array with the length of n is an element which occupies position number (n+1)/2 after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17."
},
{
"code": null,
"e": 26845,
"s": 26833,
"text": "Examples : "
},
{
"code": null,
"e": 27181,
"s": 26845,
"text": "Input : 3 10\n 10 20 30\nOutput : 1\nIn the first sample we can add number 9 \nto array (10, 20, 30). The resulting array\n(9, 10, 20, 30) will have a median in \nposition (4+1)/2 = 2, that is, 10\n\nInput : 3 4\n 1 2 3\nOutput : 4\nIn the second sample you should add numbers \n4, 5, 5, 5. The resulting array has median\nequal to 4."
},
{
"code": null,
"e": 27347,
"s": 27181,
"text": "First Approach:- The approach is to add one more number x to the array until the median of the array equals to x. Below is the implementation of the above approach:-"
},
{
"code": null,
"e": 27351,
"s": 27347,
"text": "C++"
},
{
"code": null,
"e": 27356,
"s": 27351,
"text": "Java"
},
{
"code": null,
"e": 27364,
"s": 27356,
"text": "Python3"
},
{
"code": null,
"e": 27367,
"s": 27364,
"text": "C#"
},
{
"code": null,
"e": 27371,
"s": 27367,
"text": "PHP"
},
{
"code": null,
"e": 27382,
"s": 27371,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum number// of elements needs to add to the// array so that its median equals x.#include <bits/stdc++.h>using namespace std; // Returns count of elements to be// added to make median x. This function// assumes that a[] has enough extra space.int minNumber(int a[], int n, int x){ // to sort the array in increasing order. sort(a, a + n); int k; for (k = 0; a[(n - 1) / 2] != x; k++) { a[n++] = x; sort(a, a + n); } return k;} // Driver codemain(){ int x = 10; int a[6] = { 10, 20, 30 }; int n = 3; cout << minNumber(a, n, x) << endl; return 0;}",
"e": 28006,
"s": 27382,
"text": null
},
{
"code": "// Java program to find minimum number// of elements needs to add to the// array so that its median equals x.import java.util.Arrays; class GFG{ // Returns count of elements to be// added to make median x. This function// assumes that a[] has enough extra space.static int minNumber(int a[], int n, int x){ // to sort the array in increasing order. Arrays.sort(a); int k; for (k = 0; a[(n) / 2] != x; k++) { a[n++] = x; Arrays.sort(a); } return k;} // Driver codepublic static void main(String[] args){ int x = 10; int a[] = { 10, 20, 30 }; int n = 3; System.out.println(minNumber(a, n-1, x));}} // This code has been contributed by 29AjayKumar",
"e": 28699,
"s": 28006,
"text": null
},
{
"code": "# Python3 program to find minimum number# of elements needs to add to the# array so that its median equals x. # Returns count of elements to be added # to make median x. This function# assumes that a[] has enough extra space.def minNumber(a, n, x): # to sort the array in increasing order. a.sort(reverse = False) k = 0 while(a[int((n - 1) / 2)] != x): a[n - 1] = x n += 1 a.sort(reverse = False) k += 1 return k # Driver codeif __name__ == '__main__': x = 10 a = [10, 20, 30] n = 3 print(minNumber(a, n, x)) # This code is contributed by# Surendra_Gangwar",
"e": 29317,
"s": 28699,
"text": null
},
{
"code": "// C# program to find minimum number// of elements needs to add to the// array so that its median equals x.using System; class GFG{ // Returns count of elements to be// added to make median x. This function// assumes that a[] has enough extra space.static int minNumber(int []a, int n, int x){ // to sort the array in increasing order. Array.Sort(a); int k; for (k = 0; a[(n) / 2] != x; k++) { a[n++] = x; Array.Sort(a); } return k;} // Driver codepublic static void Main(String[] args){ int x = 10; int []a = { 10, 20, 30 }; int n = 3; Console.WriteLine(minNumber(a, n-1, x));}} // This code contributed by Rajput-Ji",
"e": 29983,
"s": 29317,
"text": null
},
{
"code": "<?php// PHP program to find minimum// number of elements needs to// add to the array so that its// median equals x. // Returns count of elements// to be added to make median// x. This function assumes// that a[] has enough extra space.function minNumber($a, $n, $x){ // to sort the array in // increasing order. sort($a); $k; for ($k = 0; $a[($n - 1) / 2] != $x; $k++) { $a[$n++] = $x; sort($a); } return $k;} // Driver code$x = 10;$a = array (10, 20, 30);$n = 3;echo minNumber($a, $n, $x),\"\\n\"; // This code is contributed by ajit?>",
"e": 30564,
"s": 29983,
"text": null
},
{
"code": "<script> // Javascript program to find minimum number // of elements needs to add to the // array so that its median equals x. // Returns count of elements to be // added to make median x. This function // assumes that a[] has enough extra space. function minNumber(a, n, x) { // to sort the array in increasing order. a.sort(); let k; for (k = 0; a[parseInt((n - 1) / 2, 10)] != x; k++) { a[n++] = x; a.sort(); } return k; } let x = 10; let a = [ 10, 20, 30 ]; let n = 3; document.write(minNumber(a, n, x)); // This code is contributed by mukesh07.</script>",
"e": 31249,
"s": 30564,
"text": null
},
{
"code": null,
"e": 31259,
"s": 31249,
"text": "Output : "
},
{
"code": null,
"e": 31261,
"s": 31259,
"text": "1"
},
{
"code": null,
"e": 31289,
"s": 31261,
"text": "Time complexity : O(knLogn)"
},
{
"code": null,
"e": 31652,
"s": 31289,
"text": "Second Approach:- Better approach is to count all the elements equal to x(that is e), greater than x(that is h) and smaller than x(that is l). And then – if l is greater than h then, the ans will be (l – h) + 1 – e; And if h is greater than l then, ans will be (h – l – 1) + 1 – e;We can use Hoare’s partition scheme to count smaller, equal and greater elements."
},
{
"code": null,
"e": 31704,
"s": 31652,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 31708,
"s": 31704,
"text": "C++"
},
{
"code": null,
"e": 31713,
"s": 31708,
"text": "Java"
},
{
"code": null,
"e": 31721,
"s": 31713,
"text": "Python3"
},
{
"code": null,
"e": 31724,
"s": 31721,
"text": "C#"
},
{
"code": null,
"e": 31728,
"s": 31724,
"text": "PHP"
},
{
"code": null,
"e": 31739,
"s": 31728,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum number of// elements to add so that its median// equals x.#include <bits/stdc++.h>using namespace std; int minNumber(int a[], int n, int x){ int l = 0, h = 0, e = 0; for (int i = 0; i < n; i++) { // no. of elements equals to x, // that is, e. if (a[i] == x) e++; // no. of elements greater than x, // that is, h. else if (a[i] > x) h++; // no. of elements smaller than x, // that is, l. else if (a[i] < x) l++; } int ans = 0; if (l > h) ans = l - h; else if (l < h) ans = h - l - 1; // subtract the no. of elements // that are equal to x. return ans + 1 - e;} // Driver codeint main(){ int x = 10; int a[] = { 10, 20, 30 }; int n = sizeof(a) / sizeof(a[0]); cout << minNumber(a, n, x) << endl; return 0;}",
"e": 32636,
"s": 31739,
"text": null
},
{
"code": "// Java program to find minimum number// of elements to add so that its// median equals x.import java.util.*;import java.lang.*; class GFG { public static int minNumber(int a[], int n, int x) { int l = 0, h = 0, e = 0; for (int i = 0; i < n; i++) { // no. of elements equals to // x, that is, e. if (a[i] == x) e++; // no. of elements greater // than x, that is, h. else if (a[i] > x) h++; // no. of elements smaller // than x, that is, l. else if (a[i] < x) l++; } int ans = 0; if (l > h) ans = l - h; else if (l < h) ans = h - l - 1; // subtract the no. of elements // that are equal to x. return ans + 1 - e; } // Driven Program public static void main(String[] args) { int x = 10; int a[] = { 10, 20, 30 }; int n = a.length; System.out.println( minNumber(a, n, x)); }} // This code is contributed by// Prasad Kshirsagar",
"e": 33803,
"s": 32636,
"text": null
},
{
"code": "# Python3 program to find minimum number# of elements to add so that its median# equals x. def minNumber (a, n, x): l = 0 h = 0 e = 0 for i in range(n): # no. of elements equals to x, # that is, e. if a[i] == x: e+=1 # no. of elements greater than x, # that is, h. elif a[i] > x: h+=1 # no. of elements smaller than x, # that is, l. elif a[i] < x: l+=1 ans = 0; if l > h: ans = l - h elif l < h: ans = h - l - 1; # subtract the no. of elements # that are equal to x. return ans + 1 - e # Driver codex = 10a = [10, 20, 30]n = len(a)print(minNumber(a, n, x)) # This code is contributed# by \"Abhishek Sharma 44\"",
"e": 34585,
"s": 33803,
"text": null
},
{
"code": "// C# program to find minimum// number of elements to add// so that its median equals x.using System; class GFG{public static int minNumber(int []a, int n, int x){ int l = 0, h = 0, e = 0; for (int i = 0; i < n; i++) { // no. of elements // equals to x, // that is, e. if (a[i] == x) e++; // no. of elements // greater than x, // that is, h. else if (a[i] > x) h++; // no. of elements smaller // than x, that is, l. else if (a[i] < x) l++; } int ans = 0; if (l > h) ans = l - h; else if (l < h) ans = h - l - 1; // subtract the no. // of elements that // are equal to x. return ans + 1 - e;} // Driver Codepublic static void Main(){ int x = 10; int []a = {10, 20, 30}; int n = a.Length; Console.WriteLine( minNumber(a, n, x));}} // This code is contributed// by anuj_67.",
"e": 35599,
"s": 34585,
"text": null
},
{
"code": "<?php// PHP program to find minimum// number of elements to add so // that its median equals x. function minNumber($a, $n, $x){ $l = 0; $h = 0; $e = 0; for ($i = 0; $i < $n; $i++) { // no. of elements equals // to x, that is, e. if ($a[$i] == $x) $e++; // no. of elements greater // than x, that is, h. else if ($a[$i] > $x) $h++; // no. of elements smaller // than x, that is, l. else if ($a[$i] < $x) $l++; } $ans = 0; if ($l > $h) $ans = $l - $h; else if ($l < $h) $ans = $h - $l - 1; // subtract the no. of elements // that are equal to x. return $ans + 1 - $e;} // Driver code$x = 10;$a = array (10, 20, 30);$n = sizeof($a) ;echo minNumber($a, $n, $x), \"\\n\"; // This code is contributed by jit_t?>",
"e": 36452,
"s": 35599,
"text": null
},
{
"code": "<script> // Javascript program to find minimum number// of elements to add so that its median// equals x.function minNumber(a, n, x){ let l = 0, h = 0, e = 0; for(let i = 0; i < n; i++) { // No. of elements equals to x, // that is, e. if (a[i] == x) e++; // No. of elements greater than x, // that is, h. else if (a[i] > x) h++; // No. of elements smaller than x, // that is, l. else if (a[i] < x) l++; } let ans = 0; if (l > h) ans = l - h; else if (l < h) ans = h - l - 1; // Subtract the no. of elements // that are equal to x. return ans + 1 - e;} // Driver codelet x = 10;let a = [ 10, 20, 30 ];let n = a.length; document.write(minNumber(a, n, x)); // This code is contributed by suresh07 </script>",
"e": 37309,
"s": 36452,
"text": null
},
{
"code": null,
"e": 37319,
"s": 37309,
"text": "Output : "
},
{
"code": null,
"e": 37321,
"s": 37319,
"text": "1"
},
{
"code": null,
"e": 37344,
"s": 37321,
"text": "Time complexity : O(n)"
},
{
"code": null,
"e": 37769,
"s": 37344,
"text": "This article is contributed by Sagar Shukla. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 37787,
"s": 37769,
"text": "Prasad_Kshirsagar"
},
{
"code": null,
"e": 37793,
"s": 37787,
"text": "jit_t"
},
{
"code": null,
"e": 37798,
"s": 37793,
"text": "vt_m"
},
{
"code": null,
"e": 37815,
"s": 37798,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 37827,
"s": 37815,
"text": "29AjayKumar"
},
{
"code": null,
"e": 37837,
"s": 37827,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 37846,
"s": 37837,
"text": "mukesh07"
},
{
"code": null,
"e": 37855,
"s": 37846,
"text": "suresh07"
},
{
"code": null,
"e": 37870,
"s": 37855,
"text": "median-finding"
},
{
"code": null,
"e": 37887,
"s": 37870,
"text": "Order-Statistics"
},
{
"code": null,
"e": 37910,
"s": 37887,
"text": "statistical-algorithms"
},
{
"code": null,
"e": 37918,
"s": 37910,
"text": "Sorting"
},
{
"code": null,
"e": 37926,
"s": 37918,
"text": "Sorting"
},
{
"code": null,
"e": 38024,
"s": 37926,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38033,
"s": 38024,
"text": "HeapSort"
},
{
"code": null,
"e": 38056,
"s": 38033,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 38100,
"s": 38056,
"text": "Time Complexities of all Sorting Algorithms"
},
{
"code": null,
"e": 38111,
"s": 38100,
"text": "Radix Sort"
},
{
"code": null,
"e": 38135,
"s": 38111,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 38166,
"s": 38135,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 38222,
"s": 38166,
"text": "Count Inversions in an array | Set 1 (Using Merge Sort)"
},
{
"code": null,
"e": 38253,
"s": 38222,
"text": "Sort an array of 0s, 1s and 2s"
},
{
"code": null,
"e": 38297,
"s": 38253,
"text": "k largest(or smallest) elements in an array"
}
] |
How to find width and height of an image using Python? - GeeksforGeeks
|
13 Jan, 2021
In this article, we are going to discuss how to get the height and width of a particular image.
In order to find the height and width of an image, there are two approaches. The first approach is by using the PIL(Pillow) library and the second approach is by using the Open-CV library.
Approach 1:
PIL is the Python Imaging Library is an important module which is used for image processing. It supports many formats of images such as “jpeg”, “png”, “ppm”, “tiff”, “bmp”, “gif”. It provides many image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image.
PIL.Image.open() is used to open the image and then .width and .height property of Image are used to get the height and width of the image. The same results can be obtained by using .size property.
To use pillow library run the following command:
pip install pillow
Image Used:
Image Used
Code:
Python
# import required modulefrom PIL import Image # get imagefilepath = "geeksforgeeks.png"img = Image.open(filepath) # get width and heightwidth = img.widthheight = img.height # display width and heightprint("The height of the image is: ", height)print("The width of the image is: ", width)
Output:
Alternative:
An alternate way to get height and width is using .size property.
Example:
Image Used:
Image Used
Code:
Python
# import required modulefrom PIL import Image # get imagefilepath = "geeksforgeeks.png"img = Image.open(filepath) # get width and heightwidth,height = img.size # display width and heightprint("The height of the image is: ", height)print("The width of the image is: ", width)
Output:
Approach 2:
OpenCV in python is a library which is used for computer vision, image processing and much more. The imread(filepath) function is used to load an image from the file path specified. The .shape stores a tuple of height, width and no of channels for each pixel. The .shape[:2] will get the height and width of the image.
To install OpenCV run the following command:
pip install opencv-python
Code:
Python
# import required moduleimport cv2 # get imagefilepath = "geeksforgeeks.jpg"image = cv2.imread(filepath)#print(image.shape) # get width and heightheight, width = image.shape[:2] # display width and heightprint("The height of the image is: ", height)print("The width of the image is: ", width)
Output:
Picked
Python-OpenCV
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n13 Jan, 2021"
},
{
"code": null,
"e": 25651,
"s": 25555,
"text": "In this article, we are going to discuss how to get the height and width of a particular image."
},
{
"code": null,
"e": 25840,
"s": 25651,
"text": "In order to find the height and width of an image, there are two approaches. The first approach is by using the PIL(Pillow) library and the second approach is by using the Open-CV library."
},
{
"code": null,
"e": 25852,
"s": 25840,
"text": "Approach 1:"
},
{
"code": null,
"e": 26172,
"s": 25852,
"text": "PIL is the Python Imaging Library is an important module which is used for image processing. It supports many formats of images such as “jpeg”, “png”, “ppm”, “tiff”, “bmp”, “gif”. It provides many image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. "
},
{
"code": null,
"e": 26370,
"s": 26172,
"text": "PIL.Image.open() is used to open the image and then .width and .height property of Image are used to get the height and width of the image. The same results can be obtained by using .size property."
},
{
"code": null,
"e": 26419,
"s": 26370,
"text": "To use pillow library run the following command:"
},
{
"code": null,
"e": 26438,
"s": 26419,
"text": "pip install pillow"
},
{
"code": null,
"e": 26450,
"s": 26438,
"text": "Image Used:"
},
{
"code": null,
"e": 26461,
"s": 26450,
"text": "Image Used"
},
{
"code": null,
"e": 26467,
"s": 26461,
"text": "Code:"
},
{
"code": null,
"e": 26474,
"s": 26467,
"text": "Python"
},
{
"code": "# import required modulefrom PIL import Image # get imagefilepath = \"geeksforgeeks.png\"img = Image.open(filepath) # get width and heightwidth = img.widthheight = img.height # display width and heightprint(\"The height of the image is: \", height)print(\"The width of the image is: \", width)",
"e": 26765,
"s": 26474,
"text": null
},
{
"code": null,
"e": 26773,
"s": 26765,
"text": "Output:"
},
{
"code": null,
"e": 26786,
"s": 26773,
"text": "Alternative:"
},
{
"code": null,
"e": 26852,
"s": 26786,
"text": "An alternate way to get height and width is using .size property."
},
{
"code": null,
"e": 26861,
"s": 26852,
"text": "Example:"
},
{
"code": null,
"e": 26873,
"s": 26861,
"text": "Image Used:"
},
{
"code": null,
"e": 26884,
"s": 26873,
"text": "Image Used"
},
{
"code": null,
"e": 26890,
"s": 26884,
"text": "Code:"
},
{
"code": null,
"e": 26897,
"s": 26890,
"text": "Python"
},
{
"code": "# import required modulefrom PIL import Image # get imagefilepath = \"geeksforgeeks.png\"img = Image.open(filepath) # get width and heightwidth,height = img.size # display width and heightprint(\"The height of the image is: \", height)print(\"The width of the image is: \", width)",
"e": 27175,
"s": 26897,
"text": null
},
{
"code": null,
"e": 27183,
"s": 27175,
"text": "Output:"
},
{
"code": null,
"e": 27195,
"s": 27183,
"text": "Approach 2:"
},
{
"code": null,
"e": 27515,
"s": 27195,
"text": "OpenCV in python is a library which is used for computer vision, image processing and much more. The imread(filepath) function is used to load an image from the file path specified. The .shape stores a tuple of height, width and no of channels for each pixel. The .shape[:2] will get the height and width of the image."
},
{
"code": null,
"e": 27560,
"s": 27515,
"text": "To install OpenCV run the following command:"
},
{
"code": null,
"e": 27586,
"s": 27560,
"text": "pip install opencv-python"
},
{
"code": null,
"e": 27592,
"s": 27586,
"text": "Code:"
},
{
"code": null,
"e": 27599,
"s": 27592,
"text": "Python"
},
{
"code": "# import required moduleimport cv2 # get imagefilepath = \"geeksforgeeks.jpg\"image = cv2.imread(filepath)#print(image.shape) # get width and heightheight, width = image.shape[:2] # display width and heightprint(\"The height of the image is: \", height)print(\"The width of the image is: \", width)",
"e": 27895,
"s": 27599,
"text": null
},
{
"code": null,
"e": 27903,
"s": 27895,
"text": "Output:"
},
{
"code": null,
"e": 27910,
"s": 27903,
"text": "Picked"
},
{
"code": null,
"e": 27924,
"s": 27910,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 27935,
"s": 27924,
"text": "Python-pil"
},
{
"code": null,
"e": 27942,
"s": 27935,
"text": "Python"
},
{
"code": null,
"e": 28040,
"s": 27942,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28072,
"s": 28040,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28114,
"s": 28072,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28156,
"s": 28114,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28212,
"s": 28156,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28239,
"s": 28212,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28270,
"s": 28239,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28309,
"s": 28270,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28338,
"s": 28309,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28360,
"s": 28338,
"text": "Defaultdict in Python"
}
] |
RIPEMD Hash Function - GeeksforGeeks
|
10 Feb, 2020
Hash Function is a function that has a huge role in making a System Secure as it converts normal data given to it as an irregular value of fixed length. We can imagine it to be a Shaker in our homes. When we put data into this function it outputs an irregular value. The Irregular value it outputs is known as “Hash Value”. Hash Values are simply numbers but are often written in Hexadecimal. Computers manage values as Binary. The hash value is also a data and are often managed in Binary.
RIPEMD(RACE Integrity Primitives Evaluation Message Digest) is a group of hash function which is developed by Hans Dobbertin, Antoon Bosselaers and Bart Preneel in 1992. The development idea of RIPEMD is based on MD4 which in itself is a weak hash function. It is developed to work well with 32-bit processors.Types of RIPEMD:
RIPEMD-128
RIPEMD-160
RIPEMD-256
RIPEMD-320
It is a sub-block of the RIPEMD-160 hash algorithm. The message is processed by compression function in blocks of 512 bits and passed through two streams of this sub-block by using 5 different versions in which the value of constant ‘k’ is also different.
Different Versions of RIPEMD
The first RIPEMD was not considered as a good hash function because of some design flaws which leads to some major security problems one of which is the size of output that is 128 bit which is too small and easy to break. In the next version RIPEMD-128, the design flaw is removed but the output is still 128 bit which makes it less secure.
RIPEMD-160 is the next version which increases the output length to 160 bit and increases the security level of the hash function. This function is designed to work as a replacement for 128-bit hash functions MD4, MD5, and RIPEMD-128.
RIPEMD-256 and RIPEMD-320 are extension of RIPEMD-128 which provide same security as RIPEMD-160 and RIPEMD-128 which is designed for application which prefer large hash value rather than more security level.
Example 1:
# Python program to demonstrate# RIPEMD import hashlib # Passing the required algorithm# as string to the new constructorx = hashlib.new('ripemd160') # passing GeeksforGeeks # to x() which uses # ripemd 160 algorithm for# hashingx.update(b"GeeksForGeeks") # printing the equivalent hexadecimal# value. print("The hexadecimal equivalent of hash is :") print(x.hexdigest())
Output:
The hexadecimal equivalent of hash is :
1b4470fb3147534653ddca6d7a1b2109b5449089
In the above example, the new() constructor takes the algorithm name as a string and creates an object for that algorithm. Then the update() method takes a binary string so that it can be accepted by the hash function. The x() hash function encodes it and then using hexdigest(), hexadecimal equivalent encoded string is printed.
Example 2: Let’s see if we want to find the byte representation of the encoded hash value.
# Python program to demonstrate# RIPEMD import hashlib # Passing the required algorithm# as string to the new constructorx = hashlib.new('ripemd160') # passing GeeksforGeeks # to x() which uses # ripemd 160 algorithm for# hashingx.update(b"GeeksForGeeks") # printing the equivalent hexadecimal# value. print("The byte equivalent of hash is :") print(x.digest())
Output:
The byte equivalent of hash is :
b'\x1bDp\xfb1GSFS\xdd\xcamz\x1b!\t\xb5D\x90\x89'
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
|
[
{
"code": null,
"e": 25771,
"s": 25743,
"text": "\n10 Feb, 2020"
},
{
"code": null,
"e": 26262,
"s": 25771,
"text": "Hash Function is a function that has a huge role in making a System Secure as it converts normal data given to it as an irregular value of fixed length. We can imagine it to be a Shaker in our homes. When we put data into this function it outputs an irregular value. The Irregular value it outputs is known as “Hash Value”. Hash Values are simply numbers but are often written in Hexadecimal. Computers manage values as Binary. The hash value is also a data and are often managed in Binary."
},
{
"code": null,
"e": 26589,
"s": 26262,
"text": "RIPEMD(RACE Integrity Primitives Evaluation Message Digest) is a group of hash function which is developed by Hans Dobbertin, Antoon Bosselaers and Bart Preneel in 1992. The development idea of RIPEMD is based on MD4 which in itself is a weak hash function. It is developed to work well with 32-bit processors.Types of RIPEMD:"
},
{
"code": null,
"e": 26600,
"s": 26589,
"text": "RIPEMD-128"
},
{
"code": null,
"e": 26611,
"s": 26600,
"text": "RIPEMD-160"
},
{
"code": null,
"e": 26622,
"s": 26611,
"text": "RIPEMD-256"
},
{
"code": null,
"e": 26633,
"s": 26622,
"text": "RIPEMD-320"
},
{
"code": null,
"e": 26889,
"s": 26633,
"text": "It is a sub-block of the RIPEMD-160 hash algorithm. The message is processed by compression function in blocks of 512 bits and passed through two streams of this sub-block by using 5 different versions in which the value of constant ‘k’ is also different."
},
{
"code": null,
"e": 26918,
"s": 26889,
"text": "Different Versions of RIPEMD"
},
{
"code": null,
"e": 27259,
"s": 26918,
"text": "The first RIPEMD was not considered as a good hash function because of some design flaws which leads to some major security problems one of which is the size of output that is 128 bit which is too small and easy to break. In the next version RIPEMD-128, the design flaw is removed but the output is still 128 bit which makes it less secure."
},
{
"code": null,
"e": 27494,
"s": 27259,
"text": "RIPEMD-160 is the next version which increases the output length to 160 bit and increases the security level of the hash function. This function is designed to work as a replacement for 128-bit hash functions MD4, MD5, and RIPEMD-128."
},
{
"code": null,
"e": 27702,
"s": 27494,
"text": "RIPEMD-256 and RIPEMD-320 are extension of RIPEMD-128 which provide same security as RIPEMD-160 and RIPEMD-128 which is designed for application which prefer large hash value rather than more security level."
},
{
"code": null,
"e": 27713,
"s": 27702,
"text": "Example 1:"
},
{
"code": "# Python program to demonstrate# RIPEMD import hashlib # Passing the required algorithm# as string to the new constructorx = hashlib.new('ripemd160') # passing GeeksforGeeks # to x() which uses # ripemd 160 algorithm for# hashingx.update(b\"GeeksForGeeks\") # printing the equivalent hexadecimal# value. print(\"The hexadecimal equivalent of hash is :\") print(x.hexdigest())",
"e": 28092,
"s": 27713,
"text": null
},
{
"code": null,
"e": 28100,
"s": 28092,
"text": "Output:"
},
{
"code": null,
"e": 28182,
"s": 28100,
"text": "The hexadecimal equivalent of hash is :\n1b4470fb3147534653ddca6d7a1b2109b5449089\n"
},
{
"code": null,
"e": 28512,
"s": 28182,
"text": "In the above example, the new() constructor takes the algorithm name as a string and creates an object for that algorithm. Then the update() method takes a binary string so that it can be accepted by the hash function. The x() hash function encodes it and then using hexdigest(), hexadecimal equivalent encoded string is printed."
},
{
"code": null,
"e": 28603,
"s": 28512,
"text": "Example 2: Let’s see if we want to find the byte representation of the encoded hash value."
},
{
"code": "# Python program to demonstrate# RIPEMD import hashlib # Passing the required algorithm# as string to the new constructorx = hashlib.new('ripemd160') # passing GeeksforGeeks # to x() which uses # ripemd 160 algorithm for# hashingx.update(b\"GeeksForGeeks\") # printing the equivalent hexadecimal# value. print(\"The byte equivalent of hash is :\") print(x.digest())",
"e": 28972,
"s": 28603,
"text": null
},
{
"code": null,
"e": 28980,
"s": 28972,
"text": "Output:"
},
{
"code": null,
"e": 29063,
"s": 28980,
"text": "The byte equivalent of hash is :\nb'\\x1bDp\\xfb1GSFS\\xdd\\xcamz\\x1b!\\t\\xb5D\\x90\\x89'\n"
},
{
"code": null,
"e": 29078,
"s": 29063,
"text": "python-utility"
},
{
"code": null,
"e": 29085,
"s": 29078,
"text": "Python"
},
{
"code": null,
"e": 29183,
"s": 29085,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29201,
"s": 29183,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29233,
"s": 29201,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29255,
"s": 29233,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29297,
"s": 29255,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29327,
"s": 29297,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29353,
"s": 29327,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29382,
"s": 29353,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29426,
"s": 29382,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 29463,
"s": 29426,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Permutation Hypothesis Test in R Programming - GeeksforGeeks
|
24 Nov, 2020
In simple words, the permutation hypothesis test in R is a way of comparing a numerical value of 2 groups. The permutation Hypothesis test is an alternative to:
Independent two-sample t-test
Mann-Whitney U aka Wilcoxon Rank-Sum Test
Let’s implement this test in R programming.
Small Sample Size.
Assumptions(for parametric approach) not met.
Test something other than classic approaches comparing Means and Medians.
Difficult to estimate the SE for test-statistic.
Specify a hypothesis Choose test-stat(Eg: Mean, Median, etc. ) Determine Distribution of test-stat Convert test-stat to P-value
Specify a hypothesis
Choose test-stat(Eg: Mean, Median, etc. )
Determine Distribution of test-stat
Convert test-stat to P-value
Note:P-value = No. of permutations having a test-stat value greater than observed test-stat value/ No. of permutations.
Dataset: Chicken Diet Data. This dataset is a subset of the “chickwts” data in the “R dataset package”. Download the data set here.
Hypothesis: The weight of the chicken is independent of the type of diet.
Test-Statistics
Test-Statistics #1: The absolute value of the difference in mean weights for the two diets | Y1 – Y2 |. This is the same test statistics as the independent two-sided two-sample t-test.
Test-Statistics #2: The absolute value of the difference in median weights for the two diets | Median1 – Median2 |
R
# R program to illustrate# Permutation Hypothesis Test # load the data setd <- read.table(file = "ChickData.csv", header = T, sep = ",") # print the datasetprint(d) # check the namesnames(d)levels(d$feed) # how many observations in each diet?table(d$feed) # let's look at a boxplot of weight gain by those 2 dietsboxplot(d$weight~d$feed, las = 1, ylab = "weight (g)", xlab = "feed", main = "Weight by Feed") # calculate the difference in sample MEANSmean(d$weight[d$feed == "casein"]) # mean for caseinmean(d$weight[d$feed == "meatmeal"]) # mean for meatmeal # lets calculate the absolute diff in meanstest.stat1 <- abs(mean(d$weight[d$feed == "casein"]) - mean(d$weight[d$feed == "meatmeal"])) test.stat1 # calculate the difference in sample MEDIANSmedian(d$weight[d$feed == "casein"]) # median for caseinmedian(d$weight[d$feed == "meatmeal"]) # median for meatmeal # lets calculate the absolute diff in medianstest.stat2 <- abs(median(d$weight[d$feed == "casein"]) - median(d$weight[d$feed == "meatmeal"])) test.stat2 # Permutation Test # for reproducability of resultsset.seed(1979) # the number of observations to samplen <- length(d$feed) # the number of permutation samples to takeP <- 100000 # the variable we will resample from variable <- d$weight # initialize a matrix to store the permutation dataPermSamples <- matrix(0, nrow = n, ncol = P) # each column is a permutation sample of data# now, get those permutation samples, using a loop# let's take a moment to discuss what that code is doingfor(i in 1:P) { PermSamples[, i] <- sample(variable, size = n, replace = FALSE) } # we can take a quick look at the first 5 columns of PermSamplesPermSamples[, 1:5] # initialize vectors to store all of the Test-statsPerm.test.stat1 <- Perm.test.stat2 <- rep(0, P) # loop thru, and calculate the test-statsfor (i in 1:P) { # calculate the perm-test-stat1 and save it Perm.test.stat1[i] <- abs(mean(PermSamples[d$feed == "casein",i]) - mean(PermSamples[d$feed == "meatmeal",i])) # calculate the perm-test-stat2 and save it Perm.test.stat2[i] <- abs(median(PermSamples[d$feed == "casein",i]) - median(PermSamples[d$feed == "meatmeal",i])) } # before going too far with this, # let's remind ourselves of # the TEST STATStest.stat1; test.stat2 # and, take a look at the first 15 # permutation-TEST STATS for 1 and 2round(Perm.test.stat1[1:15], 1)round(Perm.test.stat2[1:15], 1) # and, let's calculate the permutation p-value# notice how we can ask R a true/false question(Perm.test.stat1 >= test.stat1)[1:15] # and if we ask for the mean of all of those,# it treats 0 = FALSE, 1 = TRUEmean((Perm.test.stat1 >= test.stat1)[1:15]) # Calculate the p-value, for all P = 100,000mean(Perm.test.stat1 >= test.stat1) # and, let's calculate the p-value for # option 2 of the test statistic (abs diff in medians)mean(Perm.test.stat2 >= test.stat2)
Output:
> print(d)
weight feed
1 325 meatmeal
2 257 meatmeal
3 303 meatmeal
4 315 meatmeal
5 380 meatmeal
6 153 meatmeal
7 263 meatmeal
8 242 meatmeal
9 206 meatmeal
10 344 meatmeal
11 258 meatmeal
12 368 casein
13 390 casein
14 379 casein
15 260 casein
16 404 casein
17 318 casein
18 352 casein
19 359 casein
20 216 casein
21 222 casein
22 283 casein
23 332 casein
> names(d)
[1] "weight" "feed"
> levels(d$feed)
[1] "casein" "meatmeal"
> table(d$feed)
casein meatmeal
12 11
> mean(d$weight[d$feed == "casein"]) # mean for casein
[1] 323.5833
> mean(d$weight[d$feed == "meatmeal"]) # mean for meatmeal
[1] 276.9091
> test.stat1
[1] 46.67424
> median(d$weight[d$feed == "casein"]) # median for casein
[1] 342
> median(d$weight[d$feed == "meatmeal"]) # median for meatmeal
[1] 263
> test.stat2
[1] 79
> PermSamples[, 1:5]
[,1] [,2] [,3] [,4] [,5]
[1,] 379 283 380 352 206
[2,] 380 303 258 260 380
[3,] 257 206 379 380 153
[4,] 283 242 222 404 359
[5,] 222 260 325 258 258
[6,] 315 352 153 379 263
[7,] 352 263 263 325 325
[8,] 153 325 315 359 216
[9,] 368 379 344 242 260
[10,] 344 258 368 368 257
[11,] 359 257 206 257 315
[12,] 206 153 404 222 303
[13,] 404 344 303 390 390
[14,] 325 318 318 303 352
[15,] 242 404 332 263 404
[16,] 390 380 257 206 379
[17,] 260 332 216 315 318
[18,] 303 359 352 344 368
[19,] 263 222 242 283 222
[20,] 332 368 260 332 344
[21,] 318 315 283 318 283
[22,] 216 390 390 153 332
[23,] 258 216 359 216 242
> test.stat1; test.stat2
[1] 46.67424
[1] 79
> round(Perm.test.stat1[1:15], 1)
[1] 17.1 32.4 17.6 47.1 56.1 28.9 31.0 40.8 6.8 13.8 9.1 46.5 28.9 50.9 32.7
> round(Perm.test.stat2[1:15], 1)
[1] 61.0 75.0 4.5 59.0 78.0 17.0 62.0 38.5 4.5 16.0 23.0 60.5 63.5 75.0 37.0
> (Perm.test.stat1 >= test.stat1)[1:15]
[1] FALSE FALSE FALSE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE
> mean((Perm.test.stat1 >= test.stat1)[1:15])
[1] 0.2
> mean(Perm.test.stat1 >= test.stat1)
[1] 0.09959
> mean(Perm.test.stat2 >= test.stat2)
[1] 0.05407
Picked
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
Time Series Analysis in R
R - if statement
Logistic Regression in R Programming
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n24 Nov, 2020"
},
{
"code": null,
"e": 26649,
"s": 26487,
"text": "In simple words, the permutation hypothesis test in R is a way of comparing a numerical value of 2 groups. The permutation Hypothesis test is an alternative to: "
},
{
"code": null,
"e": 26680,
"s": 26649,
"text": "Independent two-sample t-test "
},
{
"code": null,
"e": 26722,
"s": 26680,
"text": "Mann-Whitney U aka Wilcoxon Rank-Sum Test"
},
{
"code": null,
"e": 26766,
"s": 26722,
"text": "Let’s implement this test in R programming."
},
{
"code": null,
"e": 26786,
"s": 26766,
"text": "Small Sample Size. "
},
{
"code": null,
"e": 26833,
"s": 26786,
"text": "Assumptions(for parametric approach) not met. "
},
{
"code": null,
"e": 26908,
"s": 26833,
"text": "Test something other than classic approaches comparing Means and Medians. "
},
{
"code": null,
"e": 26957,
"s": 26908,
"text": "Difficult to estimate the SE for test-statistic."
},
{
"code": null,
"e": 27086,
"s": 26957,
"text": "Specify a hypothesis Choose test-stat(Eg: Mean, Median, etc. ) Determine Distribution of test-stat Convert test-stat to P-value "
},
{
"code": null,
"e": 27108,
"s": 27086,
"text": "Specify a hypothesis "
},
{
"code": null,
"e": 27151,
"s": 27108,
"text": "Choose test-stat(Eg: Mean, Median, etc. ) "
},
{
"code": null,
"e": 27188,
"s": 27151,
"text": "Determine Distribution of test-stat "
},
{
"code": null,
"e": 27218,
"s": 27188,
"text": "Convert test-stat to P-value "
},
{
"code": null,
"e": 27338,
"s": 27218,
"text": "Note:P-value = No. of permutations having a test-stat value greater than observed test-stat value/ No. of permutations."
},
{
"code": null,
"e": 27470,
"s": 27338,
"text": "Dataset: Chicken Diet Data. This dataset is a subset of the “chickwts” data in the “R dataset package”. Download the data set here."
},
{
"code": null,
"e": 27544,
"s": 27470,
"text": "Hypothesis: The weight of the chicken is independent of the type of diet."
},
{
"code": null,
"e": 27560,
"s": 27544,
"text": "Test-Statistics"
},
{
"code": null,
"e": 27745,
"s": 27560,
"text": "Test-Statistics #1: The absolute value of the difference in mean weights for the two diets | Y1 – Y2 |. This is the same test statistics as the independent two-sided two-sample t-test."
},
{
"code": null,
"e": 27860,
"s": 27745,
"text": "Test-Statistics #2: The absolute value of the difference in median weights for the two diets | Median1 – Median2 |"
},
{
"code": null,
"e": 27862,
"s": 27860,
"text": "R"
},
{
"code": "# R program to illustrate# Permutation Hypothesis Test # load the data setd <- read.table(file = \"ChickData.csv\", header = T, sep = \",\") # print the datasetprint(d) # check the namesnames(d)levels(d$feed) # how many observations in each diet?table(d$feed) # let's look at a boxplot of weight gain by those 2 dietsboxplot(d$weight~d$feed, las = 1, ylab = \"weight (g)\", xlab = \"feed\", main = \"Weight by Feed\") # calculate the difference in sample MEANSmean(d$weight[d$feed == \"casein\"]) # mean for caseinmean(d$weight[d$feed == \"meatmeal\"]) # mean for meatmeal # lets calculate the absolute diff in meanstest.stat1 <- abs(mean(d$weight[d$feed == \"casein\"]) - mean(d$weight[d$feed == \"meatmeal\"])) test.stat1 # calculate the difference in sample MEDIANSmedian(d$weight[d$feed == \"casein\"]) # median for caseinmedian(d$weight[d$feed == \"meatmeal\"]) # median for meatmeal # lets calculate the absolute diff in medianstest.stat2 <- abs(median(d$weight[d$feed == \"casein\"]) - median(d$weight[d$feed == \"meatmeal\"])) test.stat2 # Permutation Test # for reproducability of resultsset.seed(1979) # the number of observations to samplen <- length(d$feed) # the number of permutation samples to takeP <- 100000 # the variable we will resample from variable <- d$weight # initialize a matrix to store the permutation dataPermSamples <- matrix(0, nrow = n, ncol = P) # each column is a permutation sample of data# now, get those permutation samples, using a loop# let's take a moment to discuss what that code is doingfor(i in 1:P) { PermSamples[, i] <- sample(variable, size = n, replace = FALSE) } # we can take a quick look at the first 5 columns of PermSamplesPermSamples[, 1:5] # initialize vectors to store all of the Test-statsPerm.test.stat1 <- Perm.test.stat2 <- rep(0, P) # loop thru, and calculate the test-statsfor (i in 1:P) { # calculate the perm-test-stat1 and save it Perm.test.stat1[i] <- abs(mean(PermSamples[d$feed == \"casein\",i]) - mean(PermSamples[d$feed == \"meatmeal\",i])) # calculate the perm-test-stat2 and save it Perm.test.stat2[i] <- abs(median(PermSamples[d$feed == \"casein\",i]) - median(PermSamples[d$feed == \"meatmeal\",i])) } # before going too far with this, # let's remind ourselves of # the TEST STATStest.stat1; test.stat2 # and, take a look at the first 15 # permutation-TEST STATS for 1 and 2round(Perm.test.stat1[1:15], 1)round(Perm.test.stat2[1:15], 1) # and, let's calculate the permutation p-value# notice how we can ask R a true/false question(Perm.test.stat1 >= test.stat1)[1:15] # and if we ask for the mean of all of those,# it treats 0 = FALSE, 1 = TRUEmean((Perm.test.stat1 >= test.stat1)[1:15]) # Calculate the p-value, for all P = 100,000mean(Perm.test.stat1 >= test.stat1) # and, let's calculate the p-value for # option 2 of the test statistic (abs diff in medians)mean(Perm.test.stat2 >= test.stat2)",
"e": 30956,
"s": 27862,
"text": null
},
{
"code": null,
"e": 30964,
"s": 30956,
"text": "Output:"
},
{
"code": null,
"e": 31554,
"s": 30964,
"text": "> print(d) \n weight feed\n1 325 meatmeal\n2 257 meatmeal\n3 303 meatmeal\n4 315 meatmeal\n5 380 meatmeal\n6 153 meatmeal\n7 263 meatmeal\n8 242 meatmeal\n9 206 meatmeal\n10 344 meatmeal\n11 258 meatmeal\n12 368 casein\n13 390 casein\n14 379 casein\n15 260 casein\n16 404 casein\n17 318 casein\n18 352 casein\n19 359 casein\n20 216 casein\n21 222 casein\n22 283 casein\n23 332 casein\n> names(d)\n[1] \"weight\" \"feed\" \n> levels(d$feed)\n[1] \"casein\" \"meatmeal\"\n> table(d$feed)\ncasein meatmeal \n 12 11 "
},
{
"code": null,
"e": 33205,
"s": 31554,
"text": "> mean(d$weight[d$feed == \"casein\"]) # mean for casein\n[1] 323.5833\n> mean(d$weight[d$feed == \"meatmeal\"]) # mean for meatmeal\n[1] 276.9091\n> test.stat1\n[1] 46.67424\n> median(d$weight[d$feed == \"casein\"]) # median for casein\n[1] 342\n> median(d$weight[d$feed == \"meatmeal\"]) # median for meatmeal\n[1] 263\n> test.stat2\n[1] 79\n> PermSamples[, 1:5]\n [,1] [,2] [,3] [,4] [,5]\n [1,] 379 283 380 352 206\n [2,] 380 303 258 260 380\n [3,] 257 206 379 380 153\n [4,] 283 242 222 404 359\n [5,] 222 260 325 258 258\n [6,] 315 352 153 379 263\n [7,] 352 263 263 325 325\n [8,] 153 325 315 359 216\n [9,] 368 379 344 242 260\n[10,] 344 258 368 368 257\n[11,] 359 257 206 257 315\n[12,] 206 153 404 222 303\n[13,] 404 344 303 390 390\n[14,] 325 318 318 303 352\n[15,] 242 404 332 263 404\n[16,] 390 380 257 206 379\n[17,] 260 332 216 315 318\n[18,] 303 359 352 344 368\n[19,] 263 222 242 283 222\n[20,] 332 368 260 332 344\n[21,] 318 315 283 318 283\n[22,] 216 390 390 153 332\n[23,] 258 216 359 216 242\n> test.stat1; test.stat2\n[1] 46.67424\n[1] 79\n> round(Perm.test.stat1[1:15], 1)\n [1] 17.1 32.4 17.6 47.1 56.1 28.9 31.0 40.8 6.8 13.8 9.1 46.5 28.9 50.9 32.7\n> round(Perm.test.stat2[1:15], 1)\n [1] 61.0 75.0 4.5 59.0 78.0 17.0 62.0 38.5 4.5 16.0 23.0 60.5 63.5 75.0 37.0\n> (Perm.test.stat1 >= test.stat1)[1:15]\n [1] FALSE FALSE FALSE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE\n> mean((Perm.test.stat1 >= test.stat1)[1:15])\n[1] 0.2\n> mean(Perm.test.stat1 >= test.stat1)\n[1] 0.09959\n> mean(Perm.test.stat2 >= test.stat2)\n[1] 0.05407"
},
{
"code": null,
"e": 33212,
"s": 33205,
"text": "Picked"
},
{
"code": null,
"e": 33225,
"s": 33212,
"text": "R-Statistics"
},
{
"code": null,
"e": 33236,
"s": 33225,
"text": "R Language"
},
{
"code": null,
"e": 33334,
"s": 33236,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33386,
"s": 33334,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 33421,
"s": 33386,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 33459,
"s": 33421,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 33517,
"s": 33459,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 33560,
"s": 33517,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 33597,
"s": 33560,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 33646,
"s": 33597,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 33672,
"s": 33646,
"text": "Time Series Analysis in R"
},
{
"code": null,
"e": 33689,
"s": 33672,
"text": "R - if statement"
}
] |
BigDecimal compareTo() Function in Java - GeeksforGeeks
|
04 Dec, 2018
The java.math.BigDecimal.compareTo(BigDecimal bg) method checks for equality of this BigDecimal and BigDecimal object bg passed as parameter. The method considers two equal BigDecimal objects even if they are equal in value irrespective of the scale.
Syntax:
public int compareTo(BigDecimal bg)
Parameters:This function accepts only one BigDecimal object of BigDecimal type for comparison with this BigDecimal object.
Return Value:This method can return the following values :
0 : if value of this BigDecimal is equal to that of BigDecimal object passed as parameter.
1 : if value of this BigDecimal is greater than that of BigDecimal object passed as parameter.
-1 : if value of this BigDecimal is less than that of BigDecimal object passed as parameter.
Note: The function returns true when it compares 124.0 and 124.0000, as it does not compare the scale of the two BigDecimal objects.
Examples:
Input : b1 = new BigDecimal("4743.0008"), b2 = new BigDecimal("4743.00001")
b1.compareTo(b2)
Output : 1
Input : b1 = new BigDecimal(4743), b2 = new BigDecimal("4743.00");
b1.compareTo(b2)
Output : 0
Below programs illustrate the working of compareTo() function of BigDecimal class:Program 1: For greater than condition:
// Java program to demonstrate compareTo() method import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating 2 BigDecimal objects BigDecimal b1, b2; b1 = new BigDecimal(67891); b2 = new BigDecimal(12346); if (b1.compareTo(b2) == 0) { System.out.println(b1 + " and " + b2 + " are equal."); } else if (b1.compareTo(b2) == 1) { System.out.println(b1 + " is greater than " + b2 + "."); } else { System.out.println(b1 + " is lesser than " + b2 + "."); } }}
67891 is greater than 12346.
Program 2: For equal condition:
// Java program to demonstrate compareTo() method import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating 2 BigDecimal objects BigDecimal b1, b2; b1 = new BigDecimal(67891); b2 = new BigDecimal("67891.000"); if (b1.compareTo(b2) == 0) { System.out.println(b1 + " and " + b2 + " are equal."); } else if (b1.compareTo(b2) == 1) { System.out.println(b1 + " is greater than " + b2 + "."); } else { System.out.println(b1 + " is lesser than " + b2 + "."); } }}
67891 and 67891.000 are equal.
Program 3: For less than condition:
// Java program to demonstrate compareTo() method import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating 2 BigDecimal objects BigDecimal b1, b2; b1 = new BigDecimal("4743.00001"); b2 = new BigDecimal("4743.0008"); if (b1.compareTo(b2) == 0) { System.out.println(b1 + " and " + b2 + " are equal."); } else if (b1.compareTo(b2) == 1) { System.out.println(b1 + " is greater than " + b2 + "."); } else { System.out.println(b1 + " is lesser than " + b2 + "."); } }}
4743.00001 is lesser than 4743.0008.
Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#compareTo(java.math.BigDecimal)
Java-BigDecimal
Java-Functions
java-math
Java-math-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
Singleton Class in Java
Set in Java
Multithreading in Java
Collections in Java
Queue Interface In Java
Initializing a List in Java
Overriding in Java
LinkedList in Java
|
[
{
"code": null,
"e": 25688,
"s": 25660,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 25939,
"s": 25688,
"text": "The java.math.BigDecimal.compareTo(BigDecimal bg) method checks for equality of this BigDecimal and BigDecimal object bg passed as parameter. The method considers two equal BigDecimal objects even if they are equal in value irrespective of the scale."
},
{
"code": null,
"e": 25947,
"s": 25939,
"text": "Syntax:"
},
{
"code": null,
"e": 25983,
"s": 25947,
"text": "public int compareTo(BigDecimal bg)"
},
{
"code": null,
"e": 26106,
"s": 25983,
"text": "Parameters:This function accepts only one BigDecimal object of BigDecimal type for comparison with this BigDecimal object."
},
{
"code": null,
"e": 26165,
"s": 26106,
"text": "Return Value:This method can return the following values :"
},
{
"code": null,
"e": 26256,
"s": 26165,
"text": "0 : if value of this BigDecimal is equal to that of BigDecimal object passed as parameter."
},
{
"code": null,
"e": 26351,
"s": 26256,
"text": "1 : if value of this BigDecimal is greater than that of BigDecimal object passed as parameter."
},
{
"code": null,
"e": 26444,
"s": 26351,
"text": "-1 : if value of this BigDecimal is less than that of BigDecimal object passed as parameter."
},
{
"code": null,
"e": 26577,
"s": 26444,
"text": "Note: The function returns true when it compares 124.0 and 124.0000, as it does not compare the scale of the two BigDecimal objects."
},
{
"code": null,
"e": 26587,
"s": 26577,
"text": "Examples:"
},
{
"code": null,
"e": 26806,
"s": 26587,
"text": "Input : b1 = new BigDecimal(\"4743.0008\"), b2 = new BigDecimal(\"4743.00001\")\n b1.compareTo(b2)\nOutput : 1\n\nInput : b1 = new BigDecimal(4743), b2 = new BigDecimal(\"4743.00\");\n b1.compareTo(b2)\nOutput : 0\n"
},
{
"code": null,
"e": 26927,
"s": 26806,
"text": "Below programs illustrate the working of compareTo() function of BigDecimal class:Program 1: For greater than condition:"
},
{
"code": "// Java program to demonstrate compareTo() method import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating 2 BigDecimal objects BigDecimal b1, b2; b1 = new BigDecimal(67891); b2 = new BigDecimal(12346); if (b1.compareTo(b2) == 0) { System.out.println(b1 + \" and \" + b2 + \" are equal.\"); } else if (b1.compareTo(b2) == 1) { System.out.println(b1 + \" is greater than \" + b2 + \".\"); } else { System.out.println(b1 + \" is lesser than \" + b2 + \".\"); } }}",
"e": 27551,
"s": 26927,
"text": null
},
{
"code": null,
"e": 27581,
"s": 27551,
"text": "67891 is greater than 12346.\n"
},
{
"code": null,
"e": 27613,
"s": 27581,
"text": "Program 2: For equal condition:"
},
{
"code": "// Java program to demonstrate compareTo() method import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating 2 BigDecimal objects BigDecimal b1, b2; b1 = new BigDecimal(67891); b2 = new BigDecimal(\"67891.000\"); if (b1.compareTo(b2) == 0) { System.out.println(b1 + \" and \" + b2 + \" are equal.\"); } else if (b1.compareTo(b2) == 1) { System.out.println(b1 + \" is greater than \" + b2 + \".\"); } else { System.out.println(b1 + \" is lesser than \" + b2 + \".\"); } }}",
"e": 28243,
"s": 27613,
"text": null
},
{
"code": null,
"e": 28275,
"s": 28243,
"text": "67891 and 67891.000 are equal.\n"
},
{
"code": null,
"e": 28311,
"s": 28275,
"text": "Program 3: For less than condition:"
},
{
"code": "// Java program to demonstrate compareTo() method import java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating 2 BigDecimal objects BigDecimal b1, b2; b1 = new BigDecimal(\"4743.00001\"); b2 = new BigDecimal(\"4743.0008\"); if (b1.compareTo(b2) == 0) { System.out.println(b1 + \" and \" + b2 + \" are equal.\"); } else if (b1.compareTo(b2) == 1) { System.out.println(b1 + \" is greater than \" + b2 + \".\"); } else { System.out.println(b1 + \" is lesser than \" + b2 + \".\"); } }}",
"e": 28948,
"s": 28311,
"text": null
},
{
"code": null,
"e": 28986,
"s": 28948,
"text": "4743.00001 is lesser than 4743.0008.\n"
},
{
"code": null,
"e": 29097,
"s": 28986,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#compareTo(java.math.BigDecimal)"
},
{
"code": null,
"e": 29113,
"s": 29097,
"text": "Java-BigDecimal"
},
{
"code": null,
"e": 29128,
"s": 29113,
"text": "Java-Functions"
},
{
"code": null,
"e": 29138,
"s": 29128,
"text": "java-math"
},
{
"code": null,
"e": 29156,
"s": 29138,
"text": "Java-math-package"
},
{
"code": null,
"e": 29161,
"s": 29156,
"text": "Java"
},
{
"code": null,
"e": 29166,
"s": 29161,
"text": "Java"
},
{
"code": null,
"e": 29264,
"s": 29166,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29279,
"s": 29264,
"text": "Stream In Java"
},
{
"code": null,
"e": 29298,
"s": 29279,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29322,
"s": 29298,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 29334,
"s": 29322,
"text": "Set in Java"
},
{
"code": null,
"e": 29357,
"s": 29334,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 29377,
"s": 29357,
"text": "Collections in Java"
},
{
"code": null,
"e": 29401,
"s": 29377,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 29429,
"s": 29401,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 29448,
"s": 29429,
"text": "Overriding in Java"
}
] |
ex command in Linux with examples - GeeksforGeeks
|
15 May, 2019
ex(stands for extended) is a text editor in Linux which is also termed as the line editor mode of the vi editor. This editor simply provided some editing commands which has greater mobility. With the help of this editor, a user can easily move between files. Also, he/she has a lot of ways to transfer the text from one file to another. A user can quickly edit blocks of text larger than a single screen and also can make substitutions throughout a file for a given pattern by using the global replacement.
Syntax:
% ex [filename]
Note: The prompt for the ex command is the ‘:’ character.
Important ex Editor Commands:
File Manipulation: There are two ways to edit a file, either we can use an old file or we can create a new file.a) Using an old fileSyntax:% ex oldfile
Example:b) Inserting a new fileSyntax:% ex newfile
Output:p Command : This is the one of the most basic command, p for print (to the screen). Suppose if you will type 1p at the prompt, then you will notice the first line of the file:Syntax:linenumber p
Example:To print more than one line: You can leave off the p because a line number by itself is equivalent to a print command for that line. Here, you can put a range of line numbers (e.g 1, 3) means the two numbers separated which are by commas. Here, the space are optional.Syntax:Starting LineNumber, Ending LineNumber
Example:Substitute Command : Allows you to substitute one word for another.Syntax::LineNumber s/CurrentWord/NewWord/
Example:Adding Text : To enter text in a new file we use a (short for append) command and the command i is used to inserting the text before the current line.Syntax:For Append
:a
This is the text
For inserting text before the current line.
:i
This is the text
Example:w Command : The command w (short for ‘write’) is used to save your data.Syntax:w [filename]
Example:d Command : This is used to delete the lines.Syntax:[line_range] d
Example:Note: If no line number is given the current line will be deleted. It is possible to give a range of lines. For example 1, $d will delete the entire file.To search a string: Searches are carried out by including the search string in slashes (‘/’):Note: The special characters ‘^’ and ‘$’ can be used to assist the search. For example /^This/ will find a line beginning and ‘This’/file$/ will find a line ending in ‘file’Syntax:/string/
Example:Reverse Searches: Generally, these are executed in question marks (‘?’) by including the search string. The search will start at the current line and search backward through the file.Syntax:?string?
Example:Quit Command: The command q (short for ‘quit’) is used to quit the editor.Syntax:quit! or q!
Example:It will navigate you back to the bashg command : The g command (for ‘global’) is used to make multiple substitutions on a line.Syntax:s/old/new/g
Example:help command: Print a brief help message.Syntax:h
Example:j command : The j command (for ‘join’) is used to joines the text. We can also add ! to prevent whitespaces.Syntax:[starting LineNumber, ending LineNumber]j!
Example 1:1, 5j! Join first five lines, preserving whitespace
File Manipulation: There are two ways to edit a file, either we can use an old file or we can create a new file.a) Using an old fileSyntax:% ex oldfile
Example:b) Inserting a new fileSyntax:% ex newfile
Output:
a) Using an old fileSyntax:% ex oldfile
Example:
Syntax:
% ex oldfile
Example:
b) Inserting a new fileSyntax:% ex newfile
Output:
Syntax:
% ex newfile
Output:
p Command : This is the one of the most basic command, p for print (to the screen). Suppose if you will type 1p at the prompt, then you will notice the first line of the file:Syntax:linenumber p
Example:To print more than one line: You can leave off the p because a line number by itself is equivalent to a print command for that line. Here, you can put a range of line numbers (e.g 1, 3) means the two numbers separated which are by commas. Here, the space are optional.Syntax:Starting LineNumber, Ending LineNumber
Example:
Syntax:
linenumber p
Example:
To print more than one line: You can leave off the p because a line number by itself is equivalent to a print command for that line. Here, you can put a range of line numbers (e.g 1, 3) means the two numbers separated which are by commas. Here, the space are optional.Syntax:Starting LineNumber, Ending LineNumber
Example:
Syntax:
Starting LineNumber, Ending LineNumber
Example:
Substitute Command : Allows you to substitute one word for another.Syntax::LineNumber s/CurrentWord/NewWord/
Example:
Syntax:
:LineNumber s/CurrentWord/NewWord/
Example:
Adding Text : To enter text in a new file we use a (short for append) command and the command i is used to inserting the text before the current line.Syntax:For Append
:a
This is the text
For inserting text before the current line.
:i
This is the text
Example:
Syntax:
For Append
:a
This is the text
For inserting text before the current line.
:i
This is the text
Example:
w Command : The command w (short for ‘write’) is used to save your data.Syntax:w [filename]
Example:
Syntax:
w [filename]
Example:
d Command : This is used to delete the lines.Syntax:[line_range] d
Example:Note: If no line number is given the current line will be deleted. It is possible to give a range of lines. For example 1, $d will delete the entire file.
Syntax:
[line_range] d
Example:
Note: If no line number is given the current line will be deleted. It is possible to give a range of lines. For example 1, $d will delete the entire file.
To search a string: Searches are carried out by including the search string in slashes (‘/’):Note: The special characters ‘^’ and ‘$’ can be used to assist the search. For example /^This/ will find a line beginning and ‘This’/file$/ will find a line ending in ‘file’Syntax:/string/
Example:
Note: The special characters ‘^’ and ‘$’ can be used to assist the search. For example /^This/ will find a line beginning and ‘This’/file$/ will find a line ending in ‘file’
Syntax:
/string/
Example:
Reverse Searches: Generally, these are executed in question marks (‘?’) by including the search string. The search will start at the current line and search backward through the file.Syntax:?string?
Example:
Syntax:
?string?
Example:
Quit Command: The command q (short for ‘quit’) is used to quit the editor.Syntax:quit! or q!
Example:It will navigate you back to the bash
Syntax:
quit! or q!
Example:
It will navigate you back to the bash
g command : The g command (for ‘global’) is used to make multiple substitutions on a line.Syntax:s/old/new/g
Example:
Syntax:
s/old/new/g
Example:
help command: Print a brief help message.Syntax:h
Example:
Syntax:
h
Example:
j command : The j command (for ‘join’) is used to joines the text. We can also add ! to prevent whitespaces.Syntax:[starting LineNumber, ending LineNumber]j!
Example 1:1, 5j! Join first five lines, preserving whitespace
Syntax:
[starting LineNumber, ending LineNumber]j!
Example 1:
1, 5j! Join first five lines, preserving whitespace
linux-command
Linux-text-processing-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
|
[
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 26158,
"s": 25651,
"text": "ex(stands for extended) is a text editor in Linux which is also termed as the line editor mode of the vi editor. This editor simply provided some editing commands which has greater mobility. With the help of this editor, a user can easily move between files. Also, he/she has a lot of ways to transfer the text from one file to another. A user can quickly edit blocks of text larger than a single screen and also can make substitutions throughout a file for a given pattern by using the global replacement."
},
{
"code": null,
"e": 26166,
"s": 26158,
"text": "Syntax:"
},
{
"code": null,
"e": 26184,
"s": 26166,
"text": "% ex [filename] \n"
},
{
"code": null,
"e": 26242,
"s": 26184,
"text": "Note: The prompt for the ex command is the ‘:’ character."
},
{
"code": null,
"e": 26272,
"s": 26242,
"text": "Important ex Editor Commands:"
},
{
"code": null,
"e": 28754,
"s": 26272,
"text": "File Manipulation: There are two ways to edit a file, either we can use an old file or we can create a new file.a) Using an old fileSyntax:% ex oldfile\nExample:b) Inserting a new fileSyntax:% ex newfile \nOutput:p Command : This is the one of the most basic command, p for print (to the screen). Suppose if you will type 1p at the prompt, then you will notice the first line of the file:Syntax:linenumber p\nExample:To print more than one line: You can leave off the p because a line number by itself is equivalent to a print command for that line. Here, you can put a range of line numbers (e.g 1, 3) means the two numbers separated which are by commas. Here, the space are optional.Syntax:Starting LineNumber, Ending LineNumber\nExample:Substitute Command : Allows you to substitute one word for another.Syntax::LineNumber s/CurrentWord/NewWord/\nExample:Adding Text : To enter text in a new file we use a (short for append) command and the command i is used to inserting the text before the current line.Syntax:For Append\n\n:a\nThis is the text\n \n\nFor inserting text before the current line.\n\n:i\nThis is the text\n\nExample:w Command : The command w (short for ‘write’) is used to save your data.Syntax:w [filename]\nExample:d Command : This is used to delete the lines.Syntax:[line_range] d\nExample:Note: If no line number is given the current line will be deleted. It is possible to give a range of lines. For example 1, $d will delete the entire file.To search a string: Searches are carried out by including the search string in slashes (‘/’):Note: The special characters ‘^’ and ‘$’ can be used to assist the search. For example /^This/ will find a line beginning and ‘This’/file$/ will find a line ending in ‘file’Syntax:/string/\nExample:Reverse Searches: Generally, these are executed in question marks (‘?’) by including the search string. The search will start at the current line and search backward through the file.Syntax:?string?\nExample:Quit Command: The command q (short for ‘quit’) is used to quit the editor.Syntax:quit! or q!\nExample:It will navigate you back to the bashg command : The g command (for ‘global’) is used to make multiple substitutions on a line.Syntax:s/old/new/g\nExample:help command: Print a brief help message.Syntax:h\nExample:j command : The j command (for ‘join’) is used to joines the text. We can also add ! to prevent whitespaces.Syntax:[starting LineNumber, ending LineNumber]j!\nExample 1:1, 5j! Join first five lines, preserving whitespace"
},
{
"code": null,
"e": 28966,
"s": 28754,
"text": "File Manipulation: There are two ways to edit a file, either we can use an old file or we can create a new file.a) Using an old fileSyntax:% ex oldfile\nExample:b) Inserting a new fileSyntax:% ex newfile \nOutput:"
},
{
"code": null,
"e": 29015,
"s": 28966,
"text": "a) Using an old fileSyntax:% ex oldfile\nExample:"
},
{
"code": null,
"e": 29023,
"s": 29015,
"text": "Syntax:"
},
{
"code": null,
"e": 29037,
"s": 29023,
"text": "% ex oldfile\n"
},
{
"code": null,
"e": 29046,
"s": 29037,
"text": "Example:"
},
{
"code": null,
"e": 29098,
"s": 29046,
"text": "b) Inserting a new fileSyntax:% ex newfile \nOutput:"
},
{
"code": null,
"e": 29106,
"s": 29098,
"text": "Syntax:"
},
{
"code": null,
"e": 29121,
"s": 29106,
"text": "% ex newfile \n"
},
{
"code": null,
"e": 29129,
"s": 29121,
"text": "Output:"
},
{
"code": null,
"e": 29655,
"s": 29129,
"text": "p Command : This is the one of the most basic command, p for print (to the screen). Suppose if you will type 1p at the prompt, then you will notice the first line of the file:Syntax:linenumber p\nExample:To print more than one line: You can leave off the p because a line number by itself is equivalent to a print command for that line. Here, you can put a range of line numbers (e.g 1, 3) means the two numbers separated which are by commas. Here, the space are optional.Syntax:Starting LineNumber, Ending LineNumber\nExample:"
},
{
"code": null,
"e": 29663,
"s": 29655,
"text": "Syntax:"
},
{
"code": null,
"e": 29677,
"s": 29663,
"text": "linenumber p\n"
},
{
"code": null,
"e": 29686,
"s": 29677,
"text": "Example:"
},
{
"code": null,
"e": 30009,
"s": 29686,
"text": "To print more than one line: You can leave off the p because a line number by itself is equivalent to a print command for that line. Here, you can put a range of line numbers (e.g 1, 3) means the two numbers separated which are by commas. Here, the space are optional.Syntax:Starting LineNumber, Ending LineNumber\nExample:"
},
{
"code": null,
"e": 30017,
"s": 30009,
"text": "Syntax:"
},
{
"code": null,
"e": 30057,
"s": 30017,
"text": "Starting LineNumber, Ending LineNumber\n"
},
{
"code": null,
"e": 30066,
"s": 30057,
"text": "Example:"
},
{
"code": null,
"e": 30184,
"s": 30066,
"text": "Substitute Command : Allows you to substitute one word for another.Syntax::LineNumber s/CurrentWord/NewWord/\nExample:"
},
{
"code": null,
"e": 30192,
"s": 30184,
"text": "Syntax:"
},
{
"code": null,
"e": 30228,
"s": 30192,
"text": ":LineNumber s/CurrentWord/NewWord/\n"
},
{
"code": null,
"e": 30237,
"s": 30228,
"text": "Example:"
},
{
"code": null,
"e": 30504,
"s": 30237,
"text": "Adding Text : To enter text in a new file we use a (short for append) command and the command i is used to inserting the text before the current line.Syntax:For Append\n\n:a\nThis is the text\n \n\nFor inserting text before the current line.\n\n:i\nThis is the text\n\nExample:"
},
{
"code": null,
"e": 30512,
"s": 30504,
"text": "Syntax:"
},
{
"code": null,
"e": 30614,
"s": 30512,
"text": "For Append\n\n:a\nThis is the text\n \n\nFor inserting text before the current line.\n\n:i\nThis is the text\n\n"
},
{
"code": null,
"e": 30623,
"s": 30614,
"text": "Example:"
},
{
"code": null,
"e": 30724,
"s": 30623,
"text": "w Command : The command w (short for ‘write’) is used to save your data.Syntax:w [filename]\nExample:"
},
{
"code": null,
"e": 30732,
"s": 30724,
"text": "Syntax:"
},
{
"code": null,
"e": 30746,
"s": 30732,
"text": "w [filename]\n"
},
{
"code": null,
"e": 30755,
"s": 30746,
"text": "Example:"
},
{
"code": null,
"e": 30985,
"s": 30755,
"text": "d Command : This is used to delete the lines.Syntax:[line_range] d\nExample:Note: If no line number is given the current line will be deleted. It is possible to give a range of lines. For example 1, $d will delete the entire file."
},
{
"code": null,
"e": 30993,
"s": 30985,
"text": "Syntax:"
},
{
"code": null,
"e": 31009,
"s": 30993,
"text": "[line_range] d\n"
},
{
"code": null,
"e": 31018,
"s": 31009,
"text": "Example:"
},
{
"code": null,
"e": 31173,
"s": 31018,
"text": "Note: If no line number is given the current line will be deleted. It is possible to give a range of lines. For example 1, $d will delete the entire file."
},
{
"code": null,
"e": 31464,
"s": 31173,
"text": "To search a string: Searches are carried out by including the search string in slashes (‘/’):Note: The special characters ‘^’ and ‘$’ can be used to assist the search. For example /^This/ will find a line beginning and ‘This’/file$/ will find a line ending in ‘file’Syntax:/string/\nExample:"
},
{
"code": null,
"e": 31638,
"s": 31464,
"text": "Note: The special characters ‘^’ and ‘$’ can be used to assist the search. For example /^This/ will find a line beginning and ‘This’/file$/ will find a line ending in ‘file’"
},
{
"code": null,
"e": 31646,
"s": 31638,
"text": "Syntax:"
},
{
"code": null,
"e": 31656,
"s": 31646,
"text": "/string/\n"
},
{
"code": null,
"e": 31665,
"s": 31656,
"text": "Example:"
},
{
"code": null,
"e": 31873,
"s": 31665,
"text": "Reverse Searches: Generally, these are executed in question marks (‘?’) by including the search string. The search will start at the current line and search backward through the file.Syntax:?string?\nExample:"
},
{
"code": null,
"e": 31881,
"s": 31873,
"text": "Syntax:"
},
{
"code": null,
"e": 31891,
"s": 31881,
"text": "?string?\n"
},
{
"code": null,
"e": 31900,
"s": 31891,
"text": "Example:"
},
{
"code": null,
"e": 32039,
"s": 31900,
"text": "Quit Command: The command q (short for ‘quit’) is used to quit the editor.Syntax:quit! or q!\nExample:It will navigate you back to the bash"
},
{
"code": null,
"e": 32047,
"s": 32039,
"text": "Syntax:"
},
{
"code": null,
"e": 32060,
"s": 32047,
"text": "quit! or q!\n"
},
{
"code": null,
"e": 32069,
"s": 32060,
"text": "Example:"
},
{
"code": null,
"e": 32107,
"s": 32069,
"text": "It will navigate you back to the bash"
},
{
"code": null,
"e": 32225,
"s": 32107,
"text": "g command : The g command (for ‘global’) is used to make multiple substitutions on a line.Syntax:s/old/new/g\nExample:"
},
{
"code": null,
"e": 32233,
"s": 32225,
"text": "Syntax:"
},
{
"code": null,
"e": 32246,
"s": 32233,
"text": "s/old/new/g\n"
},
{
"code": null,
"e": 32255,
"s": 32246,
"text": "Example:"
},
{
"code": null,
"e": 32314,
"s": 32255,
"text": "help command: Print a brief help message.Syntax:h\nExample:"
},
{
"code": null,
"e": 32322,
"s": 32314,
"text": "Syntax:"
},
{
"code": null,
"e": 32325,
"s": 32322,
"text": "h\n"
},
{
"code": null,
"e": 32334,
"s": 32325,
"text": "Example:"
},
{
"code": null,
"e": 32558,
"s": 32334,
"text": "j command : The j command (for ‘join’) is used to joines the text. We can also add ! to prevent whitespaces.Syntax:[starting LineNumber, ending LineNumber]j!\nExample 1:1, 5j! Join first five lines, preserving whitespace"
},
{
"code": null,
"e": 32566,
"s": 32558,
"text": "Syntax:"
},
{
"code": null,
"e": 32610,
"s": 32566,
"text": "[starting LineNumber, ending LineNumber]j!\n"
},
{
"code": null,
"e": 32621,
"s": 32610,
"text": "Example 1:"
},
{
"code": null,
"e": 32677,
"s": 32621,
"text": "1, 5j! Join first five lines, preserving whitespace"
},
{
"code": null,
"e": 32691,
"s": 32677,
"text": "linux-command"
},
{
"code": null,
"e": 32722,
"s": 32691,
"text": "Linux-text-processing-commands"
},
{
"code": null,
"e": 32729,
"s": 32722,
"text": "Picked"
},
{
"code": null,
"e": 32740,
"s": 32729,
"text": "Linux-Unix"
},
{
"code": null,
"e": 32838,
"s": 32740,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32873,
"s": 32838,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 32907,
"s": 32873,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 32933,
"s": 32907,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 32962,
"s": 32933,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 32999,
"s": 32962,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 33036,
"s": 32999,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 33078,
"s": 33036,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 33104,
"s": 33078,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 33140,
"s": 33104,
"text": "uniq Command in LINUX with examples"
}
] |
Class template with multiple parameters - GeeksforGeeks
|
27 Jun, 2017
Prerequisite: Templates in C++
While creating templates, it is possible to specify more than one type. We can use more than one generic data type in a class template. They are declared as a comma-separated list within the template as below:Syntax:
template<class T1, class T2, ...>
class classname
{
...
...
};
// CPP program to illustrate// Class template with multiple parameters #include<iostream>using namespace std; // Class template with two parameterstemplate<class T1, class T2>class Test{ T1 a; T2 b; public: Test(T1 x, T2 y) { a = x; b = y; } void show() { cout << a << " and " << b << endl; }}; // Main Functionint main(){ // instantiation with float and int type Test <float, int> test1 (1.23, 123); // instantiation with float and char type Test <int, char> test2 (100, 'W'); test1.show(); test2.show(); return 0;}
Output:
1.23 and 123
100 and W
Explanation of the code:
In the above program, the Test constructor has two arguments of generic type.
The type of arguments is mentioned inside angle brackets < > while creating objects.
When argument is more than one, they are separated by commas.
Following statementTest test1 (1.23, 123);tells the compiler that the first argument is of type float and another one is int type.
Test test1 (1.23, 123);
tells the compiler that the first argument is of type float and another one is int type.
During creation of objects, constructor is called and values are received by template arguments.
This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
|
[
{
"code": null,
"e": 25369,
"s": 25341,
"text": "\n27 Jun, 2017"
},
{
"code": null,
"e": 25400,
"s": 25369,
"text": "Prerequisite: Templates in C++"
},
{
"code": null,
"e": 25617,
"s": 25400,
"text": "While creating templates, it is possible to specify more than one type. We can use more than one generic data type in a class template. They are declared as a comma-separated list within the template as below:Syntax:"
},
{
"code": null,
"e": 25693,
"s": 25617,
"text": "template<class T1, class T2, ...>\nclass classname\n{\n ...\n ...\n};\n"
},
{
"code": "// CPP program to illustrate// Class template with multiple parameters #include<iostream>using namespace std; // Class template with two parameterstemplate<class T1, class T2>class Test{ T1 a; T2 b; public: Test(T1 x, T2 y) { a = x; b = y; } void show() { cout << a << \" and \" << b << endl; }}; // Main Functionint main(){ // instantiation with float and int type Test <float, int> test1 (1.23, 123); // instantiation with float and char type Test <int, char> test2 (100, 'W'); test1.show(); test2.show(); return 0;}",
"e": 26347,
"s": 25693,
"text": null
},
{
"code": null,
"e": 26355,
"s": 26347,
"text": "Output:"
},
{
"code": null,
"e": 26380,
"s": 26355,
"text": "1.23 and 123\n100 and W\n"
},
{
"code": null,
"e": 26405,
"s": 26380,
"text": "Explanation of the code:"
},
{
"code": null,
"e": 26483,
"s": 26405,
"text": "In the above program, the Test constructor has two arguments of generic type."
},
{
"code": null,
"e": 26568,
"s": 26483,
"text": "The type of arguments is mentioned inside angle brackets < > while creating objects."
},
{
"code": null,
"e": 26630,
"s": 26568,
"text": "When argument is more than one, they are separated by commas."
},
{
"code": null,
"e": 26762,
"s": 26630,
"text": "Following statementTest test1 (1.23, 123);tells the compiler that the first argument is of type float and another one is int type."
},
{
"code": null,
"e": 26787,
"s": 26762,
"text": "Test test1 (1.23, 123);"
},
{
"code": null,
"e": 26876,
"s": 26787,
"text": "tells the compiler that the first argument is of type float and another one is int type."
},
{
"code": null,
"e": 26973,
"s": 26876,
"text": "During creation of objects, constructor is called and values are received by template arguments."
},
{
"code": null,
"e": 27291,
"s": 26973,
"text": "This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27416,
"s": 27291,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27420,
"s": 27416,
"text": "STL"
},
{
"code": null,
"e": 27424,
"s": 27420,
"text": "C++"
},
{
"code": null,
"e": 27428,
"s": 27424,
"text": "STL"
},
{
"code": null,
"e": 27432,
"s": 27428,
"text": "CPP"
},
{
"code": null,
"e": 27530,
"s": 27432,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27558,
"s": 27530,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27578,
"s": 27558,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27602,
"s": 27578,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 27635,
"s": 27602,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 27679,
"s": 27635,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27704,
"s": 27679,
"text": "std::string class in C++"
},
{
"code": null,
"e": 27749,
"s": 27704,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27773,
"s": 27749,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 27826,
"s": 27773,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
}
] |
React-Bootstrap Toasts Component - GeeksforGeeks
|
30 Apr, 2021
React-Bootstrap is a front-end framework that was designed keeping react in mind. Toasts Component is a lightweight notification that is designed to provide a way to mimic push notifications from desktop OS or mobile. We can use the following approach in ReactJS to use the react-bootstrap Toasts Component.
Toasts Props:
animation: It is used to apply the fade animation to our toast
autohide: It is used to auto-hide the toast.
delay: It is used to delay the hiding of toast.
onClose: It is a callback function that is triggered on the click of close button.
show: It is used to show the modal when it is set to true,
transition: It is used to display the series of labels, buttons, etc on a single horizontal row.
bsPrefix: It is an escape hatch for working with strongly customized Bootstrap CSS
Toast Header Props:
closeButton: It is used to specify a close button for the component.
closeLabel: For the close button, it is used to provide an accessible label.
bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS.
Toast Body Props:
as: It can be used as a custom element type for this component.
bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap
npm install bootstrap
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install react-bootstrap
npm install bootstrap
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Toast from 'react-bootstrap/Toast'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Toast Component</h4> <Toast> <Toast.Header> <img alt="Sample Image" width="20px"src="https://media.geeksforgeeks.org/wp-content/uploads/20210425122739/2-300x115.png" className="rounded mr-2" /> <strong className="mr-auto"> GeeksforGeeks </strong> <small> Last Seen: 1 hour ago </small> </Toast.Header> <Toast.Body> Greetings from GeeksforGeeks </Toast.Body> </Toast> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference:https://react-bootstrap.github.io/components/toasts/
React-Bootstrap
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to pass data from one component to other component in ReactJS ?
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Re-rendering Components in ReactJS
Axios in React: A Guide for Beginners
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 25545,
"s": 25517,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 25853,
"s": 25545,
"text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. Toasts Component is a lightweight notification that is designed to provide a way to mimic push notifications from desktop OS or mobile. We can use the following approach in ReactJS to use the react-bootstrap Toasts Component."
},
{
"code": null,
"e": 25867,
"s": 25853,
"text": "Toasts Props:"
},
{
"code": null,
"e": 25930,
"s": 25867,
"text": "animation: It is used to apply the fade animation to our toast"
},
{
"code": null,
"e": 25975,
"s": 25930,
"text": "autohide: It is used to auto-hide the toast."
},
{
"code": null,
"e": 26023,
"s": 25975,
"text": "delay: It is used to delay the hiding of toast."
},
{
"code": null,
"e": 26106,
"s": 26023,
"text": "onClose: It is a callback function that is triggered on the click of close button."
},
{
"code": null,
"e": 26165,
"s": 26106,
"text": "show: It is used to show the modal when it is set to true,"
},
{
"code": null,
"e": 26262,
"s": 26165,
"text": "transition: It is used to display the series of labels, buttons, etc on a single horizontal row."
},
{
"code": null,
"e": 26345,
"s": 26262,
"text": "bsPrefix: It is an escape hatch for working with strongly customized Bootstrap CSS"
},
{
"code": null,
"e": 26365,
"s": 26345,
"text": "Toast Header Props:"
},
{
"code": null,
"e": 26434,
"s": 26365,
"text": "closeButton: It is used to specify a close button for the component."
},
{
"code": null,
"e": 26511,
"s": 26434,
"text": "closeLabel: For the close button, it is used to provide an accessible label."
},
{
"code": null,
"e": 26595,
"s": 26511,
"text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS."
},
{
"code": null,
"e": 26613,
"s": 26595,
"text": "Toast Body Props:"
},
{
"code": null,
"e": 26677,
"s": 26613,
"text": "as: It can be used as a custom element type for this component."
},
{
"code": null,
"e": 26761,
"s": 26677,
"text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS."
},
{
"code": null,
"e": 26811,
"s": 26761,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 26906,
"s": 26811,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 26970,
"s": 26906,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 27002,
"s": 26970,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 27116,
"s": 27002,
"text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 27217,
"s": 27116,
"text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command:"
},
{
"code": null,
"e": 27231,
"s": 27217,
"text": "cd foldername"
},
{
"code": null,
"e": 27386,
"s": 27231,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap \nnpm install bootstrap"
},
{
"code": null,
"e": 27491,
"s": 27386,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 27542,
"s": 27491,
"text": "npm install react-bootstrap \nnpm install bootstrap"
},
{
"code": null,
"e": 27594,
"s": 27542,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 27612,
"s": 27594,
"text": "Project Structure"
},
{
"code": null,
"e": 27742,
"s": 27612,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 27749,
"s": 27742,
"text": "App.js"
},
{
"code": "import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Toast from 'react-bootstrap/Toast'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Toast Component</h4> <Toast> <Toast.Header> <img alt=\"Sample Image\" width=\"20px\"src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210425122739/2-300x115.png\" className=\"rounded mr-2\" /> <strong className=\"mr-auto\"> GeeksforGeeks </strong> <small> Last Seen: 1 hour ago </small> </Toast.Header> <Toast.Body> Greetings from GeeksforGeeks </Toast.Body> </Toast> </div> );}",
"e": 28539,
"s": 27749,
"text": null
},
{
"code": null,
"e": 28652,
"s": 28539,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 28662,
"s": 28652,
"text": "npm start"
},
{
"code": null,
"e": 28761,
"s": 28662,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 28824,
"s": 28761,
"text": "Reference:https://react-bootstrap.github.io/components/toasts/"
},
{
"code": null,
"e": 28840,
"s": 28824,
"text": "React-Bootstrap"
},
{
"code": null,
"e": 28848,
"s": 28840,
"text": "ReactJS"
},
{
"code": null,
"e": 28865,
"s": 28848,
"text": "Web Technologies"
},
{
"code": null,
"e": 28963,
"s": 28865,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29031,
"s": 28963,
"text": "How to pass data from one component to other component in ReactJS ?"
},
{
"code": null,
"e": 29058,
"s": 29031,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 29100,
"s": 29058,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 29135,
"s": 29100,
"text": "Re-rendering Components in ReactJS"
},
{
"code": null,
"e": 29173,
"s": 29135,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 29213,
"s": 29173,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29246,
"s": 29213,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29291,
"s": 29246,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29341,
"s": 29291,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Getting attributes of Objects in R Language - attributes() and attr() Function - GeeksforGeeks
|
23 Nov, 2021
attribute() function in R Programming Language is used to get all the attributes of data. This function is also used to set new attributes to data.
Syntax: attributes(x)
Parameters:
x: object whose attributes to be accessed.
R
# R program to illustrate# attributes functioninfo = data.frame(iris) # Load info set that you want to work ondata(info) # Print first 6 rows of info set data head(info) # Apply attributes functionattributes(info)
Output:
Here in the above code, we have applied the attributes() function so we have shown all the data which is present in the info data frame. So by applying info all the attributes in the datasets will be shown.
R
# Set different column names# retain dataframe classattributes_list <- list(names = c('Sepal.Length' ,'Sepal.Width' , 'Petal.Length', 'Petal.Width', 'Species'), class = "data.frame", row.names= c("NA","NA","NA","NA")) # New attributes from list added to info databaseattributes(info) <- attributes_list attributes(info)
Output:
$names
'Sepal.Length' 'Sepal.Width' 'Petal.Length' 'Petal.Width' 'Species'
$class
'data.frame'
$row.names
'NA' 'NA' 'NA' 'NA'
Here in the above code, we have added the new attributes to the list info from Example 1, and then printed all the attributes including the new one.
attr() will return specific data, but this function needs precise information about the data.
Syntax: attr(x = data, which = “attribute_name”)
Parameters:
x: object whose attributes to be accessed.
which: string specifying the attribute to be accessed.
R
# R program to illustrate# attr() function # Load info set that you want to work ondata(info) # Apply attr() functionattr(x = info, which = "names")
Output:
'Sepal.Length' 'Sepal.Width' 'Petal.Length' 'Petal.Width' 'Species'
Here in the above code, we have specified a particular parameter name, so only the values in names will be returned. attr() will return specific data, but attr() functions need a precise information about the data.
ruhelaa48
surinderdawra388
kumar_satyam
Programming Language
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction of Object Oriented Programming
5 Best Languages for Competitive Programming
7 Highest Paying Programming Languages For Freelancers in 2022
R - Matrices
R - Charts and Graphs
Change column name of a given DataFrame in R
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Adding elements in a vector in R programming - append() method
|
[
{
"code": null,
"e": 25957,
"s": 25929,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 26105,
"s": 25957,
"text": "attribute() function in R Programming Language is used to get all the attributes of data. This function is also used to set new attributes to data."
},
{
"code": null,
"e": 26127,
"s": 26105,
"text": "Syntax: attributes(x)"
},
{
"code": null,
"e": 26140,
"s": 26127,
"text": "Parameters: "
},
{
"code": null,
"e": 26183,
"s": 26140,
"text": "x: object whose attributes to be accessed."
},
{
"code": null,
"e": 26185,
"s": 26183,
"text": "R"
},
{
"code": "# R program to illustrate# attributes functioninfo = data.frame(iris) # Load info set that you want to work ondata(info) # Print first 6 rows of info set data head(info) # Apply attributes functionattributes(info) ",
"e": 26526,
"s": 26185,
"text": null
},
{
"code": null,
"e": 26535,
"s": 26526,
"text": "Output: "
},
{
"code": null,
"e": 26742,
"s": 26535,
"text": "Here in the above code, we have applied the attributes() function so we have shown all the data which is present in the info data frame. So by applying info all the attributes in the datasets will be shown."
},
{
"code": null,
"e": 26744,
"s": 26742,
"text": "R"
},
{
"code": "# Set different column names# retain dataframe classattributes_list <- list(names = c('Sepal.Length' ,'Sepal.Width' , 'Petal.Length', 'Petal.Width', 'Species'), class = \"data.frame\", row.names= c(\"NA\",\"NA\",\"NA\",\"NA\")) # New attributes from list added to info databaseattributes(info) <- attributes_list attributes(info)",
"e": 27177,
"s": 26744,
"text": null
},
{
"code": null,
"e": 27186,
"s": 27177,
"text": "Output: "
},
{
"code": null,
"e": 27312,
"s": 27186,
"text": "$names\n'Sepal.Length' 'Sepal.Width' 'Petal.Length' 'Petal.Width' 'Species'\n$class\n'data.frame'\n$row.names\n'NA' 'NA' 'NA' 'NA'"
},
{
"code": null,
"e": 27461,
"s": 27312,
"text": "Here in the above code, we have added the new attributes to the list info from Example 1, and then printed all the attributes including the new one."
},
{
"code": null,
"e": 27555,
"s": 27461,
"text": "attr() will return specific data, but this function needs precise information about the data."
},
{
"code": null,
"e": 27604,
"s": 27555,
"text": "Syntax: attr(x = data, which = “attribute_name”)"
},
{
"code": null,
"e": 27617,
"s": 27604,
"text": "Parameters: "
},
{
"code": null,
"e": 27661,
"s": 27617,
"text": "x: object whose attributes to be accessed. "
},
{
"code": null,
"e": 27716,
"s": 27661,
"text": "which: string specifying the attribute to be accessed."
},
{
"code": null,
"e": 27718,
"s": 27716,
"text": "R"
},
{
"code": "# R program to illustrate# attr() function # Load info set that you want to work ondata(info) # Apply attr() functionattr(x = info, which = \"names\") ",
"e": 27888,
"s": 27718,
"text": null
},
{
"code": null,
"e": 27897,
"s": 27888,
"text": "Output: "
},
{
"code": null,
"e": 27965,
"s": 27897,
"text": "'Sepal.Length' 'Sepal.Width' 'Petal.Length' 'Petal.Width' 'Species'"
},
{
"code": null,
"e": 28180,
"s": 27965,
"text": "Here in the above code, we have specified a particular parameter name, so only the values in names will be returned. attr() will return specific data, but attr() functions need a precise information about the data."
},
{
"code": null,
"e": 28190,
"s": 28180,
"text": "ruhelaa48"
},
{
"code": null,
"e": 28207,
"s": 28190,
"text": "surinderdawra388"
},
{
"code": null,
"e": 28220,
"s": 28207,
"text": "kumar_satyam"
},
{
"code": null,
"e": 28241,
"s": 28220,
"text": "Programming Language"
},
{
"code": null,
"e": 28252,
"s": 28241,
"text": "R Language"
},
{
"code": null,
"e": 28350,
"s": 28252,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28394,
"s": 28350,
"text": "Introduction of Object Oriented Programming"
},
{
"code": null,
"e": 28439,
"s": 28394,
"text": "5 Best Languages for Competitive Programming"
},
{
"code": null,
"e": 28502,
"s": 28439,
"text": "7 Highest Paying Programming Languages For Freelancers in 2022"
},
{
"code": null,
"e": 28515,
"s": 28502,
"text": "R - Matrices"
},
{
"code": null,
"e": 28537,
"s": 28515,
"text": "R - Charts and Graphs"
},
{
"code": null,
"e": 28582,
"s": 28537,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 28640,
"s": 28582,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 28692,
"s": 28640,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 28724,
"s": 28692,
"text": "Loops in R (for, while, repeat)"
}
] |
How To Remove facet_wrap Title Box in ggplot2 in R ? - GeeksforGeeks
|
11 Nov, 2021
Facet plots, where one subsets the data based on a categorical variable and makes a series of similar plots with the same scale. Facetting helps us to show the relationship between more than two categories of data. When you have multiple variables, with faceting it can be plotted in a single plot into smaller plots.
We can easily plot a facetted plot using the facet_wrap() function of the ggplot2 package. When we use facet_wrap() in ggplot2, by default it gives a title in a grey box.
Syntax:
plot + facet_wrap( ~facet-variable)
Where:
facet-variable: determines the variable around which plots have to be divided.
Let us first start with a regular plot, without making any changes so that the difference is apparent.
Here, is a basic facet plot made using the diamonds data frame which is provided by R Language natively. We have used the facet_wrap() function with ~clarity to divide the plot into facets according to their clarity.
Example: Basic plot
R
# load library ggridges and tidyverselibrary(ggridges)library(tidyverse) # Basic facet plot divided according to category clarity# ggplot() function is used to plot the chartggplot(diamonds, aes(x=factor(color), y=carat, fill=color)) + # geom_boxplot() function is used to draw ridgeline plot geom_boxplot()+ # facet_wrap() function divides the plot in facets # according to category of clarity facet_wrap(~clarity)
Output:
We can customize various aspects of a ggplot2 using the theme() function. To remove the facet_wrap() title box, we need to use “strip.background” argument inside the theme() layer with argument ‘element_blank()’.
Syntax:
plot + theme( strip.background = element_blank() )
Example: Removing the facet wrap box.
R
# load library ggridges and tidyverselibrary(ggridges)library(tidyverse) # Basic facet plot divided according to category clarity# ggplot() function is used to plot the chartggplot(diamonds, aes(x=factor(color), y=carat, fill=color)) + # geom_boxplot() function is used to draw ridgeline plot geom_boxplot()+ # facet_wrap() function divides the plot in facets according# to category of clarity facet_wrap(~clarity)+# strip.background parameter of theme# function is used to remove the facet wrap box# element_blank() makes the box background blanktheme(strip.background = element_blank())
Output:
surinderdawra388
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions?
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n11 Nov, 2021"
},
{
"code": null,
"e": 26805,
"s": 26487,
"text": "Facet plots, where one subsets the data based on a categorical variable and makes a series of similar plots with the same scale. Facetting helps us to show the relationship between more than two categories of data. When you have multiple variables, with faceting it can be plotted in a single plot into smaller plots."
},
{
"code": null,
"e": 26976,
"s": 26805,
"text": "We can easily plot a facetted plot using the facet_wrap() function of the ggplot2 package. When we use facet_wrap() in ggplot2, by default it gives a title in a grey box."
},
{
"code": null,
"e": 26985,
"s": 26976,
"text": "Syntax: "
},
{
"code": null,
"e": 27021,
"s": 26985,
"text": "plot + facet_wrap( ~facet-variable)"
},
{
"code": null,
"e": 27028,
"s": 27021,
"text": "Where:"
},
{
"code": null,
"e": 27107,
"s": 27028,
"text": "facet-variable: determines the variable around which plots have to be divided."
},
{
"code": null,
"e": 27210,
"s": 27107,
"text": "Let us first start with a regular plot, without making any changes so that the difference is apparent."
},
{
"code": null,
"e": 27427,
"s": 27210,
"text": "Here, is a basic facet plot made using the diamonds data frame which is provided by R Language natively. We have used the facet_wrap() function with ~clarity to divide the plot into facets according to their clarity."
},
{
"code": null,
"e": 27447,
"s": 27427,
"text": "Example: Basic plot"
},
{
"code": null,
"e": 27449,
"s": 27447,
"text": "R"
},
{
"code": "# load library ggridges and tidyverselibrary(ggridges)library(tidyverse) # Basic facet plot divided according to category clarity# ggplot() function is used to plot the chartggplot(diamonds, aes(x=factor(color), y=carat, fill=color)) + # geom_boxplot() function is used to draw ridgeline plot geom_boxplot()+ # facet_wrap() function divides the plot in facets # according to category of clarity facet_wrap(~clarity)",
"e": 27870,
"s": 27449,
"text": null
},
{
"code": null,
"e": 27878,
"s": 27870,
"text": "Output:"
},
{
"code": null,
"e": 28091,
"s": 27878,
"text": "We can customize various aspects of a ggplot2 using the theme() function. To remove the facet_wrap() title box, we need to use “strip.background” argument inside the theme() layer with argument ‘element_blank()’."
},
{
"code": null,
"e": 28100,
"s": 28091,
"text": "Syntax: "
},
{
"code": null,
"e": 28151,
"s": 28100,
"text": "plot + theme( strip.background = element_blank() )"
},
{
"code": null,
"e": 28189,
"s": 28151,
"text": "Example: Removing the facet wrap box."
},
{
"code": null,
"e": 28191,
"s": 28189,
"text": "R"
},
{
"code": "# load library ggridges and tidyverselibrary(ggridges)library(tidyverse) # Basic facet plot divided according to category clarity# ggplot() function is used to plot the chartggplot(diamonds, aes(x=factor(color), y=carat, fill=color)) + # geom_boxplot() function is used to draw ridgeline plot geom_boxplot()+ # facet_wrap() function divides the plot in facets according# to category of clarity facet_wrap(~clarity)+# strip.background parameter of theme# function is used to remove the facet wrap box# element_blank() makes the box background blanktheme(strip.background = element_blank())",
"e": 28785,
"s": 28191,
"text": null
},
{
"code": null,
"e": 28793,
"s": 28785,
"text": "Output:"
},
{
"code": null,
"e": 28810,
"s": 28793,
"text": "surinderdawra388"
},
{
"code": null,
"e": 28817,
"s": 28810,
"text": "Picked"
},
{
"code": null,
"e": 28826,
"s": 28817,
"text": "R-ggplot"
},
{
"code": null,
"e": 28837,
"s": 28826,
"text": "R Language"
},
{
"code": null,
"e": 28935,
"s": 28837,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28987,
"s": 28935,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29022,
"s": 28987,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29060,
"s": 29022,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29118,
"s": 29060,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29161,
"s": 29118,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29210,
"s": 29161,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29247,
"s": 29210,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 29273,
"s": 29247,
"text": "Time Series Analysis in R"
},
{
"code": null,
"e": 29290,
"s": 29273,
"text": "R - if statement"
}
] |
numpy.log10() in Python - GeeksforGeeks
|
29 Nov, 2018
About :numpy.log10(arr, out = None, *, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None, ufunc ‘log10’) : This mathematical function helps user to calculate Base-10 logarithm of x where x belongs to all the input array elements.
Parameters :
array : [array_like]Input array or object.
out : [ndarray, optional]Output array with same dimensions as Input array,
placed with result.
**kwargs : allows you to pass keyword variable length of argument to a function.
It is used when we want to handle named argument in a function.
where : [array_like, optional]True value means to calculate the universal
functions(ufunc) at that position, False value means to leave the value in the
output alone.
Return :
An array with Base-10 logarithmic value of x;
where x belongs to all elements of input array.
Code 1 : Working
# Python program explaining# log10() function import numpy as np in_array = [1, 3, 5, 10**8]print ("Input array : ", in_array) out_array = np.log10(in_array)print ("Output array : ", out_array) print("\nnp.log10(4**4) : ", np.log10(100**4))print("np.log10(2**8) : ", np.log10(10**8))
Output :
Input array : [1, 3, 5, 100000000]
Output array : [ 0. 0.47712125 0.69897 8. ]
np.log10(4**4) : 8.0
np.log10(2**8) : 8.0
Code 2 : Graphical representation
# Python program showing# Graphical representation of # log10() function import numpy as npimport matplotlib.pyplot as plt in_array = [1, 2, 3, 4, 5]out_array = np.log10(in_array) print ("out_array : ", out_array) plt.plot(in_array, in_array, color = 'blue', marker = "*") # red for numpy.log10()plt.plot(out_array, in_array, color = 'red', marker = "o")plt.title("numpy.log10()")plt.xlabel("out_array")plt.ylabel("in_array")plt.show()
Output :
out_array : [ 0. 0.30103 0.47712125 0.60205999 0.69897 ]
References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.log10.html#numpy.log10.
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25337,
"s": 25309,
"text": "\n29 Nov, 2018"
},
{
"code": null,
"e": 25580,
"s": 25337,
"text": "About :numpy.log10(arr, out = None, *, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None, ufunc ‘log10’) : This mathematical function helps user to calculate Base-10 logarithm of x where x belongs to all the input array elements."
},
{
"code": null,
"e": 25593,
"s": 25580,
"text": "Parameters :"
},
{
"code": null,
"e": 26095,
"s": 25593,
"text": "array : [array_like]Input array or object.\nout : [ndarray, optional]Output array with same dimensions as Input array, \n placed with result.\n**kwargs : allows you to pass keyword variable length of argument to a function. \n It is used when we want to handle named argument in a function.\nwhere : [array_like, optional]True value means to calculate the universal \n functions(ufunc) at that position, False value means to leave the value in the \n output alone.\n"
},
{
"code": null,
"e": 26104,
"s": 26095,
"text": "Return :"
},
{
"code": null,
"e": 26201,
"s": 26104,
"text": "An array with Base-10 logarithmic value of x; \nwhere x belongs to all elements of input array. \n"
},
{
"code": null,
"e": 26218,
"s": 26201,
"text": "Code 1 : Working"
},
{
"code": "# Python program explaining# log10() function import numpy as np in_array = [1, 3, 5, 10**8]print (\"Input array : \", in_array) out_array = np.log10(in_array)print (\"Output array : \", out_array) print(\"\\nnp.log10(4**4) : \", np.log10(100**4))print(\"np.log10(2**8) : \", np.log10(10**8))",
"e": 26508,
"s": 26218,
"text": null
},
{
"code": null,
"e": 26517,
"s": 26508,
"text": "Output :"
},
{
"code": null,
"e": 26665,
"s": 26517,
"text": "Input array : [1, 3, 5, 100000000]\nOutput array : [ 0. 0.47712125 0.69897 8. ]\n\nnp.log10(4**4) : 8.0\nnp.log10(2**8) : 8.0\n"
},
{
"code": null,
"e": 26699,
"s": 26665,
"text": "Code 2 : Graphical representation"
},
{
"code": "# Python program showing# Graphical representation of # log10() function import numpy as npimport matplotlib.pyplot as plt in_array = [1, 2, 3, 4, 5]out_array = np.log10(in_array) print (\"out_array : \", out_array) plt.plot(in_array, in_array, color = 'blue', marker = \"*\") # red for numpy.log10()plt.plot(out_array, in_array, color = 'red', marker = \"o\")plt.title(\"numpy.log10()\")plt.xlabel(\"out_array\")plt.ylabel(\"in_array\")plt.show() ",
"e": 27142,
"s": 26699,
"text": null
},
{
"code": null,
"e": 27151,
"s": 27142,
"text": "Output :"
},
{
"code": null,
"e": 27226,
"s": 27151,
"text": "out_array : [ 0. 0.30103 0.47712125 0.60205999 0.69897 ]"
},
{
"code": null,
"e": 27328,
"s": 27226,
"text": "References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.log10.html#numpy.log10."
},
{
"code": null,
"e": 27363,
"s": 27328,
"text": "Python numpy-Mathematical Function"
},
{
"code": null,
"e": 27376,
"s": 27363,
"text": "Python-numpy"
},
{
"code": null,
"e": 27383,
"s": 27376,
"text": "Python"
},
{
"code": null,
"e": 27481,
"s": 27383,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27499,
"s": 27481,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27534,
"s": 27499,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27566,
"s": 27534,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27588,
"s": 27566,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27630,
"s": 27588,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27660,
"s": 27630,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27686,
"s": 27660,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27715,
"s": 27686,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27759,
"s": 27715,
"text": "Reading and Writing to text files in Python"
}
] |
Print array after it is right rotated K times | Set 2 - GeeksforGeeks
|
26 Nov, 2021
Given an array arr[] of size N and a value K, the task is to print the array rotated by K times to the right.
Examples:
Input: arr = {1, 3, 5, 7, 9}, K = 2Output: 7 9 1 3 5
Input: arr = {1, 2, 3, 4, 5}, K = 4Output: 2 3 4 5 1
Algorithm: The given problem can be solved by reversing subarrays. Below steps can be followed to solve the problem:
Reverse all the array elements from 1 to N -1
Reverse the array elements from 1 to K – 1
Reverse the array elements from K to N -1
C++
Java
Python3
C#
Javascript
// C++ implementation for the above approach #include <bits/stdc++.h>using namespace std; // Function to rotate the array// to the right, K timesvoid RightRotate(int Array[], int N, int K){ // Reverse all the array elements reverse(Array, Array + N); // Reverse the first k elements reverse(Array, Array + K); // Reverse the elements from K // till the end of the array reverse(Array + K, Array + N); // Print the array after rotation for (int i = 0; i < N; i++) { cout << Array[i] << " "; } cout << endl;} // Driver codeint main(){ // Initialize the array int Array[] = { 1, 2, 3, 4, 5 }; // Find the size of the array int N = sizeof(Array) / sizeof(Array[0]); // Initialize K int K = 4; // Call the function and // print the answer RightRotate(Array, N, K); return 0;}
/*package whatever //do not write package name here */import java.io.*;class GFG{ // Function to rotate the array // to the right, K times static void RightRotate(int[] Array, int N, int K) { // Reverse all the array elements for (int i = 0; i < N / 2; i++) { int temp = Array[i]; Array[i] = Array[N - i - 1]; Array[N - i - 1] = temp; } // Reverse the first k elements for (int i = 0; i < K / 2; i++) { int temp = Array[i]; Array[i] = Array[K - i - 1]; Array[K - i - 1] = temp; } // Reverse the elements from K // till the end of the array for (int i = 0; i < (K + N) / 2; i++) { int temp = Array[(i + K) % N]; Array[(i + K) % N] = Array[(N - i + K - 1) % N]; Array[(N - i + K - 1) % N] = temp; } // Print the array after rotation for (int i = 0; i < N; i++) { System.out.print(Array[i] + " "); } System.out.println(); } // Driver code public static void main(String[] args) { // Initialize the array int Array[] = { 1, 2, 3, 4, 5 }; // Find the size of the array int N = Array.length; // Initialize K int K = 4; // Call the function and // print the answer RightRotate(Array, N, K); }} // This code is contributed by maddler.
# Python program for the above approachimport math # Function to rotate the array# to the right, K timesdef RightRotate(Array, N, K): # Reverse all the array elements for i in range(math.ceil(N / 2)): temp = Array[i] Array[i] = Array[N - i - 1] Array[N - i - 1] = temp # Reverse the first k elements for i in range(math.ceil(K / 2)): temp = Array[i] Array[i] = Array[K - i - 1] Array[K - i - 1] = temp # Reverse the elements from K # till the end of the array for i in range(math.ceil((K + N) / 2)): temp = Array[(i + K) % N] Array[(i + K) % N] = Array[(N - i + K - 1) % N] Array[(N - i + K - 1) % N] = temp # Print the array after rotation for i in range(N): print(Array[i], end=" ") # Driver Codearr = [1, 2, 3, 4, 5]N = len(arr)K = 4 # Call the function and# print the answerRightRotate(arr, N, K) # This code is contributed by Saurabh Jaiswal
// C# program for the above approachusing System;class GFG{ // Function to rotate the array // to the right, K times static void RightRotate(int []Array, int N, int K) { // Reverse all the array elements for (int i = 0; i < N / 2; i++) { int temp = Array[i]; Array[i] = Array[N - i - 1]; Array[N - i - 1] = temp; } // Reverse the first k elements for (int i = 0; i < K / 2; i++) { int temp = Array[i]; Array[i] = Array[K - i - 1]; Array[K - i - 1] = temp; } // Reverse the elements from K // till the end of the array for (int i = 0; i < (K + N) / 2; i++) { int temp = Array[(i + K) % N]; Array[(i + K) % N] = Array[(N - i + K - 1) % N]; Array[(N - i + K - 1) % N] = temp; } // Print the array after rotation for (int i = 0; i < N; i++) { Console.Write(Array[i] + " "); } } // Driver code public static void Main() { // Initialize the array int []Array = { 1, 2, 3, 4, 5 }; // Find the size of the array int N = Array.Length; // Initialize K int K = 4; // Call the function and // print the answer RightRotate(Array, N, K); }}// This code is contributed by Samim Hossain Mondal.
<script>// Javascript program for the above approach // Function to rotate the array// to the right, K timesfunction RightRotate(Array, N, K){ // Reverse all the array elements for (let i = 0; i < N / 2; i++) { let temp = Array[i]; Array[i] = Array[N - i - 1]; Array[N - i - 1] = temp; } // Reverse the first k elements for (let i = 0; i < K / 2; i++) { let temp = Array[i]; Array[i] = Array[K - i - 1]; Array[K - i - 1] = temp; } // Reverse the elements from K // till the end of the array for (let i = 0; i < (K + N) / 2; i++) { let temp = Array[(i + K) % N]; Array[(i + K) % N] = Array[(N - i + K - 1) % N]; Array[(N - i + K - 1) % N] = temp; } // Print the array after rotation for (let i = 0; i < N; i++) { document.write(Array[i] + " "); }} // Driver Code let arr = [ 1, 2, 3, 4, 5 ];let N = arr.length;let K =4; // Call the function and// print the answerRightRotate(arr, N, K); // This code is contributed by Samim Hossain Mondal.</script>
2 3 4 5 1
Time Complexity: O(N) Auxiliary Space: O(1)
lokeshpotta20
maddler
samim2000
_saurabh_jaiswal
Reverse
rotation
subarray
Arrays
Arrays
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Remove duplicates from sorted array
Move all negative numbers to beginning and positive to end with constant extra space
Merge Overlapping Intervals
|
[
{
"code": null,
"e": 26067,
"s": 26039,
"text": "\n26 Nov, 2021"
},
{
"code": null,
"e": 26177,
"s": 26067,
"text": "Given an array arr[] of size N and a value K, the task is to print the array rotated by K times to the right."
},
{
"code": null,
"e": 26187,
"s": 26177,
"text": "Examples:"
},
{
"code": null,
"e": 26240,
"s": 26187,
"text": "Input: arr = {1, 3, 5, 7, 9}, K = 2Output: 7 9 1 3 5"
},
{
"code": null,
"e": 26294,
"s": 26240,
"text": "Input: arr = {1, 2, 3, 4, 5}, K = 4Output: 2 3 4 5 1 "
},
{
"code": null,
"e": 26411,
"s": 26294,
"text": "Algorithm: The given problem can be solved by reversing subarrays. Below steps can be followed to solve the problem:"
},
{
"code": null,
"e": 26457,
"s": 26411,
"text": "Reverse all the array elements from 1 to N -1"
},
{
"code": null,
"e": 26500,
"s": 26457,
"text": "Reverse the array elements from 1 to K – 1"
},
{
"code": null,
"e": 26542,
"s": 26500,
"text": "Reverse the array elements from K to N -1"
},
{
"code": null,
"e": 26546,
"s": 26542,
"text": "C++"
},
{
"code": null,
"e": 26551,
"s": 26546,
"text": "Java"
},
{
"code": null,
"e": 26559,
"s": 26551,
"text": "Python3"
},
{
"code": null,
"e": 26562,
"s": 26559,
"text": "C#"
},
{
"code": null,
"e": 26573,
"s": 26562,
"text": "Javascript"
},
{
"code": "// C++ implementation for the above approach #include <bits/stdc++.h>using namespace std; // Function to rotate the array// to the right, K timesvoid RightRotate(int Array[], int N, int K){ // Reverse all the array elements reverse(Array, Array + N); // Reverse the first k elements reverse(Array, Array + K); // Reverse the elements from K // till the end of the array reverse(Array + K, Array + N); // Print the array after rotation for (int i = 0; i < N; i++) { cout << Array[i] << \" \"; } cout << endl;} // Driver codeint main(){ // Initialize the array int Array[] = { 1, 2, 3, 4, 5 }; // Find the size of the array int N = sizeof(Array) / sizeof(Array[0]); // Initialize K int K = 4; // Call the function and // print the answer RightRotate(Array, N, K); return 0;}",
"e": 27425,
"s": 26573,
"text": null
},
{
"code": "/*package whatever //do not write package name here */import java.io.*;class GFG{ // Function to rotate the array // to the right, K times static void RightRotate(int[] Array, int N, int K) { // Reverse all the array elements for (int i = 0; i < N / 2; i++) { int temp = Array[i]; Array[i] = Array[N - i - 1]; Array[N - i - 1] = temp; } // Reverse the first k elements for (int i = 0; i < K / 2; i++) { int temp = Array[i]; Array[i] = Array[K - i - 1]; Array[K - i - 1] = temp; } // Reverse the elements from K // till the end of the array for (int i = 0; i < (K + N) / 2; i++) { int temp = Array[(i + K) % N]; Array[(i + K) % N] = Array[(N - i + K - 1) % N]; Array[(N - i + K - 1) % N] = temp; } // Print the array after rotation for (int i = 0; i < N; i++) { System.out.print(Array[i] + \" \"); } System.out.println(); } // Driver code public static void main(String[] args) { // Initialize the array int Array[] = { 1, 2, 3, 4, 5 }; // Find the size of the array int N = Array.length; // Initialize K int K = 4; // Call the function and // print the answer RightRotate(Array, N, K); }} // This code is contributed by maddler.",
"e": 28870,
"s": 27425,
"text": null
},
{
"code": "# Python program for the above approachimport math # Function to rotate the array# to the right, K timesdef RightRotate(Array, N, K): # Reverse all the array elements for i in range(math.ceil(N / 2)): temp = Array[i] Array[i] = Array[N - i - 1] Array[N - i - 1] = temp # Reverse the first k elements for i in range(math.ceil(K / 2)): temp = Array[i] Array[i] = Array[K - i - 1] Array[K - i - 1] = temp # Reverse the elements from K # till the end of the array for i in range(math.ceil((K + N) / 2)): temp = Array[(i + K) % N] Array[(i + K) % N] = Array[(N - i + K - 1) % N] Array[(N - i + K - 1) % N] = temp # Print the array after rotation for i in range(N): print(Array[i], end=\" \") # Driver Codearr = [1, 2, 3, 4, 5]N = len(arr)K = 4 # Call the function and# print the answerRightRotate(arr, N, K) # This code is contributed by Saurabh Jaiswal",
"e": 29819,
"s": 28870,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to rotate the array // to the right, K times static void RightRotate(int []Array, int N, int K) { // Reverse all the array elements for (int i = 0; i < N / 2; i++) { int temp = Array[i]; Array[i] = Array[N - i - 1]; Array[N - i - 1] = temp; } // Reverse the first k elements for (int i = 0; i < K / 2; i++) { int temp = Array[i]; Array[i] = Array[K - i - 1]; Array[K - i - 1] = temp; } // Reverse the elements from K // till the end of the array for (int i = 0; i < (K + N) / 2; i++) { int temp = Array[(i + K) % N]; Array[(i + K) % N] = Array[(N - i + K - 1) % N]; Array[(N - i + K - 1) % N] = temp; } // Print the array after rotation for (int i = 0; i < N; i++) { Console.Write(Array[i] + \" \"); } } // Driver code public static void Main() { // Initialize the array int []Array = { 1, 2, 3, 4, 5 }; // Find the size of the array int N = Array.Length; // Initialize K int K = 4; // Call the function and // print the answer RightRotate(Array, N, K); }}// This code is contributed by Samim Hossain Mondal.",
"e": 31205,
"s": 29819,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to rotate the array// to the right, K timesfunction RightRotate(Array, N, K){ // Reverse all the array elements for (let i = 0; i < N / 2; i++) { let temp = Array[i]; Array[i] = Array[N - i - 1]; Array[N - i - 1] = temp; } // Reverse the first k elements for (let i = 0; i < K / 2; i++) { let temp = Array[i]; Array[i] = Array[K - i - 1]; Array[K - i - 1] = temp; } // Reverse the elements from K // till the end of the array for (let i = 0; i < (K + N) / 2; i++) { let temp = Array[(i + K) % N]; Array[(i + K) % N] = Array[(N - i + K - 1) % N]; Array[(N - i + K - 1) % N] = temp; } // Print the array after rotation for (let i = 0; i < N; i++) { document.write(Array[i] + \" \"); }} // Driver Code let arr = [ 1, 2, 3, 4, 5 ];let N = arr.length;let K =4; // Call the function and// print the answerRightRotate(arr, N, K); // This code is contributed by Samim Hossain Mondal.</script>",
"e": 32268,
"s": 31205,
"text": null
},
{
"code": null,
"e": 32279,
"s": 32268,
"text": "2 3 4 5 1 "
},
{
"code": null,
"e": 32324,
"s": 32279,
"text": "Time Complexity: O(N) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 32338,
"s": 32324,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 32346,
"s": 32338,
"text": "maddler"
},
{
"code": null,
"e": 32356,
"s": 32346,
"text": "samim2000"
},
{
"code": null,
"e": 32373,
"s": 32356,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 32381,
"s": 32373,
"text": "Reverse"
},
{
"code": null,
"e": 32390,
"s": 32381,
"text": "rotation"
},
{
"code": null,
"e": 32399,
"s": 32390,
"text": "subarray"
},
{
"code": null,
"e": 32406,
"s": 32399,
"text": "Arrays"
},
{
"code": null,
"e": 32413,
"s": 32406,
"text": "Arrays"
},
{
"code": null,
"e": 32421,
"s": 32413,
"text": "Reverse"
},
{
"code": null,
"e": 32519,
"s": 32421,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32546,
"s": 32519,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 32577,
"s": 32546,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 32602,
"s": 32577,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 32640,
"s": 32602,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 32661,
"s": 32640,
"text": "Next Greater Element"
},
{
"code": null,
"e": 32719,
"s": 32661,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 32778,
"s": 32719,
"text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)"
},
{
"code": null,
"e": 32814,
"s": 32778,
"text": "Remove duplicates from sorted array"
},
{
"code": null,
"e": 32899,
"s": 32814,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
}
] |
Find a triplet in an array such that arr[i] arr[k] and i < j < k - GeeksforGeeks
|
28 Feb, 2022
Given an array arr[] consisting of a permutation of first N natural numbers, the task is to find a triplet (i, j, k) from the given array such that arr[i] < arr[j] > arr[k], where (i < j < k). If multiple triplets exist, then print any valid triplet of indices. Otherwise, print -1.
Examples:
Input: arr[] = {2, 1, 4, 3} Output: 1 2 3 Explanation: Triplet that satisfy the given condition is (arr[1], arr[2], arr[3]) Therefore, the required output is 1 2 3.
Input: arr[] = {1, 2, 3, 4, 5} Output: -1
Naive Approach: The simplest approach to solve this problem is to traverse the array and generate all possible triplets of the given array and for each triplet, check if it satisfies the given conditions or not. If found to be true, then print that triplet. Otherwise, print -1.
Time Complexity: O(N3)Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach the idea is based on the following observations:
If the given array is sorted in ascending order or descending order from the index range [1, N – 2], then the solution does not exist.
Otherwise, at least one index exists in the given array such that the element just before and after that concerning index is less than the current element.
Follow the steps below to solve the problem:
Traverse the given array and for each array index, check if the element just before and after the current index is less than the current element or not. If found to be true, then print that the triplet (i – 1, i, i + 1).
Otherwise, print -1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <iostream>using namespace std; // Function to find a triplet// that satisfy the conditionsvoid FindTrip(int arr[], int N){ // Traverse the given array for(int i = 1; i < N - 1; i++) { // Stores current element int p = arr[i - 1]; // Stores element just before // the current element int q = arr[i]; // Stores element just after // the current element int r = arr[i + 1]; // Check the given conditions if (p < q && q > r) { // Print a triplet cout << i - 1 << " " << i << " " << i + 1; return; } } // If no triplet found cout << -1;} // Driver Codeint main(){ int arr[] = { 2, 1, 4, 3 }; int N = sizeof(arr) / sizeof(arr[0]); FindTrip(arr, N); return 0;} // This code is contributed by jyoti369
// Java program to implement// the above approachimport java.util.*;class GFG { // Function to find a triplet // that satisfy the conditions static void FindTrip(int arr[], int N) { // Traverse the given array for (int i = 1; i < N - 1; i++) { // Stores current element int p = arr[i - 1]; // Stores element just before // the current element int q = arr[i]; // Stores element just after // the current element int r = arr[i + 1]; // Check the given conditions if (p < q && q > r) { // Print a triplet System.out.println( (i - 1) + " " + (i) + " " + (i + 1)); return; } } // If no triplet found System.out.println(-1); } // Driver Code public static void main(String args[]) { int arr[] = { 2, 1, 4, 3 }; int N = arr.length; FindTrip(arr, N); }}
# Python3 program to implement# the above approach # Function to find a triplet# that satisfy the conditionsdef FindTrip(arr, N): # Traverse the given array for i in range(1, N - 1): # Stores current element p = arr[i - 1] # Stores element just before # the current element q = arr[i] # Stores element just after # the current element r = arr[i + 1] # Check the given conditions if (p < q and q > r): # Print a triplet print(i - 1, i, i + 1) return # If no triplet found print(-1) # Driver Codeif __name__ == '__main__': arr = [ 2, 1, 4, 3 ] N = len(arr) FindTrip(arr, N) # This code is contributed by mohit kumar 29
// C# program to implement// the above approach using System; class GFG{ // Function to find a triplet// that satisfy the conditionsstatic void FindTrip(int[] arr, int N){ // Traverse the given array for(int i = 1; i < N - 1; i++) { // Stores current element int p = arr[i - 1]; // Stores element just before // the current element int q = arr[i]; // Stores element just after // the current element int r = arr[i + 1]; // Check the given conditions if (p < q && q > r) { // Print a triplet Console.WriteLine((i - 1) + " " + (i) + " " + (i + 1)); return; } } // If no triplet found Console.WriteLine(-1);} // Driver Codepublic static void Main(){ int[] arr = { 2, 1, 4, 3 }; int N = arr.Length; FindTrip(arr, N);}} // This code is contributed by code_hunt
<script>// Javascript program to implement// the above approach // Function to find a triplet // that satisfy the conditions function FindTrip(arr, N) { // Traverse the given array for (let i = 1; i < N - 1; i++) { // Stores current element let p = arr[i - 1]; // Stores element just before // the current element let q = arr[i]; // Stores element just after // the current element let r = arr[i + 1]; // Check the given conditions if (p < q && q > r) { // Print a triplet document.write( (i - 1) + " " + (i) + " " + (i + 1)); return; } } // If no triplet found document.write(-1); } // Driver Code let arr = [2, 1, 4, 3 ]; let N = arr.length; FindTrip(arr, N); </script>
Output:
1 2 3
Time Complexity: O(N)
Auxiliary Space: O(1)
jyoti369
mohit kumar 29
code_hunt
avijitmondal1998
simranarora5sos
Arrays
Searching
Sorting
Arrays
Searching
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Binary Search
Median of two sorted arrays of different sizes
Find the index of an array element in Java
Two Pointers Technique
Count number of occurrences (or frequency) in a sorted array
|
[
{
"code": null,
"e": 26041,
"s": 26013,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 26324,
"s": 26041,
"text": "Given an array arr[] consisting of a permutation of first N natural numbers, the task is to find a triplet (i, j, k) from the given array such that arr[i] < arr[j] > arr[k], where (i < j < k). If multiple triplets exist, then print any valid triplet of indices. Otherwise, print -1."
},
{
"code": null,
"e": 26334,
"s": 26324,
"text": "Examples:"
},
{
"code": null,
"e": 26499,
"s": 26334,
"text": "Input: arr[] = {2, 1, 4, 3} Output: 1 2 3 Explanation: Triplet that satisfy the given condition is (arr[1], arr[2], arr[3]) Therefore, the required output is 1 2 3."
},
{
"code": null,
"e": 26541,
"s": 26499,
"text": "Input: arr[] = {1, 2, 3, 4, 5} Output: -1"
},
{
"code": null,
"e": 26821,
"s": 26541,
"text": "Naive Approach: The simplest approach to solve this problem is to traverse the array and generate all possible triplets of the given array and for each triplet, check if it satisfies the given conditions or not. If found to be true, then print that triplet. Otherwise, print -1. "
},
{
"code": null,
"e": 26865,
"s": 26821,
"text": "Time Complexity: O(N3)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 26966,
"s": 26865,
"text": "Efficient Approach: To optimize the above approach the idea is based on the following observations: "
},
{
"code": null,
"e": 27101,
"s": 26966,
"text": "If the given array is sorted in ascending order or descending order from the index range [1, N – 2], then the solution does not exist."
},
{
"code": null,
"e": 27257,
"s": 27101,
"text": "Otherwise, at least one index exists in the given array such that the element just before and after that concerning index is less than the current element."
},
{
"code": null,
"e": 27302,
"s": 27257,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27523,
"s": 27302,
"text": "Traverse the given array and for each array index, check if the element just before and after the current index is less than the current element or not. If found to be true, then print that the triplet (i – 1, i, i + 1)."
},
{
"code": null,
"e": 27544,
"s": 27523,
"text": "Otherwise, print -1."
},
{
"code": null,
"e": 27595,
"s": 27544,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27599,
"s": 27595,
"text": "C++"
},
{
"code": null,
"e": 27604,
"s": 27599,
"text": "Java"
},
{
"code": null,
"e": 27612,
"s": 27604,
"text": "Python3"
},
{
"code": null,
"e": 27615,
"s": 27612,
"text": "C#"
},
{
"code": null,
"e": 27626,
"s": 27615,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Function to find a triplet// that satisfy the conditionsvoid FindTrip(int arr[], int N){ // Traverse the given array for(int i = 1; i < N - 1; i++) { // Stores current element int p = arr[i - 1]; // Stores element just before // the current element int q = arr[i]; // Stores element just after // the current element int r = arr[i + 1]; // Check the given conditions if (p < q && q > r) { // Print a triplet cout << i - 1 << \" \" << i << \" \" << i + 1; return; } } // If no triplet found cout << -1;} // Driver Codeint main(){ int arr[] = { 2, 1, 4, 3 }; int N = sizeof(arr) / sizeof(arr[0]); FindTrip(arr, N); return 0;} // This code is contributed by jyoti369",
"e": 28627,
"s": 27626,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*;class GFG { // Function to find a triplet // that satisfy the conditions static void FindTrip(int arr[], int N) { // Traverse the given array for (int i = 1; i < N - 1; i++) { // Stores current element int p = arr[i - 1]; // Stores element just before // the current element int q = arr[i]; // Stores element just after // the current element int r = arr[i + 1]; // Check the given conditions if (p < q && q > r) { // Print a triplet System.out.println( (i - 1) + \" \" + (i) + \" \" + (i + 1)); return; } } // If no triplet found System.out.println(-1); } // Driver Code public static void main(String args[]) { int arr[] = { 2, 1, 4, 3 }; int N = arr.length; FindTrip(arr, N); }}",
"e": 29722,
"s": 28627,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to find a triplet# that satisfy the conditionsdef FindTrip(arr, N): # Traverse the given array for i in range(1, N - 1): # Stores current element p = arr[i - 1] # Stores element just before # the current element q = arr[i] # Stores element just after # the current element r = arr[i + 1] # Check the given conditions if (p < q and q > r): # Print a triplet print(i - 1, i, i + 1) return # If no triplet found print(-1) # Driver Codeif __name__ == '__main__': arr = [ 2, 1, 4, 3 ] N = len(arr) FindTrip(arr, N) # This code is contributed by mohit kumar 29",
"e": 30490,
"s": 29722,
"text": null
},
{
"code": "// C# program to implement// the above approach using System; class GFG{ // Function to find a triplet// that satisfy the conditionsstatic void FindTrip(int[] arr, int N){ // Traverse the given array for(int i = 1; i < N - 1; i++) { // Stores current element int p = arr[i - 1]; // Stores element just before // the current element int q = arr[i]; // Stores element just after // the current element int r = arr[i + 1]; // Check the given conditions if (p < q && q > r) { // Print a triplet Console.WriteLine((i - 1) + \" \" + (i) + \" \" + (i + 1)); return; } } // If no triplet found Console.WriteLine(-1);} // Driver Codepublic static void Main(){ int[] arr = { 2, 1, 4, 3 }; int N = arr.Length; FindTrip(arr, N);}} // This code is contributed by code_hunt",
"e": 31456,
"s": 30490,
"text": null
},
{
"code": "<script>// Javascript program to implement// the above approach // Function to find a triplet // that satisfy the conditions function FindTrip(arr, N) { // Traverse the given array for (let i = 1; i < N - 1; i++) { // Stores current element let p = arr[i - 1]; // Stores element just before // the current element let q = arr[i]; // Stores element just after // the current element let r = arr[i + 1]; // Check the given conditions if (p < q && q > r) { // Print a triplet document.write( (i - 1) + \" \" + (i) + \" \" + (i + 1)); return; } } // If no triplet found document.write(-1); } // Driver Code let arr = [2, 1, 4, 3 ]; let N = arr.length; FindTrip(arr, N); </script>",
"e": 32474,
"s": 31456,
"text": null
},
{
"code": null,
"e": 32482,
"s": 32474,
"text": "Output:"
},
{
"code": null,
"e": 32488,
"s": 32482,
"text": "1 2 3"
},
{
"code": null,
"e": 32510,
"s": 32488,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 32533,
"s": 32510,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 32542,
"s": 32533,
"text": "jyoti369"
},
{
"code": null,
"e": 32557,
"s": 32542,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 32567,
"s": 32557,
"text": "code_hunt"
},
{
"code": null,
"e": 32584,
"s": 32567,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 32600,
"s": 32584,
"text": "simranarora5sos"
},
{
"code": null,
"e": 32607,
"s": 32600,
"text": "Arrays"
},
{
"code": null,
"e": 32617,
"s": 32607,
"text": "Searching"
},
{
"code": null,
"e": 32625,
"s": 32617,
"text": "Sorting"
},
{
"code": null,
"e": 32632,
"s": 32625,
"text": "Arrays"
},
{
"code": null,
"e": 32642,
"s": 32632,
"text": "Searching"
},
{
"code": null,
"e": 32650,
"s": 32642,
"text": "Sorting"
},
{
"code": null,
"e": 32748,
"s": 32650,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32779,
"s": 32748,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 32804,
"s": 32779,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 32842,
"s": 32804,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 32863,
"s": 32842,
"text": "Next Greater Element"
},
{
"code": null,
"e": 32921,
"s": 32863,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 32935,
"s": 32921,
"text": "Binary Search"
},
{
"code": null,
"e": 32982,
"s": 32935,
"text": "Median of two sorted arrays of different sizes"
},
{
"code": null,
"e": 33025,
"s": 32982,
"text": "Find the index of an array element in Java"
},
{
"code": null,
"e": 33048,
"s": 33025,
"text": "Two Pointers Technique"
}
] |
CSS - azimuth
|
The azimuth property describes the position of a sound source along the horizontal axis of the listener's environment.
angle
left-side
far-left
left
center-left
center
center-right
right
far-right
right-side
far-right
behind center
Azimuth values should be shown as follows
All the HTML elements.
object.style.azimuth = "Any value defined above";
<html>
<head>
<style type = "text/css">
h1 { azimuth: 70deg; }
h3 { azimuth: behind left; }
p { azimuth: left; }
</style>
</head>
<body>
<h1>This is header1 content</h1>
<h3>This is header3 content</h3>
<p>This is my paragraph content.</p>
</body>
</html>
It will produce the following result −
This is my paragraph content.
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2745,
"s": 2626,
"text": "The azimuth property describes the position of a sound source along the horizontal axis of the listener's environment."
},
{
"code": null,
"e": 2751,
"s": 2745,
"text": "angle"
},
{
"code": null,
"e": 2761,
"s": 2751,
"text": "left-side"
},
{
"code": null,
"e": 2770,
"s": 2761,
"text": "far-left"
},
{
"code": null,
"e": 2775,
"s": 2770,
"text": "left"
},
{
"code": null,
"e": 2787,
"s": 2775,
"text": "center-left"
},
{
"code": null,
"e": 2794,
"s": 2787,
"text": "center"
},
{
"code": null,
"e": 2807,
"s": 2794,
"text": "center-right"
},
{
"code": null,
"e": 2813,
"s": 2807,
"text": "right"
},
{
"code": null,
"e": 2823,
"s": 2813,
"text": "far-right"
},
{
"code": null,
"e": 2834,
"s": 2823,
"text": "right-side"
},
{
"code": null,
"e": 2844,
"s": 2834,
"text": "far-right"
},
{
"code": null,
"e": 2858,
"s": 2844,
"text": "behind center"
},
{
"code": null,
"e": 2900,
"s": 2858,
"text": "Azimuth values should be shown as follows"
},
{
"code": null,
"e": 2923,
"s": 2900,
"text": "All the HTML elements."
},
{
"code": null,
"e": 2974,
"s": 2923,
"text": "object.style.azimuth = \"Any value defined above\";\n"
},
{
"code": null,
"e": 3312,
"s": 2974,
"text": "<html>\n <head>\n <style type = \"text/css\">\n h1 { azimuth: 70deg; }\n h3 { azimuth: behind left; }\n p { azimuth: left; }\n </style>\n </head>\n\n <body>\n \n <h1>This is header1 content</h1>\n <h3>This is header3 content</h3>\n <p>This is my paragraph content.</p>\n \n </body>\n</html> "
},
{
"code": null,
"e": 3351,
"s": 3312,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 3381,
"s": 3351,
"text": "This is my paragraph content."
},
{
"code": null,
"e": 3416,
"s": 3381,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3430,
"s": 3416,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3465,
"s": 3430,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3482,
"s": 3465,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3517,
"s": 3482,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3548,
"s": 3517,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3583,
"s": 3548,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3614,
"s": 3583,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3649,
"s": 3614,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 3680,
"s": 3649,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3713,
"s": 3680,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3744,
"s": 3713,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3751,
"s": 3744,
"text": " Print"
},
{
"code": null,
"e": 3762,
"s": 3751,
"text": " Add Notes"
}
] |
How to plot an animated image matrix in matplotlib?
|
To plot an animated image matrix in matplotlib, we can take the following steps
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a figure and a set of subplots.
Create a figure and a set of subplots.
Make an animation by repeatedly calling a function *update*.
Make an animation by repeatedly calling a function *update*.
Inside the update method, create a 6×6 dimension of matrix and display the data as an image, i.e., on a 2D regular raster.
Inside the update method, create a 6×6 dimension of matrix and display the data as an image, i.e., on a 2D regular raster.
Turn off the axes using set_axis_off().
Turn off the axes using set_axis_off().
To display the figure, use Show() method.
To display the figure, use Show() method.
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
def update(i):
im_normed = np.random.rand(6, 6)
ax.imshow(im_normed)
ax.set_axis_off()
anim = FuncAnimation(fig, update, frames=20, interval=50)
plt.show()
It will produce the following output −
|
[
{
"code": null,
"e": 1142,
"s": 1062,
"text": "To plot an animated image matrix in matplotlib, we can take the following steps"
},
{
"code": null,
"e": 1218,
"s": 1142,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1294,
"s": 1218,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1333,
"s": 1294,
"text": "Create a figure and a set of subplots."
},
{
"code": null,
"e": 1372,
"s": 1333,
"text": "Create a figure and a set of subplots."
},
{
"code": null,
"e": 1433,
"s": 1372,
"text": "Make an animation by repeatedly calling a function *update*."
},
{
"code": null,
"e": 1494,
"s": 1433,
"text": "Make an animation by repeatedly calling a function *update*."
},
{
"code": null,
"e": 1617,
"s": 1494,
"text": "Inside the update method, create a 6×6 dimension of matrix and display the data as an image, i.e., on a 2D regular raster."
},
{
"code": null,
"e": 1740,
"s": 1617,
"text": "Inside the update method, create a 6×6 dimension of matrix and display the data as an image, i.e., on a 2D regular raster."
},
{
"code": null,
"e": 1780,
"s": 1740,
"text": "Turn off the axes using set_axis_off()."
},
{
"code": null,
"e": 1820,
"s": 1780,
"text": "Turn off the axes using set_axis_off()."
},
{
"code": null,
"e": 1862,
"s": 1820,
"text": "To display the figure, use Show() method."
},
{
"code": null,
"e": 1904,
"s": 1862,
"text": "To display the figure, use Show() method."
},
{
"code": null,
"e": 2288,
"s": 1904,
"text": "from matplotlib.animation import FuncAnimation\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfig, ax = plt.subplots()\n\ndef update(i):\n im_normed = np.random.rand(6, 6)\n ax.imshow(im_normed)\n ax.set_axis_off()\n\nanim = FuncAnimation(fig, update, frames=20, interval=50)\n\nplt.show()\n"
},
{
"code": null,
"e": 2327,
"s": 2288,
"text": "It will produce the following output −"
}
] |
How to initialize variables in C#?
|
A variable is a name given to a storage area that our programs can manipulate.
Each variable in C# has a specific type, which determines the size and layout of the variable's memory the range of values that can be stored within that memory and the set of operations that can be applied to the variable.
To initialize a variable, first you need to define it.
int a;
Now to initialize, use an equal sign followed by a constant expression.
int a = 10;
We used the following syntax above.
variable_name = value;
Let us see a simple example to work with variable in C#.
Live Demo
using System;
namespace VariableDefinition {
class Program {
static void Main(string[] args) {
short a;
int b ;
double c;
a = 10;
b = 20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
}
a = 10, b = 20, c = 30
|
[
{
"code": null,
"e": 1141,
"s": 1062,
"text": "A variable is a name given to a storage area that our programs can manipulate."
},
{
"code": null,
"e": 1365,
"s": 1141,
"text": "Each variable in C# has a specific type, which determines the size and layout of the variable's memory the range of values that can be stored within that memory and the set of operations that can be applied to the variable."
},
{
"code": null,
"e": 1420,
"s": 1365,
"text": "To initialize a variable, first you need to define it."
},
{
"code": null,
"e": 1427,
"s": 1420,
"text": "int a;"
},
{
"code": null,
"e": 1499,
"s": 1427,
"text": "Now to initialize, use an equal sign followed by a constant expression."
},
{
"code": null,
"e": 1511,
"s": 1499,
"text": "int a = 10;"
},
{
"code": null,
"e": 1547,
"s": 1511,
"text": "We used the following syntax above."
},
{
"code": null,
"e": 1570,
"s": 1547,
"text": "variable_name = value;"
},
{
"code": null,
"e": 1627,
"s": 1570,
"text": "Let us see a simple example to work with variable in C#."
},
{
"code": null,
"e": 1638,
"s": 1627,
"text": " Live Demo"
},
{
"code": null,
"e": 1960,
"s": 1638,
"text": "using System;\nnamespace VariableDefinition {\n class Program {\n static void Main(string[] args) {\n short a;\n int b ;\n double c;\n a = 10;\n b = 20;\n c = a + b;\n Console.WriteLine(\"a = {0}, b = {1}, c = {2}\", a, b, c);\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 1983,
"s": 1960,
"text": "a = 10, b = 20, c = 30"
}
] |
Linear Regression Using Gradient Descent in 10 Lines of Code | by Joseph J. Bautista | Towards Data Science
|
My goal is to eventually write out articles like this for other optimization techniques. Let’s start with gradient descent. Note: This isn’t a comprehensive guide as I skim through a lot of things.
In our journey to study machine learning and artificial intelligence, it is important to know the basics before going deeper. The basics are the building blocks needed in order to understand more complex forms of architectures. For instance, you wouldn’t want to study ordinary differential equations without first understanding what, how, and why a derivative works. The same can be said with machine learning. An understanding of linear regression by using gradient descent as our optimization technique will help us understand more complex models in the future.
I remember one time explaining to a group of data scientists the random forest classification model I created for this company. I tried making an analogy by using logistic regression since I assumed that my fellow data scientists in the room would know about it. A whole lot of them said they weren’t familiar with it. I got shocked since we were talking about a more advanced method here yet they didn’t even know what a logistic regression model was. Don’t be like that.
Linear regression is one of the most basic ways we can model relationships. Our model here can be described as y=mx+b, where m is the slope (to change the steepness), b is the bias (to move the line up and down the graph), x is the explanatory variable, and y is the output. We use linear regression if we think there’s a linear relationship. For example, let’s say that the x-axis below is study_time while the y_axis is test_score.
A straight line best describes this relationship because as a student studies more, his or her test scores increase. It wouldn’t make sense to use an exponential, sinusoidal, or logarithmic function to model this relationship. Linear models offer us simplicity; linear relationships are easy to understand and interpret. Note that relationships in the real world aren’t always linear, so instead we use more advanced methods like neural networks, which are universal function approximators. More on neural networks in the future.
By tweaking m and b, we can create a line that will best describe the relationship. How do we know we’re close? By using a thing called a cost function. It literally tells us the cost. A high cost value means it’s expensive — our approximation is far from describing the real relationship. On the other hand, a low cost value means it’s cheap — our approximation is close to describing the relationship.
For linear regressions we use a cost function known as the mean squared error or MSE. We take the squared value of our real data points minus the approximated values. Our approximated values can be calculated using the current m and b values we have: y_approx = m_current*x + b_current. After that, we add all those values up and divide them by the number of data points we have, effectively just taking the average. Now you see why it’s called the mean squared error.
You’re probably thinking right now, “that sounds splendid and all but how can we uncover m and b?? Brute force??” Brute force isn’t helpful. A more efficient way is gradient descent. Imagine trying to find the lowest point blindfolded as can be seen below. What you would do is to check left and right and then feel which one brings you to a lower point. You do this every step of the way until checking left and right both brings you to a higher point.
The math behind it isn’t as complicated as it looks. What we’re doing here is applying partial derivatives with respect to both m and b to the cost function to point us to the lowest point. If you remember your math, a derivative of zero means you are at either a local minima or maxima. Which means that the closer we get to zero, the better. When we reach close to, if not, zero with our derivatives, we also inevitably get the lowest value for our cost function.
The process of finding the optimal values for m and b is to then minimize our derivatives. Training a machine learning algorithm or a neural network really is just the process of minimizing the cost function.
Here I’ll be using Python to code our linear regression model. I use Python because it’s my go-to language for doing data science. Furthermore, Python is great for both experts and beginners. The language was made for readability, so whether you’ve been programming for years or have just been programming for a day, it’s still fairly easy to navigate through someone else’s code.
def linear_regression(X, y, m_current=0, b_current=0, epochs=1000, learning_rate=0.0001): N = float(len(y)) for i in range(epochs): y_current = (m_current * X) + b_current cost = sum([data**2 for data in (y-y_current)]) / N m_gradient = -(2/N) * sum(X * (y - y_current)) b_gradient = -(2/N) * sum(y - y_current) m_current = m_current - (learning_rate * m_gradient) b_current = b_current - (learning_rate * b_gradient) return m_current, b_current, cost
X and y are our input parameters. On the other hand, m_current and b_current are our slope and bias terms respectively, both of which will be updated as we try to find the best numbers so that the equation we get best fits our data. Here epochs refer to the number of times we train our model to find the best slope and bias for our model to fit the data. Finally, learning_rate here refers to the speed of convergence, meaning how fast gradient descent finds the best parameters.
To further understand the learning_rate, let’s go back to our example of finding the lowest point blindfolded. A big learning_rate would mean that the steps we take are too big and that you might miss the lowest point entirely. However, too small of a learning_rate means that we will take a long time to reach the bottom. Try to strike a balance between the two.
The important bit is the for-loop:
for i in range(epochs): y_current = (m_current * X) + b_current cost = sum([data**2 for data in (y-y_current)]) / N m_gradient = -(2/N) * sum(X * (y - y_current)) b_gradient = -(2/N) * sum(y - y_current) m_current = m_current - (learning_rate * m_gradient) b_current = b_current - (learning_rate * b_gradient)
We iterate 1000 times because 1000 sounds good. Really depends on how much you want to iterate. Hyperparameter fine-tuning is an ongoing research right now, so you might want to check that out!
We calculate the gradient of the slope and the bias by using the equations we saw above. We then update our slope and bias by subtracting them the learning rate times and respective gradient value. The learning rate will determine the speed we will reach convergence. After 1000 iterations, we return m_current, b_current, and the cost.
Congratulations! That’s the first step in your machine learning and artificial intelligence journey. Get an intuitive feel for how gradient descent works because this is actually used in more advanced models also. The goal here is to learn the basics, and you my friend have just taken the first step. Now off you go and learn more!
|
[
{
"code": null,
"e": 369,
"s": 171,
"text": "My goal is to eventually write out articles like this for other optimization techniques. Let’s start with gradient descent. Note: This isn’t a comprehensive guide as I skim through a lot of things."
},
{
"code": null,
"e": 934,
"s": 369,
"text": "In our journey to study machine learning and artificial intelligence, it is important to know the basics before going deeper. The basics are the building blocks needed in order to understand more complex forms of architectures. For instance, you wouldn’t want to study ordinary differential equations without first understanding what, how, and why a derivative works. The same can be said with machine learning. An understanding of linear regression by using gradient descent as our optimization technique will help us understand more complex models in the future."
},
{
"code": null,
"e": 1407,
"s": 934,
"text": "I remember one time explaining to a group of data scientists the random forest classification model I created for this company. I tried making an analogy by using logistic regression since I assumed that my fellow data scientists in the room would know about it. A whole lot of them said they weren’t familiar with it. I got shocked since we were talking about a more advanced method here yet they didn’t even know what a logistic regression model was. Don’t be like that."
},
{
"code": null,
"e": 1841,
"s": 1407,
"text": "Linear regression is one of the most basic ways we can model relationships. Our model here can be described as y=mx+b, where m is the slope (to change the steepness), b is the bias (to move the line up and down the graph), x is the explanatory variable, and y is the output. We use linear regression if we think there’s a linear relationship. For example, let’s say that the x-axis below is study_time while the y_axis is test_score."
},
{
"code": null,
"e": 2371,
"s": 1841,
"text": "A straight line best describes this relationship because as a student studies more, his or her test scores increase. It wouldn’t make sense to use an exponential, sinusoidal, or logarithmic function to model this relationship. Linear models offer us simplicity; linear relationships are easy to understand and interpret. Note that relationships in the real world aren’t always linear, so instead we use more advanced methods like neural networks, which are universal function approximators. More on neural networks in the future."
},
{
"code": null,
"e": 2775,
"s": 2371,
"text": "By tweaking m and b, we can create a line that will best describe the relationship. How do we know we’re close? By using a thing called a cost function. It literally tells us the cost. A high cost value means it’s expensive — our approximation is far from describing the real relationship. On the other hand, a low cost value means it’s cheap — our approximation is close to describing the relationship."
},
{
"code": null,
"e": 3244,
"s": 2775,
"text": "For linear regressions we use a cost function known as the mean squared error or MSE. We take the squared value of our real data points minus the approximated values. Our approximated values can be calculated using the current m and b values we have: y_approx = m_current*x + b_current. After that, we add all those values up and divide them by the number of data points we have, effectively just taking the average. Now you see why it’s called the mean squared error."
},
{
"code": null,
"e": 3698,
"s": 3244,
"text": "You’re probably thinking right now, “that sounds splendid and all but how can we uncover m and b?? Brute force??” Brute force isn’t helpful. A more efficient way is gradient descent. Imagine trying to find the lowest point blindfolded as can be seen below. What you would do is to check left and right and then feel which one brings you to a lower point. You do this every step of the way until checking left and right both brings you to a higher point."
},
{
"code": null,
"e": 4164,
"s": 3698,
"text": "The math behind it isn’t as complicated as it looks. What we’re doing here is applying partial derivatives with respect to both m and b to the cost function to point us to the lowest point. If you remember your math, a derivative of zero means you are at either a local minima or maxima. Which means that the closer we get to zero, the better. When we reach close to, if not, zero with our derivatives, we also inevitably get the lowest value for our cost function."
},
{
"code": null,
"e": 4373,
"s": 4164,
"text": "The process of finding the optimal values for m and b is to then minimize our derivatives. Training a machine learning algorithm or a neural network really is just the process of minimizing the cost function."
},
{
"code": null,
"e": 4754,
"s": 4373,
"text": "Here I’ll be using Python to code our linear regression model. I use Python because it’s my go-to language for doing data science. Furthermore, Python is great for both experts and beginners. The language was made for readability, so whether you’ve been programming for years or have just been programming for a day, it’s still fairly easy to navigate through someone else’s code."
},
{
"code": null,
"e": 5272,
"s": 4754,
"text": "def linear_regression(X, y, m_current=0, b_current=0, epochs=1000, learning_rate=0.0001): N = float(len(y)) for i in range(epochs): y_current = (m_current * X) + b_current cost = sum([data**2 for data in (y-y_current)]) / N m_gradient = -(2/N) * sum(X * (y - y_current)) b_gradient = -(2/N) * sum(y - y_current) m_current = m_current - (learning_rate * m_gradient) b_current = b_current - (learning_rate * b_gradient) return m_current, b_current, cost"
},
{
"code": null,
"e": 5753,
"s": 5272,
"text": "X and y are our input parameters. On the other hand, m_current and b_current are our slope and bias terms respectively, both of which will be updated as we try to find the best numbers so that the equation we get best fits our data. Here epochs refer to the number of times we train our model to find the best slope and bias for our model to fit the data. Finally, learning_rate here refers to the speed of convergence, meaning how fast gradient descent finds the best parameters."
},
{
"code": null,
"e": 6117,
"s": 5753,
"text": "To further understand the learning_rate, let’s go back to our example of finding the lowest point blindfolded. A big learning_rate would mean that the steps we take are too big and that you might miss the lowest point entirely. However, too small of a learning_rate means that we will take a long time to reach the bottom. Try to strike a balance between the two."
},
{
"code": null,
"e": 6152,
"s": 6117,
"text": "The important bit is the for-loop:"
},
{
"code": null,
"e": 6486,
"s": 6152,
"text": "for i in range(epochs): y_current = (m_current * X) + b_current cost = sum([data**2 for data in (y-y_current)]) / N m_gradient = -(2/N) * sum(X * (y - y_current)) b_gradient = -(2/N) * sum(y - y_current) m_current = m_current - (learning_rate * m_gradient) b_current = b_current - (learning_rate * b_gradient)"
},
{
"code": null,
"e": 6680,
"s": 6486,
"text": "We iterate 1000 times because 1000 sounds good. Really depends on how much you want to iterate. Hyperparameter fine-tuning is an ongoing research right now, so you might want to check that out!"
},
{
"code": null,
"e": 7017,
"s": 6680,
"text": "We calculate the gradient of the slope and the bias by using the equations we saw above. We then update our slope and bias by subtracting them the learning rate times and respective gradient value. The learning rate will determine the speed we will reach convergence. After 1000 iterations, we return m_current, b_current, and the cost."
}
] |
Arrays Data Structure in Javascript
|
The array is a container which can hold a fixed number of items and these items should be of the same type. It stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Let's say you want to record the average temperatures of all days of the week. You can record them as follows −
let avgTempMon = 35;
let avgTempTue = 33;
let avgTempWed = 31;
let avgTempThur = 24;
let avgTempFri = 25;
let avgTempSat = 22;
let avgTempSun = 30;
But if you look at this it gets difficult to keep track of these variables. What if you had to do this for all months? It would get very difficult to keep track. So we use arrays to keep track of these −
let avgTemps = [];
avgTemps[0] = 35;
avgTemps[1] = 33;
avgTemps[2] = 31;
avgTemps[3] = 24;
avgTemps[4] = 25;
avgTemps[5] = 22;
avgTemps[6] = 30;
Now you only need to keep track of one variable to get all the values.
Arrays are represented as contiguous blocks of memory holding data in them. For example,
The above image shows an array of 10 elements. The indices are the places where each of these elements are stored. Note that index starts with 0 and each element can be accessed via its index. For example, we can fetch an element at index 6 as arr[6] which will give the result 27.
Let's look at some of the operations that can be applied to arrays in Javascript.
Creating an array
Adding an element
Removing an element
Joining 2 arrays
Sorting arrays
Searching in an array
Creating a multidimensional array
Looping through an array
|
[
{
"code": null,
"e": 1389,
"s": 1062,
"text": "The array is a container which can hold a fixed number of items and these items should be of the same type. It stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type."
},
{
"code": null,
"e": 1501,
"s": 1389,
"text": "Let's say you want to record the average temperatures of all days of the week. You can record them as follows −"
},
{
"code": null,
"e": 1649,
"s": 1501,
"text": "let avgTempMon = 35;\nlet avgTempTue = 33;\nlet avgTempWed = 31;\nlet avgTempThur = 24;\nlet avgTempFri = 25;\nlet avgTempSat = 22;\nlet avgTempSun = 30;"
},
{
"code": null,
"e": 1854,
"s": 1649,
"text": "But if you look at this it gets difficult to keep track of these variables. What if you had to do this for all months? It would get very difficult to keep track. So we use arrays to keep track of these − "
},
{
"code": null,
"e": 1999,
"s": 1854,
"text": "let avgTemps = [];\navgTemps[0] = 35;\navgTemps[1] = 33;\navgTemps[2] = 31;\navgTemps[3] = 24;\navgTemps[4] = 25;\navgTemps[5] = 22;\navgTemps[6] = 30;"
},
{
"code": null,
"e": 2070,
"s": 1999,
"text": "Now you only need to keep track of one variable to get all the values."
},
{
"code": null,
"e": 2159,
"s": 2070,
"text": "Arrays are represented as contiguous blocks of memory holding data in them. For example,"
},
{
"code": null,
"e": 2441,
"s": 2159,
"text": "The above image shows an array of 10 elements. The indices are the places where each of these elements are stored. Note that index starts with 0 and each element can be accessed via its index. For example, we can fetch an element at index 6 as arr[6] which will give the result 27."
},
{
"code": null,
"e": 2523,
"s": 2441,
"text": "Let's look at some of the operations that can be applied to arrays in Javascript."
},
{
"code": null,
"e": 2541,
"s": 2523,
"text": "Creating an array"
},
{
"code": null,
"e": 2559,
"s": 2541,
"text": "Adding an element"
},
{
"code": null,
"e": 2579,
"s": 2559,
"text": "Removing an element"
},
{
"code": null,
"e": 2596,
"s": 2579,
"text": "Joining 2 arrays"
},
{
"code": null,
"e": 2611,
"s": 2596,
"text": "Sorting arrays"
},
{
"code": null,
"e": 2633,
"s": 2611,
"text": "Searching in an array"
},
{
"code": null,
"e": 2667,
"s": 2633,
"text": "Creating a multidimensional array"
},
{
"code": null,
"e": 2692,
"s": 2667,
"text": "Looping through an array"
}
] |
Create a QR code generator app using ReactJS - GeeksforGeeks
|
27 Aug, 2021
Introduction: In this article, we are going to make a simple QR Code generator app. QR code is a two-dimensional barcode readable on smartphones. Allows coding of more than 4000 characters in a double-barcode bar. QR codes can be used to show text to a user, to open a URL, to keep contact in an address book or to write messages.
Prerequisites: The pre-requisites for this project are:
React
Functional Components
React Hooks
Javascript ES6
Approach: Our app contains two sections. In one section we will take the user inputs such as the text to encode, size of QR code, background color of QR code, and store all of that inside state variables. After that, we will build the required API string to fetch the QR code image. In the other section, we will display the required QR code
Creating a React application:
Step 1: Create a react application by typing the following command in the terminal.
npx create-react-app qrcode-gen
Step 2: Now, go to the project folder i.e qrcode.gen by running the following command.
cd qrcode-gen
Project Structure: It will look like the following.
Example: Here App.js is the only default component of our app that contains all the logic. We will be using a free opensource (no auth requires) API called ‘create-qr-code’ to fetch the required QR code image. We will also have a button to download the QR code image.
Now write down the following code in the App.js file.
Javascript
import { useEffect, useState } from 'react';
import './App.css';
function App() {
const [temp, setTemp] = useState("");
const [word, setWord] = useState("");
const [size, setSize] = useState(400);
const [bgColor, setBgColor] = useState("ffffff");
const [qrCode, setQrCode] = useState("");
// Changing the URL only when the user
// changes the input
useEffect(() => {
setQrCode
(`http://api.qrserver.com/v1/create-qr-code/?data=${word}!&size=${size}x${size}&bgcolor=${bgColor}`);
}, [word, size, bgColor]);
// Updating the input word when user
// click on the generate button
function handleClick() {
setWord(temp);
}
return (
<div className="App">
<h1>QR Code Generator</h1>
<div className="input-box">
<div className="gen">
<input type="text" onChange={
(e) => {setTemp(e.target.value)}}
placeholder="Enter text to encode" />
<button className="button"
onClick={handleClick}>
Generate
</button>
</div>
<div className="extra">
<h5>Background Color:</h5>
<input type="color" onChange={(e) =>
{ setBgColor(e.target.value.substring(1)) }} />
<h5>Dimension:</h5>
<input type="range" min="200" max="600"
value={size} onChange={(e) =>
{setSize(e.target.value)}} />
</div>
</div>
<div className="output-box">
<img src={qrCode} alt="" />
<a href={qrCode} download="QRCode">
<button type="button">Download</button>
</a>
</div>
</div>
);
}
export default App;
Now, let’s edit the file named App.css to design our app.
CSS
@import url('http://fonts.cdnfonts.com/css/lilly');
.App{
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 50px;
padding-top: 30px;
}
h1{
font-family: 'Lilly', sans-serif;
font-size: 50px;
}
.gen input{
height: 35px;
width: 250px;
font-size: 20px;
padding-left: 5px;
}
button{
position: relative;
height: 38px;
width: 100px;
top: -2px;
font-size: 18px;
border: none;
color: whitesmoke;
background-color: forestgreen;
box-shadow: 2px 2px 5px rgb(74, 182, 74);
cursor: pointer;
}
button:active{
box-shadow: none;
}
.extra{
padding-top: 20px;
display: flex;
justify-content: space-around;
gap: 10px;
}
.output-box{
display: flex;
flex-direction: column;
align-items: center;
gap: 40px;
}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
React-Questions
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to filter object array based on attributes?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
|
[
{
"code": null,
"e": 26739,
"s": 26708,
"text": " \n27 Aug, 2021\n"
},
{
"code": null,
"e": 27070,
"s": 26739,
"text": "Introduction: In this article, we are going to make a simple QR Code generator app. QR code is a two-dimensional barcode readable on smartphones. Allows coding of more than 4000 characters in a double-barcode bar. QR codes can be used to show text to a user, to open a URL, to keep contact in an address book or to write messages."
},
{
"code": null,
"e": 27126,
"s": 27070,
"text": "Prerequisites: The pre-requisites for this project are:"
},
{
"code": null,
"e": 27132,
"s": 27126,
"text": "React"
},
{
"code": null,
"e": 27154,
"s": 27132,
"text": "Functional Components"
},
{
"code": null,
"e": 27166,
"s": 27154,
"text": "React Hooks"
},
{
"code": null,
"e": 27181,
"s": 27166,
"text": "Javascript ES6"
},
{
"code": null,
"e": 27524,
"s": 27181,
"text": "Approach: Our app contains two sections. In one section we will take the user inputs such as the text to encode, size of QR code, background color of QR code, and store all of that inside state variables. After that, we will build the required API string to fetch the QR code image. In the other section, we will display the required QR code "
},
{
"code": null,
"e": 27556,
"s": 27526,
"text": "Creating a React application:"
},
{
"code": null,
"e": 27640,
"s": 27556,
"text": "Step 1: Create a react application by typing the following command in the terminal."
},
{
"code": null,
"e": 27672,
"s": 27640,
"text": "npx create-react-app qrcode-gen"
},
{
"code": null,
"e": 27759,
"s": 27672,
"text": "Step 2: Now, go to the project folder i.e qrcode.gen by running the following command."
},
{
"code": null,
"e": 27773,
"s": 27759,
"text": "cd qrcode-gen"
},
{
"code": null,
"e": 27825,
"s": 27773,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 28094,
"s": 27825,
"text": "Example: Here App.js is the only default component of our app that contains all the logic. We will be using a free opensource (no auth requires) API called ‘create-qr-code’ to fetch the required QR code image. We will also have a button to download the QR code image. "
},
{
"code": null,
"e": 28148,
"s": 28094,
"text": "Now write down the following code in the App.js file."
},
{
"code": null,
"e": 28159,
"s": 28148,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\nimport { useEffect, useState } from 'react'; \nimport './App.css'; \n \nfunction App() { \n const [temp, setTemp] = useState(\"\"); \n const [word, setWord] = useState(\"\"); \n const [size, setSize] = useState(400); \n const [bgColor, setBgColor] = useState(\"ffffff\"); \n const [qrCode, setQrCode] = useState(\"\"); \n \n // Changing the URL only when the user \n // changes the input \n useEffect(() => { \n setQrCode \n (`http://api.qrserver.com/v1/create-qr-code/?data=${word}!&size=${size}x${size}&bgcolor=${bgColor}`); \n }, [word, size, bgColor]); \n \n // Updating the input word when user \n // click on the generate button \n function handleClick() { \n setWord(temp); \n } \n \n return ( \n <div className=\"App\"> \n <h1>QR Code Generator</h1> \n <div className=\"input-box\"> \n <div className=\"gen\"> \n <input type=\"text\" onChange={ \n (e) => {setTemp(e.target.value)}} \n placeholder=\"Enter text to encode\" /> \n <button className=\"button\" \n onClick={handleClick}> \n Generate \n </button> \n </div> \n <div className=\"extra\"> \n <h5>Background Color:</h5> \n <input type=\"color\" onChange={(e) => \n { setBgColor(e.target.value.substring(1)) }} /> \n <h5>Dimension:</h5> \n <input type=\"range\" min=\"200\" max=\"600\"\n value={size} onChange={(e) => \n {setSize(e.target.value)}} /> \n </div> \n </div> \n <div className=\"output-box\"> \n <img src={qrCode} alt=\"\" /> \n <a href={qrCode} download=\"QRCode\"> \n <button type=\"button\">Download</button> \n </a> \n </div> \n </div> \n ); \n} \n \nexport default App;\n\n\n\n\n\n",
"e": 29892,
"s": 28169,
"text": null
},
{
"code": null,
"e": 29950,
"s": 29892,
"text": "Now, let’s edit the file named App.css to design our app."
},
{
"code": null,
"e": 29954,
"s": 29950,
"text": "CSS"
},
{
"code": "\n\n\n\n\n\n\n@import url('http://fonts.cdnfonts.com/css/lilly'); \n.App{ \n display: flex; \n flex-direction: column; \n justify-content: center; \n align-items: center; \n gap: 50px; \n padding-top: 30px; \n} \nh1{ \n font-family: 'Lilly', sans-serif; \n font-size: 50px; \n} \n.gen input{ \n height: 35px; \n width: 250px; \n font-size: 20px; \n padding-left: 5px; \n} \nbutton{ \n position: relative; \n height: 38px; \n width: 100px; \n top: -2px; \n font-size: 18px; \n border: none; \n color: whitesmoke; \n background-color: forestgreen; \n box-shadow: 2px 2px 5px rgb(74, 182, 74); \n cursor: pointer; \n} \nbutton:active{ \n box-shadow: none; \n} \n.extra{ \n padding-top: 20px; \n display: flex; \n justify-content: space-around; \n gap: 10px; \n} \n.output-box{ \n display: flex; \n flex-direction: column; \n align-items: center; \n gap: 40px; \n}\n\n\n\n\n\n",
"e": 30810,
"s": 29964,
"text": null
},
{
"code": null,
"e": 30923,
"s": 30810,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 30933,
"s": 30923,
"text": "npm start"
},
{
"code": null,
"e": 31032,
"s": 30933,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 31050,
"s": 31032,
"text": "\nReact-Questions\n"
},
{
"code": null,
"e": 31063,
"s": 31050,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 31073,
"s": 31063,
"text": "\nReactJS\n"
},
{
"code": null,
"e": 31092,
"s": 31073,
"text": "\nWeb Technologies\n"
},
{
"code": null,
"e": 31297,
"s": 31092,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 31337,
"s": 31297,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31398,
"s": 31337,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31439,
"s": 31398,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 31461,
"s": 31439,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 31509,
"s": 31461,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 31552,
"s": 31509,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 31597,
"s": 31552,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 31662,
"s": 31597,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 31730,
"s": 31662,
"text": "How to pass data from one component to other component in ReactJS ?"
}
] |
How to match any non-digit character in Python using Regular Expression?
|
The following code matches and prints all non-digit characters in the given string using python regex as follows.
import re
foo = 'Mo4zam5Bi6QuE7'
match = re.findall(r'\D', foo)
print match
This gives the output
['M', 'o', 'z', 'a', 'm', 'B', 'i', 'Q', 'u', 'E']
|
[
{
"code": null,
"e": 1176,
"s": 1062,
"text": "The following code matches and prints all non-digit characters in the given string using python regex as follows."
},
{
"code": null,
"e": 1252,
"s": 1176,
"text": "import re\nfoo = 'Mo4zam5Bi6QuE7'\nmatch = re.findall(r'\\D', foo)\nprint match"
},
{
"code": null,
"e": 1274,
"s": 1252,
"text": "This gives the output"
},
{
"code": null,
"e": 1325,
"s": 1274,
"text": "['M', 'o', 'z', 'a', 'm', 'B', 'i', 'Q', 'u', 'E']"
}
] |
Minimum characters required to be removed to make frequency of each character unique - GeeksforGeeks
|
24 Jun, 2021
Given string str, the task is to find the minimum count of characters that need to be deleted from the string such that the frequency of each character of the string is unique.
Examples:
Input: str = “ceabaacb” Output: 2 Explanation: The frequencies of each distinct character are as follows: c —> 2 e —> 1 a —> 3 b —> 2 Possible ways to make frequency of each character unique by minimum number of moves are:
Removing both occurrences of ‘c’ modifies str to “eabaab”
Removing an occurrence of ‘c’ and ‘e’ modifies str to “abaacb”
Therefore, the minimum removals required is 2.
Input: S = “abbbcccd” Output: 2
Approach: The problem can be solved using Greedy technique. The idea is to use Map and Priority Queue. Follow the steps below to solve the problem:
Initialize a Map, say mp, to store the frequency of each distinct character of the string.
Initialize a variable, say cntChar to store the count of characters required to be removed to make frequency of each character of the string unique.
Create a priority_queue, say pq to store the frequency of each character such that the largest frequency obtained is present at the top of the priority queue pq.
Iterate over the priority_queue until pq is empty and check if the topmost of element of pq is equal to the second topmost element of pq or not. If found to be true, then decrement the value of topmost element of pq by 1 and increment the value of cntChar by 1.
Otherwise, pop the topmost element of pq.
Finally, print the value of cntChar.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the minimum count of// characters required to be deleted to make// frequencies of all characters uniqueint minCntCharDeletionsfrequency(string& str, int N){ // Stores frequency of each // distinct character of str unordered_map<char, int> mp; // Store frequency of each distinct // character such that the largest // frequency is present at the top priority_queue<int> pq; // Stores minimum count of characters // required to be deleted to make // frequency of each character unique int cntChar = 0; // Traverse the string for (int i = 0; i < N; i++) { // Update frequency of str[i] mp[str[i]]++; } // Traverse the map for (auto it : mp) { // Insert current // frequency into pq pq.push(it.second); } // Traverse the priority_queue while (!pq.empty()) { // Stores topmost // element of pq int frequent = pq.top(); // Pop the topmost element pq.pop(); // If pq is empty if (pq.empty()) { // Return cntChar return cntChar; } // If frequent and topmost // element of pq are equal if (frequent == pq.top()) { // If frequency of the topmost // element is greater than 1 if (frequent > 1) { // Insert the decremented // value of frequent pq.push(frequent - 1); } // Update cntChar cntChar++; } } return cntChar;} // Driver Codeint main(){ string str = "abbbcccd"; // Stores length of str int N = str.length(); cout << minCntCharDeletionsfrequency( str, N); return 0;}
// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to find the minimum count of// characters required to be deleted to make// frequencies of all characters uniquestatic int minCntCharDeletionsfrequency(char[] str, int N){ // Stores frequency of each // distinct character of str HashMap<Character, Integer> mp = new HashMap<>(); // Store frequency of each distinct // character such that the largest // frequency is present at the top PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> Integer.compare(y, x)); // Stores minimum count of characters // required to be deleted to make // frequency of each character unique int cntChar = 0; // Traverse the String for (int i = 0; i < N; i++) { // Update frequency of str[i] if(mp.containsKey(str[i])) { mp.put(str[i], mp.get(str[i]) + 1); } else { mp.put(str[i], 1); } } // Traverse the map for (Map.Entry<Character, Integer> it : mp.entrySet()) { // Insert current // frequency into pq pq.add(it.getValue()); } // Traverse the priority_queue while (!pq.isEmpty()) { // Stores topmost // element of pq int frequent = pq.peek(); // Pop the topmost element pq.remove(); // If pq is empty if (pq.isEmpty()) { // Return cntChar return cntChar; } // If frequent and topmost // element of pq are equal if (frequent == pq.peek()) { // If frequency of the topmost // element is greater than 1 if (frequent > 1) { // Insert the decremented // value of frequent pq.add(frequent - 1); } // Update cntChar cntChar++; } } return cntChar;} // Driver Codepublic static void main(String[] args){ String str = "abbbcccd"; // Stores length of str int N = str.length(); System.out.print(minCntCharDeletionsfrequency( str.toCharArray(), N));}} // This code is contributed by Rajput-Ji
# Python3 program to implement# the above approach # Function to find the minimum count of# characters required to be deleted to make# frequencies of all characters uniquedef minCntCharDeletionsfrequency(str, N): # Stores frequency of each # distinct character of str mp = {} # Store frequency of each distinct # character such that the largest # frequency is present at the top pq = [] # Stores minimum count of characters # required to be deleted to make # frequency of each character unique cntChar = 0 # Traverse the string for i in range(N): # Update frequency of str[i] mp[str[i]] = mp.get(str[i], 0) + 1 # Traverse the map for it in mp: # Insert current # frequency into pq pq.append(mp[it]) pq = sorted(pq) # Traverse the priority_queue while (len(pq) > 0): # Stores topmost # element of pq frequent = pq[-1] # Pop the topmost element del pq[-1] # If pq is empty if (len(pq) == 0): # Return cntChar return cntChar # If frequent and topmost # element of pq are equal if (frequent == pq[-1]): # If frequency of the topmost # element is greater than 1 if (frequent > 1): # Insert the decremented # value of frequent pq.append(frequent - 1) # Update cntChar cntChar += 1 pq = sorted(pq) return cntChar # Driver Codeif __name__ == '__main__': str = "abbbcccd" # Stores length of str N = len(str) print(minCntCharDeletionsfrequency(str, N)) # This code is contributed by mohit kumar 29
// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the minimum count of// characters required to be deleted to make// frequencies of all characters uniquestatic int minCntCharDeletionsfrequency(char[] str, int N){ // Stores frequency of each // distinct character of str Dictionary<char, int> mp = new Dictionary<char, int>(); // Store frequency of each distinct // character such that the largest // frequency is present at the top List<int> pq = new List<int>(); // Stores minimum count of characters // required to be deleted to make // frequency of each character unique int cntChar = 0; // Traverse the String for(int i = 0; i < N; i++) { // Update frequency of str[i] if (mp.ContainsKey(str[i])) { mp[str[i]]++; } else { mp.Add(str[i], 1); } } // Traverse the map foreach(KeyValuePair<char, int> it in mp) { // Insert current // frequency into pq pq.Add(it.Value); } pq.Sort(); pq.Reverse(); // Traverse the priority_queue while (pq.Count != 0) { // Stores topmost // element of pq pq.Sort(); pq.Reverse(); int frequent = pq[0]; // Pop the topmost element pq.RemoveAt(0); // If pq is empty if (pq.Count == 0) { // Return cntChar return cntChar; } // If frequent and topmost // element of pq are equal if (frequent == pq[0]) { // If frequency of the topmost // element is greater than 1 if (frequent > 1) { // Insert the decremented // value of frequent pq.Add(frequent - 1); pq.Sort(); // pq.Reverse(); } // Update cntChar cntChar++; } } return cntChar;} // Driver Codepublic static void Main(String[] args){ String str = "abbbcccd"; // Stores length of str int N = str.Length; Console.Write(minCntCharDeletionsfrequency( str.ToCharArray(), N));}} // This code is contributed by shikhasingrajput
<script>// Javascript program to implement// the above approach // Function to find the minimum count of// characters required to be deleted to make// frequencies of all characters uniquefunction minCntCharDeletionsfrequency(str,N){ // Stores frequency of each // distinct character of str let mp = new Map(); // Store frequency of each distinct // character such that the largest // frequency is present at the top let pq =[]; // Stores minimum count of characters // required to be deleted to make // frequency of each character unique let cntChar = 0; // Traverse the String for (let i = 0; i < N; i++) { // Update frequency of str[i] if(mp.has(str[i])) { mp.set(str[i], mp.get(str[i]) + 1); } else { mp.set(str[i], 1); } } // Traverse the map for (let [key, value] of mp.entries()) { // Insert current // frequency into pq pq.push(value); } pq.sort(function(a,b){return b-a;}); // Traverse the priority_queue while (pq.length!=0) { // Stores topmost // element of pq let frequent = pq[0]; // Pop the topmost element pq.shift(); // If pq is empty if (pq.length==0) { // Return cntChar return cntChar; } // If frequent and topmost // element of pq are equal if (frequent == pq[0]) { // If frequency of the topmost // element is greater than 1 if (frequent > 1) { // Insert the decremented // value of frequent pq.push(frequent - 1); pq.sort(function(a,b){return b-a;}); } // Update cntChar cntChar++; } } return cntChar;} // Driver Codelet str = "abbbcccd";let N = str.length;document.write(minCntCharDeletionsfrequency( str.split(""), N)); // This code is contributed by unknown2108</script>
2
Time Complexity:O(N) Auxiliary Space:O(256)
mohit kumar 29
Rajput-Ji
shikhasingrajput
unknown2108
cpp-unordered_map
frequency-counting
priority-queue
Greedy
Hash
Queue
Strings
Hash
Strings
Greedy
Queue
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Huffman Coding | Greedy Algo-3
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Fractional Knapsack Problem
Activity Selection Problem | Greedy Algo-1
Job Sequencing Problem
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining)
|
[
{
"code": null,
"e": 26413,
"s": 26385,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 26590,
"s": 26413,
"text": "Given string str, the task is to find the minimum count of characters that need to be deleted from the string such that the frequency of each character of the string is unique."
},
{
"code": null,
"e": 26600,
"s": 26590,
"text": "Examples:"
},
{
"code": null,
"e": 26824,
"s": 26600,
"text": "Input: str = “ceabaacb” Output: 2 Explanation: The frequencies of each distinct character are as follows: c —> 2 e —> 1 a —> 3 b —> 2 Possible ways to make frequency of each character unique by minimum number of moves are: "
},
{
"code": null,
"e": 26882,
"s": 26824,
"text": "Removing both occurrences of ‘c’ modifies str to “eabaab”"
},
{
"code": null,
"e": 26945,
"s": 26882,
"text": "Removing an occurrence of ‘c’ and ‘e’ modifies str to “abaacb”"
},
{
"code": null,
"e": 26992,
"s": 26945,
"text": "Therefore, the minimum removals required is 2."
},
{
"code": null,
"e": 27026,
"s": 26992,
"text": "Input: S = “abbbcccd” Output: 2 "
},
{
"code": null,
"e": 27174,
"s": 27026,
"text": "Approach: The problem can be solved using Greedy technique. The idea is to use Map and Priority Queue. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27265,
"s": 27174,
"text": "Initialize a Map, say mp, to store the frequency of each distinct character of the string."
},
{
"code": null,
"e": 27414,
"s": 27265,
"text": "Initialize a variable, say cntChar to store the count of characters required to be removed to make frequency of each character of the string unique."
},
{
"code": null,
"e": 27576,
"s": 27414,
"text": "Create a priority_queue, say pq to store the frequency of each character such that the largest frequency obtained is present at the top of the priority queue pq."
},
{
"code": null,
"e": 27838,
"s": 27576,
"text": "Iterate over the priority_queue until pq is empty and check if the topmost of element of pq is equal to the second topmost element of pq or not. If found to be true, then decrement the value of topmost element of pq by 1 and increment the value of cntChar by 1."
},
{
"code": null,
"e": 27880,
"s": 27838,
"text": "Otherwise, pop the topmost element of pq."
},
{
"code": null,
"e": 27917,
"s": 27880,
"text": "Finally, print the value of cntChar."
},
{
"code": null,
"e": 27968,
"s": 27917,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27972,
"s": 27968,
"text": "C++"
},
{
"code": null,
"e": 27977,
"s": 27972,
"text": "Java"
},
{
"code": null,
"e": 27985,
"s": 27977,
"text": "Python3"
},
{
"code": null,
"e": 27988,
"s": 27985,
"text": "C#"
},
{
"code": null,
"e": 27999,
"s": 27988,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the minimum count of// characters required to be deleted to make// frequencies of all characters uniqueint minCntCharDeletionsfrequency(string& str, int N){ // Stores frequency of each // distinct character of str unordered_map<char, int> mp; // Store frequency of each distinct // character such that the largest // frequency is present at the top priority_queue<int> pq; // Stores minimum count of characters // required to be deleted to make // frequency of each character unique int cntChar = 0; // Traverse the string for (int i = 0; i < N; i++) { // Update frequency of str[i] mp[str[i]]++; } // Traverse the map for (auto it : mp) { // Insert current // frequency into pq pq.push(it.second); } // Traverse the priority_queue while (!pq.empty()) { // Stores topmost // element of pq int frequent = pq.top(); // Pop the topmost element pq.pop(); // If pq is empty if (pq.empty()) { // Return cntChar return cntChar; } // If frequent and topmost // element of pq are equal if (frequent == pq.top()) { // If frequency of the topmost // element is greater than 1 if (frequent > 1) { // Insert the decremented // value of frequent pq.push(frequent - 1); } // Update cntChar cntChar++; } } return cntChar;} // Driver Codeint main(){ string str = \"abbbcccd\"; // Stores length of str int N = str.length(); cout << minCntCharDeletionsfrequency( str, N); return 0;}",
"e": 29873,
"s": 27999,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to find the minimum count of// characters required to be deleted to make// frequencies of all characters uniquestatic int minCntCharDeletionsfrequency(char[] str, int N){ // Stores frequency of each // distinct character of str HashMap<Character, Integer> mp = new HashMap<>(); // Store frequency of each distinct // character such that the largest // frequency is present at the top PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> Integer.compare(y, x)); // Stores minimum count of characters // required to be deleted to make // frequency of each character unique int cntChar = 0; // Traverse the String for (int i = 0; i < N; i++) { // Update frequency of str[i] if(mp.containsKey(str[i])) { mp.put(str[i], mp.get(str[i]) + 1); } else { mp.put(str[i], 1); } } // Traverse the map for (Map.Entry<Character, Integer> it : mp.entrySet()) { // Insert current // frequency into pq pq.add(it.getValue()); } // Traverse the priority_queue while (!pq.isEmpty()) { // Stores topmost // element of pq int frequent = pq.peek(); // Pop the topmost element pq.remove(); // If pq is empty if (pq.isEmpty()) { // Return cntChar return cntChar; } // If frequent and topmost // element of pq are equal if (frequent == pq.peek()) { // If frequency of the topmost // element is greater than 1 if (frequent > 1) { // Insert the decremented // value of frequent pq.add(frequent - 1); } // Update cntChar cntChar++; } } return cntChar;} // Driver Codepublic static void main(String[] args){ String str = \"abbbcccd\"; // Stores length of str int N = str.length(); System.out.print(minCntCharDeletionsfrequency( str.toCharArray(), N));}} // This code is contributed by Rajput-Ji",
"e": 31936,
"s": 29873,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to find the minimum count of# characters required to be deleted to make# frequencies of all characters uniquedef minCntCharDeletionsfrequency(str, N): # Stores frequency of each # distinct character of str mp = {} # Store frequency of each distinct # character such that the largest # frequency is present at the top pq = [] # Stores minimum count of characters # required to be deleted to make # frequency of each character unique cntChar = 0 # Traverse the string for i in range(N): # Update frequency of str[i] mp[str[i]] = mp.get(str[i], 0) + 1 # Traverse the map for it in mp: # Insert current # frequency into pq pq.append(mp[it]) pq = sorted(pq) # Traverse the priority_queue while (len(pq) > 0): # Stores topmost # element of pq frequent = pq[-1] # Pop the topmost element del pq[-1] # If pq is empty if (len(pq) == 0): # Return cntChar return cntChar # If frequent and topmost # element of pq are equal if (frequent == pq[-1]): # If frequency of the topmost # element is greater than 1 if (frequent > 1): # Insert the decremented # value of frequent pq.append(frequent - 1) # Update cntChar cntChar += 1 pq = sorted(pq) return cntChar # Driver Codeif __name__ == '__main__': str = \"abbbcccd\" # Stores length of str N = len(str) print(minCntCharDeletionsfrequency(str, N)) # This code is contributed by mohit kumar 29",
"e": 33785,
"s": 31936,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the minimum count of// characters required to be deleted to make// frequencies of all characters uniquestatic int minCntCharDeletionsfrequency(char[] str, int N){ // Stores frequency of each // distinct character of str Dictionary<char, int> mp = new Dictionary<char, int>(); // Store frequency of each distinct // character such that the largest // frequency is present at the top List<int> pq = new List<int>(); // Stores minimum count of characters // required to be deleted to make // frequency of each character unique int cntChar = 0; // Traverse the String for(int i = 0; i < N; i++) { // Update frequency of str[i] if (mp.ContainsKey(str[i])) { mp[str[i]]++; } else { mp.Add(str[i], 1); } } // Traverse the map foreach(KeyValuePair<char, int> it in mp) { // Insert current // frequency into pq pq.Add(it.Value); } pq.Sort(); pq.Reverse(); // Traverse the priority_queue while (pq.Count != 0) { // Stores topmost // element of pq pq.Sort(); pq.Reverse(); int frequent = pq[0]; // Pop the topmost element pq.RemoveAt(0); // If pq is empty if (pq.Count == 0) { // Return cntChar return cntChar; } // If frequent and topmost // element of pq are equal if (frequent == pq[0]) { // If frequency of the topmost // element is greater than 1 if (frequent > 1) { // Insert the decremented // value of frequent pq.Add(frequent - 1); pq.Sort(); // pq.Reverse(); } // Update cntChar cntChar++; } } return cntChar;} // Driver Codepublic static void Main(String[] args){ String str = \"abbbcccd\"; // Stores length of str int N = str.Length; Console.Write(minCntCharDeletionsfrequency( str.ToCharArray(), N));}} // This code is contributed by shikhasingrajput",
"e": 36222,
"s": 33785,
"text": null
},
{
"code": "<script>// Javascript program to implement// the above approach // Function to find the minimum count of// characters required to be deleted to make// frequencies of all characters uniquefunction minCntCharDeletionsfrequency(str,N){ // Stores frequency of each // distinct character of str let mp = new Map(); // Store frequency of each distinct // character such that the largest // frequency is present at the top let pq =[]; // Stores minimum count of characters // required to be deleted to make // frequency of each character unique let cntChar = 0; // Traverse the String for (let i = 0; i < N; i++) { // Update frequency of str[i] if(mp.has(str[i])) { mp.set(str[i], mp.get(str[i]) + 1); } else { mp.set(str[i], 1); } } // Traverse the map for (let [key, value] of mp.entries()) { // Insert current // frequency into pq pq.push(value); } pq.sort(function(a,b){return b-a;}); // Traverse the priority_queue while (pq.length!=0) { // Stores topmost // element of pq let frequent = pq[0]; // Pop the topmost element pq.shift(); // If pq is empty if (pq.length==0) { // Return cntChar return cntChar; } // If frequent and topmost // element of pq are equal if (frequent == pq[0]) { // If frequency of the topmost // element is greater than 1 if (frequent > 1) { // Insert the decremented // value of frequent pq.push(frequent - 1); pq.sort(function(a,b){return b-a;}); } // Update cntChar cntChar++; } } return cntChar;} // Driver Codelet str = \"abbbcccd\";let N = str.length;document.write(minCntCharDeletionsfrequency( str.split(\"\"), N)); // This code is contributed by unknown2108</script>",
"e": 38041,
"s": 36222,
"text": null
},
{
"code": null,
"e": 38043,
"s": 38041,
"text": "2"
},
{
"code": null,
"e": 38089,
"s": 38045,
"text": "Time Complexity:O(N) Auxiliary Space:O(256)"
},
{
"code": null,
"e": 38104,
"s": 38089,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 38114,
"s": 38104,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 38131,
"s": 38114,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 38143,
"s": 38131,
"text": "unknown2108"
},
{
"code": null,
"e": 38161,
"s": 38143,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 38180,
"s": 38161,
"text": "frequency-counting"
},
{
"code": null,
"e": 38195,
"s": 38180,
"text": "priority-queue"
},
{
"code": null,
"e": 38202,
"s": 38195,
"text": "Greedy"
},
{
"code": null,
"e": 38207,
"s": 38202,
"text": "Hash"
},
{
"code": null,
"e": 38213,
"s": 38207,
"text": "Queue"
},
{
"code": null,
"e": 38221,
"s": 38213,
"text": "Strings"
},
{
"code": null,
"e": 38226,
"s": 38221,
"text": "Hash"
},
{
"code": null,
"e": 38234,
"s": 38226,
"text": "Strings"
},
{
"code": null,
"e": 38241,
"s": 38234,
"text": "Greedy"
},
{
"code": null,
"e": 38247,
"s": 38241,
"text": "Queue"
},
{
"code": null,
"e": 38262,
"s": 38247,
"text": "priority-queue"
},
{
"code": null,
"e": 38360,
"s": 38262,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38391,
"s": 38360,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 38472,
"s": 38391,
"text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)"
},
{
"code": null,
"e": 38500,
"s": 38472,
"text": "Fractional Knapsack Problem"
},
{
"code": null,
"e": 38543,
"s": 38500,
"text": "Activity Selection Problem | Greedy Algo-1"
},
{
"code": null,
"e": 38566,
"s": 38543,
"text": "Job Sequencing Problem"
},
{
"code": null,
"e": 38651,
"s": 38566,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 38687,
"s": 38651,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 38718,
"s": 38687,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 38752,
"s": 38718,
"text": "Hashing | Set 3 (Open Addressing)"
}
] |
How to create a PySpark dataframe from multiple lists ? - GeeksforGeeks
|
30 May, 2021
In this article, we will discuss how to create Pyspark dataframe from multiple lists.
Create data from multiple lists and give column names in another list. So, to do our task we will use the zip method.
zip(list1,list2,., list n)
Pass this zipped data to spark.createDataFrame() method
dataframe = spark.createDataFrame(data, columns)
Example 1: Python program to create two lists and create the dataframe using these two lists
Python3
# importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of college data with dictionary# with two lists in three elements eachdata = [1, 2, 3]data1 = ["sravan", "bobby", "ojaswi"] # specify column namescolumns = ['ID', 'NAME'] # creating a dataframe by zipping the two listsdataframe = spark.createDataFrame(zip(data, data1), columns) # show data framedataframe.show()
Output:
Example 2: Python program to create 4 lists and create the dataframe
Python3
# importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of college data with dictionary# with four lists in three elements eachdata = [1, 2, 3]data1 = ["sravan", "bobby", "ojaswi"]data2 = ["iit-k", "iit-mumbai", "vignan university"]data3 = ["AP", "TS", "UP"] # specify column namescolumns = ['ID', 'NAME', 'COLLEGE', 'ADDRESS'] # creating a dataframe by zipping # the two listsdataframe = spark.createDataFrame( zip(data, data1, data2, data3), columns) # show data framedataframe.show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 23988,
"s": 23901,
"text": "In this article, we will discuss how to create Pyspark dataframe from multiple lists. "
},
{
"code": null,
"e": 24106,
"s": 23988,
"text": "Create data from multiple lists and give column names in another list. So, to do our task we will use the zip method."
},
{
"code": null,
"e": 24133,
"s": 24106,
"text": "zip(list1,list2,., list n)"
},
{
"code": null,
"e": 24189,
"s": 24133,
"text": "Pass this zipped data to spark.createDataFrame() method"
},
{
"code": null,
"e": 24238,
"s": 24189,
"text": "dataframe = spark.createDataFrame(data, columns)"
},
{
"code": null,
"e": 24331,
"s": 24238,
"text": "Example 1: Python program to create two lists and create the dataframe using these two lists"
},
{
"code": null,
"e": 24339,
"s": 24331,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of college data with dictionary# with two lists in three elements eachdata = [1, 2, 3]data1 = [\"sravan\", \"bobby\", \"ojaswi\"] # specify column namescolumns = ['ID', 'NAME'] # creating a dataframe by zipping the two listsdataframe = spark.createDataFrame(zip(data, data1), columns) # show data framedataframe.show()",
"e": 24896,
"s": 24339,
"text": null
},
{
"code": null,
"e": 24904,
"s": 24896,
"text": "Output:"
},
{
"code": null,
"e": 24973,
"s": 24904,
"text": "Example 2: Python program to create 4 lists and create the dataframe"
},
{
"code": null,
"e": 24981,
"s": 24973,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of college data with dictionary# with four lists in three elements eachdata = [1, 2, 3]data1 = [\"sravan\", \"bobby\", \"ojaswi\"]data2 = [\"iit-k\", \"iit-mumbai\", \"vignan university\"]data3 = [\"AP\", \"TS\", \"UP\"] # specify column namescolumns = ['ID', 'NAME', 'COLLEGE', 'ADDRESS'] # creating a dataframe by zipping # the two listsdataframe = spark.createDataFrame( zip(data, data1, data2, data3), columns) # show data framedataframe.show()",
"e": 25657,
"s": 24981,
"text": null
},
{
"code": null,
"e": 25665,
"s": 25657,
"text": "Output:"
},
{
"code": null,
"e": 25672,
"s": 25665,
"text": "Picked"
},
{
"code": null,
"e": 25687,
"s": 25672,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 25694,
"s": 25687,
"text": "Python"
},
{
"code": null,
"e": 25792,
"s": 25694,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25801,
"s": 25792,
"text": "Comments"
},
{
"code": null,
"e": 25814,
"s": 25801,
"text": "Old Comments"
},
{
"code": null,
"e": 25846,
"s": 25814,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25902,
"s": 25846,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25944,
"s": 25902,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25986,
"s": 25944,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26022,
"s": 25986,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26044,
"s": 26022,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26083,
"s": 26044,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26110,
"s": 26083,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26141,
"s": 26110,
"text": "Python | os.path.join() method"
}
] |
Linear Regression
|
From a given set of data points, the linear regression finds an equation of straight line. The given points will follow the straight line. Using this formula, we can predict what will be the value for some other specific point, which is not present in the set currently.
For solving linear regression problems using some data points, we have to follow these formulae:
Here the m and c are the slope and the y-intercept respectively. Using these expressions, we can get the equation of straight line in this form: y = mx + c.
Input:
The (x, y) coordinates of some points. {(1,3), (2,4), (3,5), (4,6), (5,8)}
Output:
The slope: 1.2 The Intercept: 1.6
The equation: y = 1.2x + 1.6
linReg(coord)
Input: The given set of coordinate points.
Output: The slope m and y-intercept c.
Begin
for i := 1 to n, do
sumX := sumX + coord[i,0]
sumY := sumY + coord[i,1]
sumXsq := sumXsq + (coord[i,0]*coord[i,0])
sumXY := sumXY + (coord[i,0] * coord[i,1])
done
m := (n * sumXY – (sumX*sumY)) / (n * sumXsq – (sumX * sumX))
c := (sumY / n) – (m * sumX)/n
End
#include<iostream>
#include<cmath>
#define N 5
using namespace std;
void linReg(int coord[N][2], float &m, float &c) {
float sx2 = 0, sx = 0, sxy = 0, sy = 0;
for(int i = 0; i<N; i++) {
sx += coord[i][0]; //sum of x
sy += coord[i][1]; //sum of y
sx2 += coord[i][0]*coord[i][0]; //sum of x^2
sxy += coord[i][0]*coord[i][1]; //sum of x*y
}
// finding slope and intercept
m = (N*sxy-(sx*sy))/(N*sx2-(sx*sx));
c = (sy/N)-(m*sx)/N;
}
main() {
// this 2d array holds coordinate points
int point[N][2] = {{1,3},{2,4},{3,5},{4,6},{5,8}};
float m, c;
linReg(point, m, c);
cout << "The slope: " << m << " The Intercept: " << c << endl;
cout << "The equation: " << "y = "<< m <<"x + "<< c;
}
The slope: 1.2 The Intercept: 1.6
The equation: y = 1.2x + 1.6
|
[
{
"code": null,
"e": 1333,
"s": 1062,
"text": "From a given set of data points, the linear regression finds an equation of straight line. The given points will follow the straight line. Using this formula, we can predict what will be the value for some other specific point, which is not present in the set currently."
},
{
"code": null,
"e": 1430,
"s": 1333,
"text": "For solving linear regression problems using some data points, we have to follow these formulae:"
},
{
"code": null,
"e": 1587,
"s": 1430,
"text": "Here the m and c are the slope and the y-intercept respectively. Using these expressions, we can get the equation of straight line in this form: y = mx + c."
},
{
"code": null,
"e": 1740,
"s": 1587,
"text": "Input:\nThe (x, y) coordinates of some points. {(1,3), (2,4), (3,5), (4,6), (5,8)}\nOutput:\nThe slope: 1.2 The Intercept: 1.6\nThe equation: y = 1.2x + 1.6"
},
{
"code": null,
"e": 1754,
"s": 1740,
"text": "linReg(coord)"
},
{
"code": null,
"e": 1797,
"s": 1754,
"text": "Input: The given set of coordinate points."
},
{
"code": null,
"e": 1836,
"s": 1797,
"text": "Output: The slope m and y-intercept c."
},
{
"code": null,
"e": 2139,
"s": 1836,
"text": "Begin\n for i := 1 to n, do\n sumX := sumX + coord[i,0]\n sumY := sumY + coord[i,1]\n sumXsq := sumXsq + (coord[i,0]*coord[i,0])\n sumXY := sumXY + (coord[i,0] * coord[i,1])\n done\n\n m := (n * sumXY – (sumX*sumY)) / (n * sumXsq – (sumX * sumX))\n c := (sumY / n) – (m * sumX)/n\nEnd"
},
{
"code": null,
"e": 2898,
"s": 2139,
"text": "#include<iostream>\n#include<cmath>\n#define N 5\nusing namespace std;\n\nvoid linReg(int coord[N][2], float &m, float &c) {\n float sx2 = 0, sx = 0, sxy = 0, sy = 0;\n for(int i = 0; i<N; i++) {\n sx += coord[i][0]; //sum of x\n sy += coord[i][1]; //sum of y\n\n sx2 += coord[i][0]*coord[i][0]; //sum of x^2\n sxy += coord[i][0]*coord[i][1]; //sum of x*y\n }\n\n // finding slope and intercept\n m = (N*sxy-(sx*sy))/(N*sx2-(sx*sx));\n c = (sy/N)-(m*sx)/N;\n}\n\nmain() {\n // this 2d array holds coordinate points\n int point[N][2] = {{1,3},{2,4},{3,5},{4,6},{5,8}};\n float m, c;\n linReg(point, m, c);\n cout << \"The slope: \" << m << \" The Intercept: \" << c << endl;\n cout << \"The equation: \" << \"y = \"<< m <<\"x + \"<< c;\n}"
},
{
"code": null,
"e": 2961,
"s": 2898,
"text": "The slope: 1.2 The Intercept: 1.6\nThe equation: y = 1.2x + 1.6"
}
] |
Jackson - Data Binding
|
Data Binding API is used to convert JSON to and from POJO (Plain Old Java Object) using property accessor or using annotations. It is of two type.
Simple Data Binding - Converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans and null objects.
Simple Data Binding - Converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans and null objects.
Full Data Binding - Converts JSON to and from any JAVA type.
Full Data Binding - Converts JSON to and from any JAVA type.
ObjectMapper reads/writes JSON for both types of data bindings. Data Binding is most convenient way and is analogus to JAXB parer for XML.
Simple data binding refers to mapping of JSON to JAVA Core data types. Following table illustrates the relationship between JSON types vs Java Types.
Let's see simple data binding in action. Here we'll map JAVA basic types directly to JSON and vice versa.
Create a java class file named JacksonTester in C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]){
JacksonTester tester = new JacksonTester();
try {
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> studentDataMap = new HashMap<String,Object>();
int[] marks = {1,2,3};
Student student = new Student();
student.setAge(10);
student.setName("Mahesh");
// JAVA Object
studentDataMap.put("student", student);
// JAVA String
studentDataMap.put("name", "Mahesh Kumar");
// JAVA Boolean
studentDataMap.put("verified", Boolean.FALSE);
// Array
studentDataMap.put("marks", marks);
mapper.writeValue(new File("student.json"), studentDataMap);
//result student.json
//{
// "student":{"name":"Mahesh","age":10},
// "marks":[1,2,3],
// "verified":false,
// "name":"Mahesh Kumar"
//}
studentDataMap = mapper.readValue(new File("student.json"), Map.class);
System.out.println(studentDataMap.get("student"));
System.out.println(studentDataMap.get("name"));
System.out.println(studentDataMap.get("verified"));
System.out.println(studentDataMap.get("marks"));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
Verify the result
Compile the classes using javac compiler as follows:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output
{name=Mahesh, age=10}
Mahesh Kumar
false
[1, 2, 3]
Full Data Binding
Data Binding with Generics
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1901,
"s": 1753,
"text": "Data Binding API is used to convert JSON to and from POJO (Plain Old Java Object) using property accessor or using annotations. It is of two type.\n"
},
{
"code": null,
"e": 2012,
"s": 1901,
"text": "Simple Data Binding - Converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans and null objects."
},
{
"code": null,
"e": 2123,
"s": 2012,
"text": "Simple Data Binding - Converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans and null objects."
},
{
"code": null,
"e": 2184,
"s": 2123,
"text": "Full Data Binding - Converts JSON to and from any JAVA type."
},
{
"code": null,
"e": 2245,
"s": 2184,
"text": "Full Data Binding - Converts JSON to and from any JAVA type."
},
{
"code": null,
"e": 2384,
"s": 2245,
"text": "ObjectMapper reads/writes JSON for both types of data bindings. Data Binding is most convenient way and is analogus to JAXB parer for XML."
},
{
"code": null,
"e": 2534,
"s": 2384,
"text": "Simple data binding refers to mapping of JSON to JAVA Core data types. Following table illustrates the relationship between JSON types vs Java Types."
},
{
"code": null,
"e": 2640,
"s": 2534,
"text": "Let's see simple data binding in action. Here we'll map JAVA basic types directly to JSON and vice versa."
},
{
"code": null,
"e": 2711,
"s": 2640,
"text": "Create a java class file named JacksonTester in C:\\>Jackson_WORKSPACE."
},
{
"code": null,
"e": 2736,
"s": 2711,
"text": "File: JacksonTester.java"
},
{
"code": null,
"e": 5002,
"s": 2736,
"text": "import java.io.File;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\npublic class JacksonTester {\n public static void main(String args[]){\n JacksonTester tester = new JacksonTester();\n try {\n ObjectMapper mapper = new ObjectMapper();\n\n Map<String,Object> studentDataMap = new HashMap<String,Object>(); \n int[] marks = {1,2,3};\n\n Student student = new Student();\n student.setAge(10);\n student.setName(\"Mahesh\");\n // JAVA Object\n studentDataMap.put(\"student\", student);\n // JAVA String\n studentDataMap.put(\"name\", \"Mahesh Kumar\"); \t\t\n // JAVA Boolean\n studentDataMap.put(\"verified\", Boolean.FALSE);\n // Array\n studentDataMap.put(\"marks\", marks);\n\n mapper.writeValue(new File(\"student.json\"), studentDataMap);\n //result student.json\n\t\t\t//{ \n // \"student\":{\"name\":\"Mahesh\",\"age\":10},\n // \"marks\":[1,2,3],\n // \"verified\":false,\n // \"name\":\"Mahesh Kumar\"\n //}\n studentDataMap = mapper.readValue(new File(\"student.json\"), Map.class);\n\n System.out.println(studentDataMap.get(\"student\"));\n System.out.println(studentDataMap.get(\"name\"));\n System.out.println(studentDataMap.get(\"verified\"));\n System.out.println(studentDataMap.get(\"marks\"));\n } catch (JsonParseException e) {\n e.printStackTrace();\n } catch (JsonMappingException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\n\nclass Student {\n private String name;\n private int age;\n public Student(){}\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public String toString(){\n return \"Student [ name: \"+name+\", age: \"+ age+ \" ]\";\n }\t\n}"
},
{
"code": null,
"e": 5020,
"s": 5002,
"text": "Verify the result"
},
{
"code": null,
"e": 5073,
"s": 5020,
"text": "Compile the classes using javac compiler as follows:"
},
{
"code": null,
"e": 5119,
"s": 5073,
"text": "C:\\Jackson_WORKSPACE>javac JacksonTester.java"
},
{
"code": null,
"e": 5164,
"s": 5119,
"text": "Now run the jacksonTester to see the result:"
},
{
"code": null,
"e": 5204,
"s": 5164,
"text": "C:\\Jackson_WORKSPACE>java JacksonTester"
},
{
"code": null,
"e": 5222,
"s": 5204,
"text": "Verify the Output"
},
{
"code": null,
"e": 5274,
"s": 5222,
"text": "{name=Mahesh, age=10}\nMahesh Kumar\nfalse\n[1, 2, 3]\n"
},
{
"code": null,
"e": 5292,
"s": 5274,
"text": "Full Data Binding"
},
{
"code": null,
"e": 5319,
"s": 5292,
"text": "Data Binding with Generics"
},
{
"code": null,
"e": 5326,
"s": 5319,
"text": " Print"
},
{
"code": null,
"e": 5337,
"s": 5326,
"text": " Add Notes"
}
] |
How to convert Bitmap to drawable in Android?
|
This example demonstrates how do I convert Bitmap to drawable in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btnConvert"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Convert bitmap to Drawable" />
<ImageView
android:id="@+id/imageView"
android:layout_below="@id/btnConvert"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
Button button;
Bitmap bitmap;
Drawable drawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
button = findViewById(R.id.btnConvert);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawable = getApplicationContext().getResources().getDrawable(R.drawable.image);
bitmap = ((BitmapDrawable)drawable).getBitmap();
Drawable d = new BitmapDrawable(bitmap);
imageView.setImageDrawable(d);
}
});
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
|
[
{
"code": null,
"e": 1136,
"s": 1062,
"text": "This example demonstrates how do I convert Bitmap to drawable in android."
},
{
"code": null,
"e": 1265,
"s": 1136,
"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": 1330,
"s": 1265,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2089,
"s": 1330,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/btnConvert\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"20dp\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Convert bitmap to Drawable\" />\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_below=\"@id/btnConvert\"\n android:layout_marginTop=\"10dp\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"/>"
},
{
"code": null,
"e": 2146,
"s": 2089,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3218,
"s": 2146,
"text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.graphics.Bitmap;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.graphics.drawable.Drawable;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ImageView;\npublic class MainActivity extends AppCompatActivity {\n ImageView imageView;\n Button button;\n Bitmap bitmap;\n Drawable drawable;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n imageView = findViewById(R.id.imageView);\n button = findViewById(R.id.btnConvert);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n drawable = getApplicationContext().getResources().getDrawable(R.drawable.image);\n bitmap = ((BitmapDrawable)drawable).getBitmap();\n Drawable d = new BitmapDrawable(bitmap);\n imageView.setImageDrawable(d);\n }\n });\n }\n}"
},
{
"code": null,
"e": 3273,
"s": 3218,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3943,
"s": 3273,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4290,
"s": 3943,
"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": 4331,
"s": 4290,
"text": "Click here to download the project code."
}
] |
How to remove items from a select box ? - GeeksforGeeks
|
21 Jun, 2019
An option can be removed from a select box using 2 approaches in jQuery:
Method 1: Removing the option in the box directly
The option to be removed is selected by getting the select box. The value to be removed is specified on the value selector (value=’optionValue’) on the select box. The remove() method is then used to remove this selected option.
Syntax:
$("selectBox option[value='optionValue']").remove()
Example:
<!DOCTYPE html><html><head> <title> Removing an item from a select box </title></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b>Removing an item from a select box</b> <p> Select one from the given options: <select id="select1"> <option value="free"> Free </option> <option value="basic"> Basic </option> <option value="premium"> Premium </option> </select> </p> <p>Click the button below to remove one option from the select box.</p> <button onclick="removeOption()"> Remove option </button> <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script> <script type="text/javascript"> function removeOption() { /* select the option with the value of basic and remove the option*/ $("#select1 option[value='basic']").remove(); } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Method 2: Using the find() methodThe find() method can be used to find the option in the value with the value selector. This method searches through the descendants of the specified elements in the DOM and creates a new jQuery object from the matching elements.
The select box is first selected and then the find() method is applied with the value selector to find the option. The remove() method is then used to remove this selected option.
Syntax:
$('selectBox').find('[value="basic"]').remove()
Example:
<!DOCTYPE html><html> <head> <title> Removing an item from a select box </title></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> Removing an item from a select box </b> <p> Select one from the given options: <select id="select1"> <option value="free"> Free </option> <option value="basic"> Basic </option> <option value="premium"> Premium </option> </select> </p> <p> Click the button below to remove one option from the select box. </p> <button onclick="removeOption()"> Remove option </button> <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script> <script type="text/javascript"> function removeOption() { /* select the option with the value of basic and remove the option*/ $('#select1').find('[value="basic"]').remove(); } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
jQuery-Misc
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
How to get the value in an input text box using jQuery ?
Difference Between JavaScript and jQuery
QR Code Generator using HTML, CSS and jQuery
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": 25675,
"s": 25647,
"text": "\n21 Jun, 2019"
},
{
"code": null,
"e": 25748,
"s": 25675,
"text": "An option can be removed from a select box using 2 approaches in jQuery:"
},
{
"code": null,
"e": 25798,
"s": 25748,
"text": "Method 1: Removing the option in the box directly"
},
{
"code": null,
"e": 26027,
"s": 25798,
"text": "The option to be removed is selected by getting the select box. The value to be removed is specified on the value selector (value=’optionValue’) on the select box. The remove() method is then used to remove this selected option."
},
{
"code": null,
"e": 26035,
"s": 26027,
"text": "Syntax:"
},
{
"code": null,
"e": 26087,
"s": 26035,
"text": "$(\"selectBox option[value='optionValue']\").remove()"
},
{
"code": null,
"e": 26096,
"s": 26087,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head> <title> Removing an item from a select box </title></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b>Removing an item from a select box</b> <p> Select one from the given options: <select id=\"select1\"> <option value=\"free\"> Free </option> <option value=\"basic\"> Basic </option> <option value=\"premium\"> Premium </option> </select> </p> <p>Click the button below to remove one option from the select box.</p> <button onclick=\"removeOption()\"> Remove option </button> <script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"> </script> <script type=\"text/javascript\"> function removeOption() { /* select the option with the value of basic and remove the option*/ $(\"#select1 option[value='basic']\").remove(); } </script></body> </html>",
"e": 27103,
"s": 26096,
"text": null
},
{
"code": null,
"e": 27111,
"s": 27103,
"text": "Output:"
},
{
"code": null,
"e": 27139,
"s": 27111,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 27166,
"s": 27139,
"text": "After clicking the button:"
},
{
"code": null,
"e": 27428,
"s": 27166,
"text": "Method 2: Using the find() methodThe find() method can be used to find the option in the value with the value selector. This method searches through the descendants of the specified elements in the DOM and creates a new jQuery object from the matching elements."
},
{
"code": null,
"e": 27608,
"s": 27428,
"text": "The select box is first selected and then the find() method is applied with the value selector to find the option. The remove() method is then used to remove this selected option."
},
{
"code": null,
"e": 27616,
"s": 27608,
"text": "Syntax:"
},
{
"code": null,
"e": 27664,
"s": 27616,
"text": "$('selectBox').find('[value=\"basic\"]').remove()"
},
{
"code": null,
"e": 27673,
"s": 27664,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Removing an item from a select box </title></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> Removing an item from a select box </b> <p> Select one from the given options: <select id=\"select1\"> <option value=\"free\"> Free </option> <option value=\"basic\"> Basic </option> <option value=\"premium\"> Premium </option> </select> </p> <p> Click the button below to remove one option from the select box. </p> <button onclick=\"removeOption()\"> Remove option </button> <script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"> </script> <script type=\"text/javascript\"> function removeOption() { /* select the option with the value of basic and remove the option*/ $('#select1').find('[value=\"basic\"]').remove(); } </script></body> </html>",
"e": 28696,
"s": 27673,
"text": null
},
{
"code": null,
"e": 28704,
"s": 28696,
"text": "Output:"
},
{
"code": null,
"e": 28732,
"s": 28704,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 28759,
"s": 28732,
"text": "After clicking the button:"
},
{
"code": null,
"e": 28771,
"s": 28759,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 28778,
"s": 28771,
"text": "Picked"
},
{
"code": null,
"e": 28785,
"s": 28778,
"text": "JQuery"
},
{
"code": null,
"e": 28802,
"s": 28785,
"text": "Web Technologies"
},
{
"code": null,
"e": 28900,
"s": 28802,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28909,
"s": 28900,
"text": "Comments"
},
{
"code": null,
"e": 28922,
"s": 28909,
"text": "Old Comments"
},
{
"code": null,
"e": 28995,
"s": 28922,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 29018,
"s": 28995,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 29075,
"s": 29018,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 29116,
"s": 29075,
"text": "Difference Between JavaScript and jQuery"
},
{
"code": null,
"e": 29161,
"s": 29116,
"text": "QR Code Generator using HTML, CSS and jQuery"
},
{
"code": null,
"e": 29203,
"s": 29161,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29236,
"s": 29203,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29298,
"s": 29236,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29341,
"s": 29298,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
A Gentle Introduction to IoT/GPS Trajectory Clustering and Geospatial Clustering | by William Yee | Towards Data Science
|
Internet of things, connected devices, and geospatial data are all hot topics when it comes to developing value-added propositions. In this article, I will provide a gentle introduction to unsupervised learning techniques applied to GPS Trajectories.
The data comes from Microsoft Research Asia, containing data from 182 users and 17,621 trips between April 2007 and August 2012. The data is mostly densely populated with a longitude and latitude recording every 1 to 5 seconds.
Now let’s take a look at the data files themselves. Hmm ‘.plt’ format, a format I have never seen before, but let’s open it in text edit.
Okay great, looks like pandas read_csv function will work well with the .plt file format, and the accompanying documentation about the data structure looks accurate.
import pandas as pdcolnames = ['lat','long', 'null', 'alt' ,'DateTime','Date','Time']df = pd.read_csv('20090724005608.plt', skiprows=6, names = colnames)
Having the time series in a data frame is great, but we need to convert each data frame into a single observation with multiple features. Doing so will format the data for loading into clustering algorithm. Let’s aggregate the 10th 25th 50th 75th 90th and average values for speed, acceleration, and jerk . To do so, we are going to write a few python function to apply to each file.
def add_feat(df_input): """ This function takes in raw lat long time series from the microsoft geolife data.Preprocessing notes: skip the first six lines before doing pandas read csv , expecting columns in ['lat','long', 'null', 'alt' ,'DateTime','Date','Time']Requres: pandas imported as pd from vincenty import vincenty Adds: speed acceleration jerk bearing rate distance travelled """ df = df_input # add some initial shifts df['lat_shift'] = df.lat.shift(-1) df['long_shift'] = df.long.shift(-1) df['time_shift'] = df.DateTime.shift(-1) # add speed def speed(x): try: s = vincenty((x[-3],x[-2]),(x[0],x[1]), miles = True) / ((x[-1]-x[4]) * 24) except: s= np.nan return s df['speed_mph'] = df.apply(speed,axis =1) df['speed_shift'] = df.speed_mph.shift(-1) # add acceleration def accel(x): try: a = (x[-1] - x[-2]) / ((x[9] - x[4]) *24*60*60) except: a = np.nan return a df['acceleration'] = df.apply(accel, axis =1) df['acceleration_shift'] = df.acceleration.shift(-1) # add jerk def jerk(x): try: j = (x[-1] - x[-2]) / ((x[9] - x[4]) *24*60*60) except: j = np.nan return a df['jerk'] = df.apply(accel, axis =1) df['jerk_shift'] = df.jerk.shift(-1) # add y for bearing calculator def y(x): try: yy = np.sin((x[8] - x[0]) * np.pi/180) *np.cos( x[7]* np.pi/180) except: yy= np.nan return yy df['y'] = df.apply(y, axis =1) # add x for bearing calculator def x(x): try: xx = np.cos(x[0] * np.pi/180) *np.sin(x[7]* np.pi/180) - np.sin(x[0]* np.pi/180) * np.cos(x[7]* np.pi/180)*np.cos((x[8]-x[1])* np.pi/180) except: xx = np.nan return xx df['x'] = df.apply(x,axis =1) # calculate bearing def bearing(x): try: b = np.arctan2(x[-2],x[-1])*180/np.pi except: b = np.nan return b df['bearing'] = df.apply(bearing,axis=1)df['brearing_shift'] = df.bearing.shift(-1) # calculate bearing rate (rate of change of direction) def bearing_rate(x): try: br = abs(x[-1]-x[-2]) except: br = np.nan return br df['bearing_rate'] = df.apply(bearing_rate,axis=1) # calculate distance travelled def distance(x): try: dist = vincenty((x[7],x[8]),(x[0],x[1]), miles = True) except: dist= np.nan return dist df['distance'] = df.apply(distance,axis = 1) df.drop(df.tail(4).index,inplace=True) return dfdef list_df_summary(input_df): ''' Converts output from add_feat function into an observation for machine learning ''' names = ['speed_10','speed_25','speed_50','speed_75','speed_90','speed_ave', 'accel_10','accel_25','accel_50','accel_75','accel_90','accel_ave', 'jerk_10','jerk_25','jerk_50','jerk_75','jerk_90','jerk_ave', 'bearingRate_10','bearingRate_25','bearingRate_50','bearingRate_75','bearingRate_90','bearingRate_ave', 'distance_traveled','time_traveled' ,'last_lat','last_long','start_lat','start_long' ] values = list() #speed values.append(input_df.quantile(.10)[8]) values.append(input_df.quantile(.25)[8]) values.append(input_df.quantile(.50)[8]) values.append(input_df.quantile(.75)[8]) values.append(input_df.quantile(.90)[8]) values.append(input_df.mean()[8]) #accel values.append(input_df.quantile(.10)[10]) values.append(input_df.quantile(.25)[10]) values.append(input_df.quantile(.50)[10]) values.append(input_df.quantile(.75)[10]) values.append(input_df.quantile(.90)[10]) values.append(input_df.mean()[10]) #jerk values.append(input_df.quantile(.10)[12]) values.append(input_df.quantile(.25)[12]) values.append(input_df.quantile(.50)[12]) values.append(input_df.quantile(.75)[12]) values.append(input_df.quantile(.90)[12]) values.append(input_df.mean()[12]) #bearing values.append(input_df.quantile(.10)[18]) values.append(input_df.quantile(.25)[18]) values.append(input_df.quantile(.50)[18]) values.append(input_df.quantile(.75)[18]) values.append(input_df.quantile(.90)[18]) values.append(input_df.mean()[18]) #distance travelled values.append(input_df.distance.sum()) #time travelled values.append((input_df.iloc[-1,4] - input_df.iloc[0,4])*24*60) #lat long values.append(input_df.iloc[-1,0]) values.append(input_df.iloc[-1,1]) values.append(input_df.iloc[0,0]) values.append(input_df.iloc[0,1]) return pd.DataFrame([values],columns=names)
To loop through the file directory, I used a package called glob. Below is the code that accomplishes creating a list of pathnames for every .plt file in the GeoLife directory. Then runs a for loop through the .plt list and applies the previous function to get us ready for machine learning!
plts = []for folder in glob('Geolife Trajectories 1.3/Data/*/Trajectory'): for file in glob(folder +'/*.plt'): plts.append(file)large_df = []for i, file in enumerate(plts): print( int(i*100 / len(plts))) try: large_df.append(list_df_summary(add_feat(pd.read_csv(file, skiprows=6,names=colnames)))) except: print('error at: ' + file)df = pd.concat(large_df)
For my example, I am going to take a subset of the modeling_df features to create clusters. Not every feature has useful information(read more on the curse of dimensionality). It’s a bit of an iterative process, you can try different subsets to develop different clusters. Initially, I looked at the distributions of each feature to guess if it would be valuable inclusion to the unsupervised learning algorithm.
from sklearn.cluster import KMeansfrom sklearn.preprocessing import StandardScalerimport seaborn as snsfrom collections import Counter## Remove longer tripsdf_local_all_feat=df[(df.time_traveled < 300) & (df.distance_traveled < 100)& (df.speed_90<75)]## Select Features with unique distributionsdf_local = df_local_all_feat[['speed_90','speed_ave','accel_75','speed_50','accel_ave','distance_traveled','time_traveled']]## Scale Data for KMeansX = StandardScaler()X = X.fit_transform(df_local)#################################### PERFORM KMeans CLUSTERING ####################################Sum_of_squared_distances = []scores = []cluster_count = []K= range(2,15,1)for i in K: km = KMeans(n_clusters=i) km.fit(X) pred =km.predict(X) Sum_of_squared_distances.append(km.inertia_) scores.append(silhouette_score(X, pred)) cluster_count.append(i) print(Counter(pred)) print(str(silhouette_score(X, pred)) + ' clusters:' +str(i)) print('------')########################################### Elbow plot with silhouette score ###########################################sns.set_context('talk')sns.lineplot(cluster_count,scores)plt.xlabel('Cluster Count')plt.ylabel('Silhouette Score')plt.title('Elbow Method For Optimal Cluster Count')plt.show()
df_local_all_feat['cluster'] = KMeans(n_clusters=7).fit_predict(X)
Clusters 4,5 contain very few number of observations therefore, are not included in this analysis.
Let’s take a look at the final destination and the Trajectory clusters.
Looking at Tsinghua University we can see a significant amount of clusters 0 and 1.
Looking at Tecent offices we can start to see significantly more subway rides, clusters 5 and 6.
Looking at a local shopping district a less subway/train trips, but train trips typically travel longer distances (size is total distance travelled).
The larger “zoom-out” map of the above section, can be found below. We have identified 3 general points of interest, it’s time to cluster them.
Looks like we need algorithm that can combine distance with proximity, while giving the capability to exclude noise. It sounds like DB Scan would be algorithm for this application.
from sklearn.cluster import DBSCAN# pull out the only the location metricsdf_cluster = df_local_all_feat[['Last Lat', 'Last Long']]X = StandardScaler()X = X.fit_transform(df_cluster)scores = []EP =[]number =[]eps= [.08,.10,.15,.20,.25,.30,.40,.50,.60]size= [200,250,300]for ep in eps: for siz in size: db = DBSCAN(eps=ep, min_samples=siz) pred = db.fit_predict(X) print('ep:'+ str(ep) + ' size:'+ str(siz)) print(Counter(pred)) try: scores.append(silhouette_score(X, pred)) except: scores.append(np.nan) EP.append(ep) number.append(siz)
The variable eps and size will allow you to grid search the appropriate hyperparameters for your application. In the end I, landed on the following values.
db = DBSCAN(eps= 0.37, min_samples = 250)
By combing both clustering algorithms, we can filter specific trips based on point of interest to determine where people are coming from and the method of transportation used to arrive at the said point of interest.
For Tsinghua University, we can see people are generally taking shorts trip from nearby.
For the shopping district, we can see people are traveling a bit further and are mostly using transportation mode 0.
For the Tencent office, people are traveling from the furtherest away. However, people commuting from nearby are typically taking transportation mode 0, while people commuting from further away are taking transportation mode 6.
Using various unsupervised learning algorithms, we are able to determine how people travel to specific locations, how to bound points of interest, and where people originated.
With adjustments, in the data collection architecture, it would be interesting to determine how people dwell stay at a location, based on the factors of distance travelled and method of transportation.
|
[
{
"code": null,
"e": 423,
"s": 172,
"text": "Internet of things, connected devices, and geospatial data are all hot topics when it comes to developing value-added propositions. In this article, I will provide a gentle introduction to unsupervised learning techniques applied to GPS Trajectories."
},
{
"code": null,
"e": 651,
"s": 423,
"text": "The data comes from Microsoft Research Asia, containing data from 182 users and 17,621 trips between April 2007 and August 2012. The data is mostly densely populated with a longitude and latitude recording every 1 to 5 seconds."
},
{
"code": null,
"e": 789,
"s": 651,
"text": "Now let’s take a look at the data files themselves. Hmm ‘.plt’ format, a format I have never seen before, but let’s open it in text edit."
},
{
"code": null,
"e": 955,
"s": 789,
"text": "Okay great, looks like pandas read_csv function will work well with the .plt file format, and the accompanying documentation about the data structure looks accurate."
},
{
"code": null,
"e": 1109,
"s": 955,
"text": "import pandas as pdcolnames = ['lat','long', 'null', 'alt' ,'DateTime','Date','Time']df = pd.read_csv('20090724005608.plt', skiprows=6, names = colnames)"
},
{
"code": null,
"e": 1493,
"s": 1109,
"text": "Having the time series in a data frame is great, but we need to convert each data frame into a single observation with multiple features. Doing so will format the data for loading into clustering algorithm. Let’s aggregate the 10th 25th 50th 75th 90th and average values for speed, acceleration, and jerk . To do so, we are going to write a few python function to apply to each file."
},
{
"code": null,
"e": 6260,
"s": 1493,
"text": "def add_feat(df_input): \"\"\" This function takes in raw lat long time series from the microsoft geolife data.Preprocessing notes: skip the first six lines before doing pandas read csv , expecting columns in ['lat','long', 'null', 'alt' ,'DateTime','Date','Time']Requres: pandas imported as pd from vincenty import vincenty Adds: speed acceleration jerk bearing rate distance travelled \"\"\" df = df_input # add some initial shifts df['lat_shift'] = df.lat.shift(-1) df['long_shift'] = df.long.shift(-1) df['time_shift'] = df.DateTime.shift(-1) # add speed def speed(x): try: s = vincenty((x[-3],x[-2]),(x[0],x[1]), miles = True) / ((x[-1]-x[4]) * 24) except: s= np.nan return s df['speed_mph'] = df.apply(speed,axis =1) df['speed_shift'] = df.speed_mph.shift(-1) # add acceleration def accel(x): try: a = (x[-1] - x[-2]) / ((x[9] - x[4]) *24*60*60) except: a = np.nan return a df['acceleration'] = df.apply(accel, axis =1) df['acceleration_shift'] = df.acceleration.shift(-1) # add jerk def jerk(x): try: j = (x[-1] - x[-2]) / ((x[9] - x[4]) *24*60*60) except: j = np.nan return a df['jerk'] = df.apply(accel, axis =1) df['jerk_shift'] = df.jerk.shift(-1) # add y for bearing calculator def y(x): try: yy = np.sin((x[8] - x[0]) * np.pi/180) *np.cos( x[7]* np.pi/180) except: yy= np.nan return yy df['y'] = df.apply(y, axis =1) # add x for bearing calculator def x(x): try: xx = np.cos(x[0] * np.pi/180) *np.sin(x[7]* np.pi/180) - np.sin(x[0]* np.pi/180) * np.cos(x[7]* np.pi/180)*np.cos((x[8]-x[1])* np.pi/180) except: xx = np.nan return xx df['x'] = df.apply(x,axis =1) # calculate bearing def bearing(x): try: b = np.arctan2(x[-2],x[-1])*180/np.pi except: b = np.nan return b df['bearing'] = df.apply(bearing,axis=1)df['brearing_shift'] = df.bearing.shift(-1) # calculate bearing rate (rate of change of direction) def bearing_rate(x): try: br = abs(x[-1]-x[-2]) except: br = np.nan return br df['bearing_rate'] = df.apply(bearing_rate,axis=1) # calculate distance travelled def distance(x): try: dist = vincenty((x[7],x[8]),(x[0],x[1]), miles = True) except: dist= np.nan return dist df['distance'] = df.apply(distance,axis = 1) df.drop(df.tail(4).index,inplace=True) return dfdef list_df_summary(input_df): ''' Converts output from add_feat function into an observation for machine learning ''' names = ['speed_10','speed_25','speed_50','speed_75','speed_90','speed_ave', 'accel_10','accel_25','accel_50','accel_75','accel_90','accel_ave', 'jerk_10','jerk_25','jerk_50','jerk_75','jerk_90','jerk_ave', 'bearingRate_10','bearingRate_25','bearingRate_50','bearingRate_75','bearingRate_90','bearingRate_ave', 'distance_traveled','time_traveled' ,'last_lat','last_long','start_lat','start_long' ] values = list() #speed values.append(input_df.quantile(.10)[8]) values.append(input_df.quantile(.25)[8]) values.append(input_df.quantile(.50)[8]) values.append(input_df.quantile(.75)[8]) values.append(input_df.quantile(.90)[8]) values.append(input_df.mean()[8]) #accel values.append(input_df.quantile(.10)[10]) values.append(input_df.quantile(.25)[10]) values.append(input_df.quantile(.50)[10]) values.append(input_df.quantile(.75)[10]) values.append(input_df.quantile(.90)[10]) values.append(input_df.mean()[10]) #jerk values.append(input_df.quantile(.10)[12]) values.append(input_df.quantile(.25)[12]) values.append(input_df.quantile(.50)[12]) values.append(input_df.quantile(.75)[12]) values.append(input_df.quantile(.90)[12]) values.append(input_df.mean()[12]) #bearing values.append(input_df.quantile(.10)[18]) values.append(input_df.quantile(.25)[18]) values.append(input_df.quantile(.50)[18]) values.append(input_df.quantile(.75)[18]) values.append(input_df.quantile(.90)[18]) values.append(input_df.mean()[18]) #distance travelled values.append(input_df.distance.sum()) #time travelled values.append((input_df.iloc[-1,4] - input_df.iloc[0,4])*24*60) #lat long values.append(input_df.iloc[-1,0]) values.append(input_df.iloc[-1,1]) values.append(input_df.iloc[0,0]) values.append(input_df.iloc[0,1]) return pd.DataFrame([values],columns=names)"
},
{
"code": null,
"e": 6552,
"s": 6260,
"text": "To loop through the file directory, I used a package called glob. Below is the code that accomplishes creating a list of pathnames for every .plt file in the GeoLife directory. Then runs a for loop through the .plt list and applies the previous function to get us ready for machine learning!"
},
{
"code": null,
"e": 6942,
"s": 6552,
"text": "plts = []for folder in glob('Geolife Trajectories 1.3/Data/*/Trajectory'): for file in glob(folder +'/*.plt'): plts.append(file)large_df = []for i, file in enumerate(plts): print( int(i*100 / len(plts))) try: large_df.append(list_df_summary(add_feat(pd.read_csv(file, skiprows=6,names=colnames)))) except: print('error at: ' + file)df = pd.concat(large_df)"
},
{
"code": null,
"e": 7355,
"s": 6942,
"text": "For my example, I am going to take a subset of the modeling_df features to create clusters. Not every feature has useful information(read more on the curse of dimensionality). It’s a bit of an iterative process, you can try different subsets to develop different clusters. Initially, I looked at the distributions of each feature to guess if it would be valuable inclusion to the unsupervised learning algorithm."
},
{
"code": null,
"e": 8618,
"s": 7355,
"text": "from sklearn.cluster import KMeansfrom sklearn.preprocessing import StandardScalerimport seaborn as snsfrom collections import Counter## Remove longer tripsdf_local_all_feat=df[(df.time_traveled < 300) & (df.distance_traveled < 100)& (df.speed_90<75)]## Select Features with unique distributionsdf_local = df_local_all_feat[['speed_90','speed_ave','accel_75','speed_50','accel_ave','distance_traveled','time_traveled']]## Scale Data for KMeansX = StandardScaler()X = X.fit_transform(df_local)#################################### PERFORM KMeans CLUSTERING ####################################Sum_of_squared_distances = []scores = []cluster_count = []K= range(2,15,1)for i in K: km = KMeans(n_clusters=i) km.fit(X) pred =km.predict(X) Sum_of_squared_distances.append(km.inertia_) scores.append(silhouette_score(X, pred)) cluster_count.append(i) print(Counter(pred)) print(str(silhouette_score(X, pred)) + ' clusters:' +str(i)) print('------')########################################### Elbow plot with silhouette score ###########################################sns.set_context('talk')sns.lineplot(cluster_count,scores)plt.xlabel('Cluster Count')plt.ylabel('Silhouette Score')plt.title('Elbow Method For Optimal Cluster Count')plt.show()"
},
{
"code": null,
"e": 8685,
"s": 8618,
"text": "df_local_all_feat['cluster'] = KMeans(n_clusters=7).fit_predict(X)"
},
{
"code": null,
"e": 8784,
"s": 8685,
"text": "Clusters 4,5 contain very few number of observations therefore, are not included in this analysis."
},
{
"code": null,
"e": 8856,
"s": 8784,
"text": "Let’s take a look at the final destination and the Trajectory clusters."
},
{
"code": null,
"e": 8940,
"s": 8856,
"text": "Looking at Tsinghua University we can see a significant amount of clusters 0 and 1."
},
{
"code": null,
"e": 9037,
"s": 8940,
"text": "Looking at Tecent offices we can start to see significantly more subway rides, clusters 5 and 6."
},
{
"code": null,
"e": 9187,
"s": 9037,
"text": "Looking at a local shopping district a less subway/train trips, but train trips typically travel longer distances (size is total distance travelled)."
},
{
"code": null,
"e": 9331,
"s": 9187,
"text": "The larger “zoom-out” map of the above section, can be found below. We have identified 3 general points of interest, it’s time to cluster them."
},
{
"code": null,
"e": 9512,
"s": 9331,
"text": "Looks like we need algorithm that can combine distance with proximity, while giving the capability to exclude noise. It sounds like DB Scan would be algorithm for this application."
},
{
"code": null,
"e": 10141,
"s": 9512,
"text": "from sklearn.cluster import DBSCAN# pull out the only the location metricsdf_cluster = df_local_all_feat[['Last Lat', 'Last Long']]X = StandardScaler()X = X.fit_transform(df_cluster)scores = []EP =[]number =[]eps= [.08,.10,.15,.20,.25,.30,.40,.50,.60]size= [200,250,300]for ep in eps: for siz in size: db = DBSCAN(eps=ep, min_samples=siz) pred = db.fit_predict(X) print('ep:'+ str(ep) + ' size:'+ str(siz)) print(Counter(pred)) try: scores.append(silhouette_score(X, pred)) except: scores.append(np.nan) EP.append(ep) number.append(siz)"
},
{
"code": null,
"e": 10297,
"s": 10141,
"text": "The variable eps and size will allow you to grid search the appropriate hyperparameters for your application. In the end I, landed on the following values."
},
{
"code": null,
"e": 10339,
"s": 10297,
"text": "db = DBSCAN(eps= 0.37, min_samples = 250)"
},
{
"code": null,
"e": 10555,
"s": 10339,
"text": "By combing both clustering algorithms, we can filter specific trips based on point of interest to determine where people are coming from and the method of transportation used to arrive at the said point of interest."
},
{
"code": null,
"e": 10644,
"s": 10555,
"text": "For Tsinghua University, we can see people are generally taking shorts trip from nearby."
},
{
"code": null,
"e": 10761,
"s": 10644,
"text": "For the shopping district, we can see people are traveling a bit further and are mostly using transportation mode 0."
},
{
"code": null,
"e": 10989,
"s": 10761,
"text": "For the Tencent office, people are traveling from the furtherest away. However, people commuting from nearby are typically taking transportation mode 0, while people commuting from further away are taking transportation mode 6."
},
{
"code": null,
"e": 11165,
"s": 10989,
"text": "Using various unsupervised learning algorithms, we are able to determine how people travel to specific locations, how to bound points of interest, and where people originated."
}
] |
The kill() Function in Perl
|
Perl kill('KILL', (Process List)) function can be used to terminate a pseudo-process by passing it the ID returned by fork().
Note that using kill('KILL', (Process List)) on a pseudo-process() may typically cause memory leaks, because the thread that implements the pseudo-process does not get a chance to clean up its resources.
You can use kill() function to send any other signal to target processes, for example following will send SIGINT to a process IDs 104 and 102 −
#!/usr/bin/perl
kill('INT', 104, 102);
1;
|
[
{
"code": null,
"e": 1188,
"s": 1062,
"text": "Perl kill('KILL', (Process List)) function can be used to terminate a pseudo-process by passing it the ID returned by fork()."
},
{
"code": null,
"e": 1392,
"s": 1188,
"text": "Note that using kill('KILL', (Process List)) on a pseudo-process() may typically cause memory leaks, because the thread that implements the pseudo-process does not get a chance to clean up its resources."
},
{
"code": null,
"e": 1536,
"s": 1392,
"text": "You can use kill() function to send any other signal to target processes, for example following will send SIGINT to a process IDs 104 and 102 −"
},
{
"code": null,
"e": 1578,
"s": 1536,
"text": "#!/usr/bin/perl\nkill('INT', 104, 102);\n1;"
}
] |
Check a number is odd or even without modulus operator - GeeksforGeeks
|
11 May, 2021
Given a number, check whether it is even or odd.
Examples :
Input: n = 11
Output: Odd
Input: n = 10
Output: Even
Method 1: Using Loop. The idea is to start with a boolean flag variable as true and switch it n times. If flag variable gets original value (which is true) back, then n is even. Else n is false.
Below is the implementation of this idea.
C++
Java
Python3
C#
PHP
Javascript
// A simple C++ program to check for// even or odd#include <iostream>using namespace std; // Returns true if n is even, else oddbool isEven(int n){ bool isEven = true; for (int i=1; i <= n; i++) isEven = !isEven; return isEven;} // Driver codeint main(){ int n = 101; isEven(n) ? cout << "Even" : cout << "Odd"; return 0;}
// A simple Java program to// check for even or odd class GFG { // Returns true if n // is even, else odd static boolean isEven(int n) { boolean isEven = true; for (int i = 1; i <= n; i++) isEven = !isEven; return isEven; } // Driver Code public static void main(String args[]) { int n = 101; if(isEven(n)) System.out.println("Even"); else System.out.println("Odd"); }} // This code is contributed by Sam007
# A simple Python program to# check for even or odd # Returns true if n is even,# else odddef isEven(n): isEven = True; for i in range(1, n+1): if isEven == True: isEven = False; else: isEven = True; return isEven; # Driver code n = 101;if isEven(n) == True: print ("Even");else: print ("Odd"); # This code is contributed by# Manish Shaw (manishshaw1)
// A simple C# program to check for// even or oddusing System; public class GFG { // Returns true if n is even, // else odd static bool isEven(int n) { bool isEven = true; for (int i = 1; i <= n; i++) isEven = !isEven; return isEven; } // Driver code public static void Main() { int n = 101; if(isEven(n)) Console.Write("Even"); else Console.Write("Odd"); }} // This code is contributed by Sam007.
<?php// A simple PHP program to check for// even or odd // Returns true if n is even,// else oddfunction isEven($n){ $isEven = true; for ($i = 1; $i <= $n; $i++) $isEven = !$isEven; return $isEven;} // Driver code $n = 101; $is=isEven($n) ? "Even" : "Odd"; echo "$is" // This code is contributed by ajit?>
<script> // A simple Javascript program to check// for even or odd // Returns true if n is even,// else oddfunction isEven(n){ let isEven = true; for(let i = 1; i <= n; i++) isEven = !isEven; return isEven;} // Driver codelet n = 101;if (isEven(n)) document.write("Even");else document.write("Odd"); // This code is contributed by mukesh07 </script>
Odd
Method 2: By multiply and divide by 2. Divide the number by 2 and multiply by 2 if the result is same as input then it is an even number else it is an odd number.
C++
Java
Python3
C#
PHP
Javascript
// A simple C++ program to check for// even or odd#include <iostream>using namespace std; // Returns true if n is even, else oddbool isEven(int n){ // Return true if n/2 does not result // in a float value. return ((n / 2) * 2 == n);} // Driver codeint main(){ int n = 101; isEven(n) ? cout << "Even" : cout << "Odd"; return 0;}
// A simple Java program// to check for even or odd class GFG { // Returns true if n// is even, else oddstatic boolean isEven(int n){ // Return true if // n/2 does not result // in a float value. return ((n / 2) * 2 == n);} // Driver codepublic static void main(String[] args){ int n = 101; if(isEven(n) != false) System.out.print( "Even" ); else System.out.print( "Odd" );}} // This code is contributed by// Smitha Dinesh Semwal.
# A simple Python 3 program# to check for even or odd # Returns true if n# is even, else odddef isEven(n): # Return true if # n/2 does not result # in a float value. return (int(n / 2) * 2 == n) # Driver coden = 101if(isEven(n) != False): print("Even")else: print("Odd") # This code is contributed by# Smitha Dinesh Semwal.
// A simple C# program// to check for even or oddusing System;class GFG { // Returns true if n// is even, else oddstatic bool isEven(int n){ // Return true if // n/2 does not result // in a float value. return ((n / 2) * 2 == n);} // Driver codepublic static void Main(String[] args){ int n = 101; if(isEven(n) != false) Console.Write("Even"); else Console.Write("Odd");}} // This code is contributed by// Smitha Dinesh Semwal.
<?php// A simple PHP program to// check for even or odd // Returns true if n// is even, else oddfunction isEven($n){ // Return true if n/2 // does not result // in a float value. return ((int)($n / 2) * 2 == $n);} // Driver code$n = 101;if(isEven($n)) echo ("Even");else echo ("Odd"); // This code is contributed by// Manish Shaw (manishshaw1)?>
<script> // A simple Javascript program to// check for even or odd // Returns true if n is even,// else oddfunction isEven(n){ // Return true if n/2 does not result // in a float value. return (parseInt(n / 2, 10) * 2 == n);} // Driver codelet n = 101;isEven(n) ? document.write("Even") : document.write("Odd"); // This code is contributed by divyeshrabadiya07 </script>
Odd
Method 3: Using Bitwise operator &. A better solution is to use bitwise operators. We need to check whether last bit is 1 or not. If last bit is 1 then the number is odd, otherwise always even.
Explanation:
input : 5 // odd
00000101
& 00000001
--------------
00000001
--------------
input : 8 //even
00001000
& 00000001
--------------
00000000
--------------
Below is the implementation of the idea.
C++
Java
Python3
C#
PHP
Javascript
// A simple C++ program to check for// even or odd#include <iostream>using namespace std; // Returns true if n is even, else oddbool isEven(int n){ // n&1 is 1, then odd, else even return (!(n & 1));} // Driver codeint main(){ int n = 101; isEven(n) ? cout << "Even" : cout << "Odd"; return 0;}
// A simple Java program to check for// even or oddimport java.io.*;import java.util.*; public class GFG { // Returns 0 if n // is even, else odd static int isEven(int n) { // n&1 is 1, then // odd, else even return (n & 1); } // Driver code public static void main(String args[]) { int n = 101; if(isEven(n)==0) System.out.print("Even"); else System.out.print("Odd"); }} // This code is contributed// by Manish Shaw (manishshaw1)
# A simple Python program to# check for even or odd# Returns 0 if n# is even, else odddef isEven(n) : # n&1 is 1, then # odd, else even return (n & 1); # Driver coden = 101;if(isEven(n) == 0) : print ("Even");else : print ("Odd"); # This code is contributed# by Manish Shaw (manishshaw1)
// A simple C# program to check for// even or oddusing System;using System.Collections.Generic; class GFG { // Returns 0 if n // is even, else odd static int isEven(int n) { // n&1 is 1, then // odd, else even return (n & 1); } // Driver code public static void Main() { int n = 101; if(isEven(n)==0) Console.Write("Even"); else Console.Write("Odd"); }} // This code is contributed// by Manish Shaw (manishshaw1)
<?php// A simple PHP program to// check for even or odd// Returns 0 if n// is even, else oddfunction isEven($n){ // n&1 is 1, then // odd, else even return ($n & 1);} // Driver code$n = 101;if(isEven($n) == 0) echo ("Even");else echo ("Odd"); // This code is contributed// by Manish Shaw (manishshaw1)?>
<script> // A simple Javascript program to check for even or odd // Returns true if n is even, else odd function isEven(n) { // n&1 is 1, then odd, else even return (!(n & 1)); } let n = 101; isEven(n) ? document.write("Even") : document.write("Odd"); </script>
Odd
Sam007
Smitha Dinesh Semwal
jit_t
manishshaw1
mukesh07
divyeshrabadiya07
decode2207
divisibility
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Add two numbers without using arithmetic operators
Find the element that appears once
Set, Clear and Toggle a given bit of a number in C
Bit Fields in C
Bits manipulation (Important tactics)
Write an Efficient C Program to Reverse Bits of a Number
C++ bitset and its application
Check whether K-th bit is set or not
Find the Number Occurring Odd Number of Times
|
[
{
"code": null,
"e": 24909,
"s": 24881,
"text": "\n11 May, 2021"
},
{
"code": null,
"e": 24958,
"s": 24909,
"text": "Given a number, check whether it is even or odd."
},
{
"code": null,
"e": 24970,
"s": 24958,
"text": "Examples : "
},
{
"code": null,
"e": 25026,
"s": 24970,
"text": "Input: n = 11\nOutput: Odd\n\nInput: n = 10\nOutput: Even\n "
},
{
"code": null,
"e": 25221,
"s": 25026,
"text": "Method 1: Using Loop. The idea is to start with a boolean flag variable as true and switch it n times. If flag variable gets original value (which is true) back, then n is even. Else n is false."
},
{
"code": null,
"e": 25265,
"s": 25221,
"text": "Below is the implementation of this idea. "
},
{
"code": null,
"e": 25269,
"s": 25265,
"text": "C++"
},
{
"code": null,
"e": 25274,
"s": 25269,
"text": "Java"
},
{
"code": null,
"e": 25282,
"s": 25274,
"text": "Python3"
},
{
"code": null,
"e": 25285,
"s": 25282,
"text": "C#"
},
{
"code": null,
"e": 25289,
"s": 25285,
"text": "PHP"
},
{
"code": null,
"e": 25300,
"s": 25289,
"text": "Javascript"
},
{
"code": "// A simple C++ program to check for// even or odd#include <iostream>using namespace std; // Returns true if n is even, else oddbool isEven(int n){ bool isEven = true; for (int i=1; i <= n; i++) isEven = !isEven; return isEven;} // Driver codeint main(){ int n = 101; isEven(n) ? cout << \"Even\" : cout << \"Odd\"; return 0;}",
"e": 25649,
"s": 25300,
"text": null
},
{
"code": "// A simple Java program to// check for even or odd class GFG { // Returns true if n // is even, else odd static boolean isEven(int n) { boolean isEven = true; for (int i = 1; i <= n; i++) isEven = !isEven; return isEven; } // Driver Code public static void main(String args[]) { int n = 101; if(isEven(n)) System.out.println(\"Even\"); else System.out.println(\"Odd\"); }} // This code is contributed by Sam007",
"e": 26214,
"s": 25649,
"text": null
},
{
"code": "# A simple Python program to# check for even or odd # Returns true if n is even,# else odddef isEven(n): isEven = True; for i in range(1, n+1): if isEven == True: isEven = False; else: isEven = True; return isEven; # Driver code n = 101;if isEven(n) == True: print (\"Even\");else: print (\"Odd\"); # This code is contributed by# Manish Shaw (manishshaw1)",
"e": 26624,
"s": 26214,
"text": null
},
{
"code": "// A simple C# program to check for// even or oddusing System; public class GFG { // Returns true if n is even, // else odd static bool isEven(int n) { bool isEven = true; for (int i = 1; i <= n; i++) isEven = !isEven; return isEven; } // Driver code public static void Main() { int n = 101; if(isEven(n)) Console.Write(\"Even\"); else Console.Write(\"Odd\"); }} // This code is contributed by Sam007.",
"e": 27156,
"s": 26624,
"text": null
},
{
"code": "<?php// A simple PHP program to check for// even or odd // Returns true if n is even,// else oddfunction isEven($n){ $isEven = true; for ($i = 1; $i <= $n; $i++) $isEven = !$isEven; return $isEven;} // Driver code $n = 101; $is=isEven($n) ? \"Even\" : \"Odd\"; echo \"$is\" // This code is contributed by ajit?>",
"e": 27491,
"s": 27156,
"text": null
},
{
"code": "<script> // A simple Javascript program to check// for even or odd // Returns true if n is even,// else oddfunction isEven(n){ let isEven = true; for(let i = 1; i <= n; i++) isEven = !isEven; return isEven;} // Driver codelet n = 101;if (isEven(n)) document.write(\"Even\");else document.write(\"Odd\"); // This code is contributed by mukesh07 </script>",
"e": 27885,
"s": 27491,
"text": null
},
{
"code": null,
"e": 27889,
"s": 27885,
"text": "Odd"
},
{
"code": null,
"e": 28054,
"s": 27891,
"text": "Method 2: By multiply and divide by 2. Divide the number by 2 and multiply by 2 if the result is same as input then it is an even number else it is an odd number."
},
{
"code": null,
"e": 28058,
"s": 28054,
"text": "C++"
},
{
"code": null,
"e": 28063,
"s": 28058,
"text": "Java"
},
{
"code": null,
"e": 28071,
"s": 28063,
"text": "Python3"
},
{
"code": null,
"e": 28074,
"s": 28071,
"text": "C#"
},
{
"code": null,
"e": 28078,
"s": 28074,
"text": "PHP"
},
{
"code": null,
"e": 28089,
"s": 28078,
"text": "Javascript"
},
{
"code": "// A simple C++ program to check for// even or odd#include <iostream>using namespace std; // Returns true if n is even, else oddbool isEven(int n){ // Return true if n/2 does not result // in a float value. return ((n / 2) * 2 == n);} // Driver codeint main(){ int n = 101; isEven(n) ? cout << \"Even\" : cout << \"Odd\"; return 0;}",
"e": 28436,
"s": 28089,
"text": null
},
{
"code": "// A simple Java program// to check for even or odd class GFG { // Returns true if n// is even, else oddstatic boolean isEven(int n){ // Return true if // n/2 does not result // in a float value. return ((n / 2) * 2 == n);} // Driver codepublic static void main(String[] args){ int n = 101; if(isEven(n) != false) System.out.print( \"Even\" ); else System.out.print( \"Odd\" );}} // This code is contributed by// Smitha Dinesh Semwal.",
"e": 28911,
"s": 28436,
"text": null
},
{
"code": "# A simple Python 3 program# to check for even or odd # Returns true if n# is even, else odddef isEven(n): # Return true if # n/2 does not result # in a float value. return (int(n / 2) * 2 == n) # Driver coden = 101if(isEven(n) != False): print(\"Even\")else: print(\"Odd\") # This code is contributed by# Smitha Dinesh Semwal.",
"e": 29260,
"s": 28911,
"text": null
},
{
"code": "// A simple C# program// to check for even or oddusing System;class GFG { // Returns true if n// is even, else oddstatic bool isEven(int n){ // Return true if // n/2 does not result // in a float value. return ((n / 2) * 2 == n);} // Driver codepublic static void Main(String[] args){ int n = 101; if(isEven(n) != false) Console.Write(\"Even\"); else Console.Write(\"Odd\");}} // This code is contributed by// Smitha Dinesh Semwal.",
"e": 29732,
"s": 29260,
"text": null
},
{
"code": "<?php// A simple PHP program to// check for even or odd // Returns true if n// is even, else oddfunction isEven($n){ // Return true if n/2 // does not result // in a float value. return ((int)($n / 2) * 2 == $n);} // Driver code$n = 101;if(isEven($n)) echo (\"Even\");else echo (\"Odd\"); // This code is contributed by// Manish Shaw (manishshaw1)?>",
"e": 30100,
"s": 29732,
"text": null
},
{
"code": "<script> // A simple Javascript program to// check for even or odd // Returns true if n is even,// else oddfunction isEven(n){ // Return true if n/2 does not result // in a float value. return (parseInt(n / 2, 10) * 2 == n);} // Driver codelet n = 101;isEven(n) ? document.write(\"Even\") : document.write(\"Odd\"); // This code is contributed by divyeshrabadiya07 </script>",
"e": 30508,
"s": 30100,
"text": null
},
{
"code": null,
"e": 30512,
"s": 30508,
"text": "Odd"
},
{
"code": null,
"e": 30708,
"s": 30514,
"text": "Method 3: Using Bitwise operator &. A better solution is to use bitwise operators. We need to check whether last bit is 1 or not. If last bit is 1 then the number is odd, otherwise always even."
},
{
"code": null,
"e": 30722,
"s": 30708,
"text": "Explanation: "
},
{
"code": null,
"e": 31004,
"s": 30722,
"text": " input : 5 // odd\n 00000101 \n & 00000001 \n-------------- \n 00000001 \n--------------\n\ninput : 8 //even\n 00001000 \n & 00000001 \n-------------- \n 00000000 \n--------------"
},
{
"code": null,
"e": 31046,
"s": 31004,
"text": "Below is the implementation of the idea. "
},
{
"code": null,
"e": 31050,
"s": 31046,
"text": "C++"
},
{
"code": null,
"e": 31055,
"s": 31050,
"text": "Java"
},
{
"code": null,
"e": 31063,
"s": 31055,
"text": "Python3"
},
{
"code": null,
"e": 31066,
"s": 31063,
"text": "C#"
},
{
"code": null,
"e": 31070,
"s": 31066,
"text": "PHP"
},
{
"code": null,
"e": 31081,
"s": 31070,
"text": "Javascript"
},
{
"code": "// A simple C++ program to check for// even or odd#include <iostream>using namespace std; // Returns true if n is even, else oddbool isEven(int n){ // n&1 is 1, then odd, else even return (!(n & 1));} // Driver codeint main(){ int n = 101; isEven(n) ? cout << \"Even\" : cout << \"Odd\"; return 0;}",
"e": 31391,
"s": 31081,
"text": null
},
{
"code": "// A simple Java program to check for// even or oddimport java.io.*;import java.util.*; public class GFG { // Returns 0 if n // is even, else odd static int isEven(int n) { // n&1 is 1, then // odd, else even return (n & 1); } // Driver code public static void main(String args[]) { int n = 101; if(isEven(n)==0) System.out.print(\"Even\"); else System.out.print(\"Odd\"); }} // This code is contributed// by Manish Shaw (manishshaw1)",
"e": 31936,
"s": 31391,
"text": null
},
{
"code": "# A simple Python program to# check for even or odd# Returns 0 if n# is even, else odddef isEven(n) : # n&1 is 1, then # odd, else even return (n & 1); # Driver coden = 101;if(isEven(n) == 0) : print (\"Even\");else : print (\"Odd\"); # This code is contributed# by Manish Shaw (manishshaw1)",
"e": 32251,
"s": 31936,
"text": null
},
{
"code": "// A simple C# program to check for// even or oddusing System;using System.Collections.Generic; class GFG { // Returns 0 if n // is even, else odd static int isEven(int n) { // n&1 is 1, then // odd, else even return (n & 1); } // Driver code public static void Main() { int n = 101; if(isEven(n)==0) Console.Write(\"Even\"); else Console.Write(\"Odd\"); }} // This code is contributed// by Manish Shaw (manishshaw1)",
"e": 32774,
"s": 32251,
"text": null
},
{
"code": "<?php// A simple PHP program to// check for even or odd// Returns 0 if n// is even, else oddfunction isEven($n){ // n&1 is 1, then // odd, else even return ($n & 1);} // Driver code$n = 101;if(isEven($n) == 0) echo (\"Even\");else echo (\"Odd\"); // This code is contributed// by Manish Shaw (manishshaw1)?>",
"e": 33102,
"s": 32774,
"text": null
},
{
"code": "<script> // A simple Javascript program to check for even or odd // Returns true if n is even, else odd function isEven(n) { // n&1 is 1, then odd, else even return (!(n & 1)); } let n = 101; isEven(n) ? document.write(\"Even\") : document.write(\"Odd\"); </script>",
"e": 33409,
"s": 33102,
"text": null
},
{
"code": null,
"e": 33413,
"s": 33409,
"text": "Odd"
},
{
"code": null,
"e": 33422,
"s": 33415,
"text": "Sam007"
},
{
"code": null,
"e": 33443,
"s": 33422,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 33449,
"s": 33443,
"text": "jit_t"
},
{
"code": null,
"e": 33461,
"s": 33449,
"text": "manishshaw1"
},
{
"code": null,
"e": 33470,
"s": 33461,
"text": "mukesh07"
},
{
"code": null,
"e": 33488,
"s": 33470,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 33499,
"s": 33488,
"text": "decode2207"
},
{
"code": null,
"e": 33512,
"s": 33499,
"text": "divisibility"
},
{
"code": null,
"e": 33522,
"s": 33512,
"text": "Bit Magic"
},
{
"code": null,
"e": 33532,
"s": 33522,
"text": "Bit Magic"
},
{
"code": null,
"e": 33630,
"s": 33532,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33639,
"s": 33630,
"text": "Comments"
},
{
"code": null,
"e": 33652,
"s": 33639,
"text": "Old Comments"
},
{
"code": null,
"e": 33698,
"s": 33652,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 33749,
"s": 33698,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 33784,
"s": 33749,
"text": "Find the element that appears once"
},
{
"code": null,
"e": 33835,
"s": 33784,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 33851,
"s": 33835,
"text": "Bit Fields in C"
},
{
"code": null,
"e": 33889,
"s": 33851,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 33946,
"s": 33889,
"text": "Write an Efficient C Program to Reverse Bits of a Number"
},
{
"code": null,
"e": 33977,
"s": 33946,
"text": "C++ bitset and its application"
},
{
"code": null,
"e": 34014,
"s": 33977,
"text": "Check whether K-th bit is set or not"
}
] |
Different types of recurrence relations and their solutions - GeeksforGeeks
|
09 Oct, 2019
In this article, we will see how we can solve different types of recurrence relations using different approaches. Before understanding this article, you should have idea about recurrence relations and different method to solve them (See : Worst, Average and Best Cases, Asymptotic Notations, Analysis of Loops).
Type 1: Divide and conquer recurrence relations –Following are some of the examples of recurrence relations based on divide and conquer.
T(n) = 2T(n/2) + cn
T(n) = 2T(n/2) + √n
These types of recurrence relations can be easily solved using Master Method.For recurrence relation T(n) = 2T(n/2) + cn, the values of a = 2, b = 2 and k =1. Here logb(a) = log2(2) = 1 = k. Therefore, the complexity will be Θ(nlog2(n)).Similarly for recurrence relation T(n) = 2T(n/2) + √n, the values of a = 2, b = 2 and k =1/2. Here logb(a) = log2(2) = 1 > k. Therefore, the complexity will be Θ(n).
Type 2: Linear recurrence relations –Following are some of the examples of recurrence relations based on linear recurrence relation.
T(n) = T(n-1) + n for n>0 and T(0) = 1
These types of recurrence relations can be easily solved using substitution method.For example,
T(n) = T(n-1) + n
= T(n-2) + (n-1) + n
= T(n-k) + (n-(k-1))..... (n-1) + n
Substituting k = n, we get
T(n) = T(0) + 1 + 2+..... +n = n(n+1)/2 = O(n^2)
Type 3: Value substitution before solving –Sometimes, recurrence relations can’t be directly solved using techniques like substitution, recurrence tree or master method. Therefore, we need to convert the recurrence relation into appropriate form before solving. For example,
T(n) = T(√n) + 1
To solve this type of recurrence, substitute n = 2^m as:
T(2^m) = T(2^m /2) + 1
Let T(2^m) = S(m),
S(m) = S(m/2) + 1
Solving by master method, we get
S(m) = Θ(logm)
As n = 2^m or m = log2(n),
T(n) = T(2^m) = S(m) = Θ(logm) = Θ(loglogn)
Let us discuss some questions based on the approaches discussed.
Que – 1. What is the time complexity of Tower of Hanoi problem?(A) T(n) = O(sqrt(n))(D) T(n) = O(n^2)(C) T(n) = O(2^n)(D) None
Solution: For Tower of Hanoi, T(n) = 2T(n-1) + c for n>1 and T(1) = 1. Solving this,
T(n) = 2T(n-1) + c
= 2(2T(n-2)+ c) + c = 2^2*T(n-2) + (c + 2c)
= 2^k*T(n-k) + (c + 2c + .. kc)
Substituting k = (n-1), we get
T(n) = 2^(n-1)*T(1) + (c + 2c + (n-1)c) = O(2^n)
Que – 2. Consider the following recurrence:T(n) = 2 * T(ceil (sqrt(n) ) ) + 1, T(1) = 1Which one of the following is true?(A) T(n) = (loglogn)(B) T(n) = (logn)(C) T(n) = (sqrt(n))(D) T(n) = (n)
Solution: To solve this type of recurrence, substitute n = 2^m as:
T(2^m) = 2T(2^m /2) + 1
Let T(2^m) = S(m),
S(m) = 2S(m/2) + 1
Solving by master method, we get
S(m) = Θ(m)
As n = 2^m or m = log2n,
T(n) = T(2^m) = S(m) = Θ(m) = Θ(logn)
Karthiik
srinivasrocks7
12tanmayvijay
Analysis
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
Analysis of Algorithms | Big-O analysis
Analysis of different sorting techniques
Difference between NP hard and NP complete problem
Difference between Big Oh, Big Omega and Big Theta
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
|
[
{
"code": null,
"e": 25667,
"s": 25639,
"text": "\n09 Oct, 2019"
},
{
"code": null,
"e": 25979,
"s": 25667,
"text": "In this article, we will see how we can solve different types of recurrence relations using different approaches. Before understanding this article, you should have idea about recurrence relations and different method to solve them (See : Worst, Average and Best Cases, Asymptotic Notations, Analysis of Loops)."
},
{
"code": null,
"e": 26116,
"s": 25979,
"text": "Type 1: Divide and conquer recurrence relations –Following are some of the examples of recurrence relations based on divide and conquer."
},
{
"code": null,
"e": 26157,
"s": 26116,
"text": "T(n) = 2T(n/2) + cn\nT(n) = 2T(n/2) + √n\n"
},
{
"code": null,
"e": 26560,
"s": 26157,
"text": "These types of recurrence relations can be easily solved using Master Method.For recurrence relation T(n) = 2T(n/2) + cn, the values of a = 2, b = 2 and k =1. Here logb(a) = log2(2) = 1 = k. Therefore, the complexity will be Θ(nlog2(n)).Similarly for recurrence relation T(n) = 2T(n/2) + √n, the values of a = 2, b = 2 and k =1/2. Here logb(a) = log2(2) = 1 > k. Therefore, the complexity will be Θ(n)."
},
{
"code": null,
"e": 26693,
"s": 26560,
"text": "Type 2: Linear recurrence relations –Following are some of the examples of recurrence relations based on linear recurrence relation."
},
{
"code": null,
"e": 26733,
"s": 26693,
"text": "T(n) = T(n-1) + n for n>0 and T(0) = 1\n"
},
{
"code": null,
"e": 26829,
"s": 26733,
"text": "These types of recurrence relations can be easily solved using substitution method.For example,"
},
{
"code": null,
"e": 26919,
"s": 26829,
"text": "T(n) = T(n-1) + n\n = T(n-2) + (n-1) + n\n = T(n-k) + (n-(k-1))..... (n-1) + n\n"
},
{
"code": null,
"e": 26946,
"s": 26919,
"text": "Substituting k = n, we get"
},
{
"code": null,
"e": 26997,
"s": 26946,
"text": "T(n) = T(0) + 1 + 2+..... +n = n(n+1)/2 = O(n^2) \n"
},
{
"code": null,
"e": 27272,
"s": 26997,
"text": "Type 3: Value substitution before solving –Sometimes, recurrence relations can’t be directly solved using techniques like substitution, recurrence tree or master method. Therefore, we need to convert the recurrence relation into appropriate form before solving. For example,"
},
{
"code": null,
"e": 27290,
"s": 27272,
"text": "T(n) = T(√n) + 1\n"
},
{
"code": null,
"e": 27347,
"s": 27290,
"text": "To solve this type of recurrence, substitute n = 2^m as:"
},
{
"code": null,
"e": 27409,
"s": 27347,
"text": "T(2^m) = T(2^m /2) + 1\nLet T(2^m) = S(m),\nS(m) = S(m/2) + 1 \n"
},
{
"code": null,
"e": 27442,
"s": 27409,
"text": "Solving by master method, we get"
},
{
"code": null,
"e": 27529,
"s": 27442,
"text": "S(m) = Θ(logm)\nAs n = 2^m or m = log2(n),\nT(n) = T(2^m) = S(m) = Θ(logm) = Θ(loglogn)\n"
},
{
"code": null,
"e": 27594,
"s": 27529,
"text": "Let us discuss some questions based on the approaches discussed."
},
{
"code": null,
"e": 27721,
"s": 27594,
"text": "Que – 1. What is the time complexity of Tower of Hanoi problem?(A) T(n) = O(sqrt(n))(D) T(n) = O(n^2)(C) T(n) = O(2^n)(D) None"
},
{
"code": null,
"e": 27806,
"s": 27721,
"text": "Solution: For Tower of Hanoi, T(n) = 2T(n-1) + c for n>1 and T(1) = 1. Solving this,"
},
{
"code": null,
"e": 27998,
"s": 27806,
"text": "T(n) = 2T(n-1) + c\n = 2(2T(n-2)+ c) + c = 2^2*T(n-2) + (c + 2c)\n = 2^k*T(n-k) + (c + 2c + .. kc)\nSubstituting k = (n-1), we get\nT(n) = 2^(n-1)*T(1) + (c + 2c + (n-1)c) = O(2^n)\n"
},
{
"code": null,
"e": 28192,
"s": 27998,
"text": "Que – 2. Consider the following recurrence:T(n) = 2 * T(ceil (sqrt(n) ) ) + 1, T(1) = 1Which one of the following is true?(A) T(n) = (loglogn)(B) T(n) = (logn)(C) T(n) = (sqrt(n))(D) T(n) = (n)"
},
{
"code": null,
"e": 28259,
"s": 28192,
"text": "Solution: To solve this type of recurrence, substitute n = 2^m as:"
},
{
"code": null,
"e": 28431,
"s": 28259,
"text": "T(2^m) = 2T(2^m /2) + 1\nLet T(2^m) = S(m),\nS(m) = 2S(m/2) + 1 \nSolving by master method, we get\nS(m) = Θ(m)\nAs n = 2^m or m = log2n,\nT(n) = T(2^m) = S(m) = Θ(m) = Θ(logn)\n"
},
{
"code": null,
"e": 28440,
"s": 28431,
"text": "Karthiik"
},
{
"code": null,
"e": 28455,
"s": 28440,
"text": "srinivasrocks7"
},
{
"code": null,
"e": 28469,
"s": 28455,
"text": "12tanmayvijay"
},
{
"code": null,
"e": 28478,
"s": 28469,
"text": "Analysis"
},
{
"code": null,
"e": 28486,
"s": 28478,
"text": "GATE CS"
},
{
"code": null,
"e": 28584,
"s": 28486,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28621,
"s": 28584,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 28661,
"s": 28621,
"text": "Analysis of Algorithms | Big-O analysis"
},
{
"code": null,
"e": 28702,
"s": 28661,
"text": "Analysis of different sorting techniques"
},
{
"code": null,
"e": 28753,
"s": 28702,
"text": "Difference between NP hard and NP complete problem"
},
{
"code": null,
"e": 28804,
"s": 28753,
"text": "Difference between Big Oh, Big Omega and Big Theta"
},
{
"code": null,
"e": 28824,
"s": 28804,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 28848,
"s": 28824,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 28861,
"s": 28848,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 28888,
"s": 28861,
"text": "Types of Operating Systems"
}
] |
Print all possible combinations of r elements in a given array of size n - GeeksforGeeks
|
19 Jan, 2022
Given an array of size n, generate and print all possible combinations of r elements in array. For example, if input array is {1, 2, 3, 4} and r is 2, then output should be {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4} and {3, 4}.Following are two methods to do this. Method 1 (Fix Elements and Recur) We create a temporary array ‘data[]’ which stores all outputs one by one. The idea is to start from first index (index = 0) in data[], one by one fix elements at this index and recur for remaining indexes. Let the input array be {1, 2, 3, 4, 5} and r be 3. We first fix 1 at index 0 in data[], then recur for remaining indexes, then we fix 2 at index 0 and recur. Finally, we fix 3 and recur for remaining indexes. When number of elements in data[] becomes equal to r (size of a combination), we print data[].Following diagram shows recursion tree for same input.
Following is implementation of above approach.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to print all combination// of size r in an array of size n#include<bits/stdc++.h>using namespace std; void combinationUtil(int arr[], int data[], int start, int end, int index, int r); // The main function that prints// all combinations of size r// in arr[] of size n. This function// mainly uses combinationUtil()void printCombination(int arr[], int n, int r){ // A temporary array to store // all combination one by one int data[r]; // Print all combination using // temporary array 'data[]' combinationUtil(arr, data, 0, n-1, 0, r);} /* arr[] ---> Input Arraydata[] ---> Temporary array tostore current combinationstart & end ---> Starting andEnding indexes in arr[]index ---> Current index in data[]r ---> Size of a combination to be printed */void combinationUtil(int arr[], int data[], int start, int end, int index, int r){ // Current combination is ready // to be printed, print it if (index == r) { for (int j = 0; j < r; j++) cout << data[j] << " "; cout << endl; return; } // replace index with all possible // elements. The condition "end-i+1 >= r-index" // makes sure that including one element // at index will make a combination with // remaining elements at remaining positions for (int i = start; i <= end && end - i + 1 >= r - index; i++) { data[index] = arr[i]; combinationUtil(arr, data, i+1, end, index+1, r); }} // Driver codeint main(){ int arr[] = {1, 2, 3, 4, 5}; int r = 3; int n = sizeof(arr)/sizeof(arr[0]); printCombination(arr, n, r);} // This code is contributed by rathbhupendra
// Program to print all combination of size r in an array of size n#include <stdio.h>void combinationUtil(int arr[], int data[], int start, int end, int index, int r); // The main function that prints all combinations of size r// in arr[] of size n. This function mainly uses combinationUtil()void printCombination(int arr[], int n, int r){ // A temporary array to store all combination one by one int data[r]; // Print all combination using temporary array 'data[]' combinationUtil(arr, data, 0, n-1, 0, r);} /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */void combinationUtil(int arr[], int data[], int start, int end, int index, int r){ // Current combination is ready to be printed, print it if (index == r) { for (int j=0; j<r; j++) printf("%d ", data[j]); printf("\n"); return; } // replace index with all possible elements. The condition // "end-i+1 >= r-index" makes sure that including one element // at index will make a combination with remaining elements // at remaining positions for (int i=start; i<=end && end-i+1 >= r-index; i++) { data[index] = arr[i]; combinationUtil(arr, data, i+1, end, index+1, r); }} // Driver program to test above functionsint main(){ int arr[] = {1, 2, 3, 4, 5}; int r = 3; int n = sizeof(arr)/sizeof(arr[0]); printCombination(arr, n, r);}
// Java program to print all combination of size r in an array of size nimport java.io.*; class Combination { /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ static void combinationUtil(int arr[], int data[], int start, int end, int index, int r) { // Current combination is ready to be printed, print it if (index == r) { for (int j=0; j<r; j++) System.out.print(data[j]+" "); System.out.println(""); return; } // replace index with all possible elements. The condition // "end-i+1 >= r-index" makes sure that including one element // at index will make a combination with remaining elements // at remaining positions for (int i=start; i<=end && end-i+1 >= r-index; i++) { data[index] = arr[i]; combinationUtil(arr, data, i+1, end, index+1, r); } } // The main function that prints all combinations of size r // in arr[] of size n. This function mainly uses combinationUtil() static void printCombination(int arr[], int n, int r) { // A temporary array to store all combination one by one int data[]=new int[r]; // Print all combination using temporary array 'data[]' combinationUtil(arr, data, 0, n-1, 0, r); } /*Driver function to check for above function*/ public static void main (String[] args) { int arr[] = {1, 2, 3, 4, 5}; int r = 3; int n = arr.length; printCombination(arr, n, r); }} /* This code is contributed by Devesh Agrawal */
# Program to print all combination# of size r in an array of size n # The main function that prints# all combinations of size r in# arr[] of size n. This function# mainly uses combinationUtil()def printCombination(arr, n, r): # A temporary array to # store all combination # one by one data = [0]*r; # Print all combination # using temporary array 'data[]' combinationUtil(arr, data, 0, n - 1, 0, r); # arr[] ---> Input Array# data[] ---> Temporary array to# store current combination# start & end ---> Starting and Ending# indexes in arr[]# index ---> Current index in data[]# r ---> Size of a combination# to be printeddef combinationUtil(arr, data, start, end, index, r): # Current combination is ready # to be printed, print it if (index == r): for j in range(r): print(data[j], end = " "); print(); return; # replace index with all # possible elements. The # condition "end-i+1 >= # r-index" makes sure that # including one element at # index will make a combination # with remaining elements at # remaining positions i = start; while(i <= end and end - i + 1 >= r - index): data[index] = arr[i]; combinationUtil(arr, data, i + 1, end, index + 1, r); i += 1; # Driver Codearr = [1, 2, 3, 4, 5];r = 3;n = len(arr);printCombination(arr, n, r); # This code is contributed by mits
// C# program to print all// combination of size r// in an array of size nusing System; class GFG{ /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ static void combinationUtil(int []arr, int []data, int start, int end, int index, int r) { // Current combination is // ready to be printed, // print it if (index == r) { for (int j = 0; j < r; j++) Console.Write(data[j] + " "); Console.WriteLine(""); return; } // replace index with all // possible elements. The // condition "end-i+1 >= // r-index" makes sure that // including one element // at index will make a // combination with remaining // elements at remaining positions for (int i = start; i <= end && end - i + 1 >= r - index; i++) { data[index] = arr[i]; combinationUtil(arr, data, i + 1, end, index + 1, r); } } // The main function that prints // all combinations of size r // in arr[] of size n. This // function mainly uses combinationUtil() static void printCombination(int []arr, int n, int r) { // A temporary array to store // all combination one by one int []data = new int[r]; // Print all combination // using temporary array 'data[]' combinationUtil(arr, data, 0, n - 1, 0, r); } // Driver Code static public void Main () { int []arr = {1, 2, 3, 4, 5}; int r = 3; int n = arr.Length; printCombination(arr, n, r); }} // This code is contributed by m_kit
<?php// Program to print all// combination of size r// in an array of size n // The main function that// prints all combinations// of size r in arr[] of// size n. This function// mainly uses combinationUtil()function printCombination($arr, $n, $r){ // A temporary array to // store all combination // one by one $data = array(); // Print all combination // using temporary array 'data[]' combinationUtil($arr, $data, 0, $n - 1, 0, $r);} /* arr[] ---> Input Arraydata[] ---> Temporary array to store current combinationstart & end ---> Starting and Ending indexes in arr[]index ---> Current index in data[]r ---> Size of a combination to be printed */function combinationUtil($arr, $data, $start, $end, $index, $r) { // Current combination is ready // to be printed, print it if ($index == $r) { for ($j = 0; $j < $r; $j++) echo $data[$j]; echo "\n"; return; } // replace index with all // possible elements. The // condition "end-i+1 >= // r-index" makes sure that // including one element at // index will make a combination // with remaining elements at // remaining positions for ($i = $start; $i <= $end && $end - $i + 1 >= $r - $index; $i++) { $data[$index] = $arr[$i]; combinationUtil($arr, $data, $i + 1, $end, $index + 1, $r); }} // Driver Code$arr = array(1, 2, 3, 4, 5);$r = 3;$n = sizeof($arr);printCombination($arr, $n, $r); // This code is contributed by ajit?>
<script> // Javascript program to print all// combination of size r in an array of size n /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ function combinationUtil(arr,data,start,end,index,r) { // Current combination is ready to be printed, print it if (index == r) { for (let j=0; j<r; j++) { document.write(data[j]+" "); } document.write("<br>") } // replace index with all possible elements. The condition // "end-i+1 >= r-index" makes sure that including one element // at index will make a combination with remaining elements // at remaining positions for (let i=start; i<=end && end-i+1 >= r-index; i++) { data[index] = arr[i]; combinationUtil(arr, data, i+1, end, index+1, r); } } // The main function that prints all combinations of size r // in arr[] of size n. This function mainly uses combinationUtil() function printCombination(arr,n,r) { // A temporary array to store all combination one by one let data = new Array(r); // Print all combination using temporary array 'data[]' combinationUtil(arr, data, 0, n-1, 0, r); } /*Driver function to check for above function*/ let arr=[1, 2, 3, 4, 5]; let r = 3; let n = arr.length; printCombination(arr, n, r); // This code is contributed by rag2127 </script>
Output:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
Time Complexity: O(n^2)
How to handle duplicates? Note that the above method doesn’t handle duplicates. For example, if input array is {1, 2, 1} and r is 2, then the program prints {1, 2} and {2, 1} as two different combinations. We can avoid duplicates by adding following two additional things to above code. 1) Add code to sort the array before calling combinationUtil() in printCombination() 2) Add following lines at the end of for loop in combinationUtil()
// Since the elements are sorted, all occurrences of an element
// must be together
while (arr[i] == arr[i+1])
i++;
See this for an implementation that handles duplicates.Method 2 (Include and Exclude every element) Like the above method, We create a temporary array data[]. The idea here is similar to Subset Sum Problem. We one by one consider every element of input array, and recur for two cases:1) The element is included in current combination (We put the element in data[] and increment next available index in data[]) 2) The element is excluded in current combination (We do not put the element and do not change index)When number of elements in data[] become equal to r (size of a combination), we print it.This method is mainly based on Pascal’s Identity, i.e. ncr = n-1cr + n-1cr-1Following is implementation of method 2.
C++
C
Java
Python 3
C#
PHP
Javascript
// C++ Program to print all combination of// size r in an array of size n#include <bits/stdc++.h>using namespace std;void combinationUtil(int arr[], int n, int r, int index, int data[], int i); // The main function that prints all// combinations of size r in arr[]// of size n. This function mainly// uses combinationUtil()void printCombination(int arr[], int n, int r){ // A temporary array to store // all combination one by one int data[r]; // Print all combination using // temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0);} /* arr[] ---> Input Arrayn ---> Size of input arrayr ---> Size of a combination to be printedindex ---> Current index in data[]data[] ---> Temporary array to store current combinationi ---> index of current element in arr[] */void combinationUtil(int arr[], int n, int r, int index, int data[], int i){ // Current combination is ready, print it if (index == r) { for (int j = 0; j < r; j++) cout << data[j] << " "; cout << endl; return; } // When no more elements are there to put in data[] if (i >= n) return; // current is included, put next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); // current is excluded, replace it with next (Note that // i+1 is passed, but index is not changed) combinationUtil(arr, n, r, index, data, i+1);} // Driver codeint main(){ int arr[] = {1, 2, 3, 4, 5}; int r = 3; int n = sizeof(arr)/sizeof(arr[0]); printCombination(arr, n, r); return 0;} // This is code is contributed by rathbhupendra
// Program to print all combination of size r in an array of size n#include<stdio.h>void combinationUtil(int arr[],int n,int r,int index,int data[],int i); // The main function that prints all combinations of size r// in arr[] of size n. This function mainly uses combinationUtil()void printCombination(int arr[], int n, int r){ // A temporary array to store all combination one by one int data[r]; // Print all combination using temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0);} /* arr[] ---> Input Array n ---> Size of input array r ---> Size of a combination to be printed index ---> Current index in data[] data[] ---> Temporary array to store current combination i ---> index of current element in arr[] */void combinationUtil(int arr[], int n, int r, int index, int data[], int i){ // Current combination is ready, print it if (index == r) { for (int j=0; j<r; j++) printf("%d ",data[j]); printf("\n"); return; } // When no more elements are there to put in data[] if (i >= n) return; // current is included, put next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index+1, data, i+1); // current is excluded, replace it with next (Note that // i+1 is passed, but index is not changed) combinationUtil(arr, n, r, index, data, i+1);} // Driver program to test above functionsint main(){ int arr[] = {1, 2, 3, 4, 5}; int r = 3; int n = sizeof(arr)/sizeof(arr[0]); printCombination(arr, n, r); return 0;}
// Java program to print all combination of size r in an array of size nimport java.io.*; class Combination { /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Staring and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ static void combinationUtil(int arr[], int n, int r, int index, int data[], int i) { // Current combination is ready to be printed, print it if (index == r) { for (int j=0; j<r; j++) System.out.print(data[j]+" "); System.out.println(""); return; } // When no more elements are there to put in data[] if (i >= n) return; // current is included, put next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index+1, data, i+1); // current is excluded, replace it with next (Note that // i+1 is passed, but index is not changed) combinationUtil(arr, n, r, index, data, i+1); } // The main function that prints all combinations of size r // in arr[] of size n. This function mainly uses combinationUtil() static void printCombination(int arr[], int n, int r) { // A temporary array to store all combination one by one int data[]=new int[r]; // Print all combination using temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } /*Driver function to check for above function*/ public static void main (String[] args) { int arr[] = {1, 2, 3, 4, 5}; int r = 3; int n = arr.length; printCombination(arr, n, r); }}/* This code is contributed by Devesh Agrawal */
# Program to print all combination# of size r in an array of size n # The main function that prints all# combinations of size r in arr[] of# size n. This function mainly uses# combinationUtil()def printCombination(arr, n, r): # A temporary array to store # all combination one by one data = [0] * r # Print all combination using # temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0) ''' arr[] ---> Input Arrayn ---> Size of input arrayr ---> Size of a combination to be printedindex ---> Current index in data[]data[] ---> Temporary array to store current combinationi ---> index of current element in arr[] '''def combinationUtil(arr, n, r, index, data, i): # Current combination is ready, # print it if (index == r): for j in range(r): print(data[j], end = " ") print() return # When no more elements are # there to put in data[] if (i >= n): return # current is included, put # next at next location data[index] = arr[i] combinationUtil(arr, n, r, index + 1, data, i + 1) # current is excluded, replace it # with next (Note that i+1 is passed, # but index is not changed) combinationUtil(arr, n, r, index, data, i + 1) # Driver Codeif __name__ == "__main__": arr = [1, 2, 3, 4, 5] r = 3 n = len(arr) printCombination(arr, n, r) # This code is contributed# by ChitraNayal
// C# program to print all// combination of size r// in an array of size nusing System; class GFG{ /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ static void combinationUtil(int []arr, int n, int r, int index, int []data, int i) { // Current combination is ready // to be printed, print it if (index == r) { for (int j = 0; j < r; j++) Console.Write(data[j] + " "); Console.WriteLine(""); return; } // When no more elements are // there to put in data[] if (i >= n) return; // current is included, put // next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); // current is excluded, replace // it with next (Note that // i+1 is passed, but index // is not changed) combinationUtil(arr, n, r, index, data, i + 1); } // The main function that prints // all combinations of size r // in arr[] of size n. This // function mainly uses combinationUtil() static void printCombination(int []arr, int n, int r) { // A temporary array to store // all combination one by one int []data = new int[r]; // Print all combination // using temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } // Driver Code static public void Main () { int []arr = {1, 2, 3, 4, 5}; int r = 3; int n = arr.Length; printCombination(arr, n, r); }} // This code is contributed by ajit
<?php// Program to print all// combination of size r// in an array of size n // The main function that prints// all combinations of size r in// arr[] of size n. This function// mainly uses combinationUtil()function printCombination($arr, $n, $r){ // A temporary array to store // all combination one by one $data = Array(); // Print all combination using // temporary array 'data[]' combinationUtil($arr, $n, $r, 0, $data, 0);} /* arr[] ---> Input Arrayn ---> Size of input arrayr ---> Size of a combination to be printedindex ---> Current index in data[]data[] ---> Temporary array to store current combinationi ---> index of current element in arr[] */function combinationUtil($arr, $n, $r, $index, $data, $i){ // Current combination // is ready, print it if ($index == $r) { for ($j = 0; $j < $r; $j++) echo $data[$j], " "; echo "\n"; return; } // When no more elements are // there to put in data[] if ($i >= $n) return; // current is included, put // next at next location $data[$index] = $arr[$i]; combinationUtil($arr, $n, $r, $index + 1, $data, $i + 1); // current is excluded, replace // it with next (Note that i+1 // is passed, but index is not changed) combinationUtil($arr, $n, $r, $index, $data, $i + 1);} // Driver Code$arr = array(1, 2, 3, 4, 5);$r = 3;$n = sizeof($arr);printCombination($arr, $n, $r); // This code is contributed by ajit?>
<script> // Javascript program to print all// combination of size r in an array of size n /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ function combinationUtil(arr,n,r,index,data,i) { // Current combination is ready // to be printed, print it if (index == r) { for (let j=0; j<r; j++) { document.write(data[j]+" "); } document.write("<br>"); return; } // When no more elements are there // to put in data[] if (i >= n) { return; } // current is included, put // next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index+1, data, i+1); // current is excluded, replace // it with next (Note that // i+1 is passed, but index is not changed) combinationUtil(arr, n, r, index, data, i+1); } // The main function that prints // all combinations of size r // in arr[] of size n. This function // mainly uses combinationUtil() function printCombination(arr,n,r) { // A temporary array to store // all combination one by one let data=new Array(r); // Print all combination using // temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } /*Driver function to check for above function*/ let arr=[1, 2, 3, 4, 5]; let r = 3; let n = arr.length; printCombination(arr, n, r); // This code is contributed by avanitrachhadiya2155 </script>
Output :
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
How to handle duplicates in method 2? Like method 1, we can following two things to handle duplicates. 1) Add code to sort the array before calling combinationUtil() in printCombination() 2) Add following lines between two recursive calls of combinationUtil() in combinationUtil()
// Since the elements are sorted, all occurrences of an element
// must be together
while (arr[i] == arr[i+1])
i++;
See this for an implementation that handles duplicates.Below is another DFS based approach to solve this problem. Make all combinations of size kThis article is contributed by Bateesh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
jit_t
DavidXiaohaiYu
Mithun Kumar
ukasp
rathbhupendra
ritikagarwal470
rag2127
avanitrachhadiya2155
surindertarika1234
surinderdawra388
subhammahato348
akshaysingh98088
squishoberry
khushboogoyal499
Mathematical
Recursion
Mathematical
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
The Knight's tour problem | Backtracking-1
Operators in C / C++
Program for factorial of a number
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction
Program for Sum of the digits of a given number
|
[
{
"code": null,
"e": 26063,
"s": 26035,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 26924,
"s": 26063,
"text": "Given an array of size n, generate and print all possible combinations of r elements in array. For example, if input array is {1, 2, 3, 4} and r is 2, then output should be {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4} and {3, 4}.Following are two methods to do this. Method 1 (Fix Elements and Recur) We create a temporary array ‘data[]’ which stores all outputs one by one. The idea is to start from first index (index = 0) in data[], one by one fix elements at this index and recur for remaining indexes. Let the input array be {1, 2, 3, 4, 5} and r be 3. We first fix 1 at index 0 in data[], then recur for remaining indexes, then we fix 2 at index 0 and recur. Finally, we fix 3 and recur for remaining indexes. When number of elements in data[] becomes equal to r (size of a combination), we print data[].Following diagram shows recursion tree for same input. "
},
{
"code": null,
"e": 26975,
"s": 26926,
"text": "Following is implementation of above approach. "
},
{
"code": null,
"e": 26979,
"s": 26975,
"text": "C++"
},
{
"code": null,
"e": 26981,
"s": 26979,
"text": "C"
},
{
"code": null,
"e": 26986,
"s": 26981,
"text": "Java"
},
{
"code": null,
"e": 26994,
"s": 26986,
"text": "Python3"
},
{
"code": null,
"e": 26997,
"s": 26994,
"text": "C#"
},
{
"code": null,
"e": 27001,
"s": 26997,
"text": "PHP"
},
{
"code": null,
"e": 27012,
"s": 27001,
"text": "Javascript"
},
{
"code": "// C++ program to print all combination// of size r in an array of size n#include<bits/stdc++.h>using namespace std; void combinationUtil(int arr[], int data[], int start, int end, int index, int r); // The main function that prints// all combinations of size r// in arr[] of size n. This function// mainly uses combinationUtil()void printCombination(int arr[], int n, int r){ // A temporary array to store // all combination one by one int data[r]; // Print all combination using // temporary array 'data[]' combinationUtil(arr, data, 0, n-1, 0, r);} /* arr[] ---> Input Arraydata[] ---> Temporary array tostore current combinationstart & end ---> Starting andEnding indexes in arr[]index ---> Current index in data[]r ---> Size of a combination to be printed */void combinationUtil(int arr[], int data[], int start, int end, int index, int r){ // Current combination is ready // to be printed, print it if (index == r) { for (int j = 0; j < r; j++) cout << data[j] << \" \"; cout << endl; return; } // replace index with all possible // elements. The condition \"end-i+1 >= r-index\" // makes sure that including one element // at index will make a combination with // remaining elements at remaining positions for (int i = start; i <= end && end - i + 1 >= r - index; i++) { data[index] = arr[i]; combinationUtil(arr, data, i+1, end, index+1, r); }} // Driver codeint main(){ int arr[] = {1, 2, 3, 4, 5}; int r = 3; int n = sizeof(arr)/sizeof(arr[0]); printCombination(arr, n, r);} // This code is contributed by rathbhupendra",
"e": 28761,
"s": 27012,
"text": null
},
{
"code": "// Program to print all combination of size r in an array of size n#include <stdio.h>void combinationUtil(int arr[], int data[], int start, int end, int index, int r); // The main function that prints all combinations of size r// in arr[] of size n. This function mainly uses combinationUtil()void printCombination(int arr[], int n, int r){ // A temporary array to store all combination one by one int data[r]; // Print all combination using temporary array 'data[]' combinationUtil(arr, data, 0, n-1, 0, r);} /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */void combinationUtil(int arr[], int data[], int start, int end, int index, int r){ // Current combination is ready to be printed, print it if (index == r) { for (int j=0; j<r; j++) printf(\"%d \", data[j]); printf(\"\\n\"); return; } // replace index with all possible elements. The condition // \"end-i+1 >= r-index\" makes sure that including one element // at index will make a combination with remaining elements // at remaining positions for (int i=start; i<=end && end-i+1 >= r-index; i++) { data[index] = arr[i]; combinationUtil(arr, data, i+1, end, index+1, r); }} // Driver program to test above functionsint main(){ int arr[] = {1, 2, 3, 4, 5}; int r = 3; int n = sizeof(arr)/sizeof(arr[0]); printCombination(arr, n, r);}",
"e": 30368,
"s": 28761,
"text": null
},
{
"code": "// Java program to print all combination of size r in an array of size nimport java.io.*; class Combination { /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ static void combinationUtil(int arr[], int data[], int start, int end, int index, int r) { // Current combination is ready to be printed, print it if (index == r) { for (int j=0; j<r; j++) System.out.print(data[j]+\" \"); System.out.println(\"\"); return; } // replace index with all possible elements. The condition // \"end-i+1 >= r-index\" makes sure that including one element // at index will make a combination with remaining elements // at remaining positions for (int i=start; i<=end && end-i+1 >= r-index; i++) { data[index] = arr[i]; combinationUtil(arr, data, i+1, end, index+1, r); } } // The main function that prints all combinations of size r // in arr[] of size n. This function mainly uses combinationUtil() static void printCombination(int arr[], int n, int r) { // A temporary array to store all combination one by one int data[]=new int[r]; // Print all combination using temporary array 'data[]' combinationUtil(arr, data, 0, n-1, 0, r); } /*Driver function to check for above function*/ public static void main (String[] args) { int arr[] = {1, 2, 3, 4, 5}; int r = 3; int n = arr.length; printCombination(arr, n, r); }} /* This code is contributed by Devesh Agrawal */",
"e": 32171,
"s": 30368,
"text": null
},
{
"code": "# Program to print all combination# of size r in an array of size n # The main function that prints# all combinations of size r in# arr[] of size n. This function# mainly uses combinationUtil()def printCombination(arr, n, r): # A temporary array to # store all combination # one by one data = [0]*r; # Print all combination # using temporary array 'data[]' combinationUtil(arr, data, 0, n - 1, 0, r); # arr[] ---> Input Array# data[] ---> Temporary array to# store current combination# start & end ---> Starting and Ending# indexes in arr[]# index ---> Current index in data[]# r ---> Size of a combination# to be printeddef combinationUtil(arr, data, start, end, index, r): # Current combination is ready # to be printed, print it if (index == r): for j in range(r): print(data[j], end = \" \"); print(); return; # replace index with all # possible elements. The # condition \"end-i+1 >= # r-index\" makes sure that # including one element at # index will make a combination # with remaining elements at # remaining positions i = start; while(i <= end and end - i + 1 >= r - index): data[index] = arr[i]; combinationUtil(arr, data, i + 1, end, index + 1, r); i += 1; # Driver Codearr = [1, 2, 3, 4, 5];r = 3;n = len(arr);printCombination(arr, n, r); # This code is contributed by mits",
"e": 33679,
"s": 32171,
"text": null
},
{
"code": "// C# program to print all// combination of size r// in an array of size nusing System; class GFG{ /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ static void combinationUtil(int []arr, int []data, int start, int end, int index, int r) { // Current combination is // ready to be printed, // print it if (index == r) { for (int j = 0; j < r; j++) Console.Write(data[j] + \" \"); Console.WriteLine(\"\"); return; } // replace index with all // possible elements. The // condition \"end-i+1 >= // r-index\" makes sure that // including one element // at index will make a // combination with remaining // elements at remaining positions for (int i = start; i <= end && end - i + 1 >= r - index; i++) { data[index] = arr[i]; combinationUtil(arr, data, i + 1, end, index + 1, r); } } // The main function that prints // all combinations of size r // in arr[] of size n. This // function mainly uses combinationUtil() static void printCombination(int []arr, int n, int r) { // A temporary array to store // all combination one by one int []data = new int[r]; // Print all combination // using temporary array 'data[]' combinationUtil(arr, data, 0, n - 1, 0, r); } // Driver Code static public void Main () { int []arr = {1, 2, 3, 4, 5}; int r = 3; int n = arr.Length; printCombination(arr, n, r); }} // This code is contributed by m_kit",
"e": 35701,
"s": 33679,
"text": null
},
{
"code": "<?php// Program to print all// combination of size r// in an array of size n // The main function that// prints all combinations// of size r in arr[] of// size n. This function// mainly uses combinationUtil()function printCombination($arr, $n, $r){ // A temporary array to // store all combination // one by one $data = array(); // Print all combination // using temporary array 'data[]' combinationUtil($arr, $data, 0, $n - 1, 0, $r);} /* arr[] ---> Input Arraydata[] ---> Temporary array to store current combinationstart & end ---> Starting and Ending indexes in arr[]index ---> Current index in data[]r ---> Size of a combination to be printed */function combinationUtil($arr, $data, $start, $end, $index, $r) { // Current combination is ready // to be printed, print it if ($index == $r) { for ($j = 0; $j < $r; $j++) echo $data[$j]; echo \"\\n\"; return; } // replace index with all // possible elements. The // condition \"end-i+1 >= // r-index\" makes sure that // including one element at // index will make a combination // with remaining elements at // remaining positions for ($i = $start; $i <= $end && $end - $i + 1 >= $r - $index; $i++) { $data[$index] = $arr[$i]; combinationUtil($arr, $data, $i + 1, $end, $index + 1, $r); }} // Driver Code$arr = array(1, 2, 3, 4, 5);$r = 3;$n = sizeof($arr);printCombination($arr, $n, $r); // This code is contributed by ajit?>",
"e": 37349,
"s": 35701,
"text": null
},
{
"code": "<script> // Javascript program to print all// combination of size r in an array of size n /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ function combinationUtil(arr,data,start,end,index,r) { // Current combination is ready to be printed, print it if (index == r) { for (let j=0; j<r; j++) { document.write(data[j]+\" \"); } document.write(\"<br>\") } // replace index with all possible elements. The condition // \"end-i+1 >= r-index\" makes sure that including one element // at index will make a combination with remaining elements // at remaining positions for (let i=start; i<=end && end-i+1 >= r-index; i++) { data[index] = arr[i]; combinationUtil(arr, data, i+1, end, index+1, r); } } // The main function that prints all combinations of size r // in arr[] of size n. This function mainly uses combinationUtil() function printCombination(arr,n,r) { // A temporary array to store all combination one by one let data = new Array(r); // Print all combination using temporary array 'data[]' combinationUtil(arr, data, 0, n-1, 0, r); } /*Driver function to check for above function*/ let arr=[1, 2, 3, 4, 5]; let r = 3; let n = arr.length; printCombination(arr, n, r); // This code is contributed by rag2127 </script>",
"e": 39024,
"s": 37349,
"text": null
},
{
"code": null,
"e": 39033,
"s": 39024,
"text": "Output: "
},
{
"code": null,
"e": 39093,
"s": 39033,
"text": "1 2 3\n1 2 4\n1 2 5\n1 3 4\n1 3 5\n1 4 5\n2 3 4\n2 3 5\n2 4 5\n3 4 5"
},
{
"code": null,
"e": 39117,
"s": 39093,
"text": "Time Complexity: O(n^2)"
},
{
"code": null,
"e": 39558,
"s": 39117,
"text": "How to handle duplicates? Note that the above method doesn’t handle duplicates. For example, if input array is {1, 2, 1} and r is 2, then the program prints {1, 2} and {2, 1} as two different combinations. We can avoid duplicates by adding following two additional things to above code. 1) Add code to sort the array before calling combinationUtil() in printCombination() 2) Add following lines at the end of for loop in combinationUtil() "
},
{
"code": null,
"e": 39712,
"s": 39558,
"text": " // Since the elements are sorted, all occurrences of an element\n // must be together\n while (arr[i] == arr[i+1])\n i++; "
},
{
"code": null,
"e": 40431,
"s": 39712,
"text": "See this for an implementation that handles duplicates.Method 2 (Include and Exclude every element) Like the above method, We create a temporary array data[]. The idea here is similar to Subset Sum Problem. We one by one consider every element of input array, and recur for two cases:1) The element is included in current combination (We put the element in data[] and increment next available index in data[]) 2) The element is excluded in current combination (We do not put the element and do not change index)When number of elements in data[] become equal to r (size of a combination), we print it.This method is mainly based on Pascal’s Identity, i.e. ncr = n-1cr + n-1cr-1Following is implementation of method 2. "
},
{
"code": null,
"e": 40435,
"s": 40431,
"text": "C++"
},
{
"code": null,
"e": 40437,
"s": 40435,
"text": "C"
},
{
"code": null,
"e": 40442,
"s": 40437,
"text": "Java"
},
{
"code": null,
"e": 40451,
"s": 40442,
"text": "Python 3"
},
{
"code": null,
"e": 40454,
"s": 40451,
"text": "C#"
},
{
"code": null,
"e": 40458,
"s": 40454,
"text": "PHP"
},
{
"code": null,
"e": 40469,
"s": 40458,
"text": "Javascript"
},
{
"code": "// C++ Program to print all combination of// size r in an array of size n#include <bits/stdc++.h>using namespace std;void combinationUtil(int arr[], int n, int r, int index, int data[], int i); // The main function that prints all// combinations of size r in arr[]// of size n. This function mainly// uses combinationUtil()void printCombination(int arr[], int n, int r){ // A temporary array to store // all combination one by one int data[r]; // Print all combination using // temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0);} /* arr[] ---> Input Arrayn ---> Size of input arrayr ---> Size of a combination to be printedindex ---> Current index in data[]data[] ---> Temporary array to store current combinationi ---> index of current element in arr[] */void combinationUtil(int arr[], int n, int r, int index, int data[], int i){ // Current combination is ready, print it if (index == r) { for (int j = 0; j < r; j++) cout << data[j] << \" \"; cout << endl; return; } // When no more elements are there to put in data[] if (i >= n) return; // current is included, put next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); // current is excluded, replace it with next (Note that // i+1 is passed, but index is not changed) combinationUtil(arr, n, r, index, data, i+1);} // Driver codeint main(){ int arr[] = {1, 2, 3, 4, 5}; int r = 3; int n = sizeof(arr)/sizeof(arr[0]); printCombination(arr, n, r); return 0;} // This is code is contributed by rathbhupendra",
"e": 42135,
"s": 40469,
"text": null
},
{
"code": "// Program to print all combination of size r in an array of size n#include<stdio.h>void combinationUtil(int arr[],int n,int r,int index,int data[],int i); // The main function that prints all combinations of size r// in arr[] of size n. This function mainly uses combinationUtil()void printCombination(int arr[], int n, int r){ // A temporary array to store all combination one by one int data[r]; // Print all combination using temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0);} /* arr[] ---> Input Array n ---> Size of input array r ---> Size of a combination to be printed index ---> Current index in data[] data[] ---> Temporary array to store current combination i ---> index of current element in arr[] */void combinationUtil(int arr[], int n, int r, int index, int data[], int i){ // Current combination is ready, print it if (index == r) { for (int j=0; j<r; j++) printf(\"%d \",data[j]); printf(\"\\n\"); return; } // When no more elements are there to put in data[] if (i >= n) return; // current is included, put next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index+1, data, i+1); // current is excluded, replace it with next (Note that // i+1 is passed, but index is not changed) combinationUtil(arr, n, r, index, data, i+1);} // Driver program to test above functionsint main(){ int arr[] = {1, 2, 3, 4, 5}; int r = 3; int n = sizeof(arr)/sizeof(arr[0]); printCombination(arr, n, r); return 0;}",
"e": 43715,
"s": 42135,
"text": null
},
{
"code": "// Java program to print all combination of size r in an array of size nimport java.io.*; class Combination { /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Staring and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ static void combinationUtil(int arr[], int n, int r, int index, int data[], int i) { // Current combination is ready to be printed, print it if (index == r) { for (int j=0; j<r; j++) System.out.print(data[j]+\" \"); System.out.println(\"\"); return; } // When no more elements are there to put in data[] if (i >= n) return; // current is included, put next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index+1, data, i+1); // current is excluded, replace it with next (Note that // i+1 is passed, but index is not changed) combinationUtil(arr, n, r, index, data, i+1); } // The main function that prints all combinations of size r // in arr[] of size n. This function mainly uses combinationUtil() static void printCombination(int arr[], int n, int r) { // A temporary array to store all combination one by one int data[]=new int[r]; // Print all combination using temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } /*Driver function to check for above function*/ public static void main (String[] args) { int arr[] = {1, 2, 3, 4, 5}; int r = 3; int n = arr.length; printCombination(arr, n, r); }}/* This code is contributed by Devesh Agrawal */",
"e": 45500,
"s": 43715,
"text": null
},
{
"code": "# Program to print all combination# of size r in an array of size n # The main function that prints all# combinations of size r in arr[] of# size n. This function mainly uses# combinationUtil()def printCombination(arr, n, r): # A temporary array to store # all combination one by one data = [0] * r # Print all combination using # temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0) ''' arr[] ---> Input Arrayn ---> Size of input arrayr ---> Size of a combination to be printedindex ---> Current index in data[]data[] ---> Temporary array to store current combinationi ---> index of current element in arr[] '''def combinationUtil(arr, n, r, index, data, i): # Current combination is ready, # print it if (index == r): for j in range(r): print(data[j], end = \" \") print() return # When no more elements are # there to put in data[] if (i >= n): return # current is included, put # next at next location data[index] = arr[i] combinationUtil(arr, n, r, index + 1, data, i + 1) # current is excluded, replace it # with next (Note that i+1 is passed, # but index is not changed) combinationUtil(arr, n, r, index, data, i + 1) # Driver Codeif __name__ == \"__main__\": arr = [1, 2, 3, 4, 5] r = 3 n = len(arr) printCombination(arr, n, r) # This code is contributed# by ChitraNayal",
"e": 46968,
"s": 45500,
"text": null
},
{
"code": "// C# program to print all// combination of size r// in an array of size nusing System; class GFG{ /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ static void combinationUtil(int []arr, int n, int r, int index, int []data, int i) { // Current combination is ready // to be printed, print it if (index == r) { for (int j = 0; j < r; j++) Console.Write(data[j] + \" \"); Console.WriteLine(\"\"); return; } // When no more elements are // there to put in data[] if (i >= n) return; // current is included, put // next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index + 1, data, i + 1); // current is excluded, replace // it with next (Note that // i+1 is passed, but index // is not changed) combinationUtil(arr, n, r, index, data, i + 1); } // The main function that prints // all combinations of size r // in arr[] of size n. This // function mainly uses combinationUtil() static void printCombination(int []arr, int n, int r) { // A temporary array to store // all combination one by one int []data = new int[r]; // Print all combination // using temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } // Driver Code static public void Main () { int []arr = {1, 2, 3, 4, 5}; int r = 3; int n = arr.Length; printCombination(arr, n, r); }} // This code is contributed by ajit",
"e": 48944,
"s": 46968,
"text": null
},
{
"code": "<?php// Program to print all// combination of size r// in an array of size n // The main function that prints// all combinations of size r in// arr[] of size n. This function// mainly uses combinationUtil()function printCombination($arr, $n, $r){ // A temporary array to store // all combination one by one $data = Array(); // Print all combination using // temporary array 'data[]' combinationUtil($arr, $n, $r, 0, $data, 0);} /* arr[] ---> Input Arrayn ---> Size of input arrayr ---> Size of a combination to be printedindex ---> Current index in data[]data[] ---> Temporary array to store current combinationi ---> index of current element in arr[] */function combinationUtil($arr, $n, $r, $index, $data, $i){ // Current combination // is ready, print it if ($index == $r) { for ($j = 0; $j < $r; $j++) echo $data[$j], \" \"; echo \"\\n\"; return; } // When no more elements are // there to put in data[] if ($i >= $n) return; // current is included, put // next at next location $data[$index] = $arr[$i]; combinationUtil($arr, $n, $r, $index + 1, $data, $i + 1); // current is excluded, replace // it with next (Note that i+1 // is passed, but index is not changed) combinationUtil($arr, $n, $r, $index, $data, $i + 1);} // Driver Code$arr = array(1, 2, 3, 4, 5);$r = 3;$n = sizeof($arr);printCombination($arr, $n, $r); // This code is contributed by ajit?>",
"e": 50527,
"s": 48944,
"text": null
},
{
"code": "<script> // Javascript program to print all// combination of size r in an array of size n /* arr[] ---> Input Array data[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] index ---> Current index in data[] r ---> Size of a combination to be printed */ function combinationUtil(arr,n,r,index,data,i) { // Current combination is ready // to be printed, print it if (index == r) { for (let j=0; j<r; j++) { document.write(data[j]+\" \"); } document.write(\"<br>\"); return; } // When no more elements are there // to put in data[] if (i >= n) { return; } // current is included, put // next at next location data[index] = arr[i]; combinationUtil(arr, n, r, index+1, data, i+1); // current is excluded, replace // it with next (Note that // i+1 is passed, but index is not changed) combinationUtil(arr, n, r, index, data, i+1); } // The main function that prints // all combinations of size r // in arr[] of size n. This function // mainly uses combinationUtil() function printCombination(arr,n,r) { // A temporary array to store // all combination one by one let data=new Array(r); // Print all combination using // temporary array 'data[]' combinationUtil(arr, n, r, 0, data, 0); } /*Driver function to check for above function*/ let arr=[1, 2, 3, 4, 5]; let r = 3; let n = arr.length; printCombination(arr, n, r); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 52348,
"s": 50527,
"text": null
},
{
"code": null,
"e": 52358,
"s": 52348,
"text": "Output : "
},
{
"code": null,
"e": 52418,
"s": 52358,
"text": "1 2 3\n1 2 4\n1 2 5\n1 3 4\n1 3 5\n1 4 5\n2 3 4\n2 3 5\n2 4 5\n3 4 5"
},
{
"code": null,
"e": 52701,
"s": 52418,
"text": "How to handle duplicates in method 2? Like method 1, we can following two things to handle duplicates. 1) Add code to sort the array before calling combinationUtil() in printCombination() 2) Add following lines between two recursive calls of combinationUtil() in combinationUtil() "
},
{
"code": null,
"e": 52855,
"s": 52701,
"text": " // Since the elements are sorted, all occurrences of an element\n // must be together\n while (arr[i] == arr[i+1])\n i++; "
},
{
"code": null,
"e": 53165,
"s": 52855,
"text": "See this for an implementation that handles duplicates.Below is another DFS based approach to solve this problem. Make all combinations of size kThis article is contributed by Bateesh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 53171,
"s": 53165,
"text": "jit_t"
},
{
"code": null,
"e": 53186,
"s": 53171,
"text": "DavidXiaohaiYu"
},
{
"code": null,
"e": 53199,
"s": 53186,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 53205,
"s": 53199,
"text": "ukasp"
},
{
"code": null,
"e": 53219,
"s": 53205,
"text": "rathbhupendra"
},
{
"code": null,
"e": 53235,
"s": 53219,
"text": "ritikagarwal470"
},
{
"code": null,
"e": 53243,
"s": 53235,
"text": "rag2127"
},
{
"code": null,
"e": 53264,
"s": 53243,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 53283,
"s": 53264,
"text": "surindertarika1234"
},
{
"code": null,
"e": 53300,
"s": 53283,
"text": "surinderdawra388"
},
{
"code": null,
"e": 53316,
"s": 53300,
"text": "subhammahato348"
},
{
"code": null,
"e": 53333,
"s": 53316,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 53346,
"s": 53333,
"text": "squishoberry"
},
{
"code": null,
"e": 53363,
"s": 53346,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 53376,
"s": 53363,
"text": "Mathematical"
},
{
"code": null,
"e": 53386,
"s": 53376,
"text": "Recursion"
},
{
"code": null,
"e": 53399,
"s": 53386,
"text": "Mathematical"
},
{
"code": null,
"e": 53409,
"s": 53399,
"text": "Recursion"
},
{
"code": null,
"e": 53507,
"s": 53409,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 53531,
"s": 53507,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 53574,
"s": 53531,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 53617,
"s": 53574,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 53638,
"s": 53617,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 53672,
"s": 53638,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 53757,
"s": 53672,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 53767,
"s": 53757,
"text": "Recursion"
},
{
"code": null,
"e": 53794,
"s": 53767,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 53822,
"s": 53794,
"text": "Backtracking | Introduction"
}
] |
Stack remove(Object) method in Java with Example - GeeksforGeeks
|
24 Dec, 2018
The Java.util.Stack.remove(Object o) method is used to remove any particular element from the Stack.
Syntax:
Stack.remove(Object o)
Parameters: This method accepts a mandatory parameter o is of the object type of Stack and specifies the element to be removed from the Stack.
Return Value: Returns True if the specified element is found and removed from the Stack, else False.
Below program illustrate the Java.util.Stack.remove(Object o) method:
Example 1:
// Java code to illustrate remove() when position of// element is passed as parameter import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements in the Stack stack.add("Geeks"); stack.add("for"); stack.add("Geeks"); stack.add("10"); stack.add("20"); // Output the Stack System.out.println("Stack: " + stack); // Remove the element using remove() boolean res = stack.remove("20"); // Print the removed element System.out.println("Was 20 removed: " + res); // Print the final Stack System.out.println("Final Stack: " + stack); }}
Stack: [Geeks, for, Geeks, 10, 20]
Was 20 removed: true
Final Stack: [Geeks, for, Geeks, 10]
Example 2:
// Java code to illustrate remove() when position of// element is passed as parameter import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method to add elements in the Stack stack.add(10); stack.add(20); stack.add(30); stack.add(40); stack.add(50); // Output the Stack System.out.println("Stack: " + stack); // Remove the element using remove() boolean res = stack.remove("100"); // Print the removed element System.out.println("Was 100 removed: " + res); // Print the final Stack System.out.println("Final Stack: " + stack); }}
Stack: [10, 20, 30, 40, 50]
Was 100 removed: false
Final Stack: [10, 20, 30, 40, 50]
Java - util package
Java-Collections
Java-Functions
Java-Stack
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples
Reverse a string in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
|
[
{
"code": null,
"e": 25695,
"s": 25667,
"text": "\n24 Dec, 2018"
},
{
"code": null,
"e": 25796,
"s": 25695,
"text": "The Java.util.Stack.remove(Object o) method is used to remove any particular element from the Stack."
},
{
"code": null,
"e": 25804,
"s": 25796,
"text": "Syntax:"
},
{
"code": null,
"e": 25827,
"s": 25804,
"text": "Stack.remove(Object o)"
},
{
"code": null,
"e": 25970,
"s": 25827,
"text": "Parameters: This method accepts a mandatory parameter o is of the object type of Stack and specifies the element to be removed from the Stack."
},
{
"code": null,
"e": 26071,
"s": 25970,
"text": "Return Value: Returns True if the specified element is found and removed from the Stack, else False."
},
{
"code": null,
"e": 26141,
"s": 26071,
"text": "Below program illustrate the Java.util.Stack.remove(Object o) method:"
},
{
"code": null,
"e": 26152,
"s": 26141,
"text": "Example 1:"
},
{
"code": "// Java code to illustrate remove() when position of// element is passed as parameter import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements in the Stack stack.add(\"Geeks\"); stack.add(\"for\"); stack.add(\"Geeks\"); stack.add(\"10\"); stack.add(\"20\"); // Output the Stack System.out.println(\"Stack: \" + stack); // Remove the element using remove() boolean res = stack.remove(\"20\"); // Print the removed element System.out.println(\"Was 20 removed: \" + res); // Print the final Stack System.out.println(\"Final Stack: \" + stack); }}",
"e": 27000,
"s": 26152,
"text": null
},
{
"code": null,
"e": 27094,
"s": 27000,
"text": "Stack: [Geeks, for, Geeks, 10, 20]\nWas 20 removed: true\nFinal Stack: [Geeks, for, Geeks, 10]\n"
},
{
"code": null,
"e": 27105,
"s": 27094,
"text": "Example 2:"
},
{
"code": "// Java code to illustrate remove() when position of// element is passed as parameter import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method to add elements in the Stack stack.add(10); stack.add(20); stack.add(30); stack.add(40); stack.add(50); // Output the Stack System.out.println(\"Stack: \" + stack); // Remove the element using remove() boolean res = stack.remove(\"100\"); // Print the removed element System.out.println(\"Was 100 removed: \" + res); // Print the final Stack System.out.println(\"Final Stack: \" + stack); }}",
"e": 27940,
"s": 27105,
"text": null
},
{
"code": null,
"e": 28026,
"s": 27940,
"text": "Stack: [10, 20, 30, 40, 50]\nWas 100 removed: false\nFinal Stack: [10, 20, 30, 40, 50]\n"
},
{
"code": null,
"e": 28046,
"s": 28026,
"text": "Java - util package"
},
{
"code": null,
"e": 28063,
"s": 28046,
"text": "Java-Collections"
},
{
"code": null,
"e": 28078,
"s": 28063,
"text": "Java-Functions"
},
{
"code": null,
"e": 28089,
"s": 28078,
"text": "Java-Stack"
},
{
"code": null,
"e": 28094,
"s": 28089,
"text": "Java"
},
{
"code": null,
"e": 28099,
"s": 28094,
"text": "Java"
},
{
"code": null,
"e": 28116,
"s": 28099,
"text": "Java-Collections"
},
{
"code": null,
"e": 28214,
"s": 28116,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28229,
"s": 28214,
"text": "Arrays in Java"
},
{
"code": null,
"e": 28273,
"s": 28229,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 28295,
"s": 28273,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 28346,
"s": 28295,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28382,
"s": 28346,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 28407,
"s": 28382,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 28437,
"s": 28407,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28456,
"s": 28437,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28471,
"s": 28456,
"text": "Stream In Java"
}
] |
How to make a leaderboard using PHP ? - GeeksforGeeks
|
28 Dec, 2020
The purpose of this article is to make a simple program to create a leaderboard using PHP. Below is the implementation for the same using PHP. The prerequisites of this topic are PHP/MySQL and the installment of Apache Server on your computer.
Approach:
Step 1: First we will create a HTML table using <table> tag defined by the <tr> tag for creating rows. It’s just a simple HTML/CSS file. The only thing worth noting is that we are using the Bootstrap 4 CSS framework to give style to our page. You can use any other styling framework of your choice or write your own CSS if you want.
HTML
<!DOCTYPE html><html> <head> <title>LeaderBoard Using PHP</title> </head> <body> <h2>Welcome To GFG</h2> <table> <tr> <td>Ranking</td> <td>UserName</td> <td>Marks</td> </tr>
Step 2: Fetch data from SQL and display it using PHP.
Step 3: Create a MySQL database by following commands.
CREATE DATABASE leaderboard;
CREATE TABLE leaderboard(userName VARCHAR(30), marks INT(10));
Step 4: Insert some values into the database.
INSERT INTO leaderboard(userName,marks) VALUES('Devesh Pratap Singh',100);
PHP
<?php /* Connection Variable ("Servername","username","password","database") */$con = mysqli_connect("localhost", "root", "", "leaderboard"); /* Mysqli query to fetch rows in descending order of marks */$result = mysqli_query($con, "SELECT userName, marks FROM leaderboard ORDER BY marks DESC"); /* First rank will be 1 and second be 2 and so on */$ranking = 1; /* Fetch Rows from the SQL query */if (mysqli_num_rows($result)) { while ($row = mysqli_fetch_array($result)) { echo "<td>{$ranking}</td> <td>{$row['userName']}</td> <td>{$row['marks']}</td>"; $ranking++; }}?>
Step 5: Close the table tag, body tag, and html tag.
HTML
</table></body></html>
Step 6: Save this file as “index.php“.
Step 7: Copy this file inside your xampp server in htdocs directory.
Step 8: Open phpMyAdmin or MySQL server on your computer.
Step 9: Open https://localhost/index.php into your web browser.
Output produced after running
HTML-Misc
mysql
PHP-array
PHP-Misc
Picked
HTML
PHP
SQL
Web Technologies
SQL
HTML
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
How to execute PHP code using command line ?
How to convert array to string in PHP ?
How to pop an alert message box using PHP ?
PHP in_array() Function
How to delete an array element based on key in PHP?
|
[
{
"code": null,
"e": 26375,
"s": 26347,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 26620,
"s": 26375,
"text": "The purpose of this article is to make a simple program to create a leaderboard using PHP. Below is the implementation for the same using PHP. The prerequisites of this topic are PHP/MySQL and the installment of Apache Server on your computer."
},
{
"code": null,
"e": 26630,
"s": 26620,
"text": "Approach:"
},
{
"code": null,
"e": 26963,
"s": 26630,
"text": "Step 1: First we will create a HTML table using <table> tag defined by the <tr> tag for creating rows. It’s just a simple HTML/CSS file. The only thing worth noting is that we are using the Bootstrap 4 CSS framework to give style to our page. You can use any other styling framework of your choice or write your own CSS if you want."
},
{
"code": null,
"e": 26968,
"s": 26963,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>LeaderBoard Using PHP</title> </head> <body> <h2>Welcome To GFG</h2> <table> <tr> <td>Ranking</td> <td>UserName</td> <td>Marks</td> </tr>",
"e": 27241,
"s": 26968,
"text": null
},
{
"code": null,
"e": 27295,
"s": 27241,
"text": "Step 2: Fetch data from SQL and display it using PHP."
},
{
"code": null,
"e": 27350,
"s": 27295,
"text": "Step 3: Create a MySQL database by following commands."
},
{
"code": null,
"e": 27379,
"s": 27350,
"text": "CREATE DATABASE leaderboard;"
},
{
"code": null,
"e": 27442,
"s": 27379,
"text": "CREATE TABLE leaderboard(userName VARCHAR(30), marks INT(10));"
},
{
"code": null,
"e": 27488,
"s": 27442,
"text": "Step 4: Insert some values into the database."
},
{
"code": null,
"e": 27563,
"s": 27488,
"text": "INSERT INTO leaderboard(userName,marks) VALUES('Devesh Pratap Singh',100);"
},
{
"code": null,
"e": 27567,
"s": 27563,
"text": "PHP"
},
{
"code": "<?php /* Connection Variable (\"Servername\",\"username\",\"password\",\"database\") */$con = mysqli_connect(\"localhost\", \"root\", \"\", \"leaderboard\"); /* Mysqli query to fetch rows in descending order of marks */$result = mysqli_query($con, \"SELECT userName, marks FROM leaderboard ORDER BY marks DESC\"); /* First rank will be 1 and second be 2 and so on */$ranking = 1; /* Fetch Rows from the SQL query */if (mysqli_num_rows($result)) { while ($row = mysqli_fetch_array($result)) { echo \"<td>{$ranking}</td> <td>{$row['userName']}</td> <td>{$row['marks']}</td>\"; $ranking++; }}?>",
"e": 28189,
"s": 27567,
"text": null
},
{
"code": null,
"e": 28243,
"s": 28189,
"text": "Step 5: Close the table tag, body tag, and html tag. "
},
{
"code": null,
"e": 28248,
"s": 28243,
"text": "HTML"
},
{
"code": "</table></body></html>",
"e": 28271,
"s": 28248,
"text": null
},
{
"code": null,
"e": 28310,
"s": 28271,
"text": "Step 6: Save this file as “index.php“."
},
{
"code": null,
"e": 28379,
"s": 28310,
"text": "Step 7: Copy this file inside your xampp server in htdocs directory."
},
{
"code": null,
"e": 28437,
"s": 28379,
"text": "Step 8: Open phpMyAdmin or MySQL server on your computer."
},
{
"code": null,
"e": 28501,
"s": 28437,
"text": "Step 9: Open https://localhost/index.php into your web browser."
},
{
"code": null,
"e": 28531,
"s": 28501,
"text": "Output produced after running"
},
{
"code": null,
"e": 28541,
"s": 28531,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28547,
"s": 28541,
"text": "mysql"
},
{
"code": null,
"e": 28557,
"s": 28547,
"text": "PHP-array"
},
{
"code": null,
"e": 28566,
"s": 28557,
"text": "PHP-Misc"
},
{
"code": null,
"e": 28573,
"s": 28566,
"text": "Picked"
},
{
"code": null,
"e": 28578,
"s": 28573,
"text": "HTML"
},
{
"code": null,
"e": 28582,
"s": 28578,
"text": "PHP"
},
{
"code": null,
"e": 28586,
"s": 28582,
"text": "SQL"
},
{
"code": null,
"e": 28603,
"s": 28586,
"text": "Web Technologies"
},
{
"code": null,
"e": 28607,
"s": 28603,
"text": "SQL"
},
{
"code": null,
"e": 28612,
"s": 28607,
"text": "HTML"
},
{
"code": null,
"e": 28616,
"s": 28612,
"text": "PHP"
},
{
"code": null,
"e": 28714,
"s": 28616,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28738,
"s": 28714,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 28779,
"s": 28738,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 28816,
"s": 28779,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28845,
"s": 28816,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28865,
"s": 28845,
"text": "Angular File Upload"
},
{
"code": null,
"e": 28910,
"s": 28865,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 28950,
"s": 28910,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 28994,
"s": 28950,
"text": "How to pop an alert message box using PHP ?"
},
{
"code": null,
"e": 29018,
"s": 28994,
"text": "PHP in_array() Function"
}
] |
C# | Getting the list of keys of a SortedList object - GeeksforGeeks
|
01 Feb, 2019
SortedList.GetKeyList Method is used to get the list of keys in a SortedList object.
Syntax:
public virtual System.Collections.IList GetKeyList ();
Return Value: It returns an IList object containing the keys in the SortedList object.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# code for getting the keys// in a SortedList objectusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add("1", "C++"); mylist.Add("2", "Java"); mylist.Add("3", "DSA"); mylist.Add("4", "Python"); mylist.Add("5", "C#"); // taking an IList and // using GetKeyList method IList klist = mylist.GetKeyList(); // Prints the list of keys Console.WriteLine("Key List"); for (int i = 0; i < mylist.Count; i++) Console.WriteLine(klist[i]); }}
Output:
Key List
1
2
3
4
5
Example 2:
// C# code for getting the keys// in a SortedList objectusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add("First", "Ram"); mylist.Add("Second", "Shyam"); mylist.Add("Third", "Mohit"); mylist.Add("Fourth", "Rohit"); mylist.Add("Fifth", "Manish"); // taking an IList and // using GetKeyList method IList klist = mylist.GetKeyList(); // Prints the list of keys Console.WriteLine("Key List"); // will print the keys in sorted order for (int i = 0; i < mylist.Count; i++) Console.WriteLine(klist[i]); }}
Output:
Key List
Fifth
First
Fourth
Second
Third
Note:
The returned IList object is a read-only view of the keys of the SortedList object. Modifications made to the underlying SortedList are immediately reflected in the IList.
The elements of the returned IList are sorted in the same order as the keys of the SortedList.
This method is similar to the Keys property but returns an IList object instead of an ICollection object.
This method is an O(1) operation.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.getkeylist?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Collections-SortedList
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Switch Statement in C#
Convert String to Character Array in C#
Linked List Implementation in C#
|
[
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 25632,
"s": 25547,
"text": "SortedList.GetKeyList Method is used to get the list of keys in a SortedList object."
},
{
"code": null,
"e": 25640,
"s": 25632,
"text": "Syntax:"
},
{
"code": null,
"e": 25695,
"s": 25640,
"text": "public virtual System.Collections.IList GetKeyList ();"
},
{
"code": null,
"e": 25782,
"s": 25695,
"text": "Return Value: It returns an IList object containing the keys in the SortedList object."
},
{
"code": null,
"e": 25843,
"s": 25782,
"text": "Below programs illustrate the use of above-discussed method:"
},
{
"code": null,
"e": 25854,
"s": 25843,
"text": "Example 1:"
},
{
"code": "// C# code for getting the keys// in a SortedList objectusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add(\"1\", \"C++\"); mylist.Add(\"2\", \"Java\"); mylist.Add(\"3\", \"DSA\"); mylist.Add(\"4\", \"Python\"); mylist.Add(\"5\", \"C#\"); // taking an IList and // using GetKeyList method IList klist = mylist.GetKeyList(); // Prints the list of keys Console.WriteLine(\"Key List\"); for (int i = 0; i < mylist.Count; i++) Console.WriteLine(klist[i]); }}",
"e": 26598,
"s": 25854,
"text": null
},
{
"code": null,
"e": 26606,
"s": 26598,
"text": "Output:"
},
{
"code": null,
"e": 26626,
"s": 26606,
"text": "Key List\n1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 26637,
"s": 26626,
"text": "Example 2:"
},
{
"code": "// C# code for getting the keys// in a SortedList objectusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add(\"First\", \"Ram\"); mylist.Add(\"Second\", \"Shyam\"); mylist.Add(\"Third\", \"Mohit\"); mylist.Add(\"Fourth\", \"Rohit\"); mylist.Add(\"Fifth\", \"Manish\"); // taking an IList and // using GetKeyList method IList klist = mylist.GetKeyList(); // Prints the list of keys Console.WriteLine(\"Key List\"); // will print the keys in sorted order for (int i = 0; i < mylist.Count; i++) Console.WriteLine(klist[i]); }}",
"e": 27455,
"s": 26637,
"text": null
},
{
"code": null,
"e": 27463,
"s": 27455,
"text": "Output:"
},
{
"code": null,
"e": 27505,
"s": 27463,
"text": "Key List\nFifth\nFirst\nFourth\nSecond\nThird\n"
},
{
"code": null,
"e": 27511,
"s": 27505,
"text": "Note:"
},
{
"code": null,
"e": 27683,
"s": 27511,
"text": "The returned IList object is a read-only view of the keys of the SortedList object. Modifications made to the underlying SortedList are immediately reflected in the IList."
},
{
"code": null,
"e": 27778,
"s": 27683,
"text": "The elements of the returned IList are sorted in the same order as the keys of the SortedList."
},
{
"code": null,
"e": 27884,
"s": 27778,
"text": "This method is similar to the Keys property but returns an IList object instead of an ICollection object."
},
{
"code": null,
"e": 27918,
"s": 27884,
"text": "This method is an O(1) operation."
},
{
"code": null,
"e": 27929,
"s": 27918,
"text": "Reference:"
},
{
"code": null,
"e": 28038,
"s": 27929,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.getkeylist?view=netframework-4.7.2"
},
{
"code": null,
"e": 28067,
"s": 28038,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 28097,
"s": 28067,
"text": "CSharp-Collections-SortedList"
},
{
"code": null,
"e": 28111,
"s": 28097,
"text": "CSharp-method"
},
{
"code": null,
"e": 28114,
"s": 28111,
"text": "C#"
},
{
"code": null,
"e": 28212,
"s": 28114,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28235,
"s": 28212,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28263,
"s": 28235,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28280,
"s": 28263,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28302,
"s": 28280,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28331,
"s": 28302,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 28371,
"s": 28331,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28414,
"s": 28371,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 28437,
"s": 28414,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 28477,
"s": 28437,
"text": "Convert String to Character Array in C#"
}
] |
Python Bokeh - Plotting Multiple Polygons on a Graph - GeeksforGeeks
|
08 Feb, 2022
Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity.Bokeh can be used to plot multiple polygons on a graph. Plotting multiple polygons on a graph can be done using the multi_polygons() method of the plotting module.
Syntax : multi_polygons(parameters)Parameters :
xs : x-coordinates of the polygons
ys : y-coordinates of the polygons
fill_alpha : fill alpha values of the polygons
fill_color : fill color values of the polygons
hatch_alpha : hatch alpha values of the polygons, default is 1
hatch_color : hatch color values of the polygons, default is black
hatch_extra : hatch extra values of the polygons
hatch_pattern : hatch pattern values of the polygons
hatch_scale : hatch scale values of the polygons, default is 12
hatch_weight : hatch weight values of the polygons, default is 1
line_alpha : percentage value of line alpha, default is 1
line_cap : value of line cap for the line, default is butt
line_color : color of the line, default is black
line_dash : value of line dash such as : solid, dashed, dotted, dotdash, dashdot [default is solid ]
line_dash_offset : value of line dash offset, default is 0
line_join : value of line join, default in bevel
line_width : value of the width of the line, default is 1
name : user-supplied name for the model
tags : user-supplied values for the model
Other Parameters :
alpha : sets all alpha keyword arguments at once
color : sets all color keyword arguments at once
legend_field : name of a column in the data source that should be used
legend_group : name of a column in the data source that should be used
legend_label : labels the legend entry
muted : determines whether the glyph should be rendered as muted or not, default is False
name : optional user-supplied name to attach to the renderer
source : user-supplied data source
view : view for filtering the data source
visible : determines whether the glyph should be rendered or not, default is True
x_range_name : name of an extra range to use for mapping x-coordinates
y_range_name : name of an extra range to use for mapping y-coordinates
level : specifies the render level order for this glyph
Returns : an object of class GlyphRenderer
Example 1 : In this example we will be using the default values for plotting the graph.
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, show # file to save the modeloutput_file("gfg.html") # instantiating the figure objectgraph = figure(title = "Bokeh Multiple Polygons Graph") # the points to be plottedxs = [[[[0, 0, 1, 1]]]]ys = [[[[3, 2, 2, 3]]]] # plotting the graphgraph.multi_polygons(xs, ys) # displaying the modelshow(graph)
Output :
Example 2 : In this example we will be plotting the multiple polygons with various other parameters
Python3
# importing the modulesfrom bokeh.plotting import figure, output_file, show # file to save the modeloutput_file("gfg.html") # instantiating the figure objectgraph = figure(title = "Bokeh Multiple Polygons Graph") # name of the x-axisgraph.xaxis.axis_label = "x-axis" # name of the y-axisgraph.yaxis.axis_label = "y-axis" # the points to be plottedxs = [[[[0, 0, 1, 1]]], [[[2, 2, 4, 4], [2.5, 2.5, 3.5, 3.5]]], [[[2, 0, 4]]]]ys = [[[[2.5, 0.5, 0.5, 2.5]]], [[[1, 0, 0, 1], [0.75, 0.25, 0.25, 0.75]]], [[[2, 0, 0]]]] # color values of the polygonscolor = ["red", "purple", "yellow"] # fill alpha values of the polygonsfill_alpha = 0.5 # plotting the graphgraph.multi_polygons(xs, ys, color = color, fill_alpha = fill_alpha) # displaying the modelshow(graph)
Output :
sumitgumber28
Data Visualization
Python Bokeh-plotting-figure-class
Python-Bokeh
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
|
[
{
"code": null,
"e": 25565,
"s": 25537,
"text": "\n08 Feb, 2022"
},
{
"code": null,
"e": 25970,
"s": 25565,
"text": "Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity.Bokeh can be used to plot multiple polygons on a graph. Plotting multiple polygons on a graph can be done using the multi_polygons() method of the plotting module. "
},
{
"code": null,
"e": 26022,
"s": 25972,
"text": "Syntax : multi_polygons(parameters)Parameters : "
},
{
"code": null,
"e": 26057,
"s": 26022,
"text": "xs : x-coordinates of the polygons"
},
{
"code": null,
"e": 26092,
"s": 26057,
"text": "ys : y-coordinates of the polygons"
},
{
"code": null,
"e": 26139,
"s": 26092,
"text": "fill_alpha : fill alpha values of the polygons"
},
{
"code": null,
"e": 26186,
"s": 26139,
"text": "fill_color : fill color values of the polygons"
},
{
"code": null,
"e": 26249,
"s": 26186,
"text": "hatch_alpha : hatch alpha values of the polygons, default is 1"
},
{
"code": null,
"e": 26316,
"s": 26249,
"text": "hatch_color : hatch color values of the polygons, default is black"
},
{
"code": null,
"e": 26365,
"s": 26316,
"text": "hatch_extra : hatch extra values of the polygons"
},
{
"code": null,
"e": 26418,
"s": 26365,
"text": "hatch_pattern : hatch pattern values of the polygons"
},
{
"code": null,
"e": 26482,
"s": 26418,
"text": "hatch_scale : hatch scale values of the polygons, default is 12"
},
{
"code": null,
"e": 26547,
"s": 26482,
"text": "hatch_weight : hatch weight values of the polygons, default is 1"
},
{
"code": null,
"e": 26605,
"s": 26547,
"text": "line_alpha : percentage value of line alpha, default is 1"
},
{
"code": null,
"e": 26664,
"s": 26605,
"text": "line_cap : value of line cap for the line, default is butt"
},
{
"code": null,
"e": 26713,
"s": 26664,
"text": "line_color : color of the line, default is black"
},
{
"code": null,
"e": 26814,
"s": 26713,
"text": "line_dash : value of line dash such as : solid, dashed, dotted, dotdash, dashdot [default is solid ]"
},
{
"code": null,
"e": 26873,
"s": 26814,
"text": "line_dash_offset : value of line dash offset, default is 0"
},
{
"code": null,
"e": 26922,
"s": 26873,
"text": "line_join : value of line join, default in bevel"
},
{
"code": null,
"e": 26980,
"s": 26922,
"text": "line_width : value of the width of the line, default is 1"
},
{
"code": null,
"e": 27020,
"s": 26980,
"text": "name : user-supplied name for the model"
},
{
"code": null,
"e": 27062,
"s": 27020,
"text": "tags : user-supplied values for the model"
},
{
"code": null,
"e": 27083,
"s": 27062,
"text": "Other Parameters : "
},
{
"code": null,
"e": 27132,
"s": 27083,
"text": "alpha : sets all alpha keyword arguments at once"
},
{
"code": null,
"e": 27181,
"s": 27132,
"text": "color : sets all color keyword arguments at once"
},
{
"code": null,
"e": 27252,
"s": 27181,
"text": "legend_field : name of a column in the data source that should be used"
},
{
"code": null,
"e": 27323,
"s": 27252,
"text": "legend_group : name of a column in the data source that should be used"
},
{
"code": null,
"e": 27362,
"s": 27323,
"text": "legend_label : labels the legend entry"
},
{
"code": null,
"e": 27452,
"s": 27362,
"text": "muted : determines whether the glyph should be rendered as muted or not, default is False"
},
{
"code": null,
"e": 27513,
"s": 27452,
"text": "name : optional user-supplied name to attach to the renderer"
},
{
"code": null,
"e": 27548,
"s": 27513,
"text": "source : user-supplied data source"
},
{
"code": null,
"e": 27590,
"s": 27548,
"text": "view : view for filtering the data source"
},
{
"code": null,
"e": 27672,
"s": 27590,
"text": "visible : determines whether the glyph should be rendered or not, default is True"
},
{
"code": null,
"e": 27743,
"s": 27672,
"text": "x_range_name : name of an extra range to use for mapping x-coordinates"
},
{
"code": null,
"e": 27814,
"s": 27743,
"text": "y_range_name : name of an extra range to use for mapping y-coordinates"
},
{
"code": null,
"e": 27870,
"s": 27814,
"text": "level : specifies the render level order for this glyph"
},
{
"code": null,
"e": 27915,
"s": 27870,
"text": "Returns : an object of class GlyphRenderer "
},
{
"code": null,
"e": 28004,
"s": 27915,
"text": "Example 1 : In this example we will be using the default values for plotting the graph. "
},
{
"code": null,
"e": 28012,
"s": 28004,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # file to save the modeloutput_file(\"gfg.html\") # instantiating the figure objectgraph = figure(title = \"Bokeh Multiple Polygons Graph\") # the points to be plottedxs = [[[[0, 0, 1, 1]]]]ys = [[[[3, 2, 2, 3]]]] # plotting the graphgraph.multi_polygons(xs, ys) # displaying the modelshow(graph)",
"e": 28398,
"s": 28012,
"text": null
},
{
"code": null,
"e": 28409,
"s": 28398,
"text": "Output : "
},
{
"code": null,
"e": 28510,
"s": 28409,
"text": "Example 2 : In this example we will be plotting the multiple polygons with various other parameters "
},
{
"code": null,
"e": 28518,
"s": 28510,
"text": "Python3"
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # file to save the modeloutput_file(\"gfg.html\") # instantiating the figure objectgraph = figure(title = \"Bokeh Multiple Polygons Graph\") # name of the x-axisgraph.xaxis.axis_label = \"x-axis\" # name of the y-axisgraph.yaxis.axis_label = \"y-axis\" # the points to be plottedxs = [[[[0, 0, 1, 1]]], [[[2, 2, 4, 4], [2.5, 2.5, 3.5, 3.5]]], [[[2, 0, 4]]]]ys = [[[[2.5, 0.5, 0.5, 2.5]]], [[[1, 0, 0, 1], [0.75, 0.25, 0.25, 0.75]]], [[[2, 0, 0]]]] # color values of the polygonscolor = [\"red\", \"purple\", \"yellow\"] # fill alpha values of the polygonsfill_alpha = 0.5 # plotting the graphgraph.multi_polygons(xs, ys, color = color, fill_alpha = fill_alpha) # displaying the modelshow(graph)",
"e": 29350,
"s": 28518,
"text": null
},
{
"code": null,
"e": 29361,
"s": 29350,
"text": "Output : "
},
{
"code": null,
"e": 29377,
"s": 29363,
"text": "sumitgumber28"
},
{
"code": null,
"e": 29396,
"s": 29377,
"text": "Data Visualization"
},
{
"code": null,
"e": 29431,
"s": 29396,
"text": "Python Bokeh-plotting-figure-class"
},
{
"code": null,
"e": 29444,
"s": 29431,
"text": "Python-Bokeh"
},
{
"code": null,
"e": 29451,
"s": 29444,
"text": "Python"
},
{
"code": null,
"e": 29549,
"s": 29451,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29577,
"s": 29549,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 29627,
"s": 29577,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 29649,
"s": 29627,
"text": "Python map() function"
},
{
"code": null,
"e": 29693,
"s": 29649,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 29711,
"s": 29693,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29734,
"s": 29711,
"text": "Taking input in Python"
},
{
"code": null,
"e": 29769,
"s": 29734,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29801,
"s": 29769,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29823,
"s": 29801,
"text": "Enumerate() in Python"
}
] |
PyQt5 – How to add image in Label background ? - GeeksforGeeks
|
26 Mar, 2020
In this article, we will see how to add background image to a label, By default, when we create a label there is no background image although we can set background color to it.
Sometimes background image is necessary. In order to set a background image we will use setStyleSheet() method.
Syntax : label.setStyleSheet(“background-image : url(image.png)”;)
Argument : It takes string as argument.
Action performed Add background image to a label.
Code :
# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") # setting the geometry of window self.setGeometry(60, 60, 600, 400) # creating a label widget self.label_1 = QLabel(self) # moving position self.label_1.move(100, 100) # setting up the border self.label_1.setStyleSheet("border :3px solid blue;") # setting label text self.label_1.setText("no background image") # creating a label widget self.label_2 = QLabel(self) # moving position self.label_2.move(160, 170) # setting up the border and adding image to background self.label_2.setStyleSheet("background-image : url(image.png); border : 2px solid blue") # setting label text self.label_2.setText("with background image") self.label_2.resize(100, 50) # show all the widgets self.show() # 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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 26217,
"s": 26189,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 26394,
"s": 26217,
"text": "In this article, we will see how to add background image to a label, By default, when we create a label there is no background image although we can set background color to it."
},
{
"code": null,
"e": 26506,
"s": 26394,
"text": "Sometimes background image is necessary. In order to set a background image we will use setStyleSheet() method."
},
{
"code": null,
"e": 26573,
"s": 26506,
"text": "Syntax : label.setStyleSheet(“background-image : url(image.png)”;)"
},
{
"code": null,
"e": 26613,
"s": 26573,
"text": "Argument : It takes string as argument."
},
{
"code": null,
"e": 26663,
"s": 26613,
"text": "Action performed Add background image to a label."
},
{
"code": null,
"e": 26670,
"s": 26663,
"text": "Code :"
},
{
"code": "# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Python\") # setting the geometry of window self.setGeometry(60, 60, 600, 400) # creating a label widget self.label_1 = QLabel(self) # moving position self.label_1.move(100, 100) # setting up the border self.label_1.setStyleSheet(\"border :3px solid blue;\") # setting label text self.label_1.setText(\"no background image\") # creating a label widget self.label_2 = QLabel(self) # moving position self.label_2.move(160, 170) # setting up the border and adding image to background self.label_2.setStyleSheet(\"background-image : url(image.png); border : 2px solid blue\") # setting label text self.label_2.setText(\"with background image\") self.label_2.resize(100, 50) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window()# start the appsys.exit(App.exec())",
"e": 27985,
"s": 26670,
"text": null
},
{
"code": null,
"e": 27994,
"s": 27985,
"text": "Output :"
},
{
"code": null,
"e": 28005,
"s": 27994,
"text": "Python-gui"
},
{
"code": null,
"e": 28017,
"s": 28005,
"text": "Python-PyQt"
},
{
"code": null,
"e": 28024,
"s": 28017,
"text": "Python"
},
{
"code": null,
"e": 28122,
"s": 28024,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28140,
"s": 28122,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28175,
"s": 28140,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28207,
"s": 28175,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28229,
"s": 28207,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28271,
"s": 28229,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28301,
"s": 28271,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28327,
"s": 28301,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28356,
"s": 28327,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28400,
"s": 28356,
"text": "Reading and Writing to text files in Python"
}
] |
Working with Text Files in Julia - GeeksforGeeks
|
25 Aug, 2020
Julia is Programming Language that is fast and dynamic in nature (most suitable for performing numerical and scientific applications) and it is optionally typed (the rich language of descriptive type and type declarations which is used to solidify our program) and general-purpose and open-sourced. Julia supports file handling like other programming languages with much higher efficiency and associated methods i.e reading, writing, and closing a file. It is a combination of C language ( powerful performance) and Python( simplicity).
In order to work with a file in Julia, firstly we need to create a new file using “touch”(used to create a new empty file) method, “pwd”(used for checking the present working directory of the system) method and “cd”(used to change directory and create the file where we want) method.
touch("example.txt")
File Created
To open the file in Julia we have “open” method. The open method takes in two arguments i.e filename (file to open) and mode of operation (read, write or append).
For read mode we use (“r”), write mode(“w”), and append mode(“a”).
Julia
# here we open file in read mode abc = open("example.txt","r") # here we open file in write mode efg = open("example.txt","w") # here we open file in append modehij = open("example.txt","a")
file open in different mode
Just like Python, Julia also has a “do“ method that helps us to avoid the mode of operation and prevent us from the issue of closing the file every time after modifying it.
Julia
open("example.txt") do file # modify mile content end
Here we will use “read” method to read the content of a file and it takes in two arguments i.e file to read and method to read the file as (string, integer, etc).
Julia
# METHOD 1# reading the content of file as a stringmydata = read(abc, String) # METHOD 2mydata = open("example.txt") do file read(file, String)end
File Read
Here we will use “readlines” method to ready the file as an array with each line of a file as an array element.
Julia
# open file mni = open("example.txt","r"); # reading file content line by lineline_by_line = readlines(mni)
Here we will change the mode of the file from read to write in order to write file inside “open” method.
Julia
# open file in write modeabc = open("example.txt", "w")
Now , we will use write method in Julia to write content to the “example.txt ” file, and write method will delete the previous content from file or will create the file if it does not exist.
Julia
# writing to a file using write() method write(abc, " Hello World , Julia welcomes you") # We need to close the file in order # to write the content from the disk to file close(abc)
Julia
# open file in append modeabc = open("example.txt", "a") # writing to a file using write() method write(abc, " Hello World , Julia welcomes you") # We need to close the file in order to write the content from the disk to file close(abc)
Here we will learn to modify the content of a file i.e we will change the case of content in a file from uppercase to lowercase using the lowercase method.
Julia
open("example.txt") do abc # change the case of content # from uppercase to lowercase lowercase(read(abc, String)) end
Here we will use the close method in Julia to close the file after modifying its content.
Julia
close(abc) # close method will close the file
julia-FileHandling
Picked
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Get array dimensions and size of a dimension in Julia - size() Method
Exception handling in Julia
Searching in Array for a given element in Julia
Find maximum element along with its index in Julia - findmax() Method
Get number of elements of array in Julia - length() Method
Join an array of strings into a single string in Julia - join() Method
Working with Excel Files in Julia
File Handling in Julia
Getting last element of an array in Julia - last() Method
|
[
{
"code": null,
"e": 25789,
"s": 25761,
"text": "\n25 Aug, 2020"
},
{
"code": null,
"e": 26327,
"s": 25789,
"text": "Julia is Programming Language that is fast and dynamic in nature (most suitable for performing numerical and scientific applications) and it is optionally typed (the rich language of descriptive type and type declarations which is used to solidify our program) and general-purpose and open-sourced. Julia supports file handling like other programming languages with much higher efficiency and associated methods i.e reading, writing, and closing a file. It is a combination of C language ( powerful performance) and Python( simplicity)."
},
{
"code": null,
"e": 26611,
"s": 26327,
"text": "In order to work with a file in Julia, firstly we need to create a new file using “touch”(used to create a new empty file) method, “pwd”(used for checking the present working directory of the system) method and “cd”(used to change directory and create the file where we want) method."
},
{
"code": null,
"e": 26633,
"s": 26611,
"text": "touch(\"example.txt\")\n"
},
{
"code": null,
"e": 26647,
"s": 26633,
"text": "File Created "
},
{
"code": null,
"e": 26810,
"s": 26647,
"text": "To open the file in Julia we have “open” method. The open method takes in two arguments i.e filename (file to open) and mode of operation (read, write or append)."
},
{
"code": null,
"e": 26877,
"s": 26810,
"text": "For read mode we use (“r”), write mode(“w”), and append mode(“a”)."
},
{
"code": null,
"e": 26883,
"s": 26877,
"text": "Julia"
},
{
"code": "# here we open file in read mode abc = open(\"example.txt\",\"r\") # here we open file in write mode efg = open(\"example.txt\",\"w\") # here we open file in append modehij = open(\"example.txt\",\"a\")",
"e": 27080,
"s": 26883,
"text": null
},
{
"code": null,
"e": 27108,
"s": 27080,
"text": "file open in different mode"
},
{
"code": null,
"e": 27281,
"s": 27108,
"text": "Just like Python, Julia also has a “do“ method that helps us to avoid the mode of operation and prevent us from the issue of closing the file every time after modifying it."
},
{
"code": null,
"e": 27287,
"s": 27281,
"text": "Julia"
},
{
"code": "open(\"example.txt\") do file # modify mile content end",
"e": 27344,
"s": 27287,
"text": null
},
{
"code": null,
"e": 27507,
"s": 27344,
"text": "Here we will use “read” method to read the content of a file and it takes in two arguments i.e file to read and method to read the file as (string, integer, etc)."
},
{
"code": null,
"e": 27513,
"s": 27507,
"text": "Julia"
},
{
"code": "# METHOD 1# reading the content of file as a stringmydata = read(abc, String) # METHOD 2mydata = open(\"example.txt\") do file read(file, String)end",
"e": 27666,
"s": 27513,
"text": null
},
{
"code": null,
"e": 27677,
"s": 27666,
"text": "File Read "
},
{
"code": null,
"e": 27790,
"s": 27677,
"text": "Here we will use “readlines” method to ready the file as an array with each line of a file as an array element."
},
{
"code": null,
"e": 27796,
"s": 27790,
"text": "Julia"
},
{
"code": "# open file mni = open(\"example.txt\",\"r\"); # reading file content line by lineline_by_line = readlines(mni)",
"e": 27905,
"s": 27796,
"text": null
},
{
"code": null,
"e": 28010,
"s": 27905,
"text": "Here we will change the mode of the file from read to write in order to write file inside “open” method."
},
{
"code": null,
"e": 28016,
"s": 28010,
"text": "Julia"
},
{
"code": "# open file in write modeabc = open(\"example.txt\", \"w\")",
"e": 28072,
"s": 28016,
"text": null
},
{
"code": null,
"e": 28263,
"s": 28072,
"text": "Now , we will use write method in Julia to write content to the “example.txt ” file, and write method will delete the previous content from file or will create the file if it does not exist."
},
{
"code": null,
"e": 28269,
"s": 28263,
"text": "Julia"
},
{
"code": "# writing to a file using write() method write(abc, \" Hello World , Julia welcomes you\") # We need to close the file in order # to write the content from the disk to file close(abc)",
"e": 28455,
"s": 28269,
"text": null
},
{
"code": null,
"e": 28461,
"s": 28455,
"text": "Julia"
},
{
"code": "# open file in append modeabc = open(\"example.txt\", \"a\") # writing to a file using write() method write(abc, \" Hello World , Julia welcomes you\") # We need to close the file in order to write the content from the disk to file close(abc)",
"e": 28704,
"s": 28461,
"text": null
},
{
"code": null,
"e": 28860,
"s": 28704,
"text": "Here we will learn to modify the content of a file i.e we will change the case of content in a file from uppercase to lowercase using the lowercase method."
},
{
"code": null,
"e": 28866,
"s": 28860,
"text": "Julia"
},
{
"code": "open(\"example.txt\") do abc # change the case of content # from uppercase to lowercase lowercase(read(abc, String)) end",
"e": 29007,
"s": 28866,
"text": null
},
{
"code": null,
"e": 29097,
"s": 29007,
"text": "Here we will use the close method in Julia to close the file after modifying its content."
},
{
"code": null,
"e": 29103,
"s": 29097,
"text": "Julia"
},
{
"code": "close(abc) # close method will close the file",
"e": 29149,
"s": 29103,
"text": null
},
{
"code": null,
"e": 29168,
"s": 29149,
"text": "julia-FileHandling"
},
{
"code": null,
"e": 29175,
"s": 29168,
"text": "Picked"
},
{
"code": null,
"e": 29181,
"s": 29175,
"text": "Julia"
},
{
"code": null,
"e": 29279,
"s": 29181,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29352,
"s": 29279,
"text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)"
},
{
"code": null,
"e": 29422,
"s": 29352,
"text": "Get array dimensions and size of a dimension in Julia - size() Method"
},
{
"code": null,
"e": 29450,
"s": 29422,
"text": "Exception handling in Julia"
},
{
"code": null,
"e": 29498,
"s": 29450,
"text": "Searching in Array for a given element in Julia"
},
{
"code": null,
"e": 29568,
"s": 29498,
"text": "Find maximum element along with its index in Julia - findmax() Method"
},
{
"code": null,
"e": 29627,
"s": 29568,
"text": "Get number of elements of array in Julia - length() Method"
},
{
"code": null,
"e": 29698,
"s": 29627,
"text": "Join an array of strings into a single string in Julia - join() Method"
},
{
"code": null,
"e": 29732,
"s": 29698,
"text": "Working with Excel Files in Julia"
},
{
"code": null,
"e": 29755,
"s": 29732,
"text": "File Handling in Julia"
}
] |
HTML | muted Attribute - GeeksforGeeks
|
08 Dec, 2021
The HTML muted Attribute is used to specify the audio output of the video is muted, it is a Boolean attribute.Applicable:
<video muted Attribute>
Syntax
<video muted>
Example:
html
<!DOCTYPE html><html> <head> <title> HTML muted Attribute </title></head> <body style="text-align: center"> <h1 style="color:green"> GeeksforGeeks</h1> <h2 style="font-family:Impact"> HTML muted Attribute</h2> <br> <video id="Test_Video" width="360" height="240" controls muted> <source src="samplevideo.mp4" type="video/mp4"> <source src="samplevideo.ogg" type="video/ogg"> </video></body> </html>
Output:
Supported Browsers: The browsers supported by HTML muted Attribute are listed below:
Google Chrome 4.0
Internet Explorer 10.0
Firefox 11.0
Apple Safari 7.1
Opera 10.5
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26061,
"s": 26033,
"text": "\n08 Dec, 2021"
},
{
"code": null,
"e": 26185,
"s": 26061,
"text": "The HTML muted Attribute is used to specify the audio output of the video is muted, it is a Boolean attribute.Applicable: "
},
{
"code": null,
"e": 26209,
"s": 26185,
"text": "<video muted Attribute>"
},
{
"code": null,
"e": 26218,
"s": 26209,
"text": "Syntax "
},
{
"code": null,
"e": 26232,
"s": 26218,
"text": "<video muted>"
},
{
"code": null,
"e": 26243,
"s": 26232,
"text": "Example: "
},
{
"code": null,
"e": 26248,
"s": 26243,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML muted Attribute </title></head> <body style=\"text-align: center\"> <h1 style=\"color:green\"> GeeksforGeeks</h1> <h2 style=\"font-family:Impact\"> HTML muted Attribute</h2> <br> <video id=\"Test_Video\" width=\"360\" height=\"240\" controls muted> <source src=\"samplevideo.mp4\" type=\"video/mp4\"> <source src=\"samplevideo.ogg\" type=\"video/ogg\"> </video></body> </html>",
"e": 26750,
"s": 26248,
"text": null
},
{
"code": null,
"e": 26760,
"s": 26750,
"text": "Output: "
},
{
"code": null,
"e": 26847,
"s": 26760,
"text": "Supported Browsers: The browsers supported by HTML muted Attribute are listed below: "
},
{
"code": null,
"e": 26865,
"s": 26847,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 26888,
"s": 26865,
"text": "Internet Explorer 10.0"
},
{
"code": null,
"e": 26901,
"s": 26888,
"text": "Firefox 11.0"
},
{
"code": null,
"e": 26918,
"s": 26901,
"text": "Apple Safari 7.1"
},
{
"code": null,
"e": 26929,
"s": 26918,
"text": "Opera 10.5"
},
{
"code": null,
"e": 27068,
"s": 26931,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 27088,
"s": 27068,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 27104,
"s": 27088,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 27109,
"s": 27104,
"text": "HTML"
},
{
"code": null,
"e": 27126,
"s": 27109,
"text": "Web Technologies"
},
{
"code": null,
"e": 27131,
"s": 27126,
"text": "HTML"
},
{
"code": null,
"e": 27229,
"s": 27131,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27277,
"s": 27229,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27327,
"s": 27277,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27351,
"s": 27327,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 27401,
"s": 27351,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 27438,
"s": 27401,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 27478,
"s": 27438,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27511,
"s": 27478,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27556,
"s": 27511,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27599,
"s": 27556,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Output of C++ programs | Set 28 (Access Modifiers) - GeeksforGeeks
|
22 Apr, 2022
Prerequisite: Access modifiers in c, Inheritance
1. What is the output?
C++
#include <iostream>using namespace std; class access{ int a = 10; void disp() { cout<< "a: "<< a; } }; int main(){ access a; a.disp(); return 0;}
Output:
Error
Description: When the access specifiers are not specified then they are taken as private by default. The private variables can be accessed only within the class and can not be accessed using. operator too if not public.
2. What is the output?
C++
#include <iostream>using namespace std; class access{ private: int a_pri = 10; protected: int b_pro = 20; public: int c_public = 30;}; int main(){ access a; cout<< "private: " << a.a_pri; cout<< "protected: "<< a.b_pro; cout<< "public: " << a.c_public; return 0;}
Output:
error
Description: private and protected variables cannot be accessed outside the class.
3. What is the output?
C++
#include <iostream>using namespace std; class access{protected: int b_pro = 20;public: int c_public = 30;}; class access_modifier: public access{public: void disp() { cout<< "protected: "<< b_pro << endl; cout<< "public: " << c_public << endl; } }; int main(){ access_modifier a; a.disp(); return 0;}
Output:
protected: 20
public: 30
Description: protected variables can be accessed only in a derived from it. Here we cannot print a_pri as it is a private member and they cannot be accessed in the derived class irrespective of type of inheritance.
4. What is the output?
C++
#include <iostream> using namespace std; class rectangle { int x, y; public: void val (int, int); int area () { return (x * y); } }; void rectangle::val (int a, int b) { x = a; y = b; } int main () { rectangle rect; rect.val (3, 4); cout << "rect area: " << rect.area(); return 0; }
Output:
rect area: 12
Description: since both area() and val() are declared as public they can be accessed outside the class.
5. What is the output?
C++
#include <iostream>using namespace std; class access{ public: int a_public = 30;}; class access_modifier: private access{ }; class inheritance:public access_modifier{public: void disp() { cout<< access::a_public; }};int main(){ inheritance a; a.disp(); return 0;}
Output: error Description: When a class is derived as private inheritance then it’s variables becomes private and are accessed only in that class and on further inheritance they are not accessible.
This article is contributed by I.HARISH KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
surinderdawra388
simmytarika5
CPP-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of Java programs | Set 13 (Collections)
Output of Java Program | Set 3
Output of C++ programs | Set 34 (File Handling)
Different ways to copy a string in C/C++
Output of Python Program | Set 1
Output of C++ programs | Set 50
Output of Java program | Set 28
Output of Java Program | Set 2
Runtime Errors
Output of Java program | Set 5
|
[
{
"code": null,
"e": 25606,
"s": 25578,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 25655,
"s": 25606,
"text": "Prerequisite: Access modifiers in c, Inheritance"
},
{
"code": null,
"e": 25679,
"s": 25655,
"text": "1. What is the output? "
},
{
"code": null,
"e": 25683,
"s": 25679,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; class access{ int a = 10; void disp() { cout<< \"a: \"<< a; } }; int main(){ access a; a.disp(); return 0;}",
"e": 25861,
"s": 25683,
"text": null
},
{
"code": null,
"e": 25870,
"s": 25861,
"text": "Output: "
},
{
"code": null,
"e": 25876,
"s": 25870,
"text": "Error"
},
{
"code": null,
"e": 26098,
"s": 25876,
"text": "Description: When the access specifiers are not specified then they are taken as private by default. The private variables can be accessed only within the class and can not be accessed using. operator too if not public. "
},
{
"code": null,
"e": 26121,
"s": 26098,
"text": "2. What is the output?"
},
{
"code": null,
"e": 26125,
"s": 26121,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; class access{ private: int a_pri = 10; protected: int b_pro = 20; public: int c_public = 30;}; int main(){ access a; cout<< \"private: \" << a.a_pri; cout<< \"protected: \"<< a.b_pro; cout<< \"public: \" << a.c_public; return 0;}",
"e": 26421,
"s": 26125,
"text": null
},
{
"code": null,
"e": 26430,
"s": 26421,
"text": "Output: "
},
{
"code": null,
"e": 26436,
"s": 26430,
"text": "error"
},
{
"code": null,
"e": 26521,
"s": 26436,
"text": "Description: private and protected variables cannot be accessed outside the class. "
},
{
"code": null,
"e": 26544,
"s": 26521,
"text": "3. What is the output?"
},
{
"code": null,
"e": 26548,
"s": 26544,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; class access{protected: int b_pro = 20;public: int c_public = 30;}; class access_modifier: public access{public: void disp() { cout<< \"protected: \"<< b_pro << endl; cout<< \"public: \" << c_public << endl; } }; int main(){ access_modifier a; a.disp(); return 0;}",
"e": 26908,
"s": 26548,
"text": null
},
{
"code": null,
"e": 26917,
"s": 26908,
"text": "Output: "
},
{
"code": null,
"e": 26942,
"s": 26917,
"text": "protected: 20\npublic: 30"
},
{
"code": null,
"e": 27159,
"s": 26942,
"text": "Description: protected variables can be accessed only in a derived from it. Here we cannot print a_pri as it is a private member and they cannot be accessed in the derived class irrespective of type of inheritance. "
},
{
"code": null,
"e": 27182,
"s": 27159,
"text": "4. What is the output?"
},
{
"code": null,
"e": 27186,
"s": 27182,
"text": "C++"
},
{
"code": "#include <iostream> using namespace std; class rectangle { int x, y; public: void val (int, int); int area () { return (x * y); } }; void rectangle::val (int a, int b) { x = a; y = b; } int main () { rectangle rect; rect.val (3, 4); cout << \"rect area: \" << rect.area(); return 0; }",
"e": 27571,
"s": 27186,
"text": null
},
{
"code": null,
"e": 27580,
"s": 27571,
"text": "Output: "
},
{
"code": null,
"e": 27594,
"s": 27580,
"text": "rect area: 12"
},
{
"code": null,
"e": 27700,
"s": 27594,
"text": "Description: since both area() and val() are declared as public they can be accessed outside the class. "
},
{
"code": null,
"e": 27723,
"s": 27700,
"text": "5. What is the output?"
},
{
"code": null,
"e": 27727,
"s": 27723,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; class access{ public: int a_public = 30;}; class access_modifier: private access{ }; class inheritance:public access_modifier{public: void disp() { cout<< access::a_public; }};int main(){ inheritance a; a.disp(); return 0;}",
"e": 28033,
"s": 27727,
"text": null
},
{
"code": null,
"e": 28232,
"s": 28033,
"text": "Output: error Description: When a class is derived as private inheritance then it’s variables becomes private and are accessed only in that class and on further inheritance they are not accessible. "
},
{
"code": null,
"e": 28655,
"s": 28232,
"text": "This article is contributed by I.HARISH KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 28672,
"s": 28655,
"text": "surinderdawra388"
},
{
"code": null,
"e": 28685,
"s": 28672,
"text": "simmytarika5"
},
{
"code": null,
"e": 28696,
"s": 28685,
"text": "CPP-Output"
},
{
"code": null,
"e": 28711,
"s": 28696,
"text": "Program Output"
},
{
"code": null,
"e": 28809,
"s": 28711,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28856,
"s": 28809,
"text": "Output of Java programs | Set 13 (Collections)"
},
{
"code": null,
"e": 28887,
"s": 28856,
"text": "Output of Java Program | Set 3"
},
{
"code": null,
"e": 28935,
"s": 28887,
"text": "Output of C++ programs | Set 34 (File Handling)"
},
{
"code": null,
"e": 28976,
"s": 28935,
"text": "Different ways to copy a string in C/C++"
},
{
"code": null,
"e": 29009,
"s": 28976,
"text": "Output of Python Program | Set 1"
},
{
"code": null,
"e": 29041,
"s": 29009,
"text": "Output of C++ programs | Set 50"
},
{
"code": null,
"e": 29073,
"s": 29041,
"text": "Output of Java program | Set 28"
},
{
"code": null,
"e": 29104,
"s": 29073,
"text": "Output of Java Program | Set 2"
},
{
"code": null,
"e": 29119,
"s": 29104,
"text": "Runtime Errors"
}
] |
HTTP Patch - GeeksforGeeks
|
14 Jul, 2020
The HTTP Patch method is used to request a set of modifications in the request entity to be applied for the resource recognized by the Request-URI. This method plays a vital role in improving interoperability and preventing errors by making partial changes in the resource. The described set of changes are represented in a format identified as Patch Document by media type.
The Patch is a unique method where either all changes requested by the server are applied or none. If a PATCH request is passed using a cache, the Request-URI identifies one or more cached entities. Then the entries are designated as “stale” entries. There is no default format for Patch documentation and servers are required to create a document that fits the needs of the identified resource. This request method should be issued in such a way that it is idempotent as it prevents bad outcomes from the collision of two Patch request on the same resource in a similar time frame .
Patch is very much different as the server processes enclosed entity to modify the resource identified by the Request-URI. The enclosed entity contains a set of instructions that describe the procedure for modifying the current version of the resource existing in origin server. This method affects the resource identified by the Request-URI, and it can also become the cause of possible side effects on other resources.
Example: This example has been taken from RFC 5789. It describes use of Patch Document on an existing resource and the successful response received for the existing text file. In response, 204 code is used due to lack of message body and ETag response header field is used to signify the entity created at http://www.example.com/file.txt by applying Patch.
Request:
PATCH /file.txt HTTP/1.1
Host: www.example.com
Content-Type: application/example
If-Match: "e0023aa4e"
Content-Length: 100
Response:
HTTP/1.1 204 No Content
Content-Location: /file.txt
ETag: "e0023aa4f"
Error Handling in Patch:
A Patch request can fail due to occurrence of any of the mentioned errors.
Malformed patch document: This error occurs when client sends badly formatted Patch Document. It is specified by 400 (Bad Request) response.Unsupported patch document: This error occurs when client sends a Patch document format that is not supported by server for current resource identified by Request URI. It is specified by 415 (Unsupported Media Type) response.Unprocessable request: This error occurs when server considers the syntax to be valid and understands the document but is incapable of processing the request. It is specified by 422 (Unprocessable Entity) response.Resource not found: This type of error occurs when the Patch document is unable to be applied to a non-existent resource. It is specified by 404 (Not Found) response.Conflicting state: This error occurs when request cannot be applied given the state of the resource. It is specified by 409 (Conflict) response.Conflicting modification: This error occurs when the client uses If-Match or If-Unmodified-Since header to define a precondition which fails. It is specified by 412 (Precondition Failed) response. When server detects possible conflicting modification and no precondition is defined in the request, then 409 (Conflict) response is sent.Concurrent modification: This error occurs when server cannot queue concurrent requests to modify the resource when it is operating under restrictions. It is specified by 409 (Conflict) response. It is specified by 409 (Conflict) Response.
Malformed patch document: This error occurs when client sends badly formatted Patch Document. It is specified by 400 (Bad Request) response.
Unsupported patch document: This error occurs when client sends a Patch document format that is not supported by server for current resource identified by Request URI. It is specified by 415 (Unsupported Media Type) response.
Unprocessable request: This error occurs when server considers the syntax to be valid and understands the document but is incapable of processing the request. It is specified by 422 (Unprocessable Entity) response.
Resource not found: This type of error occurs when the Patch document is unable to be applied to a non-existent resource. It is specified by 404 (Not Found) response.
Conflicting state: This error occurs when request cannot be applied given the state of the resource. It is specified by 409 (Conflict) response.
Conflicting modification: This error occurs when the client uses If-Match or If-Unmodified-Since header to define a precondition which fails. It is specified by 412 (Precondition Failed) response. When server detects possible conflicting modification and no precondition is defined in the request, then 409 (Conflict) response is sent.
Concurrent modification: This error occurs when server cannot queue concurrent requests to modify the resource when it is operating under restrictions. It is specified by 409 (Conflict) response. It is specified by 409 (Conflict) Response.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTTP-headers
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26187,
"s": 26159,
"text": "\n14 Jul, 2020"
},
{
"code": null,
"e": 26563,
"s": 26187,
"text": "The HTTP Patch method is used to request a set of modifications in the request entity to be applied for the resource recognized by the Request-URI. This method plays a vital role in improving interoperability and preventing errors by making partial changes in the resource. The described set of changes are represented in a format identified as Patch Document by media type. "
},
{
"code": null,
"e": 27147,
"s": 26563,
"text": "The Patch is a unique method where either all changes requested by the server are applied or none. If a PATCH request is passed using a cache, the Request-URI identifies one or more cached entities. Then the entries are designated as “stale” entries. There is no default format for Patch documentation and servers are required to create a document that fits the needs of the identified resource. This request method should be issued in such a way that it is idempotent as it prevents bad outcomes from the collision of two Patch request on the same resource in a similar time frame ."
},
{
"code": null,
"e": 27568,
"s": 27147,
"text": "Patch is very much different as the server processes enclosed entity to modify the resource identified by the Request-URI. The enclosed entity contains a set of instructions that describe the procedure for modifying the current version of the resource existing in origin server. This method affects the resource identified by the Request-URI, and it can also become the cause of possible side effects on other resources."
},
{
"code": null,
"e": 27925,
"s": 27568,
"text": "Example: This example has been taken from RFC 5789. It describes use of Patch Document on an existing resource and the successful response received for the existing text file. In response, 204 code is used due to lack of message body and ETag response header field is used to signify the entity created at http://www.example.com/file.txt by applying Patch."
},
{
"code": null,
"e": 27934,
"s": 27925,
"text": "Request:"
},
{
"code": null,
"e": 28070,
"s": 27934,
"text": "PATCH /file.txt HTTP/1.1\n Host: www.example.com\n Content-Type: application/example\n If-Match: \"e0023aa4e\"\n Content-Length: 100\n"
},
{
"code": null,
"e": 28080,
"s": 28070,
"text": "Response:"
},
{
"code": null,
"e": 28157,
"s": 28080,
"text": "HTTP/1.1 204 No Content\n Content-Location: /file.txt\n ETag: \"e0023aa4f\"\n"
},
{
"code": null,
"e": 28182,
"s": 28157,
"text": "Error Handling in Patch:"
},
{
"code": null,
"e": 28258,
"s": 28182,
"text": "A Patch request can fail due to occurrence of any of the mentioned errors. "
},
{
"code": null,
"e": 29722,
"s": 28258,
"text": "Malformed patch document: This error occurs when client sends badly formatted Patch Document. It is specified by 400 (Bad Request) response.Unsupported patch document: This error occurs when client sends a Patch document format that is not supported by server for current resource identified by Request URI. It is specified by 415 (Unsupported Media Type) response.Unprocessable request: This error occurs when server considers the syntax to be valid and understands the document but is incapable of processing the request. It is specified by 422 (Unprocessable Entity) response.Resource not found: This type of error occurs when the Patch document is unable to be applied to a non-existent resource. It is specified by 404 (Not Found) response.Conflicting state: This error occurs when request cannot be applied given the state of the resource. It is specified by 409 (Conflict) response.Conflicting modification: This error occurs when the client uses If-Match or If-Unmodified-Since header to define a precondition which fails. It is specified by 412 (Precondition Failed) response. When server detects possible conflicting modification and no precondition is defined in the request, then 409 (Conflict) response is sent.Concurrent modification: This error occurs when server cannot queue concurrent requests to modify the resource when it is operating under restrictions. It is specified by 409 (Conflict) response. It is specified by 409 (Conflict) Response."
},
{
"code": null,
"e": 29863,
"s": 29722,
"text": "Malformed patch document: This error occurs when client sends badly formatted Patch Document. It is specified by 400 (Bad Request) response."
},
{
"code": null,
"e": 30089,
"s": 29863,
"text": "Unsupported patch document: This error occurs when client sends a Patch document format that is not supported by server for current resource identified by Request URI. It is specified by 415 (Unsupported Media Type) response."
},
{
"code": null,
"e": 30304,
"s": 30089,
"text": "Unprocessable request: This error occurs when server considers the syntax to be valid and understands the document but is incapable of processing the request. It is specified by 422 (Unprocessable Entity) response."
},
{
"code": null,
"e": 30471,
"s": 30304,
"text": "Resource not found: This type of error occurs when the Patch document is unable to be applied to a non-existent resource. It is specified by 404 (Not Found) response."
},
{
"code": null,
"e": 30616,
"s": 30471,
"text": "Conflicting state: This error occurs when request cannot be applied given the state of the resource. It is specified by 409 (Conflict) response."
},
{
"code": null,
"e": 30952,
"s": 30616,
"text": "Conflicting modification: This error occurs when the client uses If-Match or If-Unmodified-Since header to define a precondition which fails. It is specified by 412 (Precondition Failed) response. When server detects possible conflicting modification and no precondition is defined in the request, then 409 (Conflict) response is sent."
},
{
"code": null,
"e": 31192,
"s": 30952,
"text": "Concurrent modification: This error occurs when server cannot queue concurrent requests to modify the resource when it is operating under restrictions. It is specified by 409 (Conflict) response. It is specified by 409 (Conflict) Response."
},
{
"code": null,
"e": 31329,
"s": 31192,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 31342,
"s": 31329,
"text": "HTTP-headers"
},
{
"code": null,
"e": 31349,
"s": 31342,
"text": "Picked"
},
{
"code": null,
"e": 31354,
"s": 31349,
"text": "HTML"
},
{
"code": null,
"e": 31371,
"s": 31354,
"text": "Web Technologies"
},
{
"code": null,
"e": 31376,
"s": 31371,
"text": "HTML"
},
{
"code": null,
"e": 31474,
"s": 31376,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31522,
"s": 31474,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 31572,
"s": 31522,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 31622,
"s": 31572,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 31659,
"s": 31622,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 31723,
"s": 31659,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 31763,
"s": 31723,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31796,
"s": 31763,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31841,
"s": 31796,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31884,
"s": 31841,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Include and Merge Tags in Android with Example - GeeksforGeeks
|
05 Jul, 2021
Android apps are growing and one important aspect of it is reusability. Sometimes, the complexity of app design will be more and during that time, Android providing very efficient reusable features by means of the <include/> and <merge/> tags. Under <merge/> tags, we can specify a part of the layout that has to come in the main layout. It is similar to the main layout having Button, TextView, etc., It can be specified in a meaningful android naming convention XML file. eg: custom_layout.xml. In the main layout, we can reuse custom_layout by using the <include/> tag. The main advantage is many app pages may need custom_layout contents and wherever necessary, there it can be included easily by using the <include/> tag. And also in case of modifications, it is a one place change and hence maximum rework is avoided/reduced. Generally used in the idea of customization, reusability of app contents by using <include/> and <merge/> tags.
This is used to include the contents of reusable content. This is a very good idea of sharing the contents of another layout in the main layout.
XML
<!-- custom_layout is a separate layout xml file which can be shared, reused in many places--><include android:id="@+id/custom_layout" layout="@layout/custom_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" />
The <merge /> tag helps us to eliminate redundant view groups in our view hierarchy when including one layout within another. Hence in our example, directly we have android elements like Button and ImageView as this is going to get included in the main view and it will take the layout specified in the main file i.e. activity_main.xml(main layout file).
XML
<merge xmlns:android="http://schemas.android.com/apk/res/android"> <Button android:id="@+id/ButtonToInclude" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:text="Button is under merge tag" android:textColor="#fff" android:textSize="18sp" android:textStyle="italic" /> <ImageView android:id="@+id/imageViewToInclude" android:layout_width="fill_parent" android:layout_height="wrap_content" android:src="@drawable/cryptocurrency" /> </merge>
Note: We can find that <include/> and <merge/> tags look similar to ViewStub but it is not.
The ViewStub tag is a little bit different because it is not directly included, and will be loaded only when you actually need it, i.e when you set ViewStub’s visibility to “true”.
But include and merge tags are directly included and loaded at the beginning itself and mainly helpful for splitting of layouts and reusing them wherever necessary.
Attributes
Description
To supply an identifier for the layout resource to
include a custom layout in our main layout.
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 Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
XML
<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:background="#fff" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginBottom="100dp" android:text="Main Layout Text" android:textColor="@color/colorAccent" android:textSize="20sp" /> <include android:id="@+id/custom_layout" layout="@layout/custom_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
Step 3: Create a new Layout Resource File
Go to the app > res > layout > right-click > New > Layout Resource File and name the file as custom_layout. Below is the code for the custom_layout.xml and the file should be present with merge contents.
XML
<merge xmlns:android="http://schemas.android.com/apk/res/android"> <Button android:id="@+id/ButtonToInclude" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:text="Button is under merge tag" android:textColor="#fff" android:textSize="18sp" android:textStyle="italic" /> <ImageView android:id="@+id/imageViewToInclude" android:layout_width="fill_parent" android:layout_height="wrap_content" android:src="@drawable/cryptocurrency" /> </merge>
Step 4: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.os.Bundleimport android.view.Viewimport android.widget.Buttonimport android.widget.ImageViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { var customButton: Button? = null var customImageView: ImageView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // As custom layout contents are included, we can refer them as normal way // Main advantage lies here only. even this custom_layout can be reusued in different xml // and in corresponding activity file, they can be referred and there may be a // different functionality can be carried out. // get the reference of custom Layout's Button customButton = findViewById<View>(R.id.ButtonToInclude) as Button // get the reference of custom Layout's ImageView customImageView = findViewById<View>(R.id.imageViewToInclude) as ImageView // We have clicked on Custom layout button, though it is in separate xml // because of include tag, it is getting focus here and we can do // activities as we like customButton!!.setOnClickListener { Toast.makeText(applicationContext, "We have clicked on Custom layout button", Toast.LENGTH_LONG).show() } }}
We can able to get the output as attached in the video. Apply <include/> and <merge/> tag wherever necessary and enjoy the reusability feature of android apps.
saurabh1990aror
Android-Misc
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Kotlin Setters and Getters
|
[
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n05 Jul, 2021"
},
{
"code": null,
"e": 27325,
"s": 26381,
"text": "Android apps are growing and one important aspect of it is reusability. Sometimes, the complexity of app design will be more and during that time, Android providing very efficient reusable features by means of the <include/> and <merge/> tags. Under <merge/> tags, we can specify a part of the layout that has to come in the main layout. It is similar to the main layout having Button, TextView, etc., It can be specified in a meaningful android naming convention XML file. eg: custom_layout.xml. In the main layout, we can reuse custom_layout by using the <include/> tag. The main advantage is many app pages may need custom_layout contents and wherever necessary, there it can be included easily by using the <include/> tag. And also in case of modifications, it is a one place change and hence maximum rework is avoided/reduced. Generally used in the idea of customization, reusability of app contents by using <include/> and <merge/> tags."
},
{
"code": null,
"e": 27470,
"s": 27325,
"text": "This is used to include the contents of reusable content. This is a very good idea of sharing the contents of another layout in the main layout."
},
{
"code": null,
"e": 27474,
"s": 27470,
"text": "XML"
},
{
"code": "<!-- custom_layout is a separate layout xml file which can be shared, reused in many places--><include android:id=\"@+id/custom_layout\" layout=\"@layout/custom_layout\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" />",
"e": 27724,
"s": 27474,
"text": null
},
{
"code": null,
"e": 28085,
"s": 27729,
"text": "The <merge /> tag helps us to eliminate redundant view groups in our view hierarchy when including one layout within another. Hence in our example, directly we have android elements like Button and ImageView as this is going to get included in the main view and it will take the layout specified in the main file i.e. activity_main.xml(main layout file). "
},
{
"code": null,
"e": 28091,
"s": 28087,
"text": "XML"
},
{
"code": "<merge xmlns:android=\"http://schemas.android.com/apk/res/android\"> <Button android:id=\"@+id/ButtonToInclude\" android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:background=\"@color/colorPrimary\" android:text=\"Button is under merge tag\" android:textColor=\"#fff\" android:textSize=\"18sp\" android:textStyle=\"italic\" /> <ImageView android:id=\"@+id/imageViewToInclude\" android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:src=\"@drawable/cryptocurrency\" /> </merge>",
"e": 28696,
"s": 28091,
"text": null
},
{
"code": null,
"e": 28792,
"s": 28699,
"text": "Note: We can find that <include/> and <merge/> tags look similar to ViewStub but it is not. "
},
{
"code": null,
"e": 28973,
"s": 28792,
"text": "The ViewStub tag is a little bit different because it is not directly included, and will be loaded only when you actually need it, i.e when you set ViewStub’s visibility to “true”."
},
{
"code": null,
"e": 29138,
"s": 28973,
"text": "But include and merge tags are directly included and loaded at the beginning itself and mainly helpful for splitting of layouts and reusing them wherever necessary."
},
{
"code": null,
"e": 29149,
"s": 29138,
"text": "Attributes"
},
{
"code": null,
"e": 29161,
"s": 29149,
"text": "Description"
},
{
"code": null,
"e": 29213,
"s": 29161,
"text": "To supply an identifier for the layout resource to "
},
{
"code": null,
"e": 29257,
"s": 29213,
"text": "include a custom layout in our main layout."
},
{
"code": null,
"e": 29286,
"s": 29257,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 29452,
"s": 29288,
"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 Kotlin as the programming language."
},
{
"code": null,
"e": 29502,
"s": 29454,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 29620,
"s": 29504,
"text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 29626,
"s": 29622,
"text": "XML"
},
{
"code": "<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:background=\"#fff\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginBottom=\"100dp\" android:text=\"Main Layout Text\" android:textColor=\"@color/colorAccent\" android:textSize=\"20sp\" /> <include android:id=\"@+id/custom_layout\" layout=\"@layout/custom_layout\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" /> </LinearLayout>",
"e": 30430,
"s": 29626,
"text": null
},
{
"code": null,
"e": 30476,
"s": 30434,
"text": "Step 3: Create a new Layout Resource File"
},
{
"code": null,
"e": 30683,
"s": 30478,
"text": "Go to the app > res > layout > right-click > New > Layout Resource File and name the file as custom_layout. Below is the code for the custom_layout.xml and the file should be present with merge contents. "
},
{
"code": null,
"e": 30689,
"s": 30685,
"text": "XML"
},
{
"code": "<merge xmlns:android=\"http://schemas.android.com/apk/res/android\"> <Button android:id=\"@+id/ButtonToInclude\" android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:background=\"@color/colorPrimary\" android:text=\"Button is under merge tag\" android:textColor=\"#fff\" android:textSize=\"18sp\" android:textStyle=\"italic\" /> <ImageView android:id=\"@+id/imageViewToInclude\" android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:src=\"@drawable/cryptocurrency\" /> </merge>",
"e": 31294,
"s": 30689,
"text": null
},
{
"code": null,
"e": 31344,
"s": 31298,
"text": "Step 4: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 31532,
"s": 31346,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 31541,
"s": 31534,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport android.view.Viewimport android.widget.Buttonimport android.widget.ImageViewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { var customButton: Button? = null var customImageView: ImageView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // As custom layout contents are included, we can refer them as normal way // Main advantage lies here only. even this custom_layout can be reusued in different xml // and in corresponding activity file, they can be referred and there may be a // different functionality can be carried out. // get the reference of custom Layout's Button customButton = findViewById<View>(R.id.ButtonToInclude) as Button // get the reference of custom Layout's ImageView customImageView = findViewById<View>(R.id.imageViewToInclude) as ImageView // We have clicked on Custom layout button, though it is in separate xml // because of include tag, it is getting focus here and we can do // activities as we like customButton!!.setOnClickListener { Toast.makeText(applicationContext, \"We have clicked on Custom layout button\", Toast.LENGTH_LONG).show() } }}",
"e": 32952,
"s": 31541,
"text": null
},
{
"code": null,
"e": 33117,
"s": 32957,
"text": "We can able to get the output as attached in the video. Apply <include/> and <merge/> tag wherever necessary and enjoy the reusability feature of android apps."
},
{
"code": null,
"e": 33137,
"s": 33121,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 33150,
"s": 33137,
"text": "Android-Misc"
},
{
"code": null,
"e": 33158,
"s": 33150,
"text": "Android"
},
{
"code": null,
"e": 33165,
"s": 33158,
"text": "Kotlin"
},
{
"code": null,
"e": 33173,
"s": 33165,
"text": "Android"
},
{
"code": null,
"e": 33271,
"s": 33173,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33309,
"s": 33271,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 33348,
"s": 33309,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 33398,
"s": 33348,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 33449,
"s": 33398,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 33491,
"s": 33449,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 33510,
"s": 33491,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 33523,
"s": 33510,
"text": "Kotlin Array"
},
{
"code": null,
"e": 33565,
"s": 33523,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 33605,
"s": 33565,
"text": "How to Get Current Location in Android?"
}
] |
How to add days to $Date in PHP? - GeeksforGeeks
|
03 Jun, 2021
Adding days to $Date can be done in many ways. It is very easy to do by using built-in functions like strtotime(), date_add() in PHP.Method 1: Using strtotime() Function: The strtotime() Function is used to convert an English textual date-time description to a UNIX timestamp. Syntax:
strtotime( $EnglishDateTime, $time_now )
Parameters: This function accepts two optional parameters as mentioned above and described below.
$EnglishDateTime: This parameter specifies the English textual date-time description, which represents the date or time to be returned.
$time_now: This parameter specifies the timestamp used to calculate the returned value. It is an optional parameter.
Program: PHP program to add days to $Date in PHP using strtotime() function.
php
<?php// PHP program to add days to $Date // Declare a date$Date = "2019-05-10"; // Add days to date and display itecho date('Y-m-d', strtotime($Date. ' + 10 days')); ?>
2019-05-20
Method 2: Using date_add() Function: The date_add() function is used to add days, months, years, hours, minutes and seconds.Syntax:
date_add(object, interval);
Parameters: This function accepts two parameters as mentioned above and described below:
Object: It specifies the DateTime object returned by date_create() function.
Interval: It specifies the DateInterval object.
Program: PHP program to add days to $Date in PHP using date_add() function.
php
<?php// PHP program to add 10 days in date // Declare a date$date = date_create("2019-05-10"); // Use date_add() function to add date objectdate_add($date, date_interval_create_from_date_string("10 days")); // Display the added dateecho date_format($date, "Y-m-d"); ?>
2019-05-20
varshagumber28
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
Download file from URL using PHP
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
How to get parameters from a URL string in PHP?
|
[
{
"code": null,
"e": 25737,
"s": 25709,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 26024,
"s": 25737,
"text": "Adding days to $Date can be done in many ways. It is very easy to do by using built-in functions like strtotime(), date_add() in PHP.Method 1: Using strtotime() Function: The strtotime() Function is used to convert an English textual date-time description to a UNIX timestamp. Syntax: "
},
{
"code": null,
"e": 26065,
"s": 26024,
"text": "strtotime( $EnglishDateTime, $time_now )"
},
{
"code": null,
"e": 26165,
"s": 26065,
"text": "Parameters: This function accepts two optional parameters as mentioned above and described below. "
},
{
"code": null,
"e": 26301,
"s": 26165,
"text": "$EnglishDateTime: This parameter specifies the English textual date-time description, which represents the date or time to be returned."
},
{
"code": null,
"e": 26418,
"s": 26301,
"text": "$time_now: This parameter specifies the timestamp used to calculate the returned value. It is an optional parameter."
},
{
"code": null,
"e": 26497,
"s": 26418,
"text": "Program: PHP program to add days to $Date in PHP using strtotime() function. "
},
{
"code": null,
"e": 26501,
"s": 26497,
"text": "php"
},
{
"code": "<?php// PHP program to add days to $Date // Declare a date$Date = \"2019-05-10\"; // Add days to date and display itecho date('Y-m-d', strtotime($Date. ' + 10 days')); ?>",
"e": 26670,
"s": 26501,
"text": null
},
{
"code": null,
"e": 26681,
"s": 26670,
"text": "2019-05-20"
},
{
"code": null,
"e": 26817,
"s": 26683,
"text": "Method 2: Using date_add() Function: The date_add() function is used to add days, months, years, hours, minutes and seconds.Syntax: "
},
{
"code": null,
"e": 26845,
"s": 26817,
"text": "date_add(object, interval);"
},
{
"code": null,
"e": 26936,
"s": 26845,
"text": "Parameters: This function accepts two parameters as mentioned above and described below: "
},
{
"code": null,
"e": 27013,
"s": 26936,
"text": "Object: It specifies the DateTime object returned by date_create() function."
},
{
"code": null,
"e": 27061,
"s": 27013,
"text": "Interval: It specifies the DateInterval object."
},
{
"code": null,
"e": 27139,
"s": 27061,
"text": "Program: PHP program to add days to $Date in PHP using date_add() function. "
},
{
"code": null,
"e": 27143,
"s": 27139,
"text": "php"
},
{
"code": "<?php// PHP program to add 10 days in date // Declare a date$date = date_create(\"2019-05-10\"); // Use date_add() function to add date objectdate_add($date, date_interval_create_from_date_string(\"10 days\")); // Display the added dateecho date_format($date, \"Y-m-d\"); ?>",
"e": 27412,
"s": 27143,
"text": null
},
{
"code": null,
"e": 27423,
"s": 27412,
"text": "2019-05-20"
},
{
"code": null,
"e": 27440,
"s": 27425,
"text": "varshagumber28"
},
{
"code": null,
"e": 27447,
"s": 27440,
"text": "Picked"
},
{
"code": null,
"e": 27451,
"s": 27447,
"text": "PHP"
},
{
"code": null,
"e": 27464,
"s": 27451,
"text": "PHP Programs"
},
{
"code": null,
"e": 27481,
"s": 27464,
"text": "Web Technologies"
},
{
"code": null,
"e": 27508,
"s": 27481,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 27512,
"s": 27508,
"text": "PHP"
},
{
"code": null,
"e": 27610,
"s": 27512,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27650,
"s": 27610,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 27695,
"s": 27650,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 27737,
"s": 27695,
"text": "How to pass JavaScript variables to PHP ?"
},
{
"code": null,
"e": 27789,
"s": 27737,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 27822,
"s": 27789,
"text": "Download file from URL using PHP"
},
{
"code": null,
"e": 27862,
"s": 27822,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 27914,
"s": 27862,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 27956,
"s": 27914,
"text": "How to pass JavaScript variables to PHP ?"
},
{
"code": null,
"e": 28008,
"s": 27956,
"text": "Split a comma delimited string into an array in PHP"
}
] |
HTML | <audio> controls Attribute - GeeksforGeeks
|
08 Jul, 2019
The HTML <audio> controls attribute is used to specify the control to play audio. It is the Boolean value. This attribute is new in HTML5.
The audio control attribute contains the following property:
Play
Pause
Seeking
Volume
Syntax:
<audio controls>
Example:
<!DOCTYPE html><html> <head> <title> HTML Audio controls Attribute </title></head> <body style="text-align: center"> <h1 style="color: green"> GeeksforGeeks </h1> <h2 style="font-family: Impact"> HTML Audio controls Attribute </h2> <br> <audio id="Test_Audio" controls> <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.ogg" type="audio/ogg"> <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.mp3" type="audio/mpeg"> </audio></body> </html>
Output:
Supported Browsers: The browser supported by HTML <audio> controls attribute are listed below:
Google Chrome 4.0
Internet Explorer 9.0
Firefox 3.5
Safari 4.0
Opera 10.5
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26331,
"s": 26303,
"text": "\n08 Jul, 2019"
},
{
"code": null,
"e": 26470,
"s": 26331,
"text": "The HTML <audio> controls attribute is used to specify the control to play audio. It is the Boolean value. This attribute is new in HTML5."
},
{
"code": null,
"e": 26531,
"s": 26470,
"text": "The audio control attribute contains the following property:"
},
{
"code": null,
"e": 26536,
"s": 26531,
"text": "Play"
},
{
"code": null,
"e": 26542,
"s": 26536,
"text": "Pause"
},
{
"code": null,
"e": 26550,
"s": 26542,
"text": "Seeking"
},
{
"code": null,
"e": 26557,
"s": 26550,
"text": "Volume"
},
{
"code": null,
"e": 26565,
"s": 26557,
"text": "Syntax:"
},
{
"code": null,
"e": 26582,
"s": 26565,
"text": "<audio controls>"
},
{
"code": null,
"e": 26591,
"s": 26582,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML Audio controls Attribute </title></head> <body style=\"text-align: center\"> <h1 style=\"color: green\"> GeeksforGeeks </h1> <h2 style=\"font-family: Impact\"> HTML Audio controls Attribute </h2> <br> <audio id=\"Test_Audio\" controls> <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.ogg\" type=\"audio/ogg\"> <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.mp3\" type=\"audio/mpeg\"> </audio></body> </html> ",
"e": 27251,
"s": 26591,
"text": null
},
{
"code": null,
"e": 27259,
"s": 27251,
"text": "Output:"
},
{
"code": null,
"e": 27354,
"s": 27259,
"text": "Supported Browsers: The browser supported by HTML <audio> controls attribute are listed below:"
},
{
"code": null,
"e": 27372,
"s": 27354,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 27394,
"s": 27372,
"text": "Internet Explorer 9.0"
},
{
"code": null,
"e": 27406,
"s": 27394,
"text": "Firefox 3.5"
},
{
"code": null,
"e": 27417,
"s": 27406,
"text": "Safari 4.0"
},
{
"code": null,
"e": 27428,
"s": 27417,
"text": "Opera 10.5"
},
{
"code": null,
"e": 27565,
"s": 27428,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 27581,
"s": 27565,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 27586,
"s": 27581,
"text": "HTML"
},
{
"code": null,
"e": 27603,
"s": 27586,
"text": "Web Technologies"
},
{
"code": null,
"e": 27608,
"s": 27603,
"text": "HTML"
},
{
"code": null,
"e": 27706,
"s": 27608,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27754,
"s": 27706,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27804,
"s": 27754,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27828,
"s": 27804,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 27878,
"s": 27828,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 27915,
"s": 27878,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 27955,
"s": 27915,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27988,
"s": 27955,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28033,
"s": 27988,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28076,
"s": 28033,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python | C++ | Remove leading zeros from an IP address - GeeksforGeeks
|
18 Feb, 2022
Given an IP address, remove leading zeros from the IP address.Examples:
Input : 100.020.003.400
Output : 100.20.3.400
Input :001.200.001.004
Output : 1.200.1.4
Method 1 : Traversal and join
The approach is to split the given string by “.” and then convert it to an integer which removes the leading zeros and then join back them to a string.To convert a string to an integer we can use int(s) and then convert it back to string by str(s) and then join them back by using join function.
Python
C++
# Python program to remove leading zeros# an IP address and print the IP # function to remove leading zerosdef removeZeros(ip): # splits the ip by "." # converts the words to integeres to remove leading removeZeros # convert back the integer to string and join them back to a string new_ip = ".".join([str(int(i)) for i in ip.split(".")]) return new_ip ; # driver code # example1ip ="100.020.003.400" print(removeZeros(ip)) # example2ip ="001.200.001.004"print(removeZeros(ip))
// Cpp program to remove leading zeros// an IP address and print the IP #include <bits/stdc++.h>using namespace std; // function to remove leading zerosstring removeZeros(string s){ vector<string> v; // splits the ip by "." for (int i = 0; i < s.length(); i++) { string ans; while (i < s.length() && s[i] != '.') { ans += s[i]; i++; } v.push_back(ans); } vector<int> num; // converts the words to integeres to remove leading removeZeros for (auto str : v) { int temp = 0; for (int i = 0; i < str.length(); i++) { temp *= 10; temp += (str[i] - '0'); } num.push_back(temp); } string ans = ""; // Convert back the integer to string and join them back to a string for (auto i : num) { ans += '.'; string temp; while (i) { temp += ('0' + (i % 10)); i /= 10; } reverse(temp.begin(), temp.end()); ans += temp; } return ans.substr(1);} int main(){ string ip; // example1 ip = "100.020.003.400"; cout << (removeZeros(ip)) << "\n"; // example2 ip = "001.200.001.004"; cout << (removeZeros(ip)) << "\n"; return 0;}
Output:
100.20.3.400
1.200.1.4
Method 2 : Regex
Using a capture group, match the last digit and copy it and prevents all the digits from being replaced. regex \d can be explained as:
\d : Matches any decimal digit
\d Matches any decimal digit, this is equivalent
to the set class [0-9].
\b allows you to perform a “whole words only” search using a regular expression in the form of \bword\b regex \b can be explained as :
\b allows you to perform a "whole words only" search u
sing a regular expression in the form of \bword\b
Python
# Python program to remove leading zeros# an IP address and print the IP using regeximport re # function to remove leading zerosdef removeZeros(ip): new_ip = re.sub(r'\b0+(\d)', r'\1', ip) # splits the ip by "." # converts the words to integeres to remove leading removeZeros # convert back the integer to string and join them back to a string return new_ip # driver code # example1ip ="100.020.003.400" print(removeZeros(ip)) # example2ip ="001.200.001.004"print(removeZeros(ip))
Output:
100.20.3.400
1.200.1.4
khatriharsh281
Python Regex-programs
python-regex
Computer Networks
Misc
Python
Strings
Misc
Strings
Misc
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Introduction and IPv4 Datagram Header
Secure Socket Layer (SSL)
Cryptography and its Types
vector::push_back() and vector::pop_back() in C++ STL
Top 10 algorithms in Interview Questions
Overview of Data Structures | Set 1 (Linear Data Structures)
How to write Regular Expressions?
Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
|
[
{
"code": null,
"e": 25780,
"s": 25752,
"text": "\n18 Feb, 2022"
},
{
"code": null,
"e": 25854,
"s": 25780,
"text": "Given an IP address, remove leading zeros from the IP address.Examples: "
},
{
"code": null,
"e": 25946,
"s": 25854,
"text": "Input : 100.020.003.400 \nOutput : 100.20.3.400\n\nInput :001.200.001.004 \nOutput : 1.200.1.4"
},
{
"code": null,
"e": 25980,
"s": 25950,
"text": "Method 1 : Traversal and join"
},
{
"code": null,
"e": 26277,
"s": 25980,
"text": "The approach is to split the given string by “.” and then convert it to an integer which removes the leading zeros and then join back them to a string.To convert a string to an integer we can use int(s) and then convert it back to string by str(s) and then join them back by using join function. "
},
{
"code": null,
"e": 26284,
"s": 26277,
"text": "Python"
},
{
"code": null,
"e": 26288,
"s": 26284,
"text": "C++"
},
{
"code": "# Python program to remove leading zeros# an IP address and print the IP # function to remove leading zerosdef removeZeros(ip): # splits the ip by \".\" # converts the words to integeres to remove leading removeZeros # convert back the integer to string and join them back to a string new_ip = \".\".join([str(int(i)) for i in ip.split(\".\")]) return new_ip ; # driver code # example1ip =\"100.020.003.400\" print(removeZeros(ip)) # example2ip =\"001.200.001.004\"print(removeZeros(ip))",
"e": 26798,
"s": 26288,
"text": null
},
{
"code": "// Cpp program to remove leading zeros// an IP address and print the IP #include <bits/stdc++.h>using namespace std; // function to remove leading zerosstring removeZeros(string s){ vector<string> v; // splits the ip by \".\" for (int i = 0; i < s.length(); i++) { string ans; while (i < s.length() && s[i] != '.') { ans += s[i]; i++; } v.push_back(ans); } vector<int> num; // converts the words to integeres to remove leading removeZeros for (auto str : v) { int temp = 0; for (int i = 0; i < str.length(); i++) { temp *= 10; temp += (str[i] - '0'); } num.push_back(temp); } string ans = \"\"; // Convert back the integer to string and join them back to a string for (auto i : num) { ans += '.'; string temp; while (i) { temp += ('0' + (i % 10)); i /= 10; } reverse(temp.begin(), temp.end()); ans += temp; } return ans.substr(1);} int main(){ string ip; // example1 ip = \"100.020.003.400\"; cout << (removeZeros(ip)) << \"\\n\"; // example2 ip = \"001.200.001.004\"; cout << (removeZeros(ip)) << \"\\n\"; return 0;}",
"e": 28033,
"s": 26798,
"text": null
},
{
"code": null,
"e": 28043,
"s": 28033,
"text": "Output: "
},
{
"code": null,
"e": 28066,
"s": 28043,
"text": "100.20.3.400\n1.200.1.4"
},
{
"code": null,
"e": 28085,
"s": 28068,
"text": "Method 2 : Regex"
},
{
"code": null,
"e": 28222,
"s": 28085,
"text": "Using a capture group, match the last digit and copy it and prevents all the digits from being replaced. regex \\d can be explained as: "
},
{
"code": null,
"e": 28253,
"s": 28222,
"text": "\\d : Matches any decimal digit"
},
{
"code": null,
"e": 28333,
"s": 28253,
"text": "\\d Matches any decimal digit, this is equivalent\n to the set class [0-9]."
},
{
"code": null,
"e": 28470,
"s": 28333,
"text": "\\b allows you to perform a “whole words only” search using a regular expression in the form of \\bword\\b regex \\b can be explained as : "
},
{
"code": null,
"e": 28575,
"s": 28470,
"text": "\\b allows you to perform a \"whole words only\" search u\nsing a regular expression in the form of \\bword\\b"
},
{
"code": null,
"e": 28582,
"s": 28575,
"text": "Python"
},
{
"code": "# Python program to remove leading zeros# an IP address and print the IP using regeximport re # function to remove leading zerosdef removeZeros(ip): new_ip = re.sub(r'\\b0+(\\d)', r'\\1', ip) # splits the ip by \".\" # converts the words to integeres to remove leading removeZeros # convert back the integer to string and join them back to a string return new_ip # driver code # example1ip =\"100.020.003.400\" print(removeZeros(ip)) # example2ip =\"001.200.001.004\"print(removeZeros(ip))",
"e": 29094,
"s": 28582,
"text": null
},
{
"code": null,
"e": 29104,
"s": 29094,
"text": "Output: "
},
{
"code": null,
"e": 29127,
"s": 29104,
"text": "100.20.3.400\n1.200.1.4"
},
{
"code": null,
"e": 29144,
"s": 29129,
"text": "khatriharsh281"
},
{
"code": null,
"e": 29166,
"s": 29144,
"text": "Python Regex-programs"
},
{
"code": null,
"e": 29179,
"s": 29166,
"text": "python-regex"
},
{
"code": null,
"e": 29197,
"s": 29179,
"text": "Computer Networks"
},
{
"code": null,
"e": 29202,
"s": 29197,
"text": "Misc"
},
{
"code": null,
"e": 29209,
"s": 29202,
"text": "Python"
},
{
"code": null,
"e": 29217,
"s": 29209,
"text": "Strings"
},
{
"code": null,
"e": 29222,
"s": 29217,
"text": "Misc"
},
{
"code": null,
"e": 29230,
"s": 29222,
"text": "Strings"
},
{
"code": null,
"e": 29235,
"s": 29230,
"text": "Misc"
},
{
"code": null,
"e": 29253,
"s": 29235,
"text": "Computer Networks"
},
{
"code": null,
"e": 29351,
"s": 29253,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29386,
"s": 29351,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 29419,
"s": 29386,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 29457,
"s": 29419,
"text": "Introduction and IPv4 Datagram Header"
},
{
"code": null,
"e": 29483,
"s": 29457,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 29510,
"s": 29483,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 29564,
"s": 29510,
"text": "vector::push_back() and vector::pop_back() in C++ STL"
},
{
"code": null,
"e": 29605,
"s": 29564,
"text": "Top 10 algorithms in Interview Questions"
},
{
"code": null,
"e": 29666,
"s": 29605,
"text": "Overview of Data Structures | Set 1 (Linear Data Structures)"
},
{
"code": null,
"e": 29700,
"s": 29666,
"text": "How to write Regular Expressions?"
}
] |
Length of the longest subsequence such that XOR of adjacent elements is equal to K - GeeksforGeeks
|
15 Nov, 2021
Given an array arr[] of N non-negative integers and an integer K, the idea is to find the length of the longest subsequence having Xor of adjacent elements equal to K.
Examples:
Input: N = 5, arr[] = {3, 2, 4, 3, 5}, K = 1Output: 3Explanation:All the subsequences having Xor of adjacent element equal to K are {3, 2}, {2, 3}, {4, 5}, {3, 2, 3}.Therefore, the length of the longest subsequence having xor of adjacent element as 1 is 3.
Input: N = 8, arr[] = {4, 5, 4, 7, 3, 5, 4, 6}, K = 2Output: 3Explanation:All the subsequences having Xor of adjacent element equal to K are {4, 6}, {5, 7}, {7, 5}, {5, 7, 5}.Therefore, the length of the longest subsequence having xor of adjacent element as 1 is 3
Naive Approach: The idea is to use Dynamic Programming. The given problem can be solved based on the following observations:
Suppose Dp(i) represent maximum length of subsequence ending at index i.
Then, transition of one state to another state will be as follows:Find index j such that j < i and a[j] ^ a[i] = k.Therefore, Dp(i) = max(Dp(j)+1, Dp(i))
Find index j such that j < i and a[j] ^ a[i] = k.
Therefore, Dp(i) = max(Dp(j)+1, Dp(i))
Follow the steps below to solve the problem:
Initialize an integer, say ans, to store the length of the longest subsequence and an array, say dp[], to store the dp states.
Define base case as dp[0] = 1.
Iterate over the range [1, N – 1]:Iterate over the range [0, i-1] and update dp[i] as max(dp[i], dp[j] + 1) if a[i] ^ a[j] = K.Update ans as max(ans, dp[i]).
Iterate over the range [0, i-1] and update dp[i] as max(dp[i], dp[j] + 1) if a[i] ^ a[j] = K.
Update ans as max(ans, dp[i]).
Finally, print the maximum length of the longest subsequence ans.
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 find maximum length// of subsequence having XOR of// adjacent elements equal to Kint xorSubsequence(int a[], int n, int k){ // Store maximum length of subsequence int ans = 0; // Stores the dp-states int dp[n] = {0}; // Base case dp[0] = 1; // Iterate over the range [1, N-1] for (int i = 1; i < n; i++) { // Iterate over the range [0, i - 1] for (int j = i - 1; j >= 0; j--) { // If arr[i]^arr[j] == K if ((a[i] ^ a[j]) == k) // Update the dp[i] dp[i] = max(dp[i], dp[j] + 1); } // Update the maximum subsequence length ans = max(ans, dp[i]); dp[i] = max(1, dp[i]); } // If length of longest subsequence // is less than 2 then return 0 return ans >= 2 ? ans : 0;} // Driver Codeint main(){ // Input int arr[] = { 3, 2, 4, 3, 5 }; int K = 1; int N = sizeof(arr) / sizeof(arr[0]); // Print the length of longest subsequence cout << xorSubsequence(arr, N, K); return 0;} // This code is contributed by Dharanendra L V
// Java program for the above approach import java.io.*;import java.util.*;class GFG { // Function to find maximum length // of subsequence having XOR of // adjacent elements equal to K public static int xorSubsequence(int a[], int n, int k) { // Store maximum length of subsequence int ans = 0; // Stores the dp-states int dp[] = new int[n]; // Base case dp[0] = 1; // Iterate over the range [1, N-1] for (int i = 1; i < n; i++) { // Iterate over the range [0, i - 1] for (int j = i - 1; j >= 0; j--) { // If arr[i]^arr[j] == K if ((a[i] ^ a[j]) == k) // Update the dp[i] dp[i] = Math.max(dp[i], dp[j] + 1); } // Update the maximum subsequence length ans = Math.max(ans, dp[i]); dp[i] = Math.max(1, dp[i]); } // If length of longest subsequence // is less than 2 then return 0 return ans >= 2 ? ans : 0; } // Driver Code public static void main(String[] args) { // Input int arr[] = { 3, 2, 4, 3, 5 }; int K = 1; int N = arr.length; // Print the length of longest subsequence System.out.println(xorSubsequence(arr, N, K)); }}
# Python program for the above approach # Function to find maximum length# of subsequence having XOR of# adjacent elements equal to Kdef xorSubsequence(a, n, k): # Store maximum length of subsequence ans = 0; # Stores the dp-states dp = [0] * n; # Base case dp[0] = 1; # Iterate over the range [1, N-1] for i in range(1, n): # Iterate over the range [0, i - 1] for j in range(i - 1, -1, -1): # If arr[i]^arr[j] == K if ((a[i] ^ a[j]) == k): # Update the dp[i] dp[i] = max(dp[i], dp[j] + 1); # Update the maximum subsequence length ans = max(ans, dp[i]); dp[i] = max(1, dp[i]); # If length of longest subsequence # is less than 2 then return 0 return ans if ans >= 2 else 0; # Driver Codeif __name__ == '__main__': # Input arr = [3, 2, 4, 3, 5]; K = 1; N = len(arr); # Print the length of longest subsequence print(xorSubsequence(arr, N, K)); # This code contributed by shikhasingrajput
// C# program of the above approachusing System; class GFG{ // Function to find maximum length// of subsequence having XOR of// adjacent elements equal to Kstatic int xorSubsequence(int[] a, int n, int k){ // Store maximum length of subsequence int ans = 0; // Stores the dp-states int[] dp = new int[n]; // Base case dp[0] = 1; // Iterate over the range [1, N-1] for(int i = 1; i < n; i++) { // Iterate over the range [0, i - 1] for(int j = i - 1; j >= 0; j--) { // If arr[i]^arr[j] == K if ((a[i] ^ a[j]) == k) // Update the dp[i] dp[i] = Math.Max(dp[i], dp[j] + 1); } // Update the maximum subsequence length ans = Math.Max(ans, dp[i]); dp[i] = Math.Max(1, dp[i]); } // If length of longest subsequence // is less than 2 then return 0 return ans >= 2 ? ans : 0;} // Driver code static void Main(){ // Input int[] arr = { 3, 2, 4, 3, 5 }; int K = 1; int N = arr.Length; // Print the length of longest subsequence Console.WriteLine(xorSubsequence(arr, N, K)); }} // This code is contributed by divyeshrabadiya07
<script> // Javascript program of the above approach // Function to find maximum length // of subsequence having XOR of // adjacent elements equal to K function xorSubsequence(a, n, k) { // Store maximum length of subsequence let ans = 0; // Stores the dp-states let dp = new Array(n); dp.fill(0); // Base case dp[0] = 1; // Iterate over the range [1, N-1] for(let i = 1; i < n; i++) { // Iterate over the range [0, i - 1] for(let j = i - 1; j >= 0; j--) { // If arr[i]^arr[j] == K if ((a[i] ^ a[j]) == k) // Update the dp[i] dp[i] = Math.max(dp[i], dp[j] + 1); } // Update the maximum subsequence length ans = Math.max(ans, dp[i]); dp[i] = Math.max(1, dp[i]); } // If length of longest subsequence // is less than 2 then return 0 return ans >= 2 ? ans : 0; } let arr = [ 3, 2, 4, 3, 5 ]; let K = 1; let N = arr.length; // Print the length of longest subsequence document.write(xorSubsequence(arr, N, K)); </script>
3
Time Complexity: O(N2)Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized by using the property of Xor and Hashmap with dynamic programming to store the maximum length of subsequence ending at an integer, resulting in constant time transition of states in DP.
Initialize an integer say ans =0 to store the length of the longest subsequence and an array say dp[] to store the state of DP.
Initialize a HashMap say mp to store the longest length of subsequence ending at an element.
Define base case as dp[0] = 1 and push the pair {arr[0], 1} in mp.
Iterate over the range [1, N-1]:Find the length of the longest subsequence say dpj ending at element arr[i] ^K from HashMap mp.Update dp[i] as max(dp[i], dpj+1) and update the longest length of subsequence ending at element arr[i] in HashMap mp.Update the ans = max(ans, dp[i]).
Find the length of the longest subsequence say dpj ending at element arr[i] ^K from HashMap mp.
Update dp[i] as max(dp[i], dpj+1) and update the longest length of subsequence ending at element arr[i] in HashMap mp.
Update the ans = max(ans, dp[i]).
Finally, print the maximum length of the longest subsequence ans.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to find maximum length of subsequenceint xorSubsequence(int a[], int n, int k){ // Stores maximum length of subsequence int ans = 0; // Dictionary to store the longest length of // subsequence ending at an integer, say X map<int, int> map; // Stores the maximum length of // subsequence ending at index i int dp[n] = {0}; // Base case map[a[0]] = 1; dp[0] = 1; // Iterate over the range [1, N-1] for (int i = 1; i < n; i++) { int dpj; // Retrieve the longest length of // subsequence ending at integer []a^K if(map.find(a[i] ^ k) != map.end()) { dpj = map[a[i] ^ k]; } else{ dpj = -1; } // If dpj is not NULL if (dpj != 0) // Update dp[i] dp[i] = max(dp[i], dpj + 1); // Update ans ans = max(ans, dp[i]); // Update the maximum length of subsequence // ending at element is a[i] in Dictionary if(map.find(a[i]) != map.end()) { map[a[i]] = max(map[a[i]]+1, dp[i]); } else { map[a[i]] = max(1, dp[i]); } } // Return the ans if ans>=2. // Otherwise, return 0 return ans >= 2 ? ans : 0;} int main(){ // Input int arr[] = { 3, 2, 4, 3, 5 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 1; // Print the length of the longest subsequence cout << (xorSubsequence(arr, N, K)); return 0;} // This code is contributed by divyesh072019.
// Java program for above approachimport java.io.*;import java.util.*;class GFG{ // Function to find maximum length of subsequence public static int xorSubsequence(int a[], int n, int k) { // Stores maximum length of subsequence int ans = 0; // HashMap to store the longest length of // subsequence ending at an integer, say X HashMap<Integer, Integer> map = new HashMap<>(); // Stores the maximum length of // subsequence ending at index i int dp[] = new int[n]; // Base case map.put(a[0], 1); dp[0] = 1; // Iterate over the range [1, N-1] for (int i = 1; i < n; i++) { // Retrieve the longest length of // subsequence ending at integer a[]^K Integer dpj = map.get(a[i] ^ k); // If dpj is not NULL if (dpj != null) // Update dp[i] dp[i] = Math.max(dp[i], dpj + 1); // Update ans ans = Math.max(ans, dp[i]); // Update the maximum length of subsequence // ending at element is a[i] in HashMap map.put( a[i], Math.max(map.getOrDefault(a[i], 1), dp[i])); } // Return the ans if ans>=2. // Otherwise, return 0 return ans >= 2 ? ans : 0; } // Driver Code public static void main(String[] args) { // Input int arr[] = { 3, 2, 4, 3, 5 }; int N = arr.length; int K = 1; // Print the length of the longest subsequence System.out.println(xorSubsequence(arr, N, K)); }}
# Python 3 program for above approach # Function to find maximum length of subsequencedef xorSubsequence( a, n, k): # Stores maximum length of subsequence ans = 0 # HashMap to store the longest length of # subsequence ending at an integer, say X map = {} # Stores the maximum length of # subsequence ending at index i dp = [0]* n # Base case map[a[0]] = 1 dp[0] = 1 # Iterate over the range[1, N-1] for i in range(1, n): # Retrieve the longest length of # subsequence ending at integer a[] ^ K # If dpj is not NULL if (a[i] ^ k in map): # Update dp[i] dp[i] = max(dp[i], map[a[i] ^ k] + 1) # Update ans ans = max(ans, dp[i]) # Update the maximum length of subsequence # ending at element is a[i] in HashMap if a[i] in map: map[a[i]] = max(map[a[i]],dp[i]) else: map[a[i]] = max(1, dp[i]) # Return the ans if ans >= 2. # Otherwise, return 0 if ans >= 2 : return ans return 0 # Driver Codeif __name__ == "__main__": # Input arr = [3, 2, 4, 3, 5] N = len(arr) K = 1 # Print the length of the longest subsequence print(xorSubsequence(arr, N, K)) # This code is contributed by chitranayal.
// C# program for above approachusing System;using System.Collections.Generic; public class GFG{ // Function to find maximum length of subsequence public static int xorSubsequence(int []a, int n, int k) { // Stores maximum length of subsequence int ans = 0; // Dictionary to store the longest length of // subsequence ending at an integer, say X Dictionary<int, int> map = new Dictionary<int, int>(); // Stores the maximum length of // subsequence ending at index i int []dp = new int[n]; // Base case map.Add(a[0], 1); dp[0] = 1; // Iterate over the range [1, N-1] for (int i = 1; i < n; i++) { // Retrieve the longest length of // subsequence ending at integer []a^K int dpj = map.ContainsKey(a[i] ^ k)?map[a[i] ^ k]:-1; // If dpj is not NULL if (dpj != 0) // Update dp[i] dp[i] = Math.Max(dp[i], dpj + 1); // Update ans ans = Math.Max(ans, dp[i]); // Update the maximum length of subsequence // ending at element is a[i] in Dictionary if(map.ContainsKey(a[i])) { map[a[i]] = Math.Max(map[a[i]]+1, dp[i]); ; } else { map.Add(a[i], Math.Max(1, dp[i])); } } // Return the ans if ans>=2. // Otherwise, return 0 return ans >= 2 ? ans : 0; } // Driver Code public static void Main(String[] args) { // Input int []arr = { 3, 2, 4, 3, 5 }; int N = arr.Length; int K = 1; // Print the length of the longest subsequence Console.WriteLine(xorSubsequence(arr, N, K)); }} // This code is contributed by shikhasingrajput
<script> // Javascript program for above approach // Function to find maximum length of subsequencefunction xorSubsequence(a, n, k){ // Stores maximum length of subsequence var ans = 0; // Dictionary to store the longest length of // subsequence ending at an integer, say X var map = new Map(); // Stores the maximum length of // subsequence ending at index i var dp = Array(n).fill(0); // Base case map.set(a[0], 1) dp[0] = 1; // Iterate over the range [1, N-1] for (var i = 1; i < n; i++) { var dpj; // Retrieve the longest length of // subsequence ending at integer []a^K if(map.has(a[i] ^ k)) { dpj = map.get(a[i] ^ k); } else{ dpj = -1; } // If dpj is not NULL if (dpj != 0) // Update dp[i] dp[i] = Math.max(dp[i], dpj + 1); // Update ans ans = Math.max(ans, dp[i]); // Update the maximum length of subsequence // ending at element is a[i] in Dictionary if(map.has(a[i])) { map.set(a[i] , Math.max(map.get(a[i])+1, dp[i])); } else { map.set(a[i], Math.max(1, dp[i])); } } // Return the ans if ans>=2. // Otherwise, return 0 return ans >= 2 ? ans : 0;} // Inputvar arr = [3, 2, 4, 3, 5];var N = arr.length;var K = 1; // Print the length of the longest subsequencedocument.write(xorSubsequence(arr, N, K)); // This code is contributed by famously.</script>
3
Time Complexity: O(N)Auxiliary Space: O(N)
divyeshrabadiya07
shikhasingrajput
dharanendralv23
ukasp
divyesh072019
suresh07
famously
adnanirshad158
Kirti_Mangal
Arrays
Dynamic Programming
Mathematical
Recursion
Searching
Sorting
Arrays
Searching
Dynamic Programming
Mathematical
Recursion
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
|
[
{
"code": null,
"e": 26066,
"s": 26038,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 26234,
"s": 26066,
"text": "Given an array arr[] of N non-negative integers and an integer K, the idea is to find the length of the longest subsequence having Xor of adjacent elements equal to K."
},
{
"code": null,
"e": 26244,
"s": 26234,
"text": "Examples:"
},
{
"code": null,
"e": 26501,
"s": 26244,
"text": "Input: N = 5, arr[] = {3, 2, 4, 3, 5}, K = 1Output: 3Explanation:All the subsequences having Xor of adjacent element equal to K are {3, 2}, {2, 3}, {4, 5}, {3, 2, 3}.Therefore, the length of the longest subsequence having xor of adjacent element as 1 is 3."
},
{
"code": null,
"e": 26766,
"s": 26501,
"text": "Input: N = 8, arr[] = {4, 5, 4, 7, 3, 5, 4, 6}, K = 2Output: 3Explanation:All the subsequences having Xor of adjacent element equal to K are {4, 6}, {5, 7}, {7, 5}, {5, 7, 5}.Therefore, the length of the longest subsequence having xor of adjacent element as 1 is 3"
},
{
"code": null,
"e": 26891,
"s": 26766,
"text": "Naive Approach: The idea is to use Dynamic Programming. The given problem can be solved based on the following observations:"
},
{
"code": null,
"e": 26964,
"s": 26891,
"text": "Suppose Dp(i) represent maximum length of subsequence ending at index i."
},
{
"code": null,
"e": 27119,
"s": 26964,
"text": "Then, transition of one state to another state will be as follows:Find index j such that j < i and a[j] ^ a[i] = k.Therefore, Dp(i) = max(Dp(j)+1, Dp(i)) "
},
{
"code": null,
"e": 27169,
"s": 27119,
"text": "Find index j such that j < i and a[j] ^ a[i] = k."
},
{
"code": null,
"e": 27209,
"s": 27169,
"text": "Therefore, Dp(i) = max(Dp(j)+1, Dp(i)) "
},
{
"code": null,
"e": 27254,
"s": 27209,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27381,
"s": 27254,
"text": "Initialize an integer, say ans, to store the length of the longest subsequence and an array, say dp[], to store the dp states."
},
{
"code": null,
"e": 27412,
"s": 27381,
"text": "Define base case as dp[0] = 1."
},
{
"code": null,
"e": 27570,
"s": 27412,
"text": "Iterate over the range [1, N – 1]:Iterate over the range [0, i-1] and update dp[i] as max(dp[i], dp[j] + 1) if a[i] ^ a[j] = K.Update ans as max(ans, dp[i])."
},
{
"code": null,
"e": 27664,
"s": 27570,
"text": "Iterate over the range [0, i-1] and update dp[i] as max(dp[i], dp[j] + 1) if a[i] ^ a[j] = K."
},
{
"code": null,
"e": 27695,
"s": 27664,
"text": "Update ans as max(ans, dp[i])."
},
{
"code": null,
"e": 27761,
"s": 27695,
"text": "Finally, print the maximum length of the longest subsequence ans."
},
{
"code": null,
"e": 27812,
"s": 27761,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27816,
"s": 27812,
"text": "C++"
},
{
"code": null,
"e": 27821,
"s": 27816,
"text": "Java"
},
{
"code": null,
"e": 27829,
"s": 27821,
"text": "Python3"
},
{
"code": null,
"e": 27832,
"s": 27829,
"text": "C#"
},
{
"code": null,
"e": 27843,
"s": 27832,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find maximum length// of subsequence having XOR of// adjacent elements equal to Kint xorSubsequence(int a[], int n, int k){ // Store maximum length of subsequence int ans = 0; // Stores the dp-states int dp[n] = {0}; // Base case dp[0] = 1; // Iterate over the range [1, N-1] for (int i = 1; i < n; i++) { // Iterate over the range [0, i - 1] for (int j = i - 1; j >= 0; j--) { // If arr[i]^arr[j] == K if ((a[i] ^ a[j]) == k) // Update the dp[i] dp[i] = max(dp[i], dp[j] + 1); } // Update the maximum subsequence length ans = max(ans, dp[i]); dp[i] = max(1, dp[i]); } // If length of longest subsequence // is less than 2 then return 0 return ans >= 2 ? ans : 0;} // Driver Codeint main(){ // Input int arr[] = { 3, 2, 4, 3, 5 }; int K = 1; int N = sizeof(arr) / sizeof(arr[0]); // Print the length of longest subsequence cout << xorSubsequence(arr, N, K); return 0;} // This code is contributed by Dharanendra L V",
"e": 28928,
"s": 27843,
"text": null
},
{
"code": "// Java program for the above approach import java.io.*;import java.util.*;class GFG { // Function to find maximum length // of subsequence having XOR of // adjacent elements equal to K public static int xorSubsequence(int a[], int n, int k) { // Store maximum length of subsequence int ans = 0; // Stores the dp-states int dp[] = new int[n]; // Base case dp[0] = 1; // Iterate over the range [1, N-1] for (int i = 1; i < n; i++) { // Iterate over the range [0, i - 1] for (int j = i - 1; j >= 0; j--) { // If arr[i]^arr[j] == K if ((a[i] ^ a[j]) == k) // Update the dp[i] dp[i] = Math.max(dp[i], dp[j] + 1); } // Update the maximum subsequence length ans = Math.max(ans, dp[i]); dp[i] = Math.max(1, dp[i]); } // If length of longest subsequence // is less than 2 then return 0 return ans >= 2 ? ans : 0; } // Driver Code public static void main(String[] args) { // Input int arr[] = { 3, 2, 4, 3, 5 }; int K = 1; int N = arr.length; // Print the length of longest subsequence System.out.println(xorSubsequence(arr, N, K)); }}",
"e": 30290,
"s": 28928,
"text": null
},
{
"code": "# Python program for the above approach # Function to find maximum length# of subsequence having XOR of# adjacent elements equal to Kdef xorSubsequence(a, n, k): # Store maximum length of subsequence ans = 0; # Stores the dp-states dp = [0] * n; # Base case dp[0] = 1; # Iterate over the range [1, N-1] for i in range(1, n): # Iterate over the range [0, i - 1] for j in range(i - 1, -1, -1): # If arr[i]^arr[j] == K if ((a[i] ^ a[j]) == k): # Update the dp[i] dp[i] = max(dp[i], dp[j] + 1); # Update the maximum subsequence length ans = max(ans, dp[i]); dp[i] = max(1, dp[i]); # If length of longest subsequence # is less than 2 then return 0 return ans if ans >= 2 else 0; # Driver Codeif __name__ == '__main__': # Input arr = [3, 2, 4, 3, 5]; K = 1; N = len(arr); # Print the length of longest subsequence print(xorSubsequence(arr, N, K)); # This code contributed by shikhasingrajput",
"e": 31337,
"s": 30290,
"text": null
},
{
"code": "// C# program of the above approachusing System; class GFG{ // Function to find maximum length// of subsequence having XOR of// adjacent elements equal to Kstatic int xorSubsequence(int[] a, int n, int k){ // Store maximum length of subsequence int ans = 0; // Stores the dp-states int[] dp = new int[n]; // Base case dp[0] = 1; // Iterate over the range [1, N-1] for(int i = 1; i < n; i++) { // Iterate over the range [0, i - 1] for(int j = i - 1; j >= 0; j--) { // If arr[i]^arr[j] == K if ((a[i] ^ a[j]) == k) // Update the dp[i] dp[i] = Math.Max(dp[i], dp[j] + 1); } // Update the maximum subsequence length ans = Math.Max(ans, dp[i]); dp[i] = Math.Max(1, dp[i]); } // If length of longest subsequence // is less than 2 then return 0 return ans >= 2 ? ans : 0;} // Driver code static void Main(){ // Input int[] arr = { 3, 2, 4, 3, 5 }; int K = 1; int N = arr.Length; // Print the length of longest subsequence Console.WriteLine(xorSubsequence(arr, N, K)); }} // This code is contributed by divyeshrabadiya07",
"e": 32608,
"s": 31337,
"text": null
},
{
"code": "<script> // Javascript program of the above approach // Function to find maximum length // of subsequence having XOR of // adjacent elements equal to K function xorSubsequence(a, n, k) { // Store maximum length of subsequence let ans = 0; // Stores the dp-states let dp = new Array(n); dp.fill(0); // Base case dp[0] = 1; // Iterate over the range [1, N-1] for(let i = 1; i < n; i++) { // Iterate over the range [0, i - 1] for(let j = i - 1; j >= 0; j--) { // If arr[i]^arr[j] == K if ((a[i] ^ a[j]) == k) // Update the dp[i] dp[i] = Math.max(dp[i], dp[j] + 1); } // Update the maximum subsequence length ans = Math.max(ans, dp[i]); dp[i] = Math.max(1, dp[i]); } // If length of longest subsequence // is less than 2 then return 0 return ans >= 2 ? ans : 0; } let arr = [ 3, 2, 4, 3, 5 ]; let K = 1; let N = arr.length; // Print the length of longest subsequence document.write(xorSubsequence(arr, N, K)); </script>",
"e": 33834,
"s": 32608,
"text": null
},
{
"code": null,
"e": 33836,
"s": 33834,
"text": "3"
},
{
"code": null,
"e": 33882,
"s": 33838,
"text": "Time Complexity: O(N2)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 34125,
"s": 33882,
"text": "Efficient Approach: The above approach can be optimized by using the property of Xor and Hashmap with dynamic programming to store the maximum length of subsequence ending at an integer, resulting in constant time transition of states in DP. "
},
{
"code": null,
"e": 34253,
"s": 34125,
"text": "Initialize an integer say ans =0 to store the length of the longest subsequence and an array say dp[] to store the state of DP."
},
{
"code": null,
"e": 34346,
"s": 34253,
"text": "Initialize a HashMap say mp to store the longest length of subsequence ending at an element."
},
{
"code": null,
"e": 34413,
"s": 34346,
"text": "Define base case as dp[0] = 1 and push the pair {arr[0], 1} in mp."
},
{
"code": null,
"e": 34692,
"s": 34413,
"text": "Iterate over the range [1, N-1]:Find the length of the longest subsequence say dpj ending at element arr[i] ^K from HashMap mp.Update dp[i] as max(dp[i], dpj+1) and update the longest length of subsequence ending at element arr[i] in HashMap mp.Update the ans = max(ans, dp[i])."
},
{
"code": null,
"e": 34788,
"s": 34692,
"text": "Find the length of the longest subsequence say dpj ending at element arr[i] ^K from HashMap mp."
},
{
"code": null,
"e": 34907,
"s": 34788,
"text": "Update dp[i] as max(dp[i], dpj+1) and update the longest length of subsequence ending at element arr[i] in HashMap mp."
},
{
"code": null,
"e": 34941,
"s": 34907,
"text": "Update the ans = max(ans, dp[i])."
},
{
"code": null,
"e": 35007,
"s": 34941,
"text": "Finally, print the maximum length of the longest subsequence ans."
},
{
"code": null,
"e": 35058,
"s": 35007,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 35062,
"s": 35058,
"text": "C++"
},
{
"code": null,
"e": 35067,
"s": 35062,
"text": "Java"
},
{
"code": null,
"e": 35075,
"s": 35067,
"text": "Python3"
},
{
"code": null,
"e": 35078,
"s": 35075,
"text": "C#"
},
{
"code": null,
"e": 35089,
"s": 35078,
"text": "Javascript"
},
{
"code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to find maximum length of subsequenceint xorSubsequence(int a[], int n, int k){ // Stores maximum length of subsequence int ans = 0; // Dictionary to store the longest length of // subsequence ending at an integer, say X map<int, int> map; // Stores the maximum length of // subsequence ending at index i int dp[n] = {0}; // Base case map[a[0]] = 1; dp[0] = 1; // Iterate over the range [1, N-1] for (int i = 1; i < n; i++) { int dpj; // Retrieve the longest length of // subsequence ending at integer []a^K if(map.find(a[i] ^ k) != map.end()) { dpj = map[a[i] ^ k]; } else{ dpj = -1; } // If dpj is not NULL if (dpj != 0) // Update dp[i] dp[i] = max(dp[i], dpj + 1); // Update ans ans = max(ans, dp[i]); // Update the maximum length of subsequence // ending at element is a[i] in Dictionary if(map.find(a[i]) != map.end()) { map[a[i]] = max(map[a[i]]+1, dp[i]); } else { map[a[i]] = max(1, dp[i]); } } // Return the ans if ans>=2. // Otherwise, return 0 return ans >= 2 ? ans : 0;} int main(){ // Input int arr[] = { 3, 2, 4, 3, 5 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 1; // Print the length of the longest subsequence cout << (xorSubsequence(arr, N, K)); return 0;} // This code is contributed by divyesh072019.",
"e": 36722,
"s": 35089,
"text": null
},
{
"code": "// Java program for above approachimport java.io.*;import java.util.*;class GFG{ // Function to find maximum length of subsequence public static int xorSubsequence(int a[], int n, int k) { // Stores maximum length of subsequence int ans = 0; // HashMap to store the longest length of // subsequence ending at an integer, say X HashMap<Integer, Integer> map = new HashMap<>(); // Stores the maximum length of // subsequence ending at index i int dp[] = new int[n]; // Base case map.put(a[0], 1); dp[0] = 1; // Iterate over the range [1, N-1] for (int i = 1; i < n; i++) { // Retrieve the longest length of // subsequence ending at integer a[]^K Integer dpj = map.get(a[i] ^ k); // If dpj is not NULL if (dpj != null) // Update dp[i] dp[i] = Math.max(dp[i], dpj + 1); // Update ans ans = Math.max(ans, dp[i]); // Update the maximum length of subsequence // ending at element is a[i] in HashMap map.put( a[i], Math.max(map.getOrDefault(a[i], 1), dp[i])); } // Return the ans if ans>=2. // Otherwise, return 0 return ans >= 2 ? ans : 0; } // Driver Code public static void main(String[] args) { // Input int arr[] = { 3, 2, 4, 3, 5 }; int N = arr.length; int K = 1; // Print the length of the longest subsequence System.out.println(xorSubsequence(arr, N, K)); }}",
"e": 38149,
"s": 36722,
"text": null
},
{
"code": "# Python 3 program for above approach # Function to find maximum length of subsequencedef xorSubsequence( a, n, k): # Stores maximum length of subsequence ans = 0 # HashMap to store the longest length of # subsequence ending at an integer, say X map = {} # Stores the maximum length of # subsequence ending at index i dp = [0]* n # Base case map[a[0]] = 1 dp[0] = 1 # Iterate over the range[1, N-1] for i in range(1, n): # Retrieve the longest length of # subsequence ending at integer a[] ^ K # If dpj is not NULL if (a[i] ^ k in map): # Update dp[i] dp[i] = max(dp[i], map[a[i] ^ k] + 1) # Update ans ans = max(ans, dp[i]) # Update the maximum length of subsequence # ending at element is a[i] in HashMap if a[i] in map: map[a[i]] = max(map[a[i]],dp[i]) else: map[a[i]] = max(1, dp[i]) # Return the ans if ans >= 2. # Otherwise, return 0 if ans >= 2 : return ans return 0 # Driver Codeif __name__ == \"__main__\": # Input arr = [3, 2, 4, 3, 5] N = len(arr) K = 1 # Print the length of the longest subsequence print(xorSubsequence(arr, N, K)) # This code is contributed by chitranayal.",
"e": 39458,
"s": 38149,
"text": null
},
{
"code": "// C# program for above approachusing System;using System.Collections.Generic; public class GFG{ // Function to find maximum length of subsequence public static int xorSubsequence(int []a, int n, int k) { // Stores maximum length of subsequence int ans = 0; // Dictionary to store the longest length of // subsequence ending at an integer, say X Dictionary<int, int> map = new Dictionary<int, int>(); // Stores the maximum length of // subsequence ending at index i int []dp = new int[n]; // Base case map.Add(a[0], 1); dp[0] = 1; // Iterate over the range [1, N-1] for (int i = 1; i < n; i++) { // Retrieve the longest length of // subsequence ending at integer []a^K int dpj = map.ContainsKey(a[i] ^ k)?map[a[i] ^ k]:-1; // If dpj is not NULL if (dpj != 0) // Update dp[i] dp[i] = Math.Max(dp[i], dpj + 1); // Update ans ans = Math.Max(ans, dp[i]); // Update the maximum length of subsequence // ending at element is a[i] in Dictionary if(map.ContainsKey(a[i])) { map[a[i]] = Math.Max(map[a[i]]+1, dp[i]); ; } else { map.Add(a[i], Math.Max(1, dp[i])); } } // Return the ans if ans>=2. // Otherwise, return 0 return ans >= 2 ? ans : 0; } // Driver Code public static void Main(String[] args) { // Input int []arr = { 3, 2, 4, 3, 5 }; int N = arr.Length; int K = 1; // Print the length of the longest subsequence Console.WriteLine(xorSubsequence(arr, N, K)); }} // This code is contributed by shikhasingrajput",
"e": 41307,
"s": 39458,
"text": null
},
{
"code": "<script> // Javascript program for above approach // Function to find maximum length of subsequencefunction xorSubsequence(a, n, k){ // Stores maximum length of subsequence var ans = 0; // Dictionary to store the longest length of // subsequence ending at an integer, say X var map = new Map(); // Stores the maximum length of // subsequence ending at index i var dp = Array(n).fill(0); // Base case map.set(a[0], 1) dp[0] = 1; // Iterate over the range [1, N-1] for (var i = 1; i < n; i++) { var dpj; // Retrieve the longest length of // subsequence ending at integer []a^K if(map.has(a[i] ^ k)) { dpj = map.get(a[i] ^ k); } else{ dpj = -1; } // If dpj is not NULL if (dpj != 0) // Update dp[i] dp[i] = Math.max(dp[i], dpj + 1); // Update ans ans = Math.max(ans, dp[i]); // Update the maximum length of subsequence // ending at element is a[i] in Dictionary if(map.has(a[i])) { map.set(a[i] , Math.max(map.get(a[i])+1, dp[i])); } else { map.set(a[i], Math.max(1, dp[i])); } } // Return the ans if ans>=2. // Otherwise, return 0 return ans >= 2 ? ans : 0;} // Inputvar arr = [3, 2, 4, 3, 5];var N = arr.length;var K = 1; // Print the length of the longest subsequencedocument.write(xorSubsequence(arr, N, K)); // This code is contributed by famously.</script>",
"e": 42862,
"s": 41307,
"text": null
},
{
"code": null,
"e": 42864,
"s": 42862,
"text": "3"
},
{
"code": null,
"e": 42909,
"s": 42866,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 42929,
"s": 42911,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 42946,
"s": 42929,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 42962,
"s": 42946,
"text": "dharanendralv23"
},
{
"code": null,
"e": 42968,
"s": 42962,
"text": "ukasp"
},
{
"code": null,
"e": 42982,
"s": 42968,
"text": "divyesh072019"
},
{
"code": null,
"e": 42991,
"s": 42982,
"text": "suresh07"
},
{
"code": null,
"e": 43000,
"s": 42991,
"text": "famously"
},
{
"code": null,
"e": 43015,
"s": 43000,
"text": "adnanirshad158"
},
{
"code": null,
"e": 43028,
"s": 43015,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 43035,
"s": 43028,
"text": "Arrays"
},
{
"code": null,
"e": 43055,
"s": 43035,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 43068,
"s": 43055,
"text": "Mathematical"
},
{
"code": null,
"e": 43078,
"s": 43068,
"text": "Recursion"
},
{
"code": null,
"e": 43088,
"s": 43078,
"text": "Searching"
},
{
"code": null,
"e": 43096,
"s": 43088,
"text": "Sorting"
},
{
"code": null,
"e": 43103,
"s": 43096,
"text": "Arrays"
},
{
"code": null,
"e": 43113,
"s": 43103,
"text": "Searching"
},
{
"code": null,
"e": 43133,
"s": 43113,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 43146,
"s": 43133,
"text": "Mathematical"
},
{
"code": null,
"e": 43156,
"s": 43146,
"text": "Recursion"
},
{
"code": null,
"e": 43164,
"s": 43156,
"text": "Sorting"
},
{
"code": null,
"e": 43262,
"s": 43164,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43289,
"s": 43262,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 43320,
"s": 43289,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 43345,
"s": 43320,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 43383,
"s": 43345,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 43404,
"s": 43383,
"text": "Next Greater Element"
},
{
"code": null,
"e": 43433,
"s": 43404,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 43463,
"s": 43433,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 43497,
"s": 43463,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 43528,
"s": 43497,
"text": "Bellman–Ford Algorithm | DP-23"
}
] |
strlen() function in c - GeeksforGeeks
|
28 Sep, 2018
The strlen() function calculates the length of a given string.The strlen() function is defined in string.h header file. It doesn’t count null character ‘\0’.
Syntax:
int strlen(const char *str);
Parameter:
str: It represents the string variable whose length we have to find.
Return: This function returns the length of string passed.
Below programs illustrate the strlen() function in C:
Example 1:-
// c program to demonstrate// example of strlen() function. #include<stdio.h>#include <string.h> int main(){ char ch[]={'g', 'e', 'e', 'k', 's', '\0'}; printf("Length of string is: %d", strlen(ch)); return 0;}
Output :
Length of string is: 5
Example 2:-
// c program to demonstrate// example of strlen() function. #include<stdio.h>#include <string.h> int main(){ char str[]= "geeks"; printf("Length of string is: %d", strlen(str)); return 0;}
Output:
Length of string is: 5
Example 3:-
// c program to demonstrate// example of strlen() function.#include<stdio.h>#include <string.h> int main(){ char *str = "geeks"; printf("Length of string is: %d", strlen(str)); return 0;}
Output :
Length of string is: 5
C-Library
C-String
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Converting Strings to Numbers in C/C++
Function Pointer in C
rand() and srand() in C/C++
std::string class in C++
fork() in C
Different methods to reverse a string in C/C++
Enumeration (or enum) in C
|
[
{
"code": null,
"e": 25657,
"s": 25629,
"text": "\n28 Sep, 2018"
},
{
"code": null,
"e": 25815,
"s": 25657,
"text": "The strlen() function calculates the length of a given string.The strlen() function is defined in string.h header file. It doesn’t count null character ‘\\0’."
},
{
"code": null,
"e": 25823,
"s": 25815,
"text": "Syntax:"
},
{
"code": null,
"e": 25853,
"s": 25823,
"text": "int strlen(const char *str);\n"
},
{
"code": null,
"e": 25864,
"s": 25853,
"text": "Parameter:"
},
{
"code": null,
"e": 25933,
"s": 25864,
"text": "str: It represents the string variable whose length we have to find."
},
{
"code": null,
"e": 25992,
"s": 25933,
"text": "Return: This function returns the length of string passed."
},
{
"code": null,
"e": 26046,
"s": 25992,
"text": "Below programs illustrate the strlen() function in C:"
},
{
"code": null,
"e": 26058,
"s": 26046,
"text": "Example 1:-"
},
{
"code": "// c program to demonstrate// example of strlen() function. #include<stdio.h>#include <string.h> int main(){ char ch[]={'g', 'e', 'e', 'k', 's', '\\0'}; printf(\"Length of string is: %d\", strlen(ch)); return 0;}",
"e": 26278,
"s": 26058,
"text": null
},
{
"code": null,
"e": 26287,
"s": 26278,
"text": "Output :"
},
{
"code": null,
"e": 26310,
"s": 26287,
"text": "Length of string is: 5"
},
{
"code": null,
"e": 26322,
"s": 26310,
"text": "Example 2:-"
},
{
"code": "// c program to demonstrate// example of strlen() function. #include<stdio.h>#include <string.h> int main(){ char str[]= \"geeks\"; printf(\"Length of string is: %d\", strlen(str)); return 0;}",
"e": 26521,
"s": 26322,
"text": null
},
{
"code": null,
"e": 26529,
"s": 26521,
"text": "Output:"
},
{
"code": null,
"e": 26552,
"s": 26529,
"text": "Length of string is: 5"
},
{
"code": null,
"e": 26564,
"s": 26552,
"text": "Example 3:-"
},
{
"code": "// c program to demonstrate// example of strlen() function.#include<stdio.h>#include <string.h> int main(){ char *str = \"geeks\"; printf(\"Length of string is: %d\", strlen(str)); return 0;}",
"e": 26761,
"s": 26564,
"text": null
},
{
"code": null,
"e": 26770,
"s": 26761,
"text": "Output :"
},
{
"code": null,
"e": 26793,
"s": 26770,
"text": "Length of string is: 5"
},
{
"code": null,
"e": 26803,
"s": 26793,
"text": "C-Library"
},
{
"code": null,
"e": 26812,
"s": 26803,
"text": "C-String"
},
{
"code": null,
"e": 26823,
"s": 26812,
"text": "C Language"
},
{
"code": null,
"e": 26921,
"s": 26823,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26938,
"s": 26921,
"text": "Substring in C++"
},
{
"code": null,
"e": 26973,
"s": 26938,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 27019,
"s": 26973,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 27058,
"s": 27019,
"text": "Converting Strings to Numbers in C/C++"
},
{
"code": null,
"e": 27080,
"s": 27058,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27108,
"s": 27080,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 27133,
"s": 27108,
"text": "std::string class in C++"
},
{
"code": null,
"e": 27145,
"s": 27133,
"text": "fork() in C"
},
{
"code": null,
"e": 27192,
"s": 27145,
"text": "Different methods to reverse a string in C/C++"
}
] |
HashMap putIfAbsent(key, value) method in Java with Examples - GeeksforGeeks
|
19 Feb, 2021
The putIfAbsent(K key, V value) method of HashMap class is used to map the specified key with the specified value, only if no such key exists (or is mapped to null) in this HashMap instance.
Syntax:
public V putIfAbsent(K key, V value)
Parameters: This method accepts two parameters:
key: which is the key with which provided value has to be mapped.
value: which is the value which has to be associated with the provided key, if absent.
Return Value:
This method returns null (if there was no mapping with the provided key before or it was mapped to a null value) or current value associated with the provided key.
Exceptions:
This method can throw the following exceptions:
NullPointerException: if the specified key or value is null, and this map does not support null value.
IllegalArgumentException: if the specified key or value is preventing it from being stored in the map.
UnsupportedOperationException – if the put operation is not supported by this map (optional)
ClassCastException – if the key or value is of an inappropriate type for this map (optional)
Program 1:
Java
// Java program to demonstrate// putIfAbsent(Key, value) method. import java.util.HashMap; public class TestClass { // Main method public static void main(String[] args) { // create a HashMap and add some values HashMap<String, Integer> map = new HashMap<>(); map.put("a", 10000); map.put("b", 55000); map.put("c", 44300); map.put("e", 53200); // print original map System.out.println("HashMap:\n " + map.toString()); // put a new value which is not mapped // before in map map.putIfAbsent("d", 77633); System.out.println("New HashMap:\n " + map); // try to put a new value with existing key // before in map map.putIfAbsent("d", 55555); // print newly mapped map System.out.println("Unchanged HashMap:\n " + map); }}
HashMap:
{a=10000, b=55000, c=44300, e=53200}
New HashMap:
{a=10000, b=55000, c=44300, d=77633, e=53200}
Unchanged HashMap:
{a=10000, b=55000, c=44300, d=77633, e=53200}
Program 2:
Java
// Java program to demonstrate// putIfAbsent(Key, value) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // create a HashMap and add some values HashMap<String, Integer> map = new HashMap<>(); map.put("a", 10000); map.put("b", 55000); map.put("c", 44300); map.put("e", null); // print original map System.out.println("HashMap:\n " + map.toString()); // put a new value which is not mapped // before in map and store the returned // value in r1 Integer r1 = map.putIfAbsent("d", 77633); // put a new value for key 'e' which is mapped // with a null value, and store the returned // value in r2 Integer r2 = map.putIfAbsent("e", 77633); // print the value of r1 System.out.println("Value of r1:\n " + r1); // print the value of r2 System.out.println("Value of r2:\n " + r2); // print newly mapped map System.out.println("New HashMap:\n " + map); }}
HashMap:
{a=10000, b=55000, c=44300, e=null}
Value of r1:
null
Value of r2:
null
New HashMap:
{a=10000, b=55000, c=44300, d=77633, e=77633}
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#putIfAbsent-K-V-
dharmveersingh1
Java-Functions
Java-HashMap
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
|
[
{
"code": null,
"e": 25967,
"s": 25939,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 26159,
"s": 25967,
"text": "The putIfAbsent(K key, V value) method of HashMap class is used to map the specified key with the specified value, only if no such key exists (or is mapped to null) in this HashMap instance."
},
{
"code": null,
"e": 26169,
"s": 26159,
"text": "Syntax: "
},
{
"code": null,
"e": 26206,
"s": 26169,
"text": "public V putIfAbsent(K key, V value)"
},
{
"code": null,
"e": 26254,
"s": 26206,
"text": "Parameters: This method accepts two parameters:"
},
{
"code": null,
"e": 26320,
"s": 26254,
"text": "key: which is the key with which provided value has to be mapped."
},
{
"code": null,
"e": 26407,
"s": 26320,
"text": "value: which is the value which has to be associated with the provided key, if absent."
},
{
"code": null,
"e": 26422,
"s": 26407,
"text": "Return Value: "
},
{
"code": null,
"e": 26586,
"s": 26422,
"text": "This method returns null (if there was no mapping with the provided key before or it was mapped to a null value) or current value associated with the provided key."
},
{
"code": null,
"e": 26599,
"s": 26586,
"text": "Exceptions: "
},
{
"code": null,
"e": 26649,
"s": 26599,
"text": "This method can throw the following exceptions: "
},
{
"code": null,
"e": 26752,
"s": 26649,
"text": "NullPointerException: if the specified key or value is null, and this map does not support null value."
},
{
"code": null,
"e": 26855,
"s": 26752,
"text": "IllegalArgumentException: if the specified key or value is preventing it from being stored in the map."
},
{
"code": null,
"e": 26948,
"s": 26855,
"text": "UnsupportedOperationException – if the put operation is not supported by this map (optional)"
},
{
"code": null,
"e": 27041,
"s": 26948,
"text": "ClassCastException – if the key or value is of an inappropriate type for this map (optional)"
},
{
"code": null,
"e": 27054,
"s": 27041,
"text": "Program 1: "
},
{
"code": null,
"e": 27059,
"s": 27054,
"text": "Java"
},
{
"code": "// Java program to demonstrate// putIfAbsent(Key, value) method. import java.util.HashMap; public class TestClass { // Main method public static void main(String[] args) { // create a HashMap and add some values HashMap<String, Integer> map = new HashMap<>(); map.put(\"a\", 10000); map.put(\"b\", 55000); map.put(\"c\", 44300); map.put(\"e\", 53200); // print original map System.out.println(\"HashMap:\\n \" + map.toString()); // put a new value which is not mapped // before in map map.putIfAbsent(\"d\", 77633); System.out.println(\"New HashMap:\\n \" + map); // try to put a new value with existing key // before in map map.putIfAbsent(\"d\", 55555); // print newly mapped map System.out.println(\"Unchanged HashMap:\\n \" + map); }}",
"e": 27915,
"s": 27059,
"text": null
},
{
"code": null,
"e": 28088,
"s": 27915,
"text": "HashMap:\n {a=10000, b=55000, c=44300, e=53200}\nNew HashMap:\n {a=10000, b=55000, c=44300, d=77633, e=53200}\nUnchanged HashMap:\n {a=10000, b=55000, c=44300, d=77633, e=53200}"
},
{
"code": null,
"e": 28100,
"s": 28088,
"text": "Program 2: "
},
{
"code": null,
"e": 28105,
"s": 28100,
"text": "Java"
},
{
"code": "// Java program to demonstrate// putIfAbsent(Key, value) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // create a HashMap and add some values HashMap<String, Integer> map = new HashMap<>(); map.put(\"a\", 10000); map.put(\"b\", 55000); map.put(\"c\", 44300); map.put(\"e\", null); // print original map System.out.println(\"HashMap:\\n \" + map.toString()); // put a new value which is not mapped // before in map and store the returned // value in r1 Integer r1 = map.putIfAbsent(\"d\", 77633); // put a new value for key 'e' which is mapped // with a null value, and store the returned // value in r2 Integer r2 = map.putIfAbsent(\"e\", 77633); // print the value of r1 System.out.println(\"Value of r1:\\n \" + r1); // print the value of r2 System.out.println(\"Value of r2:\\n \" + r2); // print newly mapped map System.out.println(\"New HashMap:\\n \" + map); }}",
"e": 29181,
"s": 28105,
"text": null
},
{
"code": null,
"e": 29325,
"s": 29181,
"text": "HashMap:\n {a=10000, b=55000, c=44300, e=null}\nValue of r1:\n null\nValue of r2:\n null\nNew HashMap:\n {a=10000, b=55000, c=44300, d=77633, e=77633}"
},
{
"code": null,
"e": 29419,
"s": 29325,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#putIfAbsent-K-V- "
},
{
"code": null,
"e": 29435,
"s": 29419,
"text": "dharmveersingh1"
},
{
"code": null,
"e": 29450,
"s": 29435,
"text": "Java-Functions"
},
{
"code": null,
"e": 29463,
"s": 29450,
"text": "Java-HashMap"
},
{
"code": null,
"e": 29470,
"s": 29463,
"text": "Picked"
},
{
"code": null,
"e": 29475,
"s": 29470,
"text": "Java"
},
{
"code": null,
"e": 29480,
"s": 29475,
"text": "Java"
},
{
"code": null,
"e": 29578,
"s": 29480,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29629,
"s": 29578,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 29659,
"s": 29629,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29674,
"s": 29659,
"text": "Stream In Java"
},
{
"code": null,
"e": 29693,
"s": 29674,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29724,
"s": 29693,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 29742,
"s": 29724,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29774,
"s": 29742,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 29794,
"s": 29774,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29818,
"s": 29794,
"text": "Singleton Class in Java"
}
] |
Format Specifiers in Java
|
06 Jul, 2020
Format specifiers begin with a percent character (%) and terminate with a “type character, ” which indicates the type of data (int, float, etc.) that will be converted the basic manner in which the data will be represented (decimal, hexadecimal, etc.)The general syntax of a format specifier is
% [flags] [width] [.precision] [argsize] typechar
The format() method of Formatter class accepts a wide variety of format specifiers. When an uppercase specifier is used, then letters are shown in uppercase. Otherwise, the upper- and lowercase specifiers perform the same conversion.
Space format specifier : When creating columns of numbers, it is sometimes very useful to print a space before a positive number so that positive and negative number get aligned. To do this, space format specifier can be used.Syntax:Formatter().format("% d", -111);
Formatter().format("% d", 111);
Output:
-111
111
Example:// Java program to demonstrate// the space format specifier import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // Use Space format specifier formatter.format("%d", -111); System.out.println(formatter); formatter = new Formatter(); formatter.format("% d", 111); System.out.println(formatter); formatter = new Formatter(); formatter.format("% d", -222); System.out.println(formatter); formatter = new Formatter(); formatter.format("% d", 222); System.out.println(formatter); }}Output:-111
111
-222
222
+ Sign Specifier: This adds the + sign before positive numeric value, and has no effect on negative numeric value.Syntax:Formatter().format("%+d", 111);
Output:
+111
Example:// Java program to demonstrate// the + sign Specifier format specifiers. import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // + sign specifier formatter = new Formatter(); formatter.format("%+d", 111); System.out.println(formatter); // + sign specifier // on - sign, it will have no effect formatter = new Formatter(); formatter.format("%+d", -111); System.out.println(formatter); }}Output:+111
-111
( specifier: This specifier puts the negative numeric values inside the parentheses, and has no effect on the positive numeric values.Syntax:Formatter().format("%(d", -111);
Formatter().format("%(d", 111);
Output:
(111)
111
Example:// Java program to demonstrate// the ( Specifiers format specifiers. import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // ( Specifier formatter = new Formatter(); formatter.format("%(d", -111); System.out.println(formatter); formatter = new Formatter(); formatter.format("%(d", 111); System.out.println(formatter); }}Output:(111)
111
Comma, Specifier: For displaying large numbers, it is often useful to add grouping separators by comma (, ). For example, the value is 1000000 more easily read when formatted as 1, 000, 000. To add grouping specifiers (, ) use the comma(, ) Specifier.Syntax:Formatter().format("%, d", 1000000);
Output:
1, 000, 000Example:// Java program to demonstrate// the comma format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // comma Specifier formatter = new Formatter(); formatter.format("%, d", 1000000); System.out.println(formatter); // comma Specifier formatter = new Formatter(); formatter.format("%, .3f", 32659526566.4521); System.out.println(formatter); }}Output:1, 000, 000
32, 659, 526, 566.452
Left Justification(-) Specifier: By default all output is right-shifted. That is, if the field width is longer than the data printed, data will be placed on the right side of the field. One can force output to be left-justified by placing a minus sign directly after the %. For instance, %-20.4f left justifies a floating-point number with two decimal places in a 20-character field.Syntax:Formatter().format("|%-20.4f|", 1234.1234);
Output:
| 1234.1234|
|1234.1234 |
Example:// Java program to demonstrate// the left justification format specifiers. import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // right justify by default formatter = new Formatter(); formatter.format("|%20.4f|", 1234.1234); System.out.println(formatter); // left justify formatter = new Formatter(); formatter.format("|%-20.4f|", 1234.1234); System.out.println(formatter); }}Output:| 1234.1234|
|1234.1234 |
The %n format specifiers:The %n format specifier is different from the others in that it doesn’t take arguments. It is simply an escape sequence that inserts a character into the output. The %n inserts a newline. It can’t be entered directly into the format string.// Java program to demonstrate// the newline %n format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // newline format specifier formatter.format("Geeks %nFor %nGeeks"); // Print the output System.out.println(formatter); }}Output:Geeks
For
Geeks
The %% format specifiers:The %% format specifier is different from the others in that it doesn’t take arguments. It is simply an escape sequence that inserts a character into the output. The %% inserts a % sign. It can’t be entered directly into the format string.// Java program to demonstrate// the %% format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // %% format specifier formatter.format("10 %% 4 = 2"); // Print the output System.out.println(formatter); }}Output:10 % 4 = 2
The %x %X format specifiers:The %x or %X format specifier is is used to represent the integer Hexadecimal value. %x displays the hexadecimal values with lowercase alphabets whereas the %X specifier displays the hexadecimal values with uppercase alphabets.// Java program to demonstrate// the integer-Hexadecimal %x and %X// format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // %x format specifier // It prints the number in Hexadecimal // with lowercase alphabets formatter.format("%x", 250); // Print the output System.out.println("LowerCase Hexadecimal" + " using %x: " + formatter); // %X format specifier // It prints the number in Hexadecimal // with uppercase alphabets formatter = new Formatter(); formatter.format("%X", 250); // Print the output System.out.println("UpperCase Hexadecimal" + " using %X: " + formatter); }}Output:LowerCase Hexadecimal using %x: fa
UpperCase Hexadecimal using %X: FA
The %e %E format specifiers:The %e or %E format specifier is is used to represent the Scientific Notation of a value. %e displays the Scientific Notation with lowercase alphabets whereas the %E specifier displays the Scientific Notation with uppercase alphabets.// Java program to demonstrate// the Scientific Notation %e and %E// format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // %e format specifier // It prints the number in Scientific Notation // with lowercase alphabets formatter.format("%e", 123.1234); // Print the output System.out.println("LowerCase Scientific Notation" + " using %e: " + formatter); // %E format specifier // It prints the number in Scientific Notation // with uppercase alphabets formatter = new Formatter(); formatter.format("%E", 123.1234); // Print the output System.out.println("UpperCase Scientific Notation" + " using %E: " + formatter); }}Output:LowerCase Scientific Notation using %e: 1.231234e+02
UpperCase Scientific Notation using %E: 1.231234E+02
Precision FormatsA precision specifier can be applied to the %f, %e, %g, and %s format specifiers.// Java program to demonstrate// Prrecision Format specifiers import java.util.Formatter; public class GFG { public static void main(String args[]) { // Create the Formatter instance Formatter formatter = new Formatter(); // added floating-point data // using the %f or %e specifiers, // Format to 2 decimal places // in a 16 character field. formatter = new Formatter(); formatter.format("%16.2e", 123.1234567); System.out.println("Scientific notation to 2 places: " + formatter); // Format 4 decimal places. formatter = new Formatter(); formatter.format("%.4f", 123.1234567); System.out.println("Decimal floating-point" + " notation to 4 places: " + formatter); // Format 4 places. // The %g format specifier causes Formatter // to use either %f or %e, whichever is shorter formatter = new Formatter(); formatter.format("%.4g", 123.1234567); System.out.println("Scientific or Decimal floating-point " + "notation to 4 places: " + formatter); // Display at most 15 characters in a string. formatter = new Formatter(); formatter.format("%.15s", "12345678901234567890"); System.out.println("String notation to 15 places: " + formatter); // Format into 10 digit formatter = new Formatter(); formatter.format("%010d", 88); System.out.println("value in 10 digits: " + formatter); }}Output:Scientific notation to 2 places: 1.23e+02
Decimal floating-point notation to 4 places: 123.1235
Scientific or Decimal floating-point notation to 4 places: 123.1
String notation to 15 places: 123456789012345
value in 10 digits: 0000000088
Space format specifier : When creating columns of numbers, it is sometimes very useful to print a space before a positive number so that positive and negative number get aligned. To do this, space format specifier can be used.Syntax:Formatter().format("% d", -111);
Formatter().format("% d", 111);
Output:
-111
111
Example:// Java program to demonstrate// the space format specifier import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // Use Space format specifier formatter.format("%d", -111); System.out.println(formatter); formatter = new Formatter(); formatter.format("% d", 111); System.out.println(formatter); formatter = new Formatter(); formatter.format("% d", -222); System.out.println(formatter); formatter = new Formatter(); formatter.format("% d", 222); System.out.println(formatter); }}Output:-111
111
-222
222
Syntax:
Formatter().format("% d", -111);
Formatter().format("% d", 111);
Output:
-111
111
Example:
// Java program to demonstrate// the space format specifier import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // Use Space format specifier formatter.format("%d", -111); System.out.println(formatter); formatter = new Formatter(); formatter.format("% d", 111); System.out.println(formatter); formatter = new Formatter(); formatter.format("% d", -222); System.out.println(formatter); formatter = new Formatter(); formatter.format("% d", 222); System.out.println(formatter); }}
-111
111
-222
222
+ Sign Specifier: This adds the + sign before positive numeric value, and has no effect on negative numeric value.Syntax:Formatter().format("%+d", 111);
Output:
+111
Example:// Java program to demonstrate// the + sign Specifier format specifiers. import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // + sign specifier formatter = new Formatter(); formatter.format("%+d", 111); System.out.println(formatter); // + sign specifier // on - sign, it will have no effect formatter = new Formatter(); formatter.format("%+d", -111); System.out.println(formatter); }}Output:+111
-111
Syntax:
Formatter().format("%+d", 111);
Output:
+111
Example:
// Java program to demonstrate// the + sign Specifier format specifiers. import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // + sign specifier formatter = new Formatter(); formatter.format("%+d", 111); System.out.println(formatter); // + sign specifier // on - sign, it will have no effect formatter = new Formatter(); formatter.format("%+d", -111); System.out.println(formatter); }}
+111
-111
( specifier: This specifier puts the negative numeric values inside the parentheses, and has no effect on the positive numeric values.Syntax:Formatter().format("%(d", -111);
Formatter().format("%(d", 111);
Output:
(111)
111
Example:// Java program to demonstrate// the ( Specifiers format specifiers. import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // ( Specifier formatter = new Formatter(); formatter.format("%(d", -111); System.out.println(formatter); formatter = new Formatter(); formatter.format("%(d", 111); System.out.println(formatter); }}Output:(111)
111
Syntax:
Formatter().format("%(d", -111);
Formatter().format("%(d", 111);
Output:
(111)
111
Example:
// Java program to demonstrate// the ( Specifiers format specifiers. import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // ( Specifier formatter = new Formatter(); formatter.format("%(d", -111); System.out.println(formatter); formatter = new Formatter(); formatter.format("%(d", 111); System.out.println(formatter); }}
(111)
111
Comma, Specifier: For displaying large numbers, it is often useful to add grouping separators by comma (, ). For example, the value is 1000000 more easily read when formatted as 1, 000, 000. To add grouping specifiers (, ) use the comma(, ) Specifier.Syntax:Formatter().format("%, d", 1000000);
Output:
1, 000, 000Example:// Java program to demonstrate// the comma format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // comma Specifier formatter = new Formatter(); formatter.format("%, d", 1000000); System.out.println(formatter); // comma Specifier formatter = new Formatter(); formatter.format("%, .3f", 32659526566.4521); System.out.println(formatter); }}Output:1, 000, 000
32, 659, 526, 566.452
Syntax:
Formatter().format("%, d", 1000000);
Output:
1, 000, 000
Example:
// Java program to demonstrate// the comma format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // comma Specifier formatter = new Formatter(); formatter.format("%, d", 1000000); System.out.println(formatter); // comma Specifier formatter = new Formatter(); formatter.format("%, .3f", 32659526566.4521); System.out.println(formatter); }}
1, 000, 000
32, 659, 526, 566.452
Left Justification(-) Specifier: By default all output is right-shifted. That is, if the field width is longer than the data printed, data will be placed on the right side of the field. One can force output to be left-justified by placing a minus sign directly after the %. For instance, %-20.4f left justifies a floating-point number with two decimal places in a 20-character field.Syntax:Formatter().format("|%-20.4f|", 1234.1234);
Output:
| 1234.1234|
|1234.1234 |
Example:// Java program to demonstrate// the left justification format specifiers. import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // right justify by default formatter = new Formatter(); formatter.format("|%20.4f|", 1234.1234); System.out.println(formatter); // left justify formatter = new Formatter(); formatter.format("|%-20.4f|", 1234.1234); System.out.println(formatter); }}Output:| 1234.1234|
|1234.1234 |
Syntax:
Formatter().format("|%-20.4f|", 1234.1234);
Output:
| 1234.1234|
|1234.1234 |
Example:
// Java program to demonstrate// the left justification format specifiers. import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // right justify by default formatter = new Formatter(); formatter.format("|%20.4f|", 1234.1234); System.out.println(formatter); // left justify formatter = new Formatter(); formatter.format("|%-20.4f|", 1234.1234); System.out.println(formatter); }}
| 1234.1234|
|1234.1234 |
The %n format specifiers:The %n format specifier is different from the others in that it doesn’t take arguments. It is simply an escape sequence that inserts a character into the output. The %n inserts a newline. It can’t be entered directly into the format string.// Java program to demonstrate// the newline %n format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // newline format specifier formatter.format("Geeks %nFor %nGeeks"); // Print the output System.out.println(formatter); }}Output:Geeks
For
Geeks
// Java program to demonstrate// the newline %n format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // newline format specifier formatter.format("Geeks %nFor %nGeeks"); // Print the output System.out.println(formatter); }}
Geeks
For
Geeks
The %% format specifiers:The %% format specifier is different from the others in that it doesn’t take arguments. It is simply an escape sequence that inserts a character into the output. The %% inserts a % sign. It can’t be entered directly into the format string.// Java program to demonstrate// the %% format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // %% format specifier formatter.format("10 %% 4 = 2"); // Print the output System.out.println(formatter); }}Output:10 % 4 = 2
// Java program to demonstrate// the %% format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // %% format specifier formatter.format("10 %% 4 = 2"); // Print the output System.out.println(formatter); }}
10 % 4 = 2
The %x %X format specifiers:The %x or %X format specifier is is used to represent the integer Hexadecimal value. %x displays the hexadecimal values with lowercase alphabets whereas the %X specifier displays the hexadecimal values with uppercase alphabets.// Java program to demonstrate// the integer-Hexadecimal %x and %X// format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // %x format specifier // It prints the number in Hexadecimal // with lowercase alphabets formatter.format("%x", 250); // Print the output System.out.println("LowerCase Hexadecimal" + " using %x: " + formatter); // %X format specifier // It prints the number in Hexadecimal // with uppercase alphabets formatter = new Formatter(); formatter.format("%X", 250); // Print the output System.out.println("UpperCase Hexadecimal" + " using %X: " + formatter); }}Output:LowerCase Hexadecimal using %x: fa
UpperCase Hexadecimal using %X: FA
// Java program to demonstrate// the integer-Hexadecimal %x and %X// format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // %x format specifier // It prints the number in Hexadecimal // with lowercase alphabets formatter.format("%x", 250); // Print the output System.out.println("LowerCase Hexadecimal" + " using %x: " + formatter); // %X format specifier // It prints the number in Hexadecimal // with uppercase alphabets formatter = new Formatter(); formatter.format("%X", 250); // Print the output System.out.println("UpperCase Hexadecimal" + " using %X: " + formatter); }}
LowerCase Hexadecimal using %x: fa
UpperCase Hexadecimal using %X: FA
The %e %E format specifiers:The %e or %E format specifier is is used to represent the Scientific Notation of a value. %e displays the Scientific Notation with lowercase alphabets whereas the %E specifier displays the Scientific Notation with uppercase alphabets.// Java program to demonstrate// the Scientific Notation %e and %E// format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // %e format specifier // It prints the number in Scientific Notation // with lowercase alphabets formatter.format("%e", 123.1234); // Print the output System.out.println("LowerCase Scientific Notation" + " using %e: " + formatter); // %E format specifier // It prints the number in Scientific Notation // with uppercase alphabets formatter = new Formatter(); formatter.format("%E", 123.1234); // Print the output System.out.println("UpperCase Scientific Notation" + " using %E: " + formatter); }}Output:LowerCase Scientific Notation using %e: 1.231234e+02
UpperCase Scientific Notation using %E: 1.231234E+02
// Java program to demonstrate// the Scientific Notation %e and %E// format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // %e format specifier // It prints the number in Scientific Notation // with lowercase alphabets formatter.format("%e", 123.1234); // Print the output System.out.println("LowerCase Scientific Notation" + " using %e: " + formatter); // %E format specifier // It prints the number in Scientific Notation // with uppercase alphabets formatter = new Formatter(); formatter.format("%E", 123.1234); // Print the output System.out.println("UpperCase Scientific Notation" + " using %E: " + formatter); }}
LowerCase Scientific Notation using %e: 1.231234e+02
UpperCase Scientific Notation using %E: 1.231234E+02
Precision FormatsA precision specifier can be applied to the %f, %e, %g, and %s format specifiers.// Java program to demonstrate// Prrecision Format specifiers import java.util.Formatter; public class GFG { public static void main(String args[]) { // Create the Formatter instance Formatter formatter = new Formatter(); // added floating-point data // using the %f or %e specifiers, // Format to 2 decimal places // in a 16 character field. formatter = new Formatter(); formatter.format("%16.2e", 123.1234567); System.out.println("Scientific notation to 2 places: " + formatter); // Format 4 decimal places. formatter = new Formatter(); formatter.format("%.4f", 123.1234567); System.out.println("Decimal floating-point" + " notation to 4 places: " + formatter); // Format 4 places. // The %g format specifier causes Formatter // to use either %f or %e, whichever is shorter formatter = new Formatter(); formatter.format("%.4g", 123.1234567); System.out.println("Scientific or Decimal floating-point " + "notation to 4 places: " + formatter); // Display at most 15 characters in a string. formatter = new Formatter(); formatter.format("%.15s", "12345678901234567890"); System.out.println("String notation to 15 places: " + formatter); // Format into 10 digit formatter = new Formatter(); formatter.format("%010d", 88); System.out.println("value in 10 digits: " + formatter); }}Output:Scientific notation to 2 places: 1.23e+02
Decimal floating-point notation to 4 places: 123.1235
Scientific or Decimal floating-point notation to 4 places: 123.1
String notation to 15 places: 123456789012345
value in 10 digits: 0000000088
// Java program to demonstrate// Prrecision Format specifiers import java.util.Formatter; public class GFG { public static void main(String args[]) { // Create the Formatter instance Formatter formatter = new Formatter(); // added floating-point data // using the %f or %e specifiers, // Format to 2 decimal places // in a 16 character field. formatter = new Formatter(); formatter.format("%16.2e", 123.1234567); System.out.println("Scientific notation to 2 places: " + formatter); // Format 4 decimal places. formatter = new Formatter(); formatter.format("%.4f", 123.1234567); System.out.println("Decimal floating-point" + " notation to 4 places: " + formatter); // Format 4 places. // The %g format specifier causes Formatter // to use either %f or %e, whichever is shorter formatter = new Formatter(); formatter.format("%.4g", 123.1234567); System.out.println("Scientific or Decimal floating-point " + "notation to 4 places: " + formatter); // Display at most 15 characters in a string. formatter = new Formatter(); formatter.format("%.15s", "12345678901234567890"); System.out.println("String notation to 15 places: " + formatter); // Format into 10 digit formatter = new Formatter(); formatter.format("%010d", 88); System.out.println("value in 10 digits: " + formatter); }}
Scientific notation to 2 places: 1.23e+02
Decimal floating-point notation to 4 places: 123.1235
Scientific or Decimal floating-point notation to 4 places: 123.1
String notation to 15 places: 123456789012345
value in 10 digits: 0000000088
Related Article : Format Specifiers in C
Akanksha_Rai
gowtham_yuvaraj
ritudpande
Java-Output
Java-Strings
Technical Scripter 2018
Java
Technical Scripter
Java-Strings
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": 52,
"s": 24,
"text": "\n06 Jul, 2020"
},
{
"code": null,
"e": 347,
"s": 52,
"text": "Format specifiers begin with a percent character (%) and terminate with a “type character, ” which indicates the type of data (int, float, etc.) that will be converted the basic manner in which the data will be represented (decimal, hexadecimal, etc.)The general syntax of a format specifier is"
},
{
"code": null,
"e": 397,
"s": 347,
"text": "% [flags] [width] [.precision] [argsize] typechar"
},
{
"code": null,
"e": 631,
"s": 397,
"text": "The format() method of Formatter class accepts a wide variety of format specifiers. When an uppercase specifier is used, then letters are shown in uppercase. Otherwise, the upper- and lowercase specifiers perform the same conversion."
},
{
"code": null,
"e": 11155,
"s": 631,
"text": "Space format specifier : When creating columns of numbers, it is sometimes very useful to print a space before a positive number so that positive and negative number get aligned. To do this, space format specifier can be used.Syntax:Formatter().format(\"% d\", -111);\nFormatter().format(\"% d\", 111);\n\nOutput:\n-111\n 111\nExample:// Java program to demonstrate// the space format specifier import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // Use Space format specifier formatter.format(\"%d\", -111); System.out.println(formatter); formatter = new Formatter(); formatter.format(\"% d\", 111); System.out.println(formatter); formatter = new Formatter(); formatter.format(\"% d\", -222); System.out.println(formatter); formatter = new Formatter(); formatter.format(\"% d\", 222); System.out.println(formatter); }}Output:-111\n 111\n-222\n 222\n+ Sign Specifier: This adds the + sign before positive numeric value, and has no effect on negative numeric value.Syntax:Formatter().format(\"%+d\", 111);\n\nOutput:\n+111\nExample:// Java program to demonstrate// the + sign Specifier format specifiers. import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // + sign specifier formatter = new Formatter(); formatter.format(\"%+d\", 111); System.out.println(formatter); // + sign specifier // on - sign, it will have no effect formatter = new Formatter(); formatter.format(\"%+d\", -111); System.out.println(formatter); }}Output:+111\n-111\n( specifier: This specifier puts the negative numeric values inside the parentheses, and has no effect on the positive numeric values.Syntax:Formatter().format(\"%(d\", -111);\nFormatter().format(\"%(d\", 111);\n\nOutput:\n(111)\n111\nExample:// Java program to demonstrate// the ( Specifiers format specifiers. import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // ( Specifier formatter = new Formatter(); formatter.format(\"%(d\", -111); System.out.println(formatter); formatter = new Formatter(); formatter.format(\"%(d\", 111); System.out.println(formatter); }}Output:(111)\n111\nComma, Specifier: For displaying large numbers, it is often useful to add grouping separators by comma (, ). For example, the value is 1000000 more easily read when formatted as 1, 000, 000. To add grouping specifiers (, ) use the comma(, ) Specifier.Syntax:Formatter().format(\"%, d\", 1000000);\n\nOutput:\n1, 000, 000Example:// Java program to demonstrate// the comma format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // comma Specifier formatter = new Formatter(); formatter.format(\"%, d\", 1000000); System.out.println(formatter); // comma Specifier formatter = new Formatter(); formatter.format(\"%, .3f\", 32659526566.4521); System.out.println(formatter); }}Output:1, 000, 000\n32, 659, 526, 566.452\nLeft Justification(-) Specifier: By default all output is right-shifted. That is, if the field width is longer than the data printed, data will be placed on the right side of the field. One can force output to be left-justified by placing a minus sign directly after the %. For instance, %-20.4f left justifies a floating-point number with two decimal places in a 20-character field.Syntax:Formatter().format(\"|%-20.4f|\", 1234.1234);\n\nOutput:\n| 1234.1234|\n|1234.1234 |\nExample:// Java program to demonstrate// the left justification format specifiers. import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // right justify by default formatter = new Formatter(); formatter.format(\"|%20.4f|\", 1234.1234); System.out.println(formatter); // left justify formatter = new Formatter(); formatter.format(\"|%-20.4f|\", 1234.1234); System.out.println(formatter); }}Output:| 1234.1234|\n|1234.1234 |\nThe %n format specifiers:The %n format specifier is different from the others in that it doesn’t take arguments. It is simply an escape sequence that inserts a character into the output. The %n inserts a newline. It can’t be entered directly into the format string.// Java program to demonstrate// the newline %n format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // newline format specifier formatter.format(\"Geeks %nFor %nGeeks\"); // Print the output System.out.println(formatter); }}Output:Geeks \nFor \nGeeks\nThe %% format specifiers:The %% format specifier is different from the others in that it doesn’t take arguments. It is simply an escape sequence that inserts a character into the output. The %% inserts a % sign. It can’t be entered directly into the format string.// Java program to demonstrate// the %% format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // %% format specifier formatter.format(\"10 %% 4 = 2\"); // Print the output System.out.println(formatter); }}Output:10 % 4 = 2\nThe %x %X format specifiers:The %x or %X format specifier is is used to represent the integer Hexadecimal value. %x displays the hexadecimal values with lowercase alphabets whereas the %X specifier displays the hexadecimal values with uppercase alphabets.// Java program to demonstrate// the integer-Hexadecimal %x and %X// format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // %x format specifier // It prints the number in Hexadecimal // with lowercase alphabets formatter.format(\"%x\", 250); // Print the output System.out.println(\"LowerCase Hexadecimal\" + \" using %x: \" + formatter); // %X format specifier // It prints the number in Hexadecimal // with uppercase alphabets formatter = new Formatter(); formatter.format(\"%X\", 250); // Print the output System.out.println(\"UpperCase Hexadecimal\" + \" using %X: \" + formatter); }}Output:LowerCase Hexadecimal using %x: fa\nUpperCase Hexadecimal using %X: FA\nThe %e %E format specifiers:The %e or %E format specifier is is used to represent the Scientific Notation of a value. %e displays the Scientific Notation with lowercase alphabets whereas the %E specifier displays the Scientific Notation with uppercase alphabets.// Java program to demonstrate// the Scientific Notation %e and %E// format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // %e format specifier // It prints the number in Scientific Notation // with lowercase alphabets formatter.format(\"%e\", 123.1234); // Print the output System.out.println(\"LowerCase Scientific Notation\" + \" using %e: \" + formatter); // %E format specifier // It prints the number in Scientific Notation // with uppercase alphabets formatter = new Formatter(); formatter.format(\"%E\", 123.1234); // Print the output System.out.println(\"UpperCase Scientific Notation\" + \" using %E: \" + formatter); }}Output:LowerCase Scientific Notation using %e: 1.231234e+02\nUpperCase Scientific Notation using %E: 1.231234E+02\nPrecision FormatsA precision specifier can be applied to the %f, %e, %g, and %s format specifiers.// Java program to demonstrate// Prrecision Format specifiers import java.util.Formatter; public class GFG { public static void main(String args[]) { // Create the Formatter instance Formatter formatter = new Formatter(); // added floating-point data // using the %f or %e specifiers, // Format to 2 decimal places // in a 16 character field. formatter = new Formatter(); formatter.format(\"%16.2e\", 123.1234567); System.out.println(\"Scientific notation to 2 places: \" + formatter); // Format 4 decimal places. formatter = new Formatter(); formatter.format(\"%.4f\", 123.1234567); System.out.println(\"Decimal floating-point\" + \" notation to 4 places: \" + formatter); // Format 4 places. // The %g format specifier causes Formatter // to use either %f or %e, whichever is shorter formatter = new Formatter(); formatter.format(\"%.4g\", 123.1234567); System.out.println(\"Scientific or Decimal floating-point \" + \"notation to 4 places: \" + formatter); // Display at most 15 characters in a string. formatter = new Formatter(); formatter.format(\"%.15s\", \"12345678901234567890\"); System.out.println(\"String notation to 15 places: \" + formatter); // Format into 10 digit formatter = new Formatter(); formatter.format(\"%010d\", 88); System.out.println(\"value in 10 digits: \" + formatter); }}Output:Scientific notation to 2 places: 1.23e+02\nDecimal floating-point notation to 4 places: 123.1235\nScientific or Decimal floating-point notation to 4 places: 123.1\nString notation to 15 places: 123456789012345\nvalue in 10 digits: 0000000088\n"
},
{
"code": null,
"e": 12196,
"s": 11155,
"text": "Space format specifier : When creating columns of numbers, it is sometimes very useful to print a space before a positive number so that positive and negative number get aligned. To do this, space format specifier can be used.Syntax:Formatter().format(\"% d\", -111);\nFormatter().format(\"% d\", 111);\n\nOutput:\n-111\n 111\nExample:// Java program to demonstrate// the space format specifier import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // Use Space format specifier formatter.format(\"%d\", -111); System.out.println(formatter); formatter = new Formatter(); formatter.format(\"% d\", 111); System.out.println(formatter); formatter = new Formatter(); formatter.format(\"% d\", -222); System.out.println(formatter); formatter = new Formatter(); formatter.format(\"% d\", 222); System.out.println(formatter); }}Output:-111\n 111\n-222\n 222\n"
},
{
"code": null,
"e": 12204,
"s": 12196,
"text": "Syntax:"
},
{
"code": null,
"e": 12289,
"s": 12204,
"text": "Formatter().format(\"% d\", -111);\nFormatter().format(\"% d\", 111);\n\nOutput:\n-111\n 111\n"
},
{
"code": null,
"e": 12298,
"s": 12289,
"text": "Example:"
},
{
"code": "// Java program to demonstrate// the space format specifier import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // Use Space format specifier formatter.format(\"%d\", -111); System.out.println(formatter); formatter = new Formatter(); formatter.format(\"% d\", 111); System.out.println(formatter); formatter = new Formatter(); formatter.format(\"% d\", -222); System.out.println(formatter); formatter = new Formatter(); formatter.format(\"% d\", 222); System.out.println(formatter); }}",
"e": 12987,
"s": 12298,
"text": null
},
{
"code": null,
"e": 13008,
"s": 12987,
"text": "-111\n 111\n-222\n 222\n"
},
{
"code": null,
"e": 13773,
"s": 13008,
"text": "+ Sign Specifier: This adds the + sign before positive numeric value, and has no effect on negative numeric value.Syntax:Formatter().format(\"%+d\", 111);\n\nOutput:\n+111\nExample:// Java program to demonstrate// the + sign Specifier format specifiers. import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // + sign specifier formatter = new Formatter(); formatter.format(\"%+d\", 111); System.out.println(formatter); // + sign specifier // on - sign, it will have no effect formatter = new Formatter(); formatter.format(\"%+d\", -111); System.out.println(formatter); }}Output:+111\n-111\n"
},
{
"code": null,
"e": 13781,
"s": 13773,
"text": "Syntax:"
},
{
"code": null,
"e": 13828,
"s": 13781,
"text": "Formatter().format(\"%+d\", 111);\n\nOutput:\n+111\n"
},
{
"code": null,
"e": 13837,
"s": 13828,
"text": "Example:"
},
{
"code": "// Java program to demonstrate// the + sign Specifier format specifiers. import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // + sign specifier formatter = new Formatter(); formatter.format(\"%+d\", 111); System.out.println(formatter); // + sign specifier // on - sign, it will have no effect formatter = new Formatter(); formatter.format(\"%+d\", -111); System.out.println(formatter); }}",
"e": 14410,
"s": 13837,
"text": null
},
{
"code": null,
"e": 14421,
"s": 14410,
"text": "+111\n-111\n"
},
{
"code": null,
"e": 15164,
"s": 14421,
"text": "( specifier: This specifier puts the negative numeric values inside the parentheses, and has no effect on the positive numeric values.Syntax:Formatter().format(\"%(d\", -111);\nFormatter().format(\"%(d\", 111);\n\nOutput:\n(111)\n111\nExample:// Java program to demonstrate// the ( Specifiers format specifiers. import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // ( Specifier formatter = new Formatter(); formatter.format(\"%(d\", -111); System.out.println(formatter); formatter = new Formatter(); formatter.format(\"%(d\", 111); System.out.println(formatter); }}Output:(111)\n111\n"
},
{
"code": null,
"e": 15172,
"s": 15164,
"text": "Syntax:"
},
{
"code": null,
"e": 15257,
"s": 15172,
"text": "Formatter().format(\"%(d\", -111);\nFormatter().format(\"%(d\", 111);\n\nOutput:\n(111)\n111\n"
},
{
"code": null,
"e": 15266,
"s": 15257,
"text": "Example:"
},
{
"code": "// Java program to demonstrate// the ( Specifiers format specifiers. import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // ( Specifier formatter = new Formatter(); formatter.format(\"%(d\", -111); System.out.println(formatter); formatter = new Formatter(); formatter.format(\"%(d\", 111); System.out.println(formatter); }}",
"e": 15759,
"s": 15266,
"text": null
},
{
"code": null,
"e": 15770,
"s": 15759,
"text": "(111)\n111\n"
},
{
"code": null,
"e": 16677,
"s": 15770,
"text": "Comma, Specifier: For displaying large numbers, it is often useful to add grouping separators by comma (, ). For example, the value is 1000000 more easily read when formatted as 1, 000, 000. To add grouping specifiers (, ) use the comma(, ) Specifier.Syntax:Formatter().format(\"%, d\", 1000000);\n\nOutput:\n1, 000, 000Example:// Java program to demonstrate// the comma format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // comma Specifier formatter = new Formatter(); formatter.format(\"%, d\", 1000000); System.out.println(formatter); // comma Specifier formatter = new Formatter(); formatter.format(\"%, .3f\", 32659526566.4521); System.out.println(formatter); }}Output:1, 000, 000\n32, 659, 526, 566.452\n"
},
{
"code": null,
"e": 16685,
"s": 16677,
"text": "Syntax:"
},
{
"code": null,
"e": 16743,
"s": 16685,
"text": "Formatter().format(\"%, d\", 1000000);\n\nOutput:\n1, 000, 000"
},
{
"code": null,
"e": 16752,
"s": 16743,
"text": "Example:"
},
{
"code": "// Java program to demonstrate// the comma format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // comma Specifier formatter = new Formatter(); formatter.format(\"%, d\", 1000000); System.out.println(formatter); // comma Specifier formatter = new Formatter(); formatter.format(\"%, .3f\", 32659526566.4521); System.out.println(formatter); }}",
"e": 17295,
"s": 16752,
"text": null
},
{
"code": null,
"e": 17330,
"s": 17295,
"text": "1, 000, 000\n32, 659, 526, 566.452\n"
},
{
"code": null,
"e": 18437,
"s": 17330,
"text": "Left Justification(-) Specifier: By default all output is right-shifted. That is, if the field width is longer than the data printed, data will be placed on the right side of the field. One can force output to be left-justified by placing a minus sign directly after the %. For instance, %-20.4f left justifies a floating-point number with two decimal places in a 20-character field.Syntax:Formatter().format(\"|%-20.4f|\", 1234.1234);\n\nOutput:\n| 1234.1234|\n|1234.1234 |\nExample:// Java program to demonstrate// the left justification format specifiers. import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // right justify by default formatter = new Formatter(); formatter.format(\"|%20.4f|\", 1234.1234); System.out.println(formatter); // left justify formatter = new Formatter(); formatter.format(\"|%-20.4f|\", 1234.1234); System.out.println(formatter); }}Output:| 1234.1234|\n|1234.1234 |\n"
},
{
"code": null,
"e": 18445,
"s": 18437,
"text": "Syntax:"
},
{
"code": null,
"e": 18545,
"s": 18445,
"text": "Formatter().format(\"|%-20.4f|\", 1234.1234);\n\nOutput:\n| 1234.1234|\n|1234.1234 |\n"
},
{
"code": null,
"e": 18554,
"s": 18545,
"text": "Example:"
},
{
"code": "// Java program to demonstrate// the left justification format specifiers. import java.util.*; class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // right justify by default formatter = new Formatter(); formatter.format(\"|%20.4f|\", 1234.1234); System.out.println(formatter); // left justify formatter = new Formatter(); formatter.format(\"|%-20.4f|\", 1234.1234); System.out.println(formatter); }}",
"e": 19111,
"s": 18554,
"text": null
},
{
"code": null,
"e": 19158,
"s": 19111,
"text": "| 1234.1234|\n|1234.1234 |\n"
},
{
"code": null,
"e": 19847,
"s": 19158,
"text": "The %n format specifiers:The %n format specifier is different from the others in that it doesn’t take arguments. It is simply an escape sequence that inserts a character into the output. The %n inserts a newline. It can’t be entered directly into the format string.// Java program to demonstrate// the newline %n format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // newline format specifier formatter.format(\"Geeks %nFor %nGeeks\"); // Print the output System.out.println(formatter); }}Output:Geeks \nFor \nGeeks\n"
},
{
"code": "// Java program to demonstrate// the newline %n format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // newline format specifier formatter.format(\"Geeks %nFor %nGeeks\"); // Print the output System.out.println(formatter); }}",
"e": 20246,
"s": 19847,
"text": null
},
{
"code": null,
"e": 20265,
"s": 20246,
"text": "Geeks \nFor \nGeeks\n"
},
{
"code": null,
"e": 20925,
"s": 20265,
"text": "The %% format specifiers:The %% format specifier is different from the others in that it doesn’t take arguments. It is simply an escape sequence that inserts a character into the output. The %% inserts a % sign. It can’t be entered directly into the format string.// Java program to demonstrate// the %% format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // %% format specifier formatter.format(\"10 %% 4 = 2\"); // Print the output System.out.println(formatter); }}Output:10 % 4 = 2\n"
},
{
"code": "// Java program to demonstrate// the %% format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // %% format specifier formatter.format(\"10 %% 4 = 2\"); // Print the output System.out.println(formatter); }}",
"e": 21303,
"s": 20925,
"text": null
},
{
"code": null,
"e": 21315,
"s": 21303,
"text": "10 % 4 = 2\n"
},
{
"code": null,
"e": 22571,
"s": 21315,
"text": "The %x %X format specifiers:The %x or %X format specifier is is used to represent the integer Hexadecimal value. %x displays the hexadecimal values with lowercase alphabets whereas the %X specifier displays the hexadecimal values with uppercase alphabets.// Java program to demonstrate// the integer-Hexadecimal %x and %X// format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // %x format specifier // It prints the number in Hexadecimal // with lowercase alphabets formatter.format(\"%x\", 250); // Print the output System.out.println(\"LowerCase Hexadecimal\" + \" using %x: \" + formatter); // %X format specifier // It prints the number in Hexadecimal // with uppercase alphabets formatter = new Formatter(); formatter.format(\"%X\", 250); // Print the output System.out.println(\"UpperCase Hexadecimal\" + \" using %X: \" + formatter); }}Output:LowerCase Hexadecimal using %x: fa\nUpperCase Hexadecimal using %X: FA\n"
},
{
"code": "// Java program to demonstrate// the integer-Hexadecimal %x and %X// format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // %x format specifier // It prints the number in Hexadecimal // with lowercase alphabets formatter.format(\"%x\", 250); // Print the output System.out.println(\"LowerCase Hexadecimal\" + \" using %x: \" + formatter); // %X format specifier // It prints the number in Hexadecimal // with uppercase alphabets formatter = new Formatter(); formatter.format(\"%X\", 250); // Print the output System.out.println(\"UpperCase Hexadecimal\" + \" using %X: \" + formatter); }}",
"e": 23495,
"s": 22571,
"text": null
},
{
"code": null,
"e": 23566,
"s": 23495,
"text": "LowerCase Hexadecimal using %x: fa\nUpperCase Hexadecimal using %X: FA\n"
},
{
"code": null,
"e": 24907,
"s": 23566,
"text": "The %e %E format specifiers:The %e or %E format specifier is is used to represent the Scientific Notation of a value. %e displays the Scientific Notation with lowercase alphabets whereas the %E specifier displays the Scientific Notation with uppercase alphabets.// Java program to demonstrate// the Scientific Notation %e and %E// format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // %e format specifier // It prints the number in Scientific Notation // with lowercase alphabets formatter.format(\"%e\", 123.1234); // Print the output System.out.println(\"LowerCase Scientific Notation\" + \" using %e: \" + formatter); // %E format specifier // It prints the number in Scientific Notation // with uppercase alphabets formatter = new Formatter(); formatter.format(\"%E\", 123.1234); // Print the output System.out.println(\"UpperCase Scientific Notation\" + \" using %E: \" + formatter); }}Output:LowerCase Scientific Notation using %e: 1.231234e+02\nUpperCase Scientific Notation using %E: 1.231234E+02\n"
},
{
"code": "// Java program to demonstrate// the Scientific Notation %e and %E// format specifiers. import java.util.*; public class GFG { public static void main(String args[]) { // create Formatter class object Formatter formatter = new Formatter(); // %e format specifier // It prints the number in Scientific Notation // with lowercase alphabets formatter.format(\"%e\", 123.1234); // Print the output System.out.println(\"LowerCase Scientific Notation\" + \" using %e: \" + formatter); // %E format specifier // It prints the number in Scientific Notation // with uppercase alphabets formatter = new Formatter(); formatter.format(\"%E\", 123.1234); // Print the output System.out.println(\"UpperCase Scientific Notation\" + \" using %E: \" + formatter); }}",
"e": 25873,
"s": 24907,
"text": null
},
{
"code": null,
"e": 25980,
"s": 25873,
"text": "LowerCase Scientific Notation using %e: 1.231234e+02\nUpperCase Scientific Notation using %E: 1.231234E+02\n"
},
{
"code": null,
"e": 28004,
"s": 25980,
"text": "Precision FormatsA precision specifier can be applied to the %f, %e, %g, and %s format specifiers.// Java program to demonstrate// Prrecision Format specifiers import java.util.Formatter; public class GFG { public static void main(String args[]) { // Create the Formatter instance Formatter formatter = new Formatter(); // added floating-point data // using the %f or %e specifiers, // Format to 2 decimal places // in a 16 character field. formatter = new Formatter(); formatter.format(\"%16.2e\", 123.1234567); System.out.println(\"Scientific notation to 2 places: \" + formatter); // Format 4 decimal places. formatter = new Formatter(); formatter.format(\"%.4f\", 123.1234567); System.out.println(\"Decimal floating-point\" + \" notation to 4 places: \" + formatter); // Format 4 places. // The %g format specifier causes Formatter // to use either %f or %e, whichever is shorter formatter = new Formatter(); formatter.format(\"%.4g\", 123.1234567); System.out.println(\"Scientific or Decimal floating-point \" + \"notation to 4 places: \" + formatter); // Display at most 15 characters in a string. formatter = new Formatter(); formatter.format(\"%.15s\", \"12345678901234567890\"); System.out.println(\"String notation to 15 places: \" + formatter); // Format into 10 digit formatter = new Formatter(); formatter.format(\"%010d\", 88); System.out.println(\"value in 10 digits: \" + formatter); }}Output:Scientific notation to 2 places: 1.23e+02\nDecimal floating-point notation to 4 places: 123.1235\nScientific or Decimal floating-point notation to 4 places: 123.1\nString notation to 15 places: 123456789012345\nvalue in 10 digits: 0000000088\n"
},
{
"code": "// Java program to demonstrate// Prrecision Format specifiers import java.util.Formatter; public class GFG { public static void main(String args[]) { // Create the Formatter instance Formatter formatter = new Formatter(); // added floating-point data // using the %f or %e specifiers, // Format to 2 decimal places // in a 16 character field. formatter = new Formatter(); formatter.format(\"%16.2e\", 123.1234567); System.out.println(\"Scientific notation to 2 places: \" + formatter); // Format 4 decimal places. formatter = new Formatter(); formatter.format(\"%.4f\", 123.1234567); System.out.println(\"Decimal floating-point\" + \" notation to 4 places: \" + formatter); // Format 4 places. // The %g format specifier causes Formatter // to use either %f or %e, whichever is shorter formatter = new Formatter(); formatter.format(\"%.4g\", 123.1234567); System.out.println(\"Scientific or Decimal floating-point \" + \"notation to 4 places: \" + formatter); // Display at most 15 characters in a string. formatter = new Formatter(); formatter.format(\"%.15s\", \"12345678901234567890\"); System.out.println(\"String notation to 15 places: \" + formatter); // Format into 10 digit formatter = new Formatter(); formatter.format(\"%010d\", 88); System.out.println(\"value in 10 digits: \" + formatter); }}",
"e": 29677,
"s": 28004,
"text": null
},
{
"code": null,
"e": 29924,
"s": 29677,
"text": "Scientific notation to 2 places: 1.23e+02\nDecimal floating-point notation to 4 places: 123.1235\nScientific or Decimal floating-point notation to 4 places: 123.1\nString notation to 15 places: 123456789012345\nvalue in 10 digits: 0000000088\n"
},
{
"code": null,
"e": 29965,
"s": 29924,
"text": "Related Article : Format Specifiers in C"
},
{
"code": null,
"e": 29978,
"s": 29965,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 29994,
"s": 29978,
"text": "gowtham_yuvaraj"
},
{
"code": null,
"e": 30005,
"s": 29994,
"text": "ritudpande"
},
{
"code": null,
"e": 30017,
"s": 30005,
"text": "Java-Output"
},
{
"code": null,
"e": 30030,
"s": 30017,
"text": "Java-Strings"
},
{
"code": null,
"e": 30054,
"s": 30030,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 30059,
"s": 30054,
"text": "Java"
},
{
"code": null,
"e": 30078,
"s": 30059,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30091,
"s": 30078,
"text": "Java-Strings"
},
{
"code": null,
"e": 30096,
"s": 30091,
"text": "Java"
},
{
"code": null,
"e": 30194,
"s": 30096,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30245,
"s": 30194,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 30276,
"s": 30245,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 30295,
"s": 30276,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30325,
"s": 30295,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 30343,
"s": 30325,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30358,
"s": 30343,
"text": "Stream In Java"
},
{
"code": null,
"e": 30378,
"s": 30358,
"text": "Collections in Java"
},
{
"code": null,
"e": 30410,
"s": 30378,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30434,
"s": 30410,
"text": "Singleton Class in Java"
}
] |
Implement your own itoa()
|
21 Jun, 2022
itoa function converts integer into null-terminated string. It can convert negative numbers too. The standard definition of itoa function is give below:-
C
char* itoa(int num, char* buffer, int base)
The third parameter base specify the conversion base. For example:- if base is 2, then it will convert the integer into its binary compatible string or if base is 16, then it will create hexadecimal converted string form of integer number. If base is 10 and value is negative, the resulting string is preceded with a minus sign (-). With any other base, value is always considered unsigned.Reference: http://www.cplusplus.com/reference/cstdlib/itoa/?kw=itoaExamples:
itoa(1567, str, 10) should return string "1567"
itoa(-1567, str, 10) should return string "-1567"
itoa(1567, str, 2) should return string "11000011111"
itoa(1567, str, 16) should return string "61f"
Individual digits of the given number must be processed and their corresponding characters must be put in the given string. Using repeated division by the given base, we get individual digits from least significant to most significant digit. But in the output, these digits are needed in reverse order. Therefore, we reverse the string obtained after repeated division and return it.
C
/* A C++ program to implement itoa() */#include <iostream>using namespace std; /* A utility function to reverse a string */void reverse(char str[], int length){ int start = 0; int end = length -1; while (start < end) { swap(*(str+start), *(str+end)); start++; end--; }} // Implementation of itoa()char* itoa(int num, char* str, int base){ int i = 0; bool isNegative = false; /* Handle 0 explicitly, otherwise empty string is printed for 0 */ if (num == 0) { str[i++] = '0'; str[i] = '\0'; return str; } // In standard itoa(), negative numbers are handled only with // base 10. Otherwise numbers are considered unsigned. if (num < 0 && base == 10) { isNegative = true; num = -num; } // Process individual digits while (num != 0) { int rem = num % base; str[i++] = (rem > 9)? (rem-10) + 'a' : rem + '0'; num = num/base; } // If number is negative, append '-' if (isNegative) str[i++] = '-'; str[i] = '\0'; // Append string terminator // Reverse the string reverse(str, i); return str;} // Driver program to test implementation of itoa()int main(){ char str[100]; cout << "Base:10 " << itoa(1567, str, 10) << endl; cout << "Base:10 " << itoa(-1567, str, 10) << endl; cout << "Base:2 " << itoa(1567, str, 2) << endl; cout << "Base:8 " << itoa(1567, str, 8) << endl; cout << "Base:16 " << itoa(1567, str, 16) << endl; return 0;}
Output:
Base:10 1567
Base:10 -1567
Base:2 11000011111
Base:8 3037
Base:16 61f
Time Complexity : O(n)
Auxiliary Space: O(1)
This article is contributed by Neha Mahajan. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
arorakashish0911
tarakki100
CPP-Library
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String 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": 52,
"s": 24,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 208,
"s": 52,
"text": "itoa function converts integer into null-terminated string. It can convert negative numbers too. The standard definition of itoa function is give below:- "
},
{
"code": null,
"e": 210,
"s": 208,
"text": "C"
},
{
"code": "char* itoa(int num, char* buffer, int base)",
"e": 254,
"s": 210,
"text": null
},
{
"code": null,
"e": 723,
"s": 254,
"text": "The third parameter base specify the conversion base. For example:- if base is 2, then it will convert the integer into its binary compatible string or if base is 16, then it will create hexadecimal converted string form of integer number. If base is 10 and value is negative, the resulting string is preceded with a minus sign (-). With any other base, value is always considered unsigned.Reference: http://www.cplusplus.com/reference/cstdlib/itoa/?kw=itoaExamples: "
},
{
"code": null,
"e": 930,
"s": 723,
"text": " itoa(1567, str, 10) should return string \"1567\"\n itoa(-1567, str, 10) should return string \"-1567\"\n itoa(1567, str, 2) should return string \"11000011111\"\n itoa(1567, str, 16) should return string \"61f\""
},
{
"code": null,
"e": 1315,
"s": 930,
"text": "Individual digits of the given number must be processed and their corresponding characters must be put in the given string. Using repeated division by the given base, we get individual digits from least significant to most significant digit. But in the output, these digits are needed in reverse order. Therefore, we reverse the string obtained after repeated division and return it. "
},
{
"code": null,
"e": 1317,
"s": 1315,
"text": "C"
},
{
"code": "/* A C++ program to implement itoa() */#include <iostream>using namespace std; /* A utility function to reverse a string */void reverse(char str[], int length){ int start = 0; int end = length -1; while (start < end) { swap(*(str+start), *(str+end)); start++; end--; }} // Implementation of itoa()char* itoa(int num, char* str, int base){ int i = 0; bool isNegative = false; /* Handle 0 explicitly, otherwise empty string is printed for 0 */ if (num == 0) { str[i++] = '0'; str[i] = '\\0'; return str; } // In standard itoa(), negative numbers are handled only with // base 10. Otherwise numbers are considered unsigned. if (num < 0 && base == 10) { isNegative = true; num = -num; } // Process individual digits while (num != 0) { int rem = num % base; str[i++] = (rem > 9)? (rem-10) + 'a' : rem + '0'; num = num/base; } // If number is negative, append '-' if (isNegative) str[i++] = '-'; str[i] = '\\0'; // Append string terminator // Reverse the string reverse(str, i); return str;} // Driver program to test implementation of itoa()int main(){ char str[100]; cout << \"Base:10 \" << itoa(1567, str, 10) << endl; cout << \"Base:10 \" << itoa(-1567, str, 10) << endl; cout << \"Base:2 \" << itoa(1567, str, 2) << endl; cout << \"Base:8 \" << itoa(1567, str, 8) << endl; cout << \"Base:16 \" << itoa(1567, str, 16) << endl; return 0;}",
"e": 2832,
"s": 1317,
"text": null
},
{
"code": null,
"e": 2841,
"s": 2832,
"text": "Output: "
},
{
"code": null,
"e": 2911,
"s": 2841,
"text": "Base:10 1567\nBase:10 -1567\nBase:2 11000011111\nBase:8 3037\nBase:16 61f"
},
{
"code": null,
"e": 2934,
"s": 2911,
"text": "Time Complexity : O(n)"
},
{
"code": null,
"e": 2956,
"s": 2934,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3127,
"s": 2956,
"text": "This article is contributed by Neha Mahajan. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 3144,
"s": 3127,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3155,
"s": 3144,
"text": "tarakki100"
},
{
"code": null,
"e": 3167,
"s": 3155,
"text": "CPP-Library"
},
{
"code": null,
"e": 3178,
"s": 3167,
"text": "C Language"
},
{
"code": null,
"e": 3182,
"s": 3178,
"text": "C++"
},
{
"code": null,
"e": 3186,
"s": 3182,
"text": "CPP"
},
{
"code": null,
"e": 3284,
"s": 3186,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3301,
"s": 3284,
"text": "Substring in C++"
},
{
"code": null,
"e": 3336,
"s": 3301,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 3358,
"s": 3336,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 3404,
"s": 3358,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 3449,
"s": 3404,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 3467,
"s": 3449,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 3510,
"s": 3467,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3556,
"s": 3510,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 3599,
"s": 3556,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Strong and Weak Bases
|
03 Sep, 2021
The citric acid in fruits like oranges and lemons, tartaric acid in tamarind, malic acid in apples, lactic acid in milk and milk products, and hydrochloric acid in gastric juices are just a few examples of acids and bases found in nature. Many bases, such as lime water, can also be found. Many of these acids are used in our daily lives, such as vinegar or acetic acid in the kitchen, boric acid in laundry, baking soda in cooking, washing soda in cleaning, and so on.
Many acids and bases that we do not use in our daily lives are utilised in laboratories and industries, such as HCl, H2SO4, and NaOH, KOH, among others. The neutralisation process results in the creation of salt and water when these acids and bases are mixed in the proper quantities.
Acids: Acid comes from the Latin word ‘acidus’ or ‘acere,’ which signifies sour. Their sour flavour is the most prevalent feature. An acid is a chemical that in its aqueous solution produces the ionizable hydronium ion (H3O+). It turns blue litmus paper red.
Natural acids: Natural acids are derived from natural sources like fruits and animal products. Lactic, citric, and tartaric acids, for example.Mineral acids: Mineral acids are acids that have been made from minerals. Hydrochloric acid (HCl), sulphuric acid (H2SO4), and nitric acid (HNO3) are among the examples.
Natural acids: Natural acids are derived from natural sources like fruits and animal products. Lactic, citric, and tartaric acids, for example.
Mineral acids: Mineral acids are acids that have been made from minerals. Hydrochloric acid (HCl), sulphuric acid (H2SO4), and nitric acid (HNO3) are among the examples.
Bases: The bitter taste and soapy texture of bases are two of their most prevalent characteristics. A base is a chemical that produces the hydroxyl ion (OH–) in water. Bases turn the colour of red litmus paper to blue.
Strong bases: Strong bases completely ionise in water, resulting in a huge amount of OH– ions. Sodium hydroxide (NaOH), potassium hydroxide (KOH), lithium hydroxide (LiOH), and calcium hydroxide (Ca(OH)2) are just a few examples.Weak bases: Weak bases partially ionise in water, resulting in a tiny number of OH– ions. Magnesium hydroxide (Mg(OH)2) and ammonium hydroxide, for example (NH4OH).
Strong bases: Strong bases completely ionise in water, resulting in a huge amount of OH– ions. Sodium hydroxide (NaOH), potassium hydroxide (KOH), lithium hydroxide (LiOH), and calcium hydroxide (Ca(OH)2) are just a few examples.
Weak bases: Weak bases partially ionise in water, resulting in a tiny number of OH– ions. Magnesium hydroxide (Mg(OH)2) and ammonium hydroxide, for example (NH4OH).
Salts: When acids and bases react to neutralise each other, salt is created as an ionic material. Salts are made up of positively charged cations and negatively charged anions, and they can be organic or inorganic in nature. The nature of the salt is neutral because these ions are present in little concentrations.
A strong base is a fully ionic substance such as sodium hydroxide or potassium hydroxide. In solution, the molecule can be thought of as being completely broken up into metal ions and hydroxide ions.
Each mole of sodium hydroxide in solution dissolves to produce a mole of hydroxide ions.
Na + OH ⇢ Na + OH
Some strong bases, such as calcium hydroxide, aren’t very water-soluble. It makes no difference; whatever does dissolve is completely ionised into calcium and hydroxide ions. Because of its 100% ionisation, calcium hydroxide is nevertheless considered a strong base.
Calculating the pH of a strong base as
pH = – log10 [H+]
How can a solution containing hydroxide ions have a pH since pH is a measure of hydrogen ion concentration? To understand this, you must first understand the ionic product for water. Wherever there is water, a balance is established. The following is a simplified version of this equilibrium:
H2O (l) ⇌ H+ (aq) + OH
With the addition of extra hydroxide ions, such as sodium hydroxide, the equilibrium still exists, but the point of equilibrium has shifted to the left, according to Le Chatelier’s Principle. Although there will be significantly fewer hydrogen ions than in pure water, hydrogen ions will still be present. The concentration of these is measured by the pH.
A description of how to calculate the pH of a strong base:
Work out the concentration of the hydroxide ions.
Use Kw to work out the hydrogen ion concentration.
Convert the hydrogen ion concentration to a pH
Examples of some common strong bases are:
Potassium hydroxide (KOH)Sodium hydroxide (NaOH)Barium hydroxide (Ba(OH)2)Caesium hydroxide (CsOH)
Potassium hydroxide (KOH)
Sodium hydroxide (NaOH)
Barium hydroxide (Ba(OH)2)
Caesium hydroxide (CsOH)
Weak bases are basic compounds that when dissolved in liquids do not entirely break down into their constituent ions. As a result, when the weak base is dissolved in a solution, some of it dissociates into hydroxide anions and the corresponding conjugate acid, while the rest stays undissociated inside the solution.
Ionization of a weak base is a form of equilibrium process in which a chemical equilibrium between the concentration of the undissociated base and its constituent ions is achieved inside the solution (the conjugate acid and the hydroxide anion). It’s vital to remember that a weak base’s conjugate acid is usually always a weak acid. Similarly, the conjugate base of a weak acid will act as a weak base.
When a weak base is dissolved in water, the following type of equilibrium arises:
B + H2O ⇌ BH+ + OH–
A lone pair of electrons in the basic molecule absorbs a proton from the water molecule in this equilibrium process, resulting in the creation of a hydroxide ion. The weaker the base, the greater the concentration of the equilibrium to the left. Similarly, the stronger the base, the higher the equilibrium concentration to the right.
Examples of some common weak bases are:
Ammonia (NH3): The ammonium cation (denoted by the chemical formula NH4+) and the hydroxide anion are present in the solution formed when ammonia is dissolved in water (also known as ammonia water or ammonia solution). It’s worth noting, however, that only a small portion of the dissolved ammonia dissociates into these ions.Trimethylamine (N(CH3)3): TMA stands for trimethylamine, which is a weak base with the molecular formula N(CH3)3. Ammonia and methanol can be combined in the presence of a catalyst to make this chemical. It can also be made by combining paraformaldehyde and ammonium chloride in a process.Pyridine (C5H5N): Pyridine is a pyridine-like organic molecule with the formula C5H5N. This chemical compound is a weak base with a heterocyclic structure. Pyridine has a structure similar to benzene, with the exception that one of the methine groups is substituted with a single nitrogen atom. Pyridine is a colourless liquid that exists at typical temperatures and pressures. It’s also worth mentioning that pyridine is a Lewis base, which means it may give electron pairs to Lewis acids to produce Lewis adducts.
Ammonia (NH3): The ammonium cation (denoted by the chemical formula NH4+) and the hydroxide anion are present in the solution formed when ammonia is dissolved in water (also known as ammonia water or ammonia solution). It’s worth noting, however, that only a small portion of the dissolved ammonia dissociates into these ions.
Trimethylamine (N(CH3)3): TMA stands for trimethylamine, which is a weak base with the molecular formula N(CH3)3. Ammonia and methanol can be combined in the presence of a catalyst to make this chemical. It can also be made by combining paraformaldehyde and ammonium chloride in a process.
Pyridine (C5H5N): Pyridine is a pyridine-like organic molecule with the formula C5H5N. This chemical compound is a weak base with a heterocyclic structure. Pyridine has a structure similar to benzene, with the exception that one of the methine groups is substituted with a single nitrogen atom. Pyridine is a colourless liquid that exists at typical temperatures and pressures. It’s also worth mentioning that pyridine is a Lewis base, which means it may give electron pairs to Lewis acids to produce Lewis adducts.
Question 1: Explain why a sodium sulphate aqueous solution is neutral and a sodium carbonate aqueous solution is basic in nature.
Answer:
Aqueous sodium sulphate solution is hydrolyzed to create sodium hydroxide and sulphuric acid, both of which are strong bases and acids. As a result, the aqueous solution is pH neutral. When sodium carbonate is dissolved in water, it is partially hydrolyzed, yielding sodium hydroxide and carbonic acid.
Sodium hydroxide is now a strong base that is fully ionised and produces a significant number of hydroxide ions [OH– (aq)]. Carbonic acid, on the other hand, is a weak acid that is only minimally ionised and hence produces a modest number of hydrogen ions [H+ (aq)]. The combination is basic because it includes more hydroxide ions than hydrogen ions.
Question 2: Is sodium hydroxide a base that isn’t very strong? Is there any reason to believe that?
Answer:
A strong base is sodium hydroxide, a chemical substance having the formula NaOH. This is due to the fact that when sodium hydroxide is dissolved in water, it almost completely ionises. The basic chemicals that do not totally ionise in water are known as weak bases. An example of a weak base is ammonia. When NH3 is dissolved in water, it interacts with the water molecules and dissociates into ammonium cation and hydroxide anions. However, some ammonia in the solution stays unionised.
Question 3: Is water a weak base?
Answer:
Pure water does, in fact, act as a weak base. In reality, pure water is a weak acid as well as a weak basic. This is because a little amount of water dissociates into protons and hydroxide anions, forming hydronium ions and hydroxide ions with the remaining water molecules.
Question 4: Why do acids like HCl, HNO3, and others have acidic properties in aqueous solutions, but molecules like alcohol and glucose don’t?
Answer:
In aqueous solutions, ionised solutions such as HCl, HNO3, and others become acidic due to the presence of H+ ions. Because alcohol and glucose solutions do not generate any of these ions, they do not have acidic properties.
Question 5: Why does acid in an aqueous solution transmit electricity?
Answer:
When acid forms a solution in water, it becomes ionised, and electricity is carried through it as a result of the existence of these ions.
Question 6: Why not keep curd and sour substances in brass and copper vessels?
Answer:
Acids in curd and sour things react with copper vessels and brass to generate hazardous chemicals.
Question 7: Why does the colour of dry litmus paper not change when exposed to dry HCl gas?
Answer:
The acidic quality of dry HCl gas is not transmitted since it does not release H+ ions.
Picked
Class 10
School Chemistry
School Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Internet
Mobile Technologies - Definition, Types, Uses, Advantages
Metals and Non-Metals - Definition, Properties, Uses and Applications
Chemical Indicators - Definition, Types, Examples
Rusting of Iron - Explanation, Chemical Reaction, Prevention
Biodegradable and Non-biodegradable Materials
Causes and Effects of Water Pollution
Importance of Chemistry in Everyday Life
Fuel Cells - Definition, Types, Advantages, Limitations
Metals and Non-Metals - Definition, Properties, Uses and Applications
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Sep, 2021"
},
{
"code": null,
"e": 498,
"s": 28,
"text": "The citric acid in fruits like oranges and lemons, tartaric acid in tamarind, malic acid in apples, lactic acid in milk and milk products, and hydrochloric acid in gastric juices are just a few examples of acids and bases found in nature. Many bases, such as lime water, can also be found. Many of these acids are used in our daily lives, such as vinegar or acetic acid in the kitchen, boric acid in laundry, baking soda in cooking, washing soda in cleaning, and so on."
},
{
"code": null,
"e": 783,
"s": 498,
"text": "Many acids and bases that we do not use in our daily lives are utilised in laboratories and industries, such as HCl, H2SO4, and NaOH, KOH, among others. The neutralisation process results in the creation of salt and water when these acids and bases are mixed in the proper quantities."
},
{
"code": null,
"e": 1042,
"s": 783,
"text": "Acids: Acid comes from the Latin word ‘acidus’ or ‘acere,’ which signifies sour. Their sour flavour is the most prevalent feature. An acid is a chemical that in its aqueous solution produces the ionizable hydronium ion (H3O+). It turns blue litmus paper red."
},
{
"code": null,
"e": 1355,
"s": 1042,
"text": "Natural acids: Natural acids are derived from natural sources like fruits and animal products. Lactic, citric, and tartaric acids, for example.Mineral acids: Mineral acids are acids that have been made from minerals. Hydrochloric acid (HCl), sulphuric acid (H2SO4), and nitric acid (HNO3) are among the examples."
},
{
"code": null,
"e": 1499,
"s": 1355,
"text": "Natural acids: Natural acids are derived from natural sources like fruits and animal products. Lactic, citric, and tartaric acids, for example."
},
{
"code": null,
"e": 1669,
"s": 1499,
"text": "Mineral acids: Mineral acids are acids that have been made from minerals. Hydrochloric acid (HCl), sulphuric acid (H2SO4), and nitric acid (HNO3) are among the examples."
},
{
"code": null,
"e": 1888,
"s": 1669,
"text": "Bases: The bitter taste and soapy texture of bases are two of their most prevalent characteristics. A base is a chemical that produces the hydroxyl ion (OH–) in water. Bases turn the colour of red litmus paper to blue."
},
{
"code": null,
"e": 2282,
"s": 1888,
"text": "Strong bases: Strong bases completely ionise in water, resulting in a huge amount of OH– ions. Sodium hydroxide (NaOH), potassium hydroxide (KOH), lithium hydroxide (LiOH), and calcium hydroxide (Ca(OH)2) are just a few examples.Weak bases: Weak bases partially ionise in water, resulting in a tiny number of OH– ions. Magnesium hydroxide (Mg(OH)2) and ammonium hydroxide, for example (NH4OH)."
},
{
"code": null,
"e": 2512,
"s": 2282,
"text": "Strong bases: Strong bases completely ionise in water, resulting in a huge amount of OH– ions. Sodium hydroxide (NaOH), potassium hydroxide (KOH), lithium hydroxide (LiOH), and calcium hydroxide (Ca(OH)2) are just a few examples."
},
{
"code": null,
"e": 2677,
"s": 2512,
"text": "Weak bases: Weak bases partially ionise in water, resulting in a tiny number of OH– ions. Magnesium hydroxide (Mg(OH)2) and ammonium hydroxide, for example (NH4OH)."
},
{
"code": null,
"e": 2993,
"s": 2677,
"text": "Salts: When acids and bases react to neutralise each other, salt is created as an ionic material. Salts are made up of positively charged cations and negatively charged anions, and they can be organic or inorganic in nature. The nature of the salt is neutral because these ions are present in little concentrations."
},
{
"code": null,
"e": 3193,
"s": 2993,
"text": "A strong base is a fully ionic substance such as sodium hydroxide or potassium hydroxide. In solution, the molecule can be thought of as being completely broken up into metal ions and hydroxide ions."
},
{
"code": null,
"e": 3282,
"s": 3193,
"text": "Each mole of sodium hydroxide in solution dissolves to produce a mole of hydroxide ions."
},
{
"code": null,
"e": 3300,
"s": 3282,
"text": "Na + OH ⇢ Na + OH"
},
{
"code": null,
"e": 3567,
"s": 3300,
"text": "Some strong bases, such as calcium hydroxide, aren’t very water-soluble. It makes no difference; whatever does dissolve is completely ionised into calcium and hydroxide ions. Because of its 100% ionisation, calcium hydroxide is nevertheless considered a strong base."
},
{
"code": null,
"e": 3606,
"s": 3567,
"text": "Calculating the pH of a strong base as"
},
{
"code": null,
"e": 3624,
"s": 3606,
"text": "pH = – log10 [H+]"
},
{
"code": null,
"e": 3917,
"s": 3624,
"text": "How can a solution containing hydroxide ions have a pH since pH is a measure of hydrogen ion concentration? To understand this, you must first understand the ionic product for water. Wherever there is water, a balance is established. The following is a simplified version of this equilibrium:"
},
{
"code": null,
"e": 3940,
"s": 3917,
"text": "H2O (l) ⇌ H+ (aq) + OH"
},
{
"code": null,
"e": 4296,
"s": 3940,
"text": "With the addition of extra hydroxide ions, such as sodium hydroxide, the equilibrium still exists, but the point of equilibrium has shifted to the left, according to Le Chatelier’s Principle. Although there will be significantly fewer hydrogen ions than in pure water, hydrogen ions will still be present. The concentration of these is measured by the pH."
},
{
"code": null,
"e": 4355,
"s": 4296,
"text": "A description of how to calculate the pH of a strong base:"
},
{
"code": null,
"e": 4405,
"s": 4355,
"text": "Work out the concentration of the hydroxide ions."
},
{
"code": null,
"e": 4456,
"s": 4405,
"text": "Use Kw to work out the hydrogen ion concentration."
},
{
"code": null,
"e": 4503,
"s": 4456,
"text": "Convert the hydrogen ion concentration to a pH"
},
{
"code": null,
"e": 4545,
"s": 4503,
"text": "Examples of some common strong bases are:"
},
{
"code": null,
"e": 4644,
"s": 4545,
"text": "Potassium hydroxide (KOH)Sodium hydroxide (NaOH)Barium hydroxide (Ba(OH)2)Caesium hydroxide (CsOH)"
},
{
"code": null,
"e": 4670,
"s": 4644,
"text": "Potassium hydroxide (KOH)"
},
{
"code": null,
"e": 4694,
"s": 4670,
"text": "Sodium hydroxide (NaOH)"
},
{
"code": null,
"e": 4721,
"s": 4694,
"text": "Barium hydroxide (Ba(OH)2)"
},
{
"code": null,
"e": 4746,
"s": 4721,
"text": "Caesium hydroxide (CsOH)"
},
{
"code": null,
"e": 5063,
"s": 4746,
"text": "Weak bases are basic compounds that when dissolved in liquids do not entirely break down into their constituent ions. As a result, when the weak base is dissolved in a solution, some of it dissociates into hydroxide anions and the corresponding conjugate acid, while the rest stays undissociated inside the solution."
},
{
"code": null,
"e": 5468,
"s": 5063,
"text": " Ionization of a weak base is a form of equilibrium process in which a chemical equilibrium between the concentration of the undissociated base and its constituent ions is achieved inside the solution (the conjugate acid and the hydroxide anion). It’s vital to remember that a weak base’s conjugate acid is usually always a weak acid. Similarly, the conjugate base of a weak acid will act as a weak base."
},
{
"code": null,
"e": 5550,
"s": 5468,
"text": "When a weak base is dissolved in water, the following type of equilibrium arises:"
},
{
"code": null,
"e": 5570,
"s": 5550,
"text": "B + H2O ⇌ BH+ + OH–"
},
{
"code": null,
"e": 5905,
"s": 5570,
"text": "A lone pair of electrons in the basic molecule absorbs a proton from the water molecule in this equilibrium process, resulting in the creation of a hydroxide ion. The weaker the base, the greater the concentration of the equilibrium to the left. Similarly, the stronger the base, the higher the equilibrium concentration to the right."
},
{
"code": null,
"e": 5945,
"s": 5905,
"text": "Examples of some common weak bases are:"
},
{
"code": null,
"e": 7076,
"s": 5945,
"text": "Ammonia (NH3): The ammonium cation (denoted by the chemical formula NH4+) and the hydroxide anion are present in the solution formed when ammonia is dissolved in water (also known as ammonia water or ammonia solution). It’s worth noting, however, that only a small portion of the dissolved ammonia dissociates into these ions.Trimethylamine (N(CH3)3): TMA stands for trimethylamine, which is a weak base with the molecular formula N(CH3)3. Ammonia and methanol can be combined in the presence of a catalyst to make this chemical. It can also be made by combining paraformaldehyde and ammonium chloride in a process.Pyridine (C5H5N): Pyridine is a pyridine-like organic molecule with the formula C5H5N. This chemical compound is a weak base with a heterocyclic structure. Pyridine has a structure similar to benzene, with the exception that one of the methine groups is substituted with a single nitrogen atom. Pyridine is a colourless liquid that exists at typical temperatures and pressures. It’s also worth mentioning that pyridine is a Lewis base, which means it may give electron pairs to Lewis acids to produce Lewis adducts."
},
{
"code": null,
"e": 7403,
"s": 7076,
"text": "Ammonia (NH3): The ammonium cation (denoted by the chemical formula NH4+) and the hydroxide anion are present in the solution formed when ammonia is dissolved in water (also known as ammonia water or ammonia solution). It’s worth noting, however, that only a small portion of the dissolved ammonia dissociates into these ions."
},
{
"code": null,
"e": 7693,
"s": 7403,
"text": "Trimethylamine (N(CH3)3): TMA stands for trimethylamine, which is a weak base with the molecular formula N(CH3)3. Ammonia and methanol can be combined in the presence of a catalyst to make this chemical. It can also be made by combining paraformaldehyde and ammonium chloride in a process."
},
{
"code": null,
"e": 8209,
"s": 7693,
"text": "Pyridine (C5H5N): Pyridine is a pyridine-like organic molecule with the formula C5H5N. This chemical compound is a weak base with a heterocyclic structure. Pyridine has a structure similar to benzene, with the exception that one of the methine groups is substituted with a single nitrogen atom. Pyridine is a colourless liquid that exists at typical temperatures and pressures. It’s also worth mentioning that pyridine is a Lewis base, which means it may give electron pairs to Lewis acids to produce Lewis adducts."
},
{
"code": null,
"e": 8339,
"s": 8209,
"text": "Question 1: Explain why a sodium sulphate aqueous solution is neutral and a sodium carbonate aqueous solution is basic in nature."
},
{
"code": null,
"e": 8347,
"s": 8339,
"text": "Answer:"
},
{
"code": null,
"e": 8651,
"s": 8347,
"text": "Aqueous sodium sulphate solution is hydrolyzed to create sodium hydroxide and sulphuric acid, both of which are strong bases and acids. As a result, the aqueous solution is pH neutral. When sodium carbonate is dissolved in water, it is partially hydrolyzed, yielding sodium hydroxide and carbonic acid. "
},
{
"code": null,
"e": 9003,
"s": 8651,
"text": "Sodium hydroxide is now a strong base that is fully ionised and produces a significant number of hydroxide ions [OH– (aq)]. Carbonic acid, on the other hand, is a weak acid that is only minimally ionised and hence produces a modest number of hydrogen ions [H+ (aq)]. The combination is basic because it includes more hydroxide ions than hydrogen ions."
},
{
"code": null,
"e": 9103,
"s": 9003,
"text": "Question 2: Is sodium hydroxide a base that isn’t very strong? Is there any reason to believe that?"
},
{
"code": null,
"e": 9111,
"s": 9103,
"text": "Answer:"
},
{
"code": null,
"e": 9599,
"s": 9111,
"text": "A strong base is sodium hydroxide, a chemical substance having the formula NaOH. This is due to the fact that when sodium hydroxide is dissolved in water, it almost completely ionises. The basic chemicals that do not totally ionise in water are known as weak bases. An example of a weak base is ammonia. When NH3 is dissolved in water, it interacts with the water molecules and dissociates into ammonium cation and hydroxide anions. However, some ammonia in the solution stays unionised."
},
{
"code": null,
"e": 9633,
"s": 9599,
"text": "Question 3: Is water a weak base?"
},
{
"code": null,
"e": 9641,
"s": 9633,
"text": "Answer:"
},
{
"code": null,
"e": 9916,
"s": 9641,
"text": "Pure water does, in fact, act as a weak base. In reality, pure water is a weak acid as well as a weak basic. This is because a little amount of water dissociates into protons and hydroxide anions, forming hydronium ions and hydroxide ions with the remaining water molecules."
},
{
"code": null,
"e": 10059,
"s": 9916,
"text": "Question 4: Why do acids like HCl, HNO3, and others have acidic properties in aqueous solutions, but molecules like alcohol and glucose don’t?"
},
{
"code": null,
"e": 10067,
"s": 10059,
"text": "Answer:"
},
{
"code": null,
"e": 10292,
"s": 10067,
"text": "In aqueous solutions, ionised solutions such as HCl, HNO3, and others become acidic due to the presence of H+ ions. Because alcohol and glucose solutions do not generate any of these ions, they do not have acidic properties."
},
{
"code": null,
"e": 10363,
"s": 10292,
"text": "Question 5: Why does acid in an aqueous solution transmit electricity?"
},
{
"code": null,
"e": 10371,
"s": 10363,
"text": "Answer:"
},
{
"code": null,
"e": 10510,
"s": 10371,
"text": "When acid forms a solution in water, it becomes ionised, and electricity is carried through it as a result of the existence of these ions."
},
{
"code": null,
"e": 10589,
"s": 10510,
"text": "Question 6: Why not keep curd and sour substances in brass and copper vessels?"
},
{
"code": null,
"e": 10597,
"s": 10589,
"text": "Answer:"
},
{
"code": null,
"e": 10696,
"s": 10597,
"text": "Acids in curd and sour things react with copper vessels and brass to generate hazardous chemicals."
},
{
"code": null,
"e": 10788,
"s": 10696,
"text": "Question 7: Why does the colour of dry litmus paper not change when exposed to dry HCl gas?"
},
{
"code": null,
"e": 10796,
"s": 10788,
"text": "Answer:"
},
{
"code": null,
"e": 10884,
"s": 10796,
"text": "The acidic quality of dry HCl gas is not transmitted since it does not release H+ ions."
},
{
"code": null,
"e": 10891,
"s": 10884,
"text": "Picked"
},
{
"code": null,
"e": 10900,
"s": 10891,
"text": "Class 10"
},
{
"code": null,
"e": 10917,
"s": 10900,
"text": "School Chemistry"
},
{
"code": null,
"e": 10933,
"s": 10917,
"text": "School Learning"
},
{
"code": null,
"e": 11031,
"s": 10933,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11056,
"s": 11031,
"text": "Introduction to Internet"
},
{
"code": null,
"e": 11114,
"s": 11056,
"text": "Mobile Technologies - Definition, Types, Uses, Advantages"
},
{
"code": null,
"e": 11184,
"s": 11114,
"text": "Metals and Non-Metals - Definition, Properties, Uses and Applications"
},
{
"code": null,
"e": 11234,
"s": 11184,
"text": "Chemical Indicators - Definition, Types, Examples"
},
{
"code": null,
"e": 11295,
"s": 11234,
"text": "Rusting of Iron - Explanation, Chemical Reaction, Prevention"
},
{
"code": null,
"e": 11341,
"s": 11295,
"text": "Biodegradable and Non-biodegradable Materials"
},
{
"code": null,
"e": 11379,
"s": 11341,
"text": "Causes and Effects of Water Pollution"
},
{
"code": null,
"e": 11420,
"s": 11379,
"text": "Importance of Chemistry in Everyday Life"
},
{
"code": null,
"e": 11476,
"s": 11420,
"text": "Fuel Cells - Definition, Types, Advantages, Limitations"
}
] |
Convert CSV to HTML Table using Python Pandas and Flask Framework
|
26 May, 2022
In this article, we are going to convert a CSV file into an HTML table using Python Pandas and Flask Framework.
Sample CSV file :
USERNAME,IDENTIFIER,FIRST_NAME,LAST_NAME
booker12,9012,Rachel,Booker
grey07,2070,Laura,Grey
johnson81,4081,Craig,Johnson
jenkins46,9346,Mary,Jenkins
smith79,5079,Jamie,Smith
Step 1: Create an environment. Create a project folder and a venv folder within.
py -3 -m venv venv
Step 2: Activate the environment.
venv\Scripts\activate
Step 3: Install Flask and Pandas.
pip install Flask
pip install pandas
Step 1: Create ‘app.py’ folder and write the code given below.
Python3
# importing flaskfrom flask import Flask, render_template # importing pandas moduleimport pandas as pd app = Flask(__name__) # reading the data in the csv filedf = pd.read_csv('sample_data.csv')df.to_csv('sample_data.csv', index=None) # route to html page - "table"@app.route('/')@app.route('/table')def table(): # converting csv to html data = pd.read_csv('sample_data.csv') return render_template('table.html', tables=[data.to_html()], titles=['']) if __name__ == "__main__": app.run(host="localhost", port=int("5000"))
Step 2: Create the folder ‘templates’. create the file ‘table.html’ inside the ‘templates’ folder.
HTML
<!DOCTYPE html><html lang="en"> <head> <title> Table </title> </head> <body> <div align="center"> <table> <h1> <!--Displaying the converted table--> {% for table in tables %} <h2>{{titles[loop.index]}}</h2> {{ table|safe }} {% endfor %} </h1> </table> </div> </body></html>
Step 3: Add the ‘sample_data.csv’ file.
Step 4: The project structure will look like this.
Structure of the project
Step 1: Run the server.
Step 2: Browse the URL ‘localhost:5000’.
Step 3: The output web page will be displayed.
Output:
Output : CSV to HTML Table
Flask Projects
Python Flask
Python-pandas
Python-projects
Python
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, 2022"
},
{
"code": null,
"e": 140,
"s": 28,
"text": "In this article, we are going to convert a CSV file into an HTML table using Python Pandas and Flask Framework."
},
{
"code": null,
"e": 158,
"s": 140,
"text": "Sample CSV file :"
},
{
"code": null,
"e": 332,
"s": 158,
"text": "USERNAME,IDENTIFIER,FIRST_NAME,LAST_NAME\nbooker12,9012,Rachel,Booker\ngrey07,2070,Laura,Grey\njohnson81,4081,Craig,Johnson\njenkins46,9346,Mary,Jenkins\nsmith79,5079,Jamie,Smith"
},
{
"code": null,
"e": 413,
"s": 332,
"text": "Step 1: Create an environment. Create a project folder and a venv folder within."
},
{
"code": null,
"e": 432,
"s": 413,
"text": "py -3 -m venv venv"
},
{
"code": null,
"e": 466,
"s": 432,
"text": "Step 2: Activate the environment."
},
{
"code": null,
"e": 488,
"s": 466,
"text": "venv\\Scripts\\activate"
},
{
"code": null,
"e": 522,
"s": 488,
"text": "Step 3: Install Flask and Pandas."
},
{
"code": null,
"e": 540,
"s": 522,
"text": "pip install Flask"
},
{
"code": null,
"e": 559,
"s": 540,
"text": "pip install pandas"
},
{
"code": null,
"e": 622,
"s": 559,
"text": "Step 1: Create ‘app.py’ folder and write the code given below."
},
{
"code": null,
"e": 630,
"s": 622,
"text": "Python3"
},
{
"code": "# importing flaskfrom flask import Flask, render_template # importing pandas moduleimport pandas as pd app = Flask(__name__) # reading the data in the csv filedf = pd.read_csv('sample_data.csv')df.to_csv('sample_data.csv', index=None) # route to html page - \"table\"@app.route('/')@app.route('/table')def table(): # converting csv to html data = pd.read_csv('sample_data.csv') return render_template('table.html', tables=[data.to_html()], titles=['']) if __name__ == \"__main__\": app.run(host=\"localhost\", port=int(\"5000\"))",
"e": 1181,
"s": 630,
"text": null
},
{
"code": null,
"e": 1280,
"s": 1181,
"text": "Step 2: Create the folder ‘templates’. create the file ‘table.html’ inside the ‘templates’ folder."
},
{
"code": null,
"e": 1285,
"s": 1280,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> Table </title> </head> <body> <div align=\"center\"> <table> <h1> <!--Displaying the converted table--> {% for table in tables %} <h2>{{titles[loop.index]}}</h2> {{ table|safe }} {% endfor %} </h1> </table> </div> </body></html>",
"e": 1784,
"s": 1285,
"text": null
},
{
"code": null,
"e": 1824,
"s": 1784,
"text": "Step 3: Add the ‘sample_data.csv’ file."
},
{
"code": null,
"e": 1875,
"s": 1824,
"text": "Step 4: The project structure will look like this."
},
{
"code": null,
"e": 1901,
"s": 1875,
"text": "Structure of the project"
},
{
"code": null,
"e": 1925,
"s": 1901,
"text": "Step 1: Run the server."
},
{
"code": null,
"e": 1966,
"s": 1925,
"text": "Step 2: Browse the URL ‘localhost:5000’."
},
{
"code": null,
"e": 2013,
"s": 1966,
"text": "Step 3: The output web page will be displayed."
},
{
"code": null,
"e": 2021,
"s": 2013,
"text": "Output:"
},
{
"code": null,
"e": 2048,
"s": 2021,
"text": "Output : CSV to HTML Table"
},
{
"code": null,
"e": 2063,
"s": 2048,
"text": "Flask Projects"
},
{
"code": null,
"e": 2076,
"s": 2063,
"text": "Python Flask"
},
{
"code": null,
"e": 2090,
"s": 2076,
"text": "Python-pandas"
},
{
"code": null,
"e": 2106,
"s": 2090,
"text": "Python-projects"
},
{
"code": null,
"e": 2113,
"s": 2106,
"text": "Python"
}
] |
HTTP headers | If-None-Match
|
18 Nov, 2019
The HTTP Header If-None-Match is a request-type header. Generally, it is used to update the entity tags on the server. Firstly, the Client provides the Server with a set of entity tags (E-tags). The Server compares the given tags with those it already has for the resource. Then, the Server will provide the requested page with a 200 status code only when none of the entity tags given to it matches. Or else, a 304 Not Modified status is returned by the Server.
There are two types of algorithms used to compare the entity tags. They are:
Weak Comparison Algorithm
Strong Comparison Algorithm
Weak comparison algorithm: It neglects minor differences which are considered to be unimportant between the entity tags. For example, two tags having the same contents but with different dates are considered to be identical.
Strong comparison algorithm: It checks the tags byte-to-byte.
Syntax:
If-None-Match: "entity_tag"
If-None-Match: *
Note : “*” is used to represent any resource.
Directives: This header accepts two directives as mentioned above and described below:
entity_tag: It represents the resource which is requested. It is a string which contains alphabets, numbers and other special characters enclosed within double quotes (” “).
“*”: It represents any resource and is used to avoid race conditions between PUT operations. When this directive is used, the server should not perform the requested method if the entity is given to it already exists for that resource.
Examples:
If-None-Match:"2780-5524acffbda80-gzip"
If-None-Match:"2780-5524acffbda80-gzip"
If-None-Match:*
If-None-Match:*
To check this If-None-Match in action go to Inspect Element -> Network check the request header for If-None-Match like below. The If-None-Match header is highlighted.
Supported Browsers: The browsers are compatible with HTTP If-None-Match header are listefd below:
Google Chrome
Internet Explorer
Mozilla Firefox
Microsoft Edge
Opera
Safari
HTTP-headers
Picked
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": "\n18 Nov, 2019"
},
{
"code": null,
"e": 491,
"s": 28,
"text": "The HTTP Header If-None-Match is a request-type header. Generally, it is used to update the entity tags on the server. Firstly, the Client provides the Server with a set of entity tags (E-tags). The Server compares the given tags with those it already has for the resource. Then, the Server will provide the requested page with a 200 status code only when none of the entity tags given to it matches. Or else, a 304 Not Modified status is returned by the Server."
},
{
"code": null,
"e": 568,
"s": 491,
"text": "There are two types of algorithms used to compare the entity tags. They are:"
},
{
"code": null,
"e": 594,
"s": 568,
"text": "Weak Comparison Algorithm"
},
{
"code": null,
"e": 622,
"s": 594,
"text": "Strong Comparison Algorithm"
},
{
"code": null,
"e": 847,
"s": 622,
"text": "Weak comparison algorithm: It neglects minor differences which are considered to be unimportant between the entity tags. For example, two tags having the same contents but with different dates are considered to be identical."
},
{
"code": null,
"e": 909,
"s": 847,
"text": "Strong comparison algorithm: It checks the tags byte-to-byte."
},
{
"code": null,
"e": 917,
"s": 909,
"text": "Syntax:"
},
{
"code": null,
"e": 945,
"s": 917,
"text": "If-None-Match: \"entity_tag\""
},
{
"code": null,
"e": 962,
"s": 945,
"text": "If-None-Match: *"
},
{
"code": null,
"e": 1008,
"s": 962,
"text": "Note : “*” is used to represent any resource."
},
{
"code": null,
"e": 1095,
"s": 1008,
"text": "Directives: This header accepts two directives as mentioned above and described below:"
},
{
"code": null,
"e": 1269,
"s": 1095,
"text": "entity_tag: It represents the resource which is requested. It is a string which contains alphabets, numbers and other special characters enclosed within double quotes (” “)."
},
{
"code": null,
"e": 1505,
"s": 1269,
"text": "“*”: It represents any resource and is used to avoid race conditions between PUT operations. When this directive is used, the server should not perform the requested method if the entity is given to it already exists for that resource."
},
{
"code": null,
"e": 1515,
"s": 1505,
"text": "Examples:"
},
{
"code": null,
"e": 1555,
"s": 1515,
"text": "If-None-Match:\"2780-5524acffbda80-gzip\""
},
{
"code": null,
"e": 1595,
"s": 1555,
"text": "If-None-Match:\"2780-5524acffbda80-gzip\""
},
{
"code": null,
"e": 1611,
"s": 1595,
"text": "If-None-Match:*"
},
{
"code": null,
"e": 1627,
"s": 1611,
"text": "If-None-Match:*"
},
{
"code": null,
"e": 1794,
"s": 1627,
"text": "To check this If-None-Match in action go to Inspect Element -> Network check the request header for If-None-Match like below. The If-None-Match header is highlighted."
},
{
"code": null,
"e": 1892,
"s": 1794,
"text": "Supported Browsers: The browsers are compatible with HTTP If-None-Match header are listefd below:"
},
{
"code": null,
"e": 1906,
"s": 1892,
"text": "Google Chrome"
},
{
"code": null,
"e": 1924,
"s": 1906,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1940,
"s": 1924,
"text": "Mozilla Firefox"
},
{
"code": null,
"e": 1955,
"s": 1940,
"text": "Microsoft Edge"
},
{
"code": null,
"e": 1961,
"s": 1955,
"text": "Opera"
},
{
"code": null,
"e": 1968,
"s": 1961,
"text": "Safari"
},
{
"code": null,
"e": 1981,
"s": 1968,
"text": "HTTP-headers"
},
{
"code": null,
"e": 1988,
"s": 1981,
"text": "Picked"
},
{
"code": null,
"e": 2005,
"s": 1988,
"text": "Web Technologies"
}
] |
Renaming columns for PySpark DataFrames Aggregates
|
19 Dec, 2021
In this article, we will discuss how to rename columns for PySpark dataframe aggregates using Pyspark.
Dataframe in use:
In PySpark, groupBy() is used to collect the identical data into groups on the PySpark DataFrame and perform aggregate functions on the grouped data. These are available in functions module:
We can use this method to change the column name which is aggregated.
Syntax:
dataframe.groupBy(‘column_name_group’).agg(aggregate_function(‘column_name’).alias(“new_column_name”))
where,
dataframe is the input dataframe
column_name_group is the grouped column
aggregate_function is the function from the above functions
column_name is the column where aggregation is performed
new_column_name is the new name for column_name
Example 1: Aggregating DEPT column with sum() and avg() by changing FEE column name to Total Fee
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession #import functionsfrom pyspark.sql import functions # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # aggregating DEPT column with sum() and avg() # by changing FEE column name to Total Feedataframe.groupBy('DEPT').agg(functions.sum('FEE').alias( "Total Fee"), functions.avg('FEE').alias("Average Fee")).show()
Output:
Example 2 : Aggregating DEPT column with min(),count(),mean() and max() by changing FEE column name to Total Fee
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession #import functionsfrom pyspark.sql import functions # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # aggregating DEPT column with min(),count(),mean() # and max() by changing FEE column name to Total Feedataframe.groupBy('DEPT').agg(functions.min('FEE').alias("Minimum Fee"), functions.max('FEE').alias("Maximum Fee"), functions.count('FEE').alias("No of Fee"), functions.mean('FEE').alias("Average Fee")).show()
Output:
This takes a resultant aggregated column name and renames this column. After aggregation, It will return the column names as aggregate_operation(old_column)
so using this we can replace this with our new column
Syntax:
dataframe.groupBy(“column_name_group”).agg({“column_name”:”aggregate_operation”}).withColumnRenamed(“aggregate_operation(column_name)”, “new_column_name”)
Example: Aggregating DEPT column with sum() FEE and rename to Total Fee
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession #import functionsfrom pyspark.sql import functions # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # aggregating DEPT column with sum() FEE and rename to Total Feedataframe.groupBy("DEPT").agg({"FEE": "sum"}).withColumnRenamed( "sum(FEE)", "Total Fee").show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 131,
"s": 28,
"text": "In this article, we will discuss how to rename columns for PySpark dataframe aggregates using Pyspark."
},
{
"code": null,
"e": 149,
"s": 131,
"text": "Dataframe in use:"
},
{
"code": null,
"e": 341,
"s": 149,
"text": "In PySpark, groupBy() is used to collect the identical data into groups on the PySpark DataFrame and perform aggregate functions on the grouped data. These are available in functions module:"
},
{
"code": null,
"e": 411,
"s": 341,
"text": "We can use this method to change the column name which is aggregated."
},
{
"code": null,
"e": 419,
"s": 411,
"text": "Syntax:"
},
{
"code": null,
"e": 522,
"s": 419,
"text": "dataframe.groupBy(‘column_name_group’).agg(aggregate_function(‘column_name’).alias(“new_column_name”))"
},
{
"code": null,
"e": 529,
"s": 522,
"text": "where,"
},
{
"code": null,
"e": 563,
"s": 529,
"text": "dataframe is the input dataframe"
},
{
"code": null,
"e": 603,
"s": 563,
"text": "column_name_group is the grouped column"
},
{
"code": null,
"e": 663,
"s": 603,
"text": "aggregate_function is the function from the above functions"
},
{
"code": null,
"e": 720,
"s": 663,
"text": "column_name is the column where aggregation is performed"
},
{
"code": null,
"e": 768,
"s": 720,
"text": "new_column_name is the new name for column_name"
},
{
"code": null,
"e": 865,
"s": 768,
"text": "Example 1: Aggregating DEPT column with sum() and avg() by changing FEE column name to Total Fee"
},
{
"code": null,
"e": 873,
"s": 865,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession #import functionsfrom pyspark.sql import functions # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # aggregating DEPT column with sum() and avg() # by changing FEE column name to Total Feedataframe.groupBy('DEPT').agg(functions.sum('FEE').alias( \"Total Fee\"), functions.avg('FEE').alias(\"Average Fee\")).show()",
"e": 1863,
"s": 873,
"text": null
},
{
"code": null,
"e": 1871,
"s": 1863,
"text": "Output:"
},
{
"code": null,
"e": 1984,
"s": 1871,
"text": "Example 2 : Aggregating DEPT column with min(),count(),mean() and max() by changing FEE column name to Total Fee"
},
{
"code": null,
"e": 1992,
"s": 1984,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession #import functionsfrom pyspark.sql import functions # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # aggregating DEPT column with min(),count(),mean() # and max() by changing FEE column name to Total Feedataframe.groupBy('DEPT').agg(functions.min('FEE').alias(\"Minimum Fee\"), functions.max('FEE').alias(\"Maximum Fee\"), functions.count('FEE').alias(\"No of Fee\"), functions.mean('FEE').alias(\"Average Fee\")).show()",
"e": 3170,
"s": 1992,
"text": null
},
{
"code": null,
"e": 3178,
"s": 3170,
"text": "Output:"
},
{
"code": null,
"e": 3335,
"s": 3178,
"text": "This takes a resultant aggregated column name and renames this column. After aggregation, It will return the column names as aggregate_operation(old_column)"
},
{
"code": null,
"e": 3389,
"s": 3335,
"text": "so using this we can replace this with our new column"
},
{
"code": null,
"e": 3397,
"s": 3389,
"text": "Syntax:"
},
{
"code": null,
"e": 3552,
"s": 3397,
"text": "dataframe.groupBy(“column_name_group”).agg({“column_name”:”aggregate_operation”}).withColumnRenamed(“aggregate_operation(column_name)”, “new_column_name”)"
},
{
"code": null,
"e": 3624,
"s": 3552,
"text": "Example: Aggregating DEPT column with sum() FEE and rename to Total Fee"
},
{
"code": null,
"e": 3632,
"s": 3624,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession #import functionsfrom pyspark.sql import functions # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # aggregating DEPT column with sum() FEE and rename to Total Feedataframe.groupBy(\"DEPT\").agg({\"FEE\": \"sum\"}).withColumnRenamed( \"sum(FEE)\", \"Total Fee\").show()",
"e": 4572,
"s": 3632,
"text": null
},
{
"code": null,
"e": 4580,
"s": 4572,
"text": "Output:"
},
{
"code": null,
"e": 4587,
"s": 4580,
"text": "Picked"
},
{
"code": null,
"e": 4602,
"s": 4587,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 4609,
"s": 4602,
"text": "Python"
}
] |
Cropping an Image in a circular way using Python
|
24 Feb, 2021
In this article, we will learn to crop an image circularly using a pillow library. Cropping an image circularly means selecting a circular region inside an image and removing everything outside the circle.
Approach:
If you have an L mode image, the image becomes grayscale. So we create a new image with mode “L”.
An image is created with a white circle in the middle with dimensions same as the input image.
Convert a new image to an array.
Convert original image from an array.
Stack these two arrays together to crop out only the circular middle part.
Let’s take this initial image :
Step 1: Import the module and read the image.
Python3
import numpy as npfrom PIL import Image, ImageDraw img = Image.open("/content/gfg.jpeg")display(img)
Output:
Step 2: Create an image.
We will use pieslice() function to get the circular part of the image in white, then we will superimpose the original image and the luminous image.
ImageDraw.Draw.pieslice() Same as arc, but also draws straight lines between the endpoints and the center of the bounding box.
Syntax: PIL.ImageDraw.Draw.pieslice(xy, start, end, fill=None, outline=None)
Parameters:xy – Four points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or [x0, y0, x1, y1].start – Starting angle, in degrees. Angles are measured from 3 o’clock, increasing clockwise.end – Ending angle, in degrees.fill – Color to use for the fill.outline – Color to use for the outline.
Returns: An Image object in pieslice shape.
Code:
Python3
h,w = img.size # creating luminous imagelum_img = Image.new('L',[h,w] ,0) draw = ImageDraw.Draw(lum_img)draw.pieslice([(0,0),(h,w)],0,360,fill=255)img_arr = np.array(img)lum_img_arr = np.array(lum_img)display(Image.fromarray(lum_img_arr))
Output:
Step 3: Stack these two arrays together to crop out only the circular middle part.
Python3
final_img_arr = np.dstack((img_arr, lum_img_arr))display(Image.fromarray(final_img_arr))
Output:
Below is the full implementation:
Python3
import numpy as npfrom PIL import Image, ImageDraw img=Image.open("img.jpg")display(img) height,width = img.sizelum_img = Image.new('L', [height,width] , 0) draw = ImageDraw.Draw(lum_img)draw.pieslice([(0,0), (height,width)], 0, 360, fill = 255, outline = "white")img_arr =np.array(img)lum_img_arr =np.array(lum_img)display(Image.fromarray(lum_img_arr))final_img_arr = np.dstack((img_arr,lum_img_arr))display(Image.fromarray(final_img_arr))
Output:
Image-Processing
Picked
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Feb, 2021"
},
{
"code": null,
"e": 261,
"s": 54,
"text": "In this article, we will learn to crop an image circularly using a pillow library. Cropping an image circularly means selecting a circular region inside an image and removing everything outside the circle. "
},
{
"code": null,
"e": 271,
"s": 261,
"text": "Approach:"
},
{
"code": null,
"e": 369,
"s": 271,
"text": "If you have an L mode image, the image becomes grayscale. So we create a new image with mode “L”."
},
{
"code": null,
"e": 464,
"s": 369,
"text": "An image is created with a white circle in the middle with dimensions same as the input image."
},
{
"code": null,
"e": 497,
"s": 464,
"text": "Convert a new image to an array."
},
{
"code": null,
"e": 535,
"s": 497,
"text": "Convert original image from an array."
},
{
"code": null,
"e": 610,
"s": 535,
"text": "Stack these two arrays together to crop out only the circular middle part."
},
{
"code": null,
"e": 642,
"s": 610,
"text": "Let’s take this initial image :"
},
{
"code": null,
"e": 688,
"s": 642,
"text": "Step 1: Import the module and read the image."
},
{
"code": null,
"e": 696,
"s": 688,
"text": "Python3"
},
{
"code": "import numpy as npfrom PIL import Image, ImageDraw img = Image.open(\"/content/gfg.jpeg\")display(img)",
"e": 800,
"s": 696,
"text": null
},
{
"code": null,
"e": 808,
"s": 800,
"text": "Output:"
},
{
"code": null,
"e": 833,
"s": 808,
"text": "Step 2: Create an image."
},
{
"code": null,
"e": 981,
"s": 833,
"text": "We will use pieslice() function to get the circular part of the image in white, then we will superimpose the original image and the luminous image."
},
{
"code": null,
"e": 1108,
"s": 981,
"text": "ImageDraw.Draw.pieslice() Same as arc, but also draws straight lines between the endpoints and the center of the bounding box."
},
{
"code": null,
"e": 1185,
"s": 1108,
"text": "Syntax: PIL.ImageDraw.Draw.pieslice(xy, start, end, fill=None, outline=None)"
},
{
"code": null,
"e": 1491,
"s": 1185,
"text": "Parameters:xy – Four points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or [x0, y0, x1, y1].start – Starting angle, in degrees. Angles are measured from 3 o’clock, increasing clockwise.end – Ending angle, in degrees.fill – Color to use for the fill.outline – Color to use for the outline."
},
{
"code": null,
"e": 1535,
"s": 1491,
"text": "Returns: An Image object in pieslice shape."
},
{
"code": null,
"e": 1541,
"s": 1535,
"text": "Code:"
},
{
"code": null,
"e": 1549,
"s": 1541,
"text": "Python3"
},
{
"code": "h,w = img.size # creating luminous imagelum_img = Image.new('L',[h,w] ,0) draw = ImageDraw.Draw(lum_img)draw.pieslice([(0,0),(h,w)],0,360,fill=255)img_arr = np.array(img)lum_img_arr = np.array(lum_img)display(Image.fromarray(lum_img_arr))",
"e": 1789,
"s": 1549,
"text": null
},
{
"code": null,
"e": 1797,
"s": 1789,
"text": "Output:"
},
{
"code": null,
"e": 1880,
"s": 1797,
"text": "Step 3: Stack these two arrays together to crop out only the circular middle part."
},
{
"code": null,
"e": 1888,
"s": 1880,
"text": "Python3"
},
{
"code": "final_img_arr = np.dstack((img_arr, lum_img_arr))display(Image.fromarray(final_img_arr))",
"e": 1977,
"s": 1888,
"text": null
},
{
"code": null,
"e": 1985,
"s": 1977,
"text": "Output:"
},
{
"code": null,
"e": 2019,
"s": 1985,
"text": "Below is the full implementation:"
},
{
"code": null,
"e": 2027,
"s": 2019,
"text": "Python3"
},
{
"code": "import numpy as npfrom PIL import Image, ImageDraw img=Image.open(\"img.jpg\")display(img) height,width = img.sizelum_img = Image.new('L', [height,width] , 0) draw = ImageDraw.Draw(lum_img)draw.pieslice([(0,0), (height,width)], 0, 360, fill = 255, outline = \"white\")img_arr =np.array(img)lum_img_arr =np.array(lum_img)display(Image.fromarray(lum_img_arr))final_img_arr = np.dstack((img_arr,lum_img_arr))display(Image.fromarray(final_img_arr))",
"e": 2485,
"s": 2027,
"text": null
},
{
"code": null,
"e": 2493,
"s": 2485,
"text": "Output:"
},
{
"code": null,
"e": 2510,
"s": 2493,
"text": "Image-Processing"
},
{
"code": null,
"e": 2517,
"s": 2510,
"text": "Picked"
},
{
"code": null,
"e": 2528,
"s": 2517,
"text": "Python-pil"
},
{
"code": null,
"e": 2535,
"s": 2528,
"text": "Python"
},
{
"code": null,
"e": 2633,
"s": 2535,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2675,
"s": 2633,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2697,
"s": 2675,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2723,
"s": 2697,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2755,
"s": 2723,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2784,
"s": 2755,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2811,
"s": 2784,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2832,
"s": 2811,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2855,
"s": 2832,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2891,
"s": 2855,
"text": "Convert integer to string in Python"
}
] |
How to validate mobile number length in ReactJS ?
|
12 Feb, 2021
Validating mobile number length is an important step to check whether the number entered by the user is genuine or not. Material UI for React has this component available for us and it is very easy to integrate. We can use the error Property for TextField Component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React, { useState } from "react";import TextField from "@material-ui/core/TextField";import InputAdornment from "@material-ui/core/InputAdornment"; const App = () => { const [mobile, setmobile] = useState(""); const [isError, setIsError] = useState(false); return ( <div style={{ marginLeft: "40%", }} > <h2>Validate Mobile number length in ReactJS?</h2> <TextField type="tel" error={isError} value={mobile} label="Enter Phone Number" onChange={(e) => { setmobile(e.target.value); if (e.target.value.length > 10) { setIsError(true); } }} InputProps={{ startAdornment: <InputAdornment position="start"> +91 </InputAdornment>, }} /> <h3>Your Mobile Number is: +91 {mobile} </h3> </div> );}; export default App;
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output. In the above example, we can see when the user exceeds the 10 digits, the TextField color turns to red to indicate the error, this is how we can validate mobile number length in ReactJS.
React-Questions
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Node.js | fs.writeFileSync() Method
Remove elements from a JavaScript Array
Form validation using HTML and JavaScript
How to create a multi-page website using React.js ?
ReactJS setState()
Create a Responsive Navbar using ReactJS
How to do crud operations in ReactJS ?
Re-rendering Components in ReactJS
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Feb, 2021"
},
{
"code": null,
"e": 335,
"s": 28,
"text": "Validating mobile number length is an important step to check whether the number entered by the user is genuine or not. Material UI for React has this component available for us and it is very easy to integrate. We can use the error Property for TextField Component in ReactJS using the following approach."
},
{
"code": null,
"e": 385,
"s": 335,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 449,
"s": 385,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 481,
"s": 449,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 581,
"s": 481,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 595,
"s": 581,
"text": "cd foldername"
},
{
"code": null,
"e": 704,
"s": 595,
"text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:"
},
{
"code": null,
"e": 734,
"s": 704,
"text": "npm install @material-ui/core"
},
{
"code": null,
"e": 786,
"s": 734,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 804,
"s": 786,
"text": "Project Structure"
},
{
"code": null,
"e": 933,
"s": 804,
"text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 944,
"s": 933,
"text": "Javascript"
},
{
"code": "import React, { useState } from \"react\";import TextField from \"@material-ui/core/TextField\";import InputAdornment from \"@material-ui/core/InputAdornment\"; const App = () => { const [mobile, setmobile] = useState(\"\"); const [isError, setIsError] = useState(false); return ( <div style={{ marginLeft: \"40%\", }} > <h2>Validate Mobile number length in ReactJS?</h2> <TextField type=\"tel\" error={isError} value={mobile} label=\"Enter Phone Number\" onChange={(e) => { setmobile(e.target.value); if (e.target.value.length > 10) { setIsError(true); } }} InputProps={{ startAdornment: <InputAdornment position=\"start\"> +91 </InputAdornment>, }} /> <h3>Your Mobile Number is: +91 {mobile} </h3> </div> );}; export default App;",
"e": 1841,
"s": 944,
"text": null
},
{
"code": null,
"e": 1954,
"s": 1841,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project."
},
{
"code": null,
"e": 1964,
"s": 1954,
"text": "npm start"
},
{
"code": null,
"e": 2250,
"s": 1964,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output. In the above example, we can see when the user exceeds the 10 digits, the TextField color turns to red to indicate the error, this is how we can validate mobile number length in ReactJS."
},
{
"code": null,
"e": 2266,
"s": 2250,
"text": "React-Questions"
},
{
"code": null,
"e": 2277,
"s": 2266,
"text": "JavaScript"
},
{
"code": null,
"e": 2285,
"s": 2277,
"text": "ReactJS"
},
{
"code": null,
"e": 2302,
"s": 2285,
"text": "Web Technologies"
},
{
"code": null,
"e": 2400,
"s": 2302,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2461,
"s": 2400,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2533,
"s": 2461,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2569,
"s": 2533,
"text": "Node.js | fs.writeFileSync() Method"
},
{
"code": null,
"e": 2609,
"s": 2569,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2651,
"s": 2609,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 2703,
"s": 2651,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 2722,
"s": 2703,
"text": "ReactJS setState()"
},
{
"code": null,
"e": 2763,
"s": 2722,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 2802,
"s": 2763,
"text": "How to do crud operations in ReactJS ?"
}
] |
Python IF Statement
|
It is similar to that of other languages. The if statement contains a logical expression using which data is compared and a decision is made based on the result of the comparison.
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if statement is executed. If boolean expression evaluates to FALSE, then the first set of code after the end of the if statement(s) is executed.
#!/usr/bin/python
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
print "Good bye!"
When the above code is executed, it produces the following result −
1 - Got a true expression value
|
[
{
"code": null,
"e": 2558,
"s": 2378,
"text": "It is similar to that of other languages. The if statement contains a logical expression using which data is compared and a decision is made based on the result of the comparison."
},
{
"code": null,
"e": 2590,
"s": 2558,
"text": "if expression:\n statement(s)\n"
},
{
"code": null,
"e": 2822,
"s": 2590,
"text": "If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if statement is executed. If boolean expression evaluates to FALSE, then the first set of code after the end of the if statement(s) is executed."
},
{
"code": null,
"e": 3012,
"s": 2822,
"text": "#!/usr/bin/python\n\nvar1 = 100\nif var1:\n print \"1 - Got a true expression value\"\n print var1\n\nvar2 = 0\nif var2:\n print \"2 - Got a true expression value\"\n print var2\nprint \"Good bye!\""
},
{
"code": null,
"e": 3080,
"s": 3012,
"text": "When the above code is executed, it produces the following result −"
}
] |
Python | Pandas Series.dt.second
|
20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.second attribute return a numpy array containing the second of the datetime in the underlying data of the given series object.
Syntax: Series.dt.second
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.second attribute to return the seconds of the datetime in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-10-21 09:30:45', '2019-7-18 12:30:21', '2008-02-2 10:30:38', '2010-4-22 09:25:19', '2019-11-8 02:22:44']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)
Output :
Now we will use Series.dt.second attribute to return the seconds of the datetime in the underlying data of the given Series object.
# return the secondresult = sr.dt.second # print the resultprint(result)
Output :As we can see in the output, the Series.dt.second attribute has successfully accessed and returned the second of the datetime in the underlying data of the given series object. Example #2 : Use Series.dt.second attribute to return the seconds of the datetime in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'H')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)
Output :
Now we will use Series.dt.second attribute to return the seconds of the datetime in the underlying data of the given Series object.
# return the secondresult = sr.dt.second # print the resultprint(result)
Output :As we can see in the output, the Series.dt.second attribute has successfully accessed and returned the second of the datetime in the underlying data of the given series object.
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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": "\n20 Mar, 2019"
},
{
"code": null,
"e": 276,
"s": 28,
"text": "Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.second attribute return a numpy array containing the second of the datetime in the underlying data of the given series object."
},
{
"code": null,
"e": 301,
"s": 276,
"text": "Syntax: Series.dt.second"
},
{
"code": null,
"e": 318,
"s": 301,
"text": "Parameter : None"
},
{
"code": null,
"e": 340,
"s": 318,
"text": "Returns : numpy array"
},
{
"code": null,
"e": 472,
"s": 340,
"text": "Example #1: Use Series.dt.second attribute to return the seconds of the datetime in the underlying data of the given Series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-10-21 09:30:45', '2019-7-18 12:30:21', '2008-02-2 10:30:38', '2010-4-22 09:25:19', '2019-11-8 02:22:44']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)",
"e": 880,
"s": 472,
"text": null
},
{
"code": null,
"e": 889,
"s": 880,
"text": "Output :"
},
{
"code": null,
"e": 1021,
"s": 889,
"text": "Now we will use Series.dt.second attribute to return the seconds of the datetime in the underlying data of the given Series object."
},
{
"code": "# return the secondresult = sr.dt.second # print the resultprint(result)",
"e": 1095,
"s": 1021,
"text": null
},
{
"code": null,
"e": 1413,
"s": 1095,
"text": "Output :As we can see in the output, the Series.dt.second attribute has successfully accessed and returned the second of the datetime in the underlying data of the given series object. Example #2 : Use Series.dt.second attribute to return the seconds of the datetime in the underlying data of the given Series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'H')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)",
"e": 1687,
"s": 1413,
"text": null
},
{
"code": null,
"e": 1696,
"s": 1687,
"text": "Output :"
},
{
"code": null,
"e": 1828,
"s": 1696,
"text": "Now we will use Series.dt.second attribute to return the seconds of the datetime in the underlying data of the given Series object."
},
{
"code": "# return the secondresult = sr.dt.second # print the resultprint(result)",
"e": 1902,
"s": 1828,
"text": null
},
{
"code": null,
"e": 2087,
"s": 1902,
"text": "Output :As we can see in the output, the Series.dt.second attribute has successfully accessed and returned the second of the datetime in the underlying data of the given series object."
},
{
"code": null,
"e": 2117,
"s": 2087,
"text": "Python pandas-series-datetime"
},
{
"code": null,
"e": 2131,
"s": 2117,
"text": "Python-pandas"
},
{
"code": null,
"e": 2138,
"s": 2131,
"text": "Python"
},
{
"code": null,
"e": 2236,
"s": 2138,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2268,
"s": 2236,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2295,
"s": 2268,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2316,
"s": 2295,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2339,
"s": 2316,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2395,
"s": 2339,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2426,
"s": 2395,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2468,
"s": 2426,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2510,
"s": 2468,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2549,
"s": 2510,
"text": "Python | Get unique values from a list"
}
] |
#pragma Directive in C/C++
|
03 Feb, 2022
This directive is a special purpose directive and is used to turn on or off some features. These types of directives are compiler-specific i.e., they vary from compiler to compiler. Some of the #pragma directives are discussed below:
#pragma startup and #pragma exit: These directives helps us to specify the functions that are needed to run before program startup( before the control passes to main()) and just before program exit (just before the control returns from main()).Note: Below program will not work with GCC compilers.Look at the below program:#include<stdio.h> void func1(); void func2(); #pragma startup func1 #pragma exit func2 void func1() { printf("Inside func1()\n"); } void func2() { printf("Inside func2()\n"); } int main() { printf("Inside main()\n"); return 0; } Output:Inside func1()
Inside main()
Inside func2()
The above code will produce the output as given below when run on GCC compilers:Inside main()
This happens because GCC does not support #pragma startup or exit. However, you can use the below code for a similar output on GCC compilers.#include<stdio.h> void func1(); void func2(); void __attribute__((constructor)) func1(); void __attribute__((destructor)) func2(); void func1() { printf("Inside func1()\n"); } void func2() { printf("Inside func2()\n"); } int main() { printf("Inside main()\n"); return 0; } Output:Inside func1()
Inside main()
Inside func2()
#pragma warn Directive: This directive is used to hide the warning messages which are displayed during compilation. This may be useful for us when we have a large program and we want to solve all the errors before looking on warnings then by using it we can focus on errors by hiding all warnings. we can again let the warnings be visible by making slight changes in syntax.Syntax:#pragma warn +xxx (To show the warning)
#pragma warn -xxx (To hide the warning)
#pragma warn .xxx (To toggle between hide and show)
We can hide the warnings as shown below:#pragma warn -rvl: This directive hides those warning which are raised when a function which is supposed to return a value does not return a value.#pragma warn -par: This directive hides those warning which are raised when a function does not uses the parameters passed to it.#pragma warn -rch: This directive hides those warning which are raised when a code is unreachable. For example: any code written after the return statement in a function is unreachable.Example:// Example to explain the working of // #pragma warn directive// This program is compatible with C/C++ compiler #include<stdio.h> #pragma warn -rvl /* return value */#pragma warn -par /* parameter never used */#pragma warn -rch /*unreachable code */ int show(int x){ // parameter x is never used in // the function printf("GEEKSFORGEEKS"); // function does not have a // return statement} int main(){ show(10); return 0;}Output:GEEKSFORGEEKS
The above program compiles successfully without any warnings to give the output “GEEKSFORGEEKS”.#pragma GCC poison: This directive is supported by the GCC compiler and is used to remove an identifier completely from the program. If we want to block an identifier then we can use the #pragma GCC poison directive.Example:// Program to illustrate the // #pragma GCC poison directive #include<stdio.h> #pragma GCC poison printf int main(){ int a=10; if(a==10) { printf("GEEKSFORGEEKS"); } else printf("bye"); return 0;}The above program will give the below error:prog.c: In function 'main':
prog.c:14:9: error: attempt to use poisoned "printf"
printf("GEEKSFORGEEKS");
^
prog.c:17:9: error: attempt to use poisoned "printf"
printf("bye");
^
#pragma GCC dependency: The #pragma GCC dependency allows you to check the relative dates of the current file and another file. If the other file is more recent than the current file, a warning is issued. This is useful if the current file is derived from the other file, and should be regenerated.Syntax:#pragma GCC dependency "parse.y"
#pragma GCC dependency "/usr/include/time.h" rerun fixincludes
#pragma GCC system_header: This pragma takes no arguments. It causes the rest of the code in the current file to be treated as if it came from a system header.#pragma once: The #pragma once directive has a very simple concept. The header file containing this directive is included only once even if the programmer includes it multiple times during a compilation. This is not included in any ISO C++ standard. This directive works similar to the #include guard idiom. Use of #pragma once saves the program from multiple inclusion optimisation.Syntax:#pragma once
#pragma startup and #pragma exit: These directives helps us to specify the functions that are needed to run before program startup( before the control passes to main()) and just before program exit (just before the control returns from main()).Note: Below program will not work with GCC compilers.Look at the below program:#include<stdio.h> void func1(); void func2(); #pragma startup func1 #pragma exit func2 void func1() { printf("Inside func1()\n"); } void func2() { printf("Inside func2()\n"); } int main() { printf("Inside main()\n"); return 0; } Output:Inside func1()
Inside main()
Inside func2()
The above code will produce the output as given below when run on GCC compilers:Inside main()
This happens because GCC does not support #pragma startup or exit. However, you can use the below code for a similar output on GCC compilers.#include<stdio.h> void func1(); void func2(); void __attribute__((constructor)) func1(); void __attribute__((destructor)) func2(); void func1() { printf("Inside func1()\n"); } void func2() { printf("Inside func2()\n"); } int main() { printf("Inside main()\n"); return 0; } Output:Inside func1()
Inside main()
Inside func2()
Note: Below program will not work with GCC compilers.Look at the below program:
#include<stdio.h> void func1(); void func2(); #pragma startup func1 #pragma exit func2 void func1() { printf("Inside func1()\n"); } void func2() { printf("Inside func2()\n"); } int main() { printf("Inside main()\n"); return 0; }
Inside func1()
Inside main()
Inside func2()
The above code will produce the output as given below when run on GCC compilers:
Inside main()
This happens because GCC does not support #pragma startup or exit. However, you can use the below code for a similar output on GCC compilers.
#include<stdio.h> void func1(); void func2(); void __attribute__((constructor)) func1(); void __attribute__((destructor)) func2(); void func1() { printf("Inside func1()\n"); } void func2() { printf("Inside func2()\n"); } int main() { printf("Inside main()\n"); return 0; }
Inside func1()
Inside main()
Inside func2()
#pragma warn Directive: This directive is used to hide the warning messages which are displayed during compilation. This may be useful for us when we have a large program and we want to solve all the errors before looking on warnings then by using it we can focus on errors by hiding all warnings. we can again let the warnings be visible by making slight changes in syntax.Syntax:#pragma warn +xxx (To show the warning)
#pragma warn -xxx (To hide the warning)
#pragma warn .xxx (To toggle between hide and show)
We can hide the warnings as shown below:#pragma warn -rvl: This directive hides those warning which are raised when a function which is supposed to return a value does not return a value.#pragma warn -par: This directive hides those warning which are raised when a function does not uses the parameters passed to it.#pragma warn -rch: This directive hides those warning which are raised when a code is unreachable. For example: any code written after the return statement in a function is unreachable.Example:// Example to explain the working of // #pragma warn directive// This program is compatible with C/C++ compiler #include<stdio.h> #pragma warn -rvl /* return value */#pragma warn -par /* parameter never used */#pragma warn -rch /*unreachable code */ int show(int x){ // parameter x is never used in // the function printf("GEEKSFORGEEKS"); // function does not have a // return statement} int main(){ show(10); return 0;}Output:GEEKSFORGEEKS
The above program compiles successfully without any warnings to give the output “GEEKSFORGEEKS”.
Syntax:
#pragma warn +xxx (To show the warning)
#pragma warn -xxx (To hide the warning)
#pragma warn .xxx (To toggle between hide and show)
We can hide the warnings as shown below:
#pragma warn -rvl: This directive hides those warning which are raised when a function which is supposed to return a value does not return a value.
#pragma warn -par: This directive hides those warning which are raised when a function does not uses the parameters passed to it.
#pragma warn -rch: This directive hides those warning which are raised when a code is unreachable. For example: any code written after the return statement in a function is unreachable.
Example:
// Example to explain the working of // #pragma warn directive// This program is compatible with C/C++ compiler #include<stdio.h> #pragma warn -rvl /* return value */#pragma warn -par /* parameter never used */#pragma warn -rch /*unreachable code */ int show(int x){ // parameter x is never used in // the function printf("GEEKSFORGEEKS"); // function does not have a // return statement} int main(){ show(10); return 0;}
GEEKSFORGEEKS
The above program compiles successfully without any warnings to give the output “GEEKSFORGEEKS”.
#pragma GCC poison: This directive is supported by the GCC compiler and is used to remove an identifier completely from the program. If we want to block an identifier then we can use the #pragma GCC poison directive.Example:// Program to illustrate the // #pragma GCC poison directive #include<stdio.h> #pragma GCC poison printf int main(){ int a=10; if(a==10) { printf("GEEKSFORGEEKS"); } else printf("bye"); return 0;}The above program will give the below error:prog.c: In function 'main':
prog.c:14:9: error: attempt to use poisoned "printf"
printf("GEEKSFORGEEKS");
^
prog.c:17:9: error: attempt to use poisoned "printf"
printf("bye");
^
Example:
// Program to illustrate the // #pragma GCC poison directive #include<stdio.h> #pragma GCC poison printf int main(){ int a=10; if(a==10) { printf("GEEKSFORGEEKS"); } else printf("bye"); return 0;}
The above program will give the below error:
prog.c: In function 'main':
prog.c:14:9: error: attempt to use poisoned "printf"
printf("GEEKSFORGEEKS");
^
prog.c:17:9: error: attempt to use poisoned "printf"
printf("bye");
^
#pragma GCC dependency: The #pragma GCC dependency allows you to check the relative dates of the current file and another file. If the other file is more recent than the current file, a warning is issued. This is useful if the current file is derived from the other file, and should be regenerated.Syntax:#pragma GCC dependency "parse.y"
#pragma GCC dependency "/usr/include/time.h" rerun fixincludes
Syntax:
#pragma GCC dependency "parse.y"
#pragma GCC dependency "/usr/include/time.h" rerun fixincludes
#pragma GCC system_header: This pragma takes no arguments. It causes the rest of the code in the current file to be treated as if it came from a system header.
#pragma once: The #pragma once directive has a very simple concept. The header file containing this directive is included only once even if the programmer includes it multiple times during a compilation. This is not included in any ISO C++ standard. This directive works similar to the #include guard idiom. Use of #pragma once saves the program from multiple inclusion optimisation.Syntax:#pragma once
Syntax:
#pragma once
C-Macro & Preprocessor
Macro & Preprocessor
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Feb, 2022"
},
{
"code": null,
"e": 286,
"s": 52,
"text": "This directive is a special purpose directive and is used to turn on or off some features. These types of directives are compiler-specific i.e., they vary from compiler to compiler. Some of the #pragma directives are discussed below:"
},
{
"code": null,
"e": 4847,
"s": 286,
"text": "#pragma startup and #pragma exit: These directives helps us to specify the functions that are needed to run before program startup( before the control passes to main()) and just before program exit (just before the control returns from main()).Note: Below program will not work with GCC compilers.Look at the below program:#include<stdio.h> void func1(); void func2(); #pragma startup func1 #pragma exit func2 void func1() { printf(\"Inside func1()\\n\"); } void func2() { printf(\"Inside func2()\\n\"); } int main() { printf(\"Inside main()\\n\"); return 0; } Output:Inside func1()\nInside main()\nInside func2()\nThe above code will produce the output as given below when run on GCC compilers:Inside main()\nThis happens because GCC does not support #pragma startup or exit. However, you can use the below code for a similar output on GCC compilers.#include<stdio.h> void func1(); void func2(); void __attribute__((constructor)) func1(); void __attribute__((destructor)) func2(); void func1() { printf(\"Inside func1()\\n\"); } void func2() { printf(\"Inside func2()\\n\"); } int main() { printf(\"Inside main()\\n\"); return 0; } Output:Inside func1()\nInside main()\nInside func2()\n#pragma warn Directive: This directive is used to hide the warning messages which are displayed during compilation. This may be useful for us when we have a large program and we want to solve all the errors before looking on warnings then by using it we can focus on errors by hiding all warnings. we can again let the warnings be visible by making slight changes in syntax.Syntax:#pragma warn +xxx (To show the warning)\n#pragma warn -xxx (To hide the warning)\n#pragma warn .xxx (To toggle between hide and show)\nWe can hide the warnings as shown below:#pragma warn -rvl: This directive hides those warning which are raised when a function which is supposed to return a value does not return a value.#pragma warn -par: This directive hides those warning which are raised when a function does not uses the parameters passed to it.#pragma warn -rch: This directive hides those warning which are raised when a code is unreachable. For example: any code written after the return statement in a function is unreachable.Example:// Example to explain the working of // #pragma warn directive// This program is compatible with C/C++ compiler #include<stdio.h> #pragma warn -rvl /* return value */#pragma warn -par /* parameter never used */#pragma warn -rch /*unreachable code */ int show(int x){ // parameter x is never used in // the function printf(\"GEEKSFORGEEKS\"); // function does not have a // return statement} int main(){ show(10); return 0;}Output:GEEKSFORGEEKS\nThe above program compiles successfully without any warnings to give the output “GEEKSFORGEEKS”.#pragma GCC poison: This directive is supported by the GCC compiler and is used to remove an identifier completely from the program. If we want to block an identifier then we can use the #pragma GCC poison directive.Example:// Program to illustrate the // #pragma GCC poison directive #include<stdio.h> #pragma GCC poison printf int main(){ int a=10; if(a==10) { printf(\"GEEKSFORGEEKS\"); } else printf(\"bye\"); return 0;}The above program will give the below error:prog.c: In function 'main':\nprog.c:14:9: error: attempt to use poisoned \"printf\"\n printf(\"GEEKSFORGEEKS\");\n ^\nprog.c:17:9: error: attempt to use poisoned \"printf\"\n printf(\"bye\");\n ^\n#pragma GCC dependency: The #pragma GCC dependency allows you to check the relative dates of the current file and another file. If the other file is more recent than the current file, a warning is issued. This is useful if the current file is derived from the other file, and should be regenerated.Syntax:#pragma GCC dependency \"parse.y\"\n#pragma GCC dependency \"/usr/include/time.h\" rerun fixincludes\n#pragma GCC system_header: This pragma takes no arguments. It causes the rest of the code in the current file to be treated as if it came from a system header.#pragma once: The #pragma once directive has a very simple concept. The header file containing this directive is included only once even if the programmer includes it multiple times during a compilation. This is not included in any ISO C++ standard. This directive works similar to the #include guard idiom. Use of #pragma once saves the program from multiple inclusion optimisation.Syntax:#pragma once"
},
{
"code": null,
"e": 6102,
"s": 4847,
"text": "#pragma startup and #pragma exit: These directives helps us to specify the functions that are needed to run before program startup( before the control passes to main()) and just before program exit (just before the control returns from main()).Note: Below program will not work with GCC compilers.Look at the below program:#include<stdio.h> void func1(); void func2(); #pragma startup func1 #pragma exit func2 void func1() { printf(\"Inside func1()\\n\"); } void func2() { printf(\"Inside func2()\\n\"); } int main() { printf(\"Inside main()\\n\"); return 0; } Output:Inside func1()\nInside main()\nInside func2()\nThe above code will produce the output as given below when run on GCC compilers:Inside main()\nThis happens because GCC does not support #pragma startup or exit. However, you can use the below code for a similar output on GCC compilers.#include<stdio.h> void func1(); void func2(); void __attribute__((constructor)) func1(); void __attribute__((destructor)) func2(); void func1() { printf(\"Inside func1()\\n\"); } void func2() { printf(\"Inside func2()\\n\"); } int main() { printf(\"Inside main()\\n\"); return 0; } Output:Inside func1()\nInside main()\nInside func2()\n"
},
{
"code": null,
"e": 6182,
"s": 6102,
"text": "Note: Below program will not work with GCC compilers.Look at the below program:"
},
{
"code": "#include<stdio.h> void func1(); void func2(); #pragma startup func1 #pragma exit func2 void func1() { printf(\"Inside func1()\\n\"); } void func2() { printf(\"Inside func2()\\n\"); } int main() { printf(\"Inside main()\\n\"); return 0; } ",
"e": 6459,
"s": 6182,
"text": null
},
{
"code": null,
"e": 6504,
"s": 6459,
"text": "Inside func1()\nInside main()\nInside func2()\n"
},
{
"code": null,
"e": 6585,
"s": 6504,
"text": "The above code will produce the output as given below when run on GCC compilers:"
},
{
"code": null,
"e": 6600,
"s": 6585,
"text": "Inside main()\n"
},
{
"code": null,
"e": 6742,
"s": 6600,
"text": "This happens because GCC does not support #pragma startup or exit. However, you can use the below code for a similar output on GCC compilers."
},
{
"code": "#include<stdio.h> void func1(); void func2(); void __attribute__((constructor)) func1(); void __attribute__((destructor)) func2(); void func1() { printf(\"Inside func1()\\n\"); } void func2() { printf(\"Inside func2()\\n\"); } int main() { printf(\"Inside main()\\n\"); return 0; } ",
"e": 7061,
"s": 6742,
"text": null
},
{
"code": null,
"e": 7106,
"s": 7061,
"text": "Inside func1()\nInside main()\nInside func2()\n"
},
{
"code": null,
"e": 8730,
"s": 7106,
"text": "#pragma warn Directive: This directive is used to hide the warning messages which are displayed during compilation. This may be useful for us when we have a large program and we want to solve all the errors before looking on warnings then by using it we can focus on errors by hiding all warnings. we can again let the warnings be visible by making slight changes in syntax.Syntax:#pragma warn +xxx (To show the warning)\n#pragma warn -xxx (To hide the warning)\n#pragma warn .xxx (To toggle between hide and show)\nWe can hide the warnings as shown below:#pragma warn -rvl: This directive hides those warning which are raised when a function which is supposed to return a value does not return a value.#pragma warn -par: This directive hides those warning which are raised when a function does not uses the parameters passed to it.#pragma warn -rch: This directive hides those warning which are raised when a code is unreachable. For example: any code written after the return statement in a function is unreachable.Example:// Example to explain the working of // #pragma warn directive// This program is compatible with C/C++ compiler #include<stdio.h> #pragma warn -rvl /* return value */#pragma warn -par /* parameter never used */#pragma warn -rch /*unreachable code */ int show(int x){ // parameter x is never used in // the function printf(\"GEEKSFORGEEKS\"); // function does not have a // return statement} int main(){ show(10); return 0;}Output:GEEKSFORGEEKS\nThe above program compiles successfully without any warnings to give the output “GEEKSFORGEEKS”."
},
{
"code": null,
"e": 8738,
"s": 8730,
"text": "Syntax:"
},
{
"code": null,
"e": 8871,
"s": 8738,
"text": "#pragma warn +xxx (To show the warning)\n#pragma warn -xxx (To hide the warning)\n#pragma warn .xxx (To toggle between hide and show)\n"
},
{
"code": null,
"e": 8912,
"s": 8871,
"text": "We can hide the warnings as shown below:"
},
{
"code": null,
"e": 9060,
"s": 8912,
"text": "#pragma warn -rvl: This directive hides those warning which are raised when a function which is supposed to return a value does not return a value."
},
{
"code": null,
"e": 9190,
"s": 9060,
"text": "#pragma warn -par: This directive hides those warning which are raised when a function does not uses the parameters passed to it."
},
{
"code": null,
"e": 9376,
"s": 9190,
"text": "#pragma warn -rch: This directive hides those warning which are raised when a code is unreachable. For example: any code written after the return statement in a function is unreachable."
},
{
"code": null,
"e": 9385,
"s": 9376,
"text": "Example:"
},
{
"code": "// Example to explain the working of // #pragma warn directive// This program is compatible with C/C++ compiler #include<stdio.h> #pragma warn -rvl /* return value */#pragma warn -par /* parameter never used */#pragma warn -rch /*unreachable code */ int show(int x){ // parameter x is never used in // the function printf(\"GEEKSFORGEEKS\"); // function does not have a // return statement} int main(){ show(10); return 0;}",
"e": 9870,
"s": 9385,
"text": null
},
{
"code": null,
"e": 9885,
"s": 9870,
"text": "GEEKSFORGEEKS\n"
},
{
"code": null,
"e": 9982,
"s": 9885,
"text": "The above program compiles successfully without any warnings to give the output “GEEKSFORGEEKS”."
},
{
"code": null,
"e": 10704,
"s": 9982,
"text": "#pragma GCC poison: This directive is supported by the GCC compiler and is used to remove an identifier completely from the program. If we want to block an identifier then we can use the #pragma GCC poison directive.Example:// Program to illustrate the // #pragma GCC poison directive #include<stdio.h> #pragma GCC poison printf int main(){ int a=10; if(a==10) { printf(\"GEEKSFORGEEKS\"); } else printf(\"bye\"); return 0;}The above program will give the below error:prog.c: In function 'main':\nprog.c:14:9: error: attempt to use poisoned \"printf\"\n printf(\"GEEKSFORGEEKS\");\n ^\nprog.c:17:9: error: attempt to use poisoned \"printf\"\n printf(\"bye\");\n ^\n"
},
{
"code": null,
"e": 10713,
"s": 10704,
"text": "Example:"
},
{
"code": "// Program to illustrate the // #pragma GCC poison directive #include<stdio.h> #pragma GCC poison printf int main(){ int a=10; if(a==10) { printf(\"GEEKSFORGEEKS\"); } else printf(\"bye\"); return 0;}",
"e": 10953,
"s": 10713,
"text": null
},
{
"code": null,
"e": 10998,
"s": 10953,
"text": "The above program will give the below error:"
},
{
"code": null,
"e": 11213,
"s": 10998,
"text": "prog.c: In function 'main':\nprog.c:14:9: error: attempt to use poisoned \"printf\"\n printf(\"GEEKSFORGEEKS\");\n ^\nprog.c:17:9: error: attempt to use poisoned \"printf\"\n printf(\"bye\");\n ^\n"
},
{
"code": null,
"e": 11615,
"s": 11213,
"text": "#pragma GCC dependency: The #pragma GCC dependency allows you to check the relative dates of the current file and another file. If the other file is more recent than the current file, a warning is issued. This is useful if the current file is derived from the other file, and should be regenerated.Syntax:#pragma GCC dependency \"parse.y\"\n#pragma GCC dependency \"/usr/include/time.h\" rerun fixincludes\n"
},
{
"code": null,
"e": 11623,
"s": 11615,
"text": "Syntax:"
},
{
"code": null,
"e": 11720,
"s": 11623,
"text": "#pragma GCC dependency \"parse.y\"\n#pragma GCC dependency \"/usr/include/time.h\" rerun fixincludes\n"
},
{
"code": null,
"e": 11880,
"s": 11720,
"text": "#pragma GCC system_header: This pragma takes no arguments. It causes the rest of the code in the current file to be treated as if it came from a system header."
},
{
"code": null,
"e": 12283,
"s": 11880,
"text": "#pragma once: The #pragma once directive has a very simple concept. The header file containing this directive is included only once even if the programmer includes it multiple times during a compilation. This is not included in any ISO C++ standard. This directive works similar to the #include guard idiom. Use of #pragma once saves the program from multiple inclusion optimisation.Syntax:#pragma once"
},
{
"code": null,
"e": 12291,
"s": 12283,
"text": "Syntax:"
},
{
"code": null,
"e": 12304,
"s": 12291,
"text": "#pragma once"
},
{
"code": null,
"e": 12327,
"s": 12304,
"text": "C-Macro & Preprocessor"
},
{
"code": null,
"e": 12348,
"s": 12327,
"text": "Macro & Preprocessor"
},
{
"code": null,
"e": 12359,
"s": 12348,
"text": "C Language"
},
{
"code": null,
"e": 12363,
"s": 12359,
"text": "C++"
},
{
"code": null,
"e": 12367,
"s": 12363,
"text": "CPP"
}
] |
elinks - Unix, Linux Command
|
elinks [OPTION]... [URL]...
ELinks is a text mode WWW browser, supporting colors, table rendering, background downloading, menu driven configuration interface, tabbed browsing and slim code.
Frames are supported. You can have different file formats associated with external viewers. mailto: and telnet: are supported via external clients.
ELinks can handle both local files and remote URLs. The main supported remote URL protocols are HTTP, HTTPS (with SSL support compiled in) and FTP. Additional protocol support exists for BitTorrent finger, Gopher, SMB and NNTP.
The homepage of ELinks can be found at <http://elinks.cz/>, where the ELinks manual is also hosted.
Most options can be set in the user interface or config file, so usually you do not need to care about them. Note that this list is roughly equivalent to the output of running ELinks with the option --long-help.
-eval ’set protocol.file.allow_special_files = 1’
Generated using output from ELinks version 0.11.0.GIT.
Other files that ELinks uses from ~/.elinks/ includes the user defined CSS stylesheet. The name of the file can set in the document.css.stylesheet option.
ELinks is known to work on Linux, FreeBSD, OpenBSD, Solaris, IRIX, HPUX, Digital Unix, AIX, OS/2, BeOS and RISC OS. Port for Win32 is in state of beta testing.
Please report any other bugs you find to the either the ELinks mailing list at <elinks-users@linuxfromscratch.org> or if you prefer enter them into the bug tracking system <http://bugzilla.elinks.or.cz/>. More information about how to get in contact with developers and getting help can be found on the community page <http://elinks.or.cz/community.html>.
ELinks is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License <http://www.gnu.org/copyleft/gpl.html> as published by the Free Software Foundation; version 2 of the License.
The Links browser - on which ELinks is based - was written by Mikulas Patocka <mikulas@artax.karlin.mff.cuni.cz>. ELinks was written by Petr Baudis <pasky@ucw.cz>. See file AUTHORS in the source tree for a list of people contributing to this project.
This manual page was written by Peter Gervai <grin@tolna.net>, using excerpts from a (yet?) unknown Links fan for the Debian GNU/Linux system (but may be used by others). Contributions from Francis A. Holop. Extended, clarified and made more up-to-date by Petr Baudis <pasky@ucw.cz>. Updated by Zas <zas@norz.org>. The conversion to Asciidoc and trimming was done by Jonas Fonseca <fonseca@diku.dk>.
elinkskeys(5), elinks.conf(5), links(1), lynx(1), w3m(1), wget(1)
|
[
{
"code": null,
"e": 10743,
"s": 10713,
"text": "\nelinks [OPTION]... [URL]...\n"
},
{
"code": null,
"e": 10912,
"s": 10747,
"text": "\nELinks is a text mode WWW browser, supporting colors, table rendering, background downloading, menu driven configuration interface, tabbed browsing and slim code.\n"
},
{
"code": null,
"e": 11064,
"s": 10914,
"text": "\nFrames are supported. You can have different file formats associated with external viewers. mailto: and telnet: are supported via external clients.\n"
},
{
"code": null,
"e": 11296,
"s": 11066,
"text": "\nELinks can handle both local files and remote URLs. The main supported remote URL protocols are HTTP, HTTPS (with SSL support compiled in) and FTP. Additional protocol support exists for BitTorrent finger, Gopher, SMB and NNTP.\n"
},
{
"code": null,
"e": 11400,
"s": 11298,
"text": "\nThe homepage of ELinks can be found at <http://elinks.cz/>, where the ELinks manual is also hosted.\n"
},
{
"code": null,
"e": 11618,
"s": 11404,
"text": "\nMost options can be set in the user interface or config file, so usually you do not need to care about them. Note that this list is roughly equivalent to the output of running ELinks with the option --long-help.\n"
},
{
"code": null,
"e": 11697,
"s": 11646,
"text": "-eval ’set protocol.file.allow_special_files = 1’\n"
},
{
"code": null,
"e": 11790,
"s": 11733,
"text": "\nGenerated using output from ELinks version 0.11.0.GIT.\n"
},
{
"code": null,
"e": 11997,
"s": 11840,
"text": "\nOther files that ELinks uses from ~/.elinks/ includes the user defined CSS stylesheet. The name of the file can set in the document.css.stylesheet option.\n"
},
{
"code": null,
"e": 12163,
"s": 12001,
"text": "\nELinks is known to work on Linux, FreeBSD, OpenBSD, Solaris, IRIX, HPUX, Digital Unix, AIX, OS/2, BeOS and RISC OS. Port for Win32 is in state of beta testing.\n"
},
{
"code": null,
"e": 12525,
"s": 12167,
"text": "\nPlease report any other bugs you find to the either the ELinks mailing list at <elinks-users@linuxfromscratch.org> or if you prefer enter them into the bug tracking system <http://bugzilla.elinks.or.cz/>. More information about how to get in contact with developers and getting help can be found on the community page <http://elinks.or.cz/community.html>.\n"
},
{
"code": null,
"e": 12758,
"s": 12529,
"text": "\nELinks is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License <http://www.gnu.org/copyleft/gpl.html> as published by the Free Software Foundation; version 2 of the License.\n"
},
{
"code": null,
"e": 13015,
"s": 12762,
"text": "\nThe Links browser - on which ELinks is based - was written by Mikulas Patocka <mikulas@artax.karlin.mff.cuni.cz>. ELinks was written by Petr Baudis <pasky@ucw.cz>. See file AUTHORS in the source tree for a list of people contributing to this project.\n"
},
{
"code": null,
"e": 13419,
"s": 13017,
"text": "\nThis manual page was written by Peter Gervai <grin@tolna.net>, using excerpts from a (yet?) unknown Links fan for the Debian GNU/Linux system (but may be used by others). Contributions from Francis A. Holop. Extended, clarified and made more up-to-date by Petr Baudis <pasky@ucw.cz>. Updated by Zas <zas@norz.org>. The conversion to Asciidoc and trimming was done by Jonas Fonseca <fonseca@diku.dk>.\n"
}
] |
Difference between ++*p, *p++ and *++p
|
11 Oct, 2021
Predict the output of following C programs.
C
// PROGRAM 1#include <stdio.h>int main(void){ int arr[] = {10, 20}; int *p = arr; ++*p; printf("arr[0] = %d, arr[1] = %d, *p = %d", arr[0], arr[1], *p); return 0;}
C
// PROGRAM 2#include <stdio.h>int main(void){ int arr[] = {10, 20}; int *p = arr; *p++; printf("arr[0] = %d, arr[1] = %d, *p = %d", arr[0], arr[1], *p); return 0;}
C
// PROGRAM 3#include <stdio.h>int main(void){ int arr[] = {10, 20}; int *p = arr; *++p; printf("arr[0] = %d, arr[1] = %d, *p = %d", arr[0], arr[1], *p); return 0;}
The output of above programs and all such programs can be easily guessed by remembering following simple rules about postfix ++, prefix ++ and * (dereference) operators 1) Precedence of prefix ++ and * is same. Associativity of both is right to left. 2) Precedence of postfix ++ is higher than both * and prefix ++. Associativity of postfix ++ is left to right.(Refer: Precedence Table)The expression ++*p has two operators of same precedence, so compiler looks for associativity. Associativity of operators is right to left. Therefore the expression is treated as ++(*p). Therefore the output of first program is “arr[0] = 11, arr[1] = 20, *p = 11“.The expression *p++ is treated as *(p++) as the precedence of postfix ++ is higher than *. Therefore the output of second program is “arr[0] = 10, arr[1] = 20, *p = 20 “.The expression *++p has two operators of same precedence, so compiler looks for associativity. Associativity of operators is right to left. Therefore the expression is treated as *(++p). Therefore the output of third program is “arr[0] = 10, arr[1] = 20, *p = 20“.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
srinam
tarya461
brishabh786
C-Operators
cpp-operator
cpp-pointer
C Language
Difference Between
cpp-operator
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 99,
"s": 54,
"text": "Predict the output of following C programs. "
},
{
"code": null,
"e": 101,
"s": 99,
"text": "C"
},
{
"code": "// PROGRAM 1#include <stdio.h>int main(void){ int arr[] = {10, 20}; int *p = arr; ++*p; printf(\"arr[0] = %d, arr[1] = %d, *p = %d\", arr[0], arr[1], *p); return 0;}",
"e": 305,
"s": 101,
"text": null
},
{
"code": null,
"e": 307,
"s": 305,
"text": "C"
},
{
"code": "// PROGRAM 2#include <stdio.h>int main(void){ int arr[] = {10, 20}; int *p = arr; *p++; printf(\"arr[0] = %d, arr[1] = %d, *p = %d\", arr[0], arr[1], *p); return 0;}",
"e": 511,
"s": 307,
"text": null
},
{
"code": null,
"e": 513,
"s": 511,
"text": "C"
},
{
"code": "// PROGRAM 3#include <stdio.h>int main(void){ int arr[] = {10, 20}; int *p = arr; *++p; printf(\"arr[0] = %d, arr[1] = %d, *p = %d\", arr[0], arr[1], *p); return 0;}",
"e": 717,
"s": 513,
"text": null
},
{
"code": null,
"e": 1927,
"s": 717,
"text": "The output of above programs and all such programs can be easily guessed by remembering following simple rules about postfix ++, prefix ++ and * (dereference) operators 1) Precedence of prefix ++ and * is same. Associativity of both is right to left. 2) Precedence of postfix ++ is higher than both * and prefix ++. Associativity of postfix ++ is left to right.(Refer: Precedence Table)The expression ++*p has two operators of same precedence, so compiler looks for associativity. Associativity of operators is right to left. Therefore the expression is treated as ++(*p). Therefore the output of first program is “arr[0] = 11, arr[1] = 20, *p = 11“.The expression *p++ is treated as *(p++) as the precedence of postfix ++ is higher than *. Therefore the output of second program is “arr[0] = 10, arr[1] = 20, *p = 20 “.The expression *++p has two operators of same precedence, so compiler looks for associativity. Associativity of operators is right to left. Therefore the expression is treated as *(++p). Therefore the output of third program is “arr[0] = 10, arr[1] = 20, *p = 20“.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 1934,
"s": 1927,
"text": "srinam"
},
{
"code": null,
"e": 1943,
"s": 1934,
"text": "tarya461"
},
{
"code": null,
"e": 1955,
"s": 1943,
"text": "brishabh786"
},
{
"code": null,
"e": 1967,
"s": 1955,
"text": "C-Operators"
},
{
"code": null,
"e": 1980,
"s": 1967,
"text": "cpp-operator"
},
{
"code": null,
"e": 1992,
"s": 1980,
"text": "cpp-pointer"
},
{
"code": null,
"e": 2003,
"s": 1992,
"text": "C Language"
},
{
"code": null,
"e": 2022,
"s": 2003,
"text": "Difference Between"
},
{
"code": null,
"e": 2035,
"s": 2022,
"text": "cpp-operator"
},
{
"code": null,
"e": 2133,
"s": 2035,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2150,
"s": 2133,
"text": "Substring in C++"
},
{
"code": null,
"e": 2172,
"s": 2150,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 2207,
"s": 2172,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 2253,
"s": 2207,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 2298,
"s": 2253,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 2338,
"s": 2298,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 2369,
"s": 2338,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 2430,
"s": 2369,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2498,
"s": 2430,
"text": "Difference Between Method Overloading and Method Overriding in Java"
}
] |
How to Use Spell Checker in MS Word?
|
05 Aug, 2021
Everyday in business or in other fields there are lots of information or documentation files are there that are required to store for future use. For anyone, it is very difficult to store that information for a long time. Earlier letters, office files, documents, projects, and information are stored in a form of registrar, file, or by paperwork but finding it may be difficult for us. It takes a lot of time. To resolve this issue Microsoft brings software called MS Word.
Microsoft Word is a software tool that allows users to create documents like articles, letters, projects files very easily. It has various features like editing and formatting, graphics, designs, fonts styles, printing documents, etc.
Features of MS Word
Various Page Designs, page numbers, borderTables3D models, chart, and iconsWordArtPage Layout formatsInserting Online pictures and videoText color and many more.Date and TimePage DesignsDifferent text fonts
Various Page Designs, page numbers, border
Tables
3D models, chart, and icons
WordArt
Page Layout formats
Inserting Online pictures and video
Text color and many more.
Date and Time
Page Designs
Different text fonts
Microsoft Word has a special feature called spell check that allows you to check spelling and grammatical mistakes that you made in the document. Basically spell check is a software tool that identifies the misspelled words present in the document. It also allows you to search a particular word in the document that you know you’ve misspelled in the whole document.
In Microsoft Word documents, Word’s spell check function is set to automatically check your spelling while you type. Errors in your document will have color-coded underlines reflecting your choices, like red for spelling errors, green for grammar errors, and blue for contextual spelling errors.
Step 1: On the navigation menu bar click on the File option.
Step 2: Next click on the option button as shown in the figure:
Step 3: A word option dialog box will appear on the screen.
Step 4: Now select the Proofing option from the left menu as shown in the figure:
Step 5: Check all boxes as shown in the figure:
Step 6: Next click on the OK button.
Finally, Spell Check is enabled in MS Word.
Step 1: On the navigation menu bar click on the Review option.
Step 2: Next click on the spellings & grammar option as shown in the figure:
Note – If there is any spelling or grammatical mistake in your Word document, then the following dialog box appears with misspelled words present in the red underlined text.
Step 3: If there is a spelling mistake in the document then it will appear in the red underline text as shown in the figure:
Step 4: Select the correct spelling from the suggestion menu.
Step 5: Next click on the YES option.
Note: If all spellings are correct in your Word document, then the following pop-up window will appear on the screen.
Step 6: Click on the OK option.
Finally, all the spellings and grammars are manually checked.
Step 1: Right-click on the red-underlined word.
A menu with correctly spelled options will appear in which you can select the correct word or you can ignore it.
Step 2: Now choose the correct spelling from the menu as shown in the figure:
These are some of the ways to enable the spell check feature in MS Word.
class 6
School Learning
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 503,
"s": 28,
"text": "Everyday in business or in other fields there are lots of information or documentation files are there that are required to store for future use. For anyone, it is very difficult to store that information for a long time. Earlier letters, office files, documents, projects, and information are stored in a form of registrar, file, or by paperwork but finding it may be difficult for us. It takes a lot of time. To resolve this issue Microsoft brings software called MS Word."
},
{
"code": null,
"e": 738,
"s": 503,
"text": "Microsoft Word is a software tool that allows users to create documents like articles, letters, projects files very easily. It has various features like editing and formatting, graphics, designs, fonts styles, printing documents, etc."
},
{
"code": null,
"e": 758,
"s": 738,
"text": "Features of MS Word"
},
{
"code": null,
"e": 965,
"s": 758,
"text": "Various Page Designs, page numbers, borderTables3D models, chart, and iconsWordArtPage Layout formatsInserting Online pictures and videoText color and many more.Date and TimePage DesignsDifferent text fonts"
},
{
"code": null,
"e": 1008,
"s": 965,
"text": "Various Page Designs, page numbers, border"
},
{
"code": null,
"e": 1015,
"s": 1008,
"text": "Tables"
},
{
"code": null,
"e": 1043,
"s": 1015,
"text": "3D models, chart, and icons"
},
{
"code": null,
"e": 1051,
"s": 1043,
"text": "WordArt"
},
{
"code": null,
"e": 1071,
"s": 1051,
"text": "Page Layout formats"
},
{
"code": null,
"e": 1107,
"s": 1071,
"text": "Inserting Online pictures and video"
},
{
"code": null,
"e": 1133,
"s": 1107,
"text": "Text color and many more."
},
{
"code": null,
"e": 1147,
"s": 1133,
"text": "Date and Time"
},
{
"code": null,
"e": 1160,
"s": 1147,
"text": "Page Designs"
},
{
"code": null,
"e": 1181,
"s": 1160,
"text": "Different text fonts"
},
{
"code": null,
"e": 1549,
"s": 1181,
"text": "Microsoft Word has a special feature called spell check that allows you to check spelling and grammatical mistakes that you made in the document. Basically spell check is a software tool that identifies the misspelled words present in the document. It also allows you to search a particular word in the document that you know you’ve misspelled in the whole document. "
},
{
"code": null,
"e": 1845,
"s": 1549,
"text": "In Microsoft Word documents, Word’s spell check function is set to automatically check your spelling while you type. Errors in your document will have color-coded underlines reflecting your choices, like red for spelling errors, green for grammar errors, and blue for contextual spelling errors."
},
{
"code": null,
"e": 1906,
"s": 1845,
"text": "Step 1: On the navigation menu bar click on the File option."
},
{
"code": null,
"e": 1970,
"s": 1906,
"text": "Step 2: Next click on the option button as shown in the figure:"
},
{
"code": null,
"e": 2030,
"s": 1970,
"text": "Step 3: A word option dialog box will appear on the screen."
},
{
"code": null,
"e": 2112,
"s": 2030,
"text": "Step 4: Now select the Proofing option from the left menu as shown in the figure:"
},
{
"code": null,
"e": 2160,
"s": 2112,
"text": "Step 5: Check all boxes as shown in the figure:"
},
{
"code": null,
"e": 2197,
"s": 2160,
"text": "Step 6: Next click on the OK button."
},
{
"code": null,
"e": 2241,
"s": 2197,
"text": "Finally, Spell Check is enabled in MS Word."
},
{
"code": null,
"e": 2304,
"s": 2241,
"text": "Step 1: On the navigation menu bar click on the Review option."
},
{
"code": null,
"e": 2381,
"s": 2304,
"text": "Step 2: Next click on the spellings & grammar option as shown in the figure:"
},
{
"code": null,
"e": 2555,
"s": 2381,
"text": "Note – If there is any spelling or grammatical mistake in your Word document, then the following dialog box appears with misspelled words present in the red underlined text."
},
{
"code": null,
"e": 2680,
"s": 2555,
"text": "Step 3: If there is a spelling mistake in the document then it will appear in the red underline text as shown in the figure:"
},
{
"code": null,
"e": 2742,
"s": 2680,
"text": "Step 4: Select the correct spelling from the suggestion menu."
},
{
"code": null,
"e": 2780,
"s": 2742,
"text": "Step 5: Next click on the YES option."
},
{
"code": null,
"e": 2898,
"s": 2780,
"text": "Note: If all spellings are correct in your Word document, then the following pop-up window will appear on the screen."
},
{
"code": null,
"e": 2930,
"s": 2898,
"text": "Step 6: Click on the OK option."
},
{
"code": null,
"e": 2992,
"s": 2930,
"text": "Finally, all the spellings and grammars are manually checked."
},
{
"code": null,
"e": 3040,
"s": 2992,
"text": "Step 1: Right-click on the red-underlined word."
},
{
"code": null,
"e": 3153,
"s": 3040,
"text": "A menu with correctly spelled options will appear in which you can select the correct word or you can ignore it."
},
{
"code": null,
"e": 3231,
"s": 3153,
"text": "Step 2: Now choose the correct spelling from the menu as shown in the figure:"
},
{
"code": null,
"e": 3304,
"s": 3231,
"text": "These are some of the ways to enable the spell check feature in MS Word."
},
{
"code": null,
"e": 3312,
"s": 3304,
"text": "class 6"
},
{
"code": null,
"e": 3328,
"s": 3312,
"text": "School Learning"
},
{
"code": null,
"e": 3347,
"s": 3328,
"text": "School Programming"
}
] |
Perl | sleep() Function
|
07 May, 2019
sleep() function in Perl is an inbuilt function which is used to delay the execution of the current script for a specified number of seconds or forever if parameter is not specified. The sleep( ) function accepts seconds as a parameter and returns the same on success.
Syntax: sleep(seconds)
Returns: seconds passed to it as parameter, on success
Example 1:
#!/usr/bin/perl -w # Using localtime() function# to print the timeprint scalar localtime(); # calling the sleep functionsleep(5); print "\n"; print scalar localtime();
Thu Mar 28 06:02:21 2019
Thu Mar 28 06:02:26 2019
Example 2:
#!/usr/bin/perl -w # Using localtime() function# to print the timeprint scalar localtime(); # Using rand() to generate random delaysleep(rand(7)); print "\n"; print scalar localtime();
Thu Mar 28 06:02:26 2019
Thu Mar 28 06:02:27 2019
Perl-function
Perl-Inbuilt-Functions
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n07 May, 2019"
},
{
"code": null,
"e": 322,
"s": 53,
"text": "sleep() function in Perl is an inbuilt function which is used to delay the execution of the current script for a specified number of seconds or forever if parameter is not specified. The sleep( ) function accepts seconds as a parameter and returns the same on success."
},
{
"code": null,
"e": 345,
"s": 322,
"text": "Syntax: sleep(seconds)"
},
{
"code": null,
"e": 400,
"s": 345,
"text": "Returns: seconds passed to it as parameter, on success"
},
{
"code": null,
"e": 411,
"s": 400,
"text": "Example 1:"
},
{
"code": "#!/usr/bin/perl -w # Using localtime() function# to print the timeprint scalar localtime(); # calling the sleep functionsleep(5); print \"\\n\"; print scalar localtime();",
"e": 583,
"s": 411,
"text": null
},
{
"code": null,
"e": 634,
"s": 583,
"text": "Thu Mar 28 06:02:21 2019\nThu Mar 28 06:02:26 2019\n"
},
{
"code": null,
"e": 645,
"s": 634,
"text": "Example 2:"
},
{
"code": "#!/usr/bin/perl -w # Using localtime() function# to print the timeprint scalar localtime(); # Using rand() to generate random delaysleep(rand(7)); print \"\\n\"; print scalar localtime();",
"e": 834,
"s": 645,
"text": null
},
{
"code": null,
"e": 885,
"s": 834,
"text": "Thu Mar 28 06:02:26 2019\nThu Mar 28 06:02:27 2019\n"
},
{
"code": null,
"e": 899,
"s": 885,
"text": "Perl-function"
},
{
"code": null,
"e": 922,
"s": 899,
"text": "Perl-Inbuilt-Functions"
},
{
"code": null,
"e": 927,
"s": 922,
"text": "Perl"
},
{
"code": null,
"e": 932,
"s": 927,
"text": "Perl"
}
] |
Working with Geospatial Data in Python
|
23 Aug, 2021
Spatial data, also known as geospatial data, GIS data, or geodata, is a type of numeric data that defines the geographic location of a physical object, such as a building, a street, a town, a city, a country, or other physical objects, using a geographic coordinate system. You may determine not just the position of an object, but also its length, size, area, and shape using spatial data.
To work with geospatial data in python we need the GeoPandas & GeoPlot library
GeoPandas is an open-source project to make working with geospatial data in python easier. GeoPandas extends the data types used by pandas to allow spatial operations on geometric types. Geometric operations are performed shapely. Geopandas further depends on fiona for file access and matplotlib for plotting. GeoPandas depends on its spatial functionality on a large geospatial, open-source stack of libraries (GEOS, GDAL, and PROJ). See the Dependencies section below for more details.
Required dependencies:
numpy
pandas (version 0.24 or later)
shapely (interface to GEOS)
fiona (interface to GDAL)
pyproj (interface to PROJ; version 2.2.0 or later)
Further, optional dependencies are:
rtree (optional; spatial index to improve performance and required for overlay operations; interface to libspatialindex)
psycopg2 (optional; for PostGIS connection)
GeoAlchemy2 (optional; for writing to PostGIS)
geopy (optional; For plotting, these additional for geocoding)
packages may be used:
matplotlib (>= 2.2.0)
mapclassify (>= 2.2.0)
Geoplot is a geospatial data visualization library for data scientists and geospatial analysts that want to get things done quickly. Below we’ll cover the basics of Geoplot and explore how it’s applied. Geoplot is for Python 3.6+ versions only.
Note: Please install all the dependencies and modules for the proper functioning of the given codes.
Installing can be done through Anaconda:
Syntax:
conda install geopandas
conda install geoplot
conda-forge is a community effort that provides conda packages for a wide range of software. It provides the conda-forge package channel for conda from which packages can be installed, in addition to the “defaults” channel provided by Anaconda. GeoPandas and all its dependencies are available on the conda-forge channel and can be installed as:
Syntax:
conda install --channel conda-forge geopandas
conda install geoplot -c conda-forge
GeoPandas can also be installed with pip if all dependencies can be installed as well:
Syntax:
pip install geopandas
pip install geoplot
You may install the latest development version by cloning the GitHub repository and using pip to install from the local directory:
Syntax:
git clone https://github.com/geopandas/geopandas.git
cd geopandas
pip install
It is also possible to install the latest development version directly from the GitHub repository with:
Syntax:
pip install git+git://github.com/geopandas/geopandas.git
After installing packages along with their dependencies open a python editor like spyder. Before beginning with code we need to download some shapefiles (.shp extension). You can download country-level data as well as global-level data from here under “Free spatial data”. To get shapefile used in tutorial click here.
First, we will import the geopandas library and then read our shapefile using the variable “world_data”. Geopandas can read almost any vector-based spatial data format including ESRI shapefile, GeoJSON files and more using the command:
Syntax: geopandas.read_file()
Parameters
filename: str, path object, or file-like object. Either the absolute or relative path to the file or URL to be opened or any object with a read() method (such as an open file or StringIO)
bbox: tuple | GeoDataFrame or GeoSeries | shapely Geometry, default None. Filter features by given bounding box, GeoSeries, GeoDataFrame or a shapely geometry. CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame. Cannot be used with mask.
mask: dict | GeoDataFrame or GeoSeries | shapely Geometry, default None. Filter for features that intersect with the given dict-like geojson geometry, GeoSeries, GeoDataFrame or shapely geometry. CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame. Cannot be used with bbox.
rows: int or slice, default None. Load in specific rows by passing an integer (first n rows) or a slice() object.
**kwargs : Keyword args to be passed to the open or BytesCollection method in the fiona library when opening the file. For more information on possible keywords, type: import fiona; help(fiona.open)
Example:
Python3
import geopandas as gpd # Reading the world shapefileworld_data = gpd.read_file(r'world.shp') world_data
Output:
If you want to check which type of data you are using then go to the console and type “type(world_data)” which tells you that it’s not pandas data, it’s a geopandas geodata. Next, we are going to plot those GeoDataFrames using plot() method.
Syntax: GeoDataFrame.plot()
Example:
Python3
import geopandas as gpd # Reading the world shapefileworld_data = gpd.read_file(r'world.shp') world_data.plot()
Output:
If we see the “world_data” GeoDataFrame there are many columns(Geoseries) shown, you can choose specific Geoseries by:
Syntax:
data[[‘attribute 1’, ‘attribute 2’]]
Example:
Python3
import geopandas as gpd # Reading the world shapefileworld_data = gpd.read_file(r'world.shp') world_data = world_data[['NAME', 'geometry']]
Output:
We can calculate the area of each country using geopandas by creating a new column “area” and using the area property.
Syntax:
GeoSeries.area
Returns a Series containing the area of each geometry in the GeoSeries expressed in the units of the CRS.
Example:
Python3
import geopandas as gpd # Reading the world shapefileworld_data = gpd.read_file(r'world.shp') world_data = world_data[['NAME', 'geometry']] # Calculating the area of each countryworld_data['area'] = world_data.area
Output:
We can remove a specific element from the Geoseries. Here we are removing the continent named “Antarctica” from the “Name” Geoseries.
Syntax:
data[data[‘attribute’] != ‘element’]
Example:
Python3
import geopandas as gpd # Reading the world shapefileworld_data = gpd.read_file(r'world.shp') world_data = world_data[['NAME', 'geometry']] # Calculating the area of each countryworld_data['area'] = world_data.area # Removing Antarctica from GeoPandas GeoDataframeworld_data = world_data[world_data['NAME'] != 'Antarctica']world_data.plot()
Output:
We can visualize/plot a specific country by selecting it. In the below example, we are selecting “India” from the “NAME” column.
Syntax:
data[data.attribute==”element”].plot()
Example:
Python3
import geopandas as gpdimport matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable # Reading the world shapefile world_data = gpd.read_file(r'world.shp')world_data = world_data[['NAME', 'geometry']] # Calculating the area of each country world_data['area'] = world_data.area # Removing Antarctica from GeoPandas GeoDataframeworld_data = world_data[world_data['NAME'] != 'Antarctica']world_data[world_data.NAME=="India"].plot()
Output:
We can check our current Coordinate System using Geopandas CRS i.e Coordinates Reference System. Also, we can change it to a projection coordination system. The Coordinate Reference System (CRS) is represented as a pyproj.CRS object. We can check current CRS using the following syntax.
Syntax:
GeoDataFrame.crs
to_crs() method transform geometries to a new coordinate reference system. Transform all geometries in an active geometry column to a different coordinate reference system. The CRS attribute on the current GeoSeries must be set. Either CRS or epsg may be specified for output. This method will transform all points in all objects. It has no notion or projecting entire geometries. All segment joining points are assumed to be lined in the current projection, not geodesics. Objects crossing the dateline (or another projection boundary) will have undesirable behavior.
Syntax: GeoDataFrame.to_crs(crs=None, epsg=None, inplace=False)
Parameters
crs: pyproj.CRS, optional if epsg is specified. The value can be anything accepted by pyproj.CRS.from_user_input(), such as an authority string (eg “EPSG:4326”) or a WKT string.
epsg: int, optional if crs is specified. EPSG code specifying output projection.
inplace: bool, optional, default: False. Whether to return a new GeoDataFrame or do the transformation in place.
Example:
Python3
import geopandas as gpd # Reading the world shapefileworld_data = gpd.read_file(r'world.shp') world_data = world_data[['NAME', 'geometry']] # Calculating the area of each countryworld_data['area'] = world_data.area # Removing Antarctica from GeoPandas GeoDataframeworld_data = world_data[world_data['NAME'] != 'Antarctica'] # Changing the projectioncurrent_crs = world_data.crsworld_data.to_crs(epsg=3857, inplace=True) world.plot()
Output:
We can color each country in the world using a head column and cmap. To find out head column type “world_data.head()” in console. We can choose different color maps(cmap) available in matplotlib. In the following code, we have colored countries using plot() arguments column and cmap.
Example:
Python3
import geopandas as gpd # Reading the world shapefileworld_data = gpd.read_file(r'world.shp') world_data = world_data[['NAME', 'geometry']] # Calculating the area of each countryworld_data['area'] = world_data.area # Removing Antarctica from GeoPandas GeoDataframeworld_data = world_data[world_data['NAME'] != 'Antarctica'] # Changing the projectioncurrent_crs = world_data.crsworld_data.to_crs(epsg=3857, inplace=True) world_data.plot(column='NAME', cmap='hsv')
Output:
Next, we are going to convert the area in sq. km by dividing it to 10^6 i.e (1000000). Output can be seen in variable explorer in the “world_data” variable.
We can add a legend to our world map along with a label using plot() arguments
legend: bool (default False). Plot a legend. Ignored if no column is given, or if color is given.
legend_kwds: dict (default None). Keyword arguments to pass to matplotlib.pyplot.legend() or matplotlib.pyplot.colorbar(). Additional accepted keywords when scheme is specified:fmt: string. A formatting specification for the bin edges of the classes in the legend. For example, to have no decimals: {“fmt”: “{:.0f}”}.labels: list-like. A list of legend labels to override the auto-generated labels. Needs to have the same number of elements as the number of classes (k).interval: boolean (default False). An option to control brackets from mapclassify legend. If True, open/closed interval brackets are shown in the legend.
fmt: string. A formatting specification for the bin edges of the classes in the legend. For example, to have no decimals: {“fmt”: “{:.0f}”}.
labels: list-like. A list of legend labels to override the auto-generated labels. Needs to have the same number of elements as the number of classes (k).
interval: boolean (default False). An option to control brackets from mapclassify legend. If True, open/closed interval brackets are shown in the legend.
Example:
Python3
import geopandas as gpd # Reading the world shapefileworld_data = gpd.read_file(r'world.shp') world_data = world_data[['NAME', 'geometry']] # Calculating the area of each countryworld_data['area'] = world_data.area # Removing Antarctica from GeoPandas GeoDataframeworld_data = world_data[world_data['NAME'] != 'Antarctica']world_data.plot() # Changing the projectioncurrent_crs = world_data.crsworld_data.to_crs(epsg=3857, inplace=True)world_data.plot(column='NAME', cmap='hsv') # Re-calculate the areas in Sq. Km.world_data['area'] = world_data.area/1000000 # Adding a legendworld_data.plot(column='area', cmap='hsv', legend=True, legend_kwds={'label': "Area of the country (Sq. Km.)"}, figsize=(7, 7))
Output:
We can also resize the legend using ax and cax arguments of plot().
ax: matplotlib.pyplot. Artist (default None). axes on which to draw the plot.
cax: matplotlib.pyplot Artist (default None). axes on which to draw the legend in case of color map.
For this, we need matplotlib library.
The axes_divider.make_axes_locatable function takes an existing axes, adds it to a new AxesDivider, and returns the AxesDivider. The append_axes method of the AxesDivider can then be used to create new axes on a given side (“top”, “right”, “bottom”, or “left”) of the original axes. To create axes at the given position with the same height (or width) of the main axes-
Syntax:
append_axes(self, position, size, pad=None, add_to_figure=True, **kwargs)
position can take any value from: “left”, “right”, “bottom” or “top”.
size and pad should be axes_grid.axes_size compatible.
Example:
Python3
import geopandas as gpdimport matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatable # Reading the world shapefileworld_data = gpd.read_file(r'world.shp') world_data = world_data[['NAME', 'geometry']] # Calculating the area of each countryworld_data['area'] = world_data.area # Removing Antarctica from GeoPandas GeoDataframeworld_data = world_data[world_data['NAME'] != 'Antarctica']world_data.plot() # Changing the projectioncurrent_crs = world_data.crsworld_data.to_crs(epsg=3857, inplace=True)world_data.plot(column='NAME', cmap='hsv') # Re-calculate the areas in Sq. Km.world_data['area'] = world_data.area/1000000 # Adding a legendworld_data.plot(column='area', cmap='hsv', legend=True, legend_kwds={'label': "Area of the country (Sq. Km.)"}, figsize=(7, 7)) # Resizing the legendfig, ax = plt.subplots(figsize=(10, 10))divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="7%", pad=0.1)world_data.plot(column='area', cmap='hsv', legend=True, legend_kwds={'label': "Area of the country (Sq. Km.)"}, ax=ax, cax=cax)
Output:
First, we will import Geoplot library. Next, we will load one of the sample datasets(geojson file) present in geoplot. In the below example, we are going to use “world” ,”contiguous_usa”,”usa_cities”,”melbourne” and “melbourne_schools” datasets. List of datasets present in geoplot are mentioned below:
usa_cities
contiguous_usa
nyc_collision_factors
nyc_boroughs
ny_census
obesity_by_state
la_flights
dc_roads
nyc_map_pluto_sample
nyc_collisions_sample
boston_zip_codes
boston_airbnb_listings
napoleon_troop_movements
nyc_fatal_collisions
nyc_injurious_collisions
nyc_police_precincts
nyc_parking_tickets
world
melbourne
melbourne_schools
san_francisco
san_francisco_street_trees_sample
california_congressional_districts
We can add our own datasets by editing the datasets.py file. Click here for some free sample datasets.
If you have polygonal data, you can plot that using a geoplot polyplot.
If your data consists of a bunch of points instead, you can display those points using pointplot.
Syntax :
geoplot.datasets.get_path(str)
Syntax for plotting:
geoplot.polyplot(var)
geoplot.pointplot(var)
Example:
Python3
import geoplot as gpltimport geopandas as gpd # Reading the world shapefilepath = gplt.datasets.get_path("world")world = gpd.read_file(path)gplt.polyplot(world) path = gplt.datasets.get_path("contiguous_usa")contiguous_usa = gpd.read_file(path)gplt.polyplot(contiguous_usa) path = gplt.datasets.get_path("usa_cities")usa_cities = gpd.read_file(path)gplt.pointplot(usa_cities) path = gplt.datasets.get_path("melbourne")melbourne = gpd.read_file(path)gplt.polyplot(melbourne) path = gplt.datasets.get_path("melbourne_schools")melbourne_schools = gpd.read_file(path)gplt.pointplot(melbourne_schools)
World Dataset:
USA Dataset:
USA Cities Dataset:
Melbourne Dataset:
Melbourne Schools Dataset:
We can combine these two plots using overplotting. Overplotting is the act of stacking several different plots on top of one another, useful for providing additional context for our plots:
Example:
Python3
import geoplot as gpltimport geopandas as gpd # Reading the world shapefile path = gplt.datasets.get_path("usa_cities")usa_cities = gpd.read_file(path) path = gplt.datasets.get_path("contiguous_usa")contiguous_usa = gpd.read_file(path) path = gplt.datasets.get_path("melbourne")melbourne = gpd.read_file(path) path = gplt.datasets.get_path("melbourne_schools")melbourne_schools = gpd.read_file(path) ax = gplt.polyplot(contiguous_usa)gplt.pointplot(usa_cities, ax=ax) ax = gplt.polyplot(melbourne)gplt.pointplot(melbourne_schools, ax=ax)
Output:
You may have noticed that this map of the United States appears to be odd. Because the Earth is a sphere, it is difficult to depict it in two dimensions. As a result, we use some type of projection, or means of flattening the sphere, whenever we take data off the sphere and place it on a map. When you plot data without a projection, or “carte blanche,” your map will be distorted. We can “correct” the distortions by picking up a projection method. Here we are going to use Albers equal-area and WebMercator projection.
Along with this, we are also going to add some other parameters such as hue, legend, cmap, and scheme.
The hue parameter applies a colormap to a data column.
The legend parameter toggles a legend.
Change the colormap using matplotlib’s cmap.
For a categorical colormap, use a scheme.
Example:
Python3
import geoplot as gpltimport geopandas as gpdimport geoplot.crs as gcrs # Reading the world shapefile path = gplt.datasets.get_path("contiguous_usa")contiguous_usa = gpd.read_file(path) path = gplt.datasets.get_path("usa_cities")usa_cities = gpd.read_file(path) ax = gplt.polyplot(contiguous_usa, projection=gcrs.AlbersEqualArea())gplt.pointplot(usa_cities, ax=ax, hue="ELEV_IN_FT",cmap='rainbow', legend=True) ax = gplt.webmap(contiguous_usa, projection=gcrs.WebMercator())gplt.pointplot(usa_cities, ax=ax, hue='ELEV_IN_FT', cmap='terrain', legend=True)
Output:
A choropleth takes data that has been aggregated on some meaningful polygonal level (e.g. census tract, state, country, or continent) and uses color to display it to the reader. It’s a well-known plot type, and it’s perhaps the most general-purpose and well-known of the spatial plot types. A basic choropleth requires polygonal geometries and a hue variable. Change the colormap using matplotlib’s cmap. The legend parameter toggles the legend.
Syntax:
geoplot.choropleth(var)
Example:
Python3
import geoplot as gpltimport geopandas as gpdimport geoplot.crs as gcrs # Reading the world shapefile boroughs = gpd.read_file(gplt.datasets.get_path('nyc_boroughs')) gplt.choropleth(boroughs, hue='Shape_Area', projection=gcrs.AlbersEqualArea(), cmap='RdPu', legend=True)
Output:
To pass the keyword argument to the legend, use the legend_kwargs argument. To specify a categorical colormap, use a scheme. Use legend_labels and legend_values to customize the labels and values that appear in the legend. Here we are going to use mapclassify which is an open-source python library for Choropleth map classification. To install mapclassify use:
mapclassify is available in on conda via the conda-forge channel:
Syntax:
conda install -c conda-forge mapclassify
mapclassify is also available on the Python Package Index:
Syntax:
pip install -U mapclassify
Example:
Python3
import geoplot as gpltimport geopandas as gpdimport geoplot.crs as gcrsimport mapclassify as mc # Reading the world shapefile contiguous_usa = gpd.read_file(gplt.datasets.get_path('contiguous_usa')) scheme = mc.FisherJenks(contiguous_usa['population'], k=5) gplt.choropleth( contiguous_usa, hue='population', projection=gcrs.AlbersEqualArea(), edgecolor='white', linewidth=1, cmap='Reds', legend=True, legend_kwargs={'loc': 'lower left'}, scheme=scheme, legend_labels=[ '<3 million', '3-6.7 million', '6.7-12.8 million', '12.8-25 million', '25-37 million' ])
Output:
Kernel density estimation is a technique that non-parametrically estimates a distribution function for a set of point observations without using parameters. KDEs are a popular method for examining data distributions; in this figure, the technique is applied to a geospatial situation. A basic KDEplot takes pointwise data as input.
Syntax:
geoplot.kdeplot(var)
Example:
Python3
import geoplot as gpltimport geopandas as gpdimport geoplot.crs as gcrs # Reading the world shapefile boroughs = gpd.read_file(gplt.datasets.get_path('nyc_boroughs')) collisions = gpd.read_file(gplt.datasets.get_path('nyc_collision_factors')) ax = gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea()) gplt.kdeplot(collisions, ax=ax)
Output:
A Sankey diagram depicts the flow of information through a network. It’s useful for displaying the magnitudes of data flowing through a system. This figure places the Sankey diagram in a geospatial context, making it helpful for monitoring traffic loads on a road network or travel volumes between airports, for example. A basic Sankey requires a GeoDataFrame of LineString or MultiPoint geometries. hue adds color gradation to the map. Use matplotlib’s cmap to control the colormap. For a categorical colormap, specify the scheme. legend toggles a legend. Here we are using Mollweide projection
Syntax;
geoplot.sankey(var)
Example:
Python3
import geoplot as gpltimport geopandas as gpdimport geoplot.crs as gcrsimport mapclassify as mc # Reading the world shapefile la_flights = gpd.read_file(gplt.datasets.get_path('la_flights'))world = gpd.read_file(gplt.datasets.get_path('world'))scheme = mc.Quantiles(la_flights['Passengers'], k=5) ax = gplt.sankey(la_flights, projection=gcrs.Mollweide(), scale='Passengers', hue='Passengers', scheme=scheme, cmap='Oranges', legend=True) gplt.polyplot(world, ax=ax, facecolor='lightgray', edgecolor='white')ax.set_global(); ax.outline_patch.set_visible(True)
Output:
Data Visualization
Picked
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 445,
"s": 54,
"text": "Spatial data, also known as geospatial data, GIS data, or geodata, is a type of numeric data that defines the geographic location of a physical object, such as a building, a street, a town, a city, a country, or other physical objects, using a geographic coordinate system. You may determine not just the position of an object, but also its length, size, area, and shape using spatial data."
},
{
"code": null,
"e": 524,
"s": 445,
"text": "To work with geospatial data in python we need the GeoPandas & GeoPlot library"
},
{
"code": null,
"e": 1014,
"s": 524,
"text": "GeoPandas is an open-source project to make working with geospatial data in python easier. GeoPandas extends the data types used by pandas to allow spatial operations on geometric types. Geometric operations are performed shapely. Geopandas further depends on fiona for file access and matplotlib for plotting. GeoPandas depends on its spatial functionality on a large geospatial, open-source stack of libraries (GEOS, GDAL, and PROJ). See the Dependencies section below for more details. "
},
{
"code": null,
"e": 1037,
"s": 1014,
"text": "Required dependencies:"
},
{
"code": null,
"e": 1043,
"s": 1037,
"text": "numpy"
},
{
"code": null,
"e": 1074,
"s": 1043,
"text": "pandas (version 0.24 or later)"
},
{
"code": null,
"e": 1102,
"s": 1074,
"text": "shapely (interface to GEOS)"
},
{
"code": null,
"e": 1128,
"s": 1102,
"text": "fiona (interface to GDAL)"
},
{
"code": null,
"e": 1179,
"s": 1128,
"text": "pyproj (interface to PROJ; version 2.2.0 or later)"
},
{
"code": null,
"e": 1215,
"s": 1179,
"text": "Further, optional dependencies are:"
},
{
"code": null,
"e": 1336,
"s": 1215,
"text": "rtree (optional; spatial index to improve performance and required for overlay operations; interface to libspatialindex)"
},
{
"code": null,
"e": 1380,
"s": 1336,
"text": "psycopg2 (optional; for PostGIS connection)"
},
{
"code": null,
"e": 1427,
"s": 1380,
"text": "GeoAlchemy2 (optional; for writing to PostGIS)"
},
{
"code": null,
"e": 1490,
"s": 1427,
"text": "geopy (optional; For plotting, these additional for geocoding)"
},
{
"code": null,
"e": 1512,
"s": 1490,
"text": "packages may be used:"
},
{
"code": null,
"e": 1534,
"s": 1512,
"text": "matplotlib (>= 2.2.0)"
},
{
"code": null,
"e": 1557,
"s": 1534,
"text": "mapclassify (>= 2.2.0)"
},
{
"code": null,
"e": 1802,
"s": 1557,
"text": "Geoplot is a geospatial data visualization library for data scientists and geospatial analysts that want to get things done quickly. Below we’ll cover the basics of Geoplot and explore how it’s applied. Geoplot is for Python 3.6+ versions only."
},
{
"code": null,
"e": 1903,
"s": 1802,
"text": "Note: Please install all the dependencies and modules for the proper functioning of the given codes."
},
{
"code": null,
"e": 1944,
"s": 1903,
"text": "Installing can be done through Anaconda:"
},
{
"code": null,
"e": 1952,
"s": 1944,
"text": "Syntax:"
},
{
"code": null,
"e": 1998,
"s": 1952,
"text": "conda install geopandas\nconda install geoplot"
},
{
"code": null,
"e": 2344,
"s": 1998,
"text": "conda-forge is a community effort that provides conda packages for a wide range of software. It provides the conda-forge package channel for conda from which packages can be installed, in addition to the “defaults” channel provided by Anaconda. GeoPandas and all its dependencies are available on the conda-forge channel and can be installed as:"
},
{
"code": null,
"e": 2352,
"s": 2344,
"text": "Syntax:"
},
{
"code": null,
"e": 2435,
"s": 2352,
"text": "conda install --channel conda-forge geopandas\nconda install geoplot -c conda-forge"
},
{
"code": null,
"e": 2522,
"s": 2435,
"text": "GeoPandas can also be installed with pip if all dependencies can be installed as well:"
},
{
"code": null,
"e": 2530,
"s": 2522,
"text": "Syntax:"
},
{
"code": null,
"e": 2572,
"s": 2530,
"text": "pip install geopandas\npip install geoplot"
},
{
"code": null,
"e": 2703,
"s": 2572,
"text": "You may install the latest development version by cloning the GitHub repository and using pip to install from the local directory:"
},
{
"code": null,
"e": 2711,
"s": 2703,
"text": "Syntax:"
},
{
"code": null,
"e": 2789,
"s": 2711,
"text": "git clone https://github.com/geopandas/geopandas.git\ncd geopandas\npip install"
},
{
"code": null,
"e": 2893,
"s": 2789,
"text": "It is also possible to install the latest development version directly from the GitHub repository with:"
},
{
"code": null,
"e": 2901,
"s": 2893,
"text": "Syntax:"
},
{
"code": null,
"e": 2958,
"s": 2901,
"text": "pip install git+git://github.com/geopandas/geopandas.git"
},
{
"code": null,
"e": 3278,
"s": 2958,
"text": "After installing packages along with their dependencies open a python editor like spyder. Before beginning with code we need to download some shapefiles (.shp extension). You can download country-level data as well as global-level data from here under “Free spatial data”. To get shapefile used in tutorial click here. "
},
{
"code": null,
"e": 3514,
"s": 3278,
"text": "First, we will import the geopandas library and then read our shapefile using the variable “world_data”. Geopandas can read almost any vector-based spatial data format including ESRI shapefile, GeoJSON files and more using the command:"
},
{
"code": null,
"e": 3544,
"s": 3514,
"text": "Syntax: geopandas.read_file()"
},
{
"code": null,
"e": 3555,
"s": 3544,
"text": "Parameters"
},
{
"code": null,
"e": 3743,
"s": 3555,
"text": "filename: str, path object, or file-like object. Either the absolute or relative path to the file or URL to be opened or any object with a read() method (such as an open file or StringIO)"
},
{
"code": null,
"e": 3996,
"s": 3743,
"text": "bbox: tuple | GeoDataFrame or GeoSeries | shapely Geometry, default None. Filter features by given bounding box, GeoSeries, GeoDataFrame or a shapely geometry. CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame. Cannot be used with mask."
},
{
"code": null,
"e": 4285,
"s": 3996,
"text": "mask: dict | GeoDataFrame or GeoSeries | shapely Geometry, default None. Filter for features that intersect with the given dict-like geojson geometry, GeoSeries, GeoDataFrame or shapely geometry. CRS mis-matches are resolved if given a GeoSeries or GeoDataFrame. Cannot be used with bbox."
},
{
"code": null,
"e": 4399,
"s": 4285,
"text": "rows: int or slice, default None. Load in specific rows by passing an integer (first n rows) or a slice() object."
},
{
"code": null,
"e": 4598,
"s": 4399,
"text": "**kwargs : Keyword args to be passed to the open or BytesCollection method in the fiona library when opening the file. For more information on possible keywords, type: import fiona; help(fiona.open)"
},
{
"code": null,
"e": 4607,
"s": 4598,
"text": "Example:"
},
{
"code": null,
"e": 4615,
"s": 4607,
"text": "Python3"
},
{
"code": "import geopandas as gpd # Reading the world shapefileworld_data = gpd.read_file(r'world.shp') world_data",
"e": 4722,
"s": 4615,
"text": null
},
{
"code": null,
"e": 4730,
"s": 4722,
"text": "Output:"
},
{
"code": null,
"e": 4973,
"s": 4730,
"text": "If you want to check which type of data you are using then go to the console and type “type(world_data)” which tells you that it’s not pandas data, it’s a geopandas geodata. Next, we are going to plot those GeoDataFrames using plot() method. "
},
{
"code": null,
"e": 5001,
"s": 4973,
"text": "Syntax: GeoDataFrame.plot()"
},
{
"code": null,
"e": 5010,
"s": 5001,
"text": "Example:"
},
{
"code": null,
"e": 5018,
"s": 5010,
"text": "Python3"
},
{
"code": "import geopandas as gpd # Reading the world shapefileworld_data = gpd.read_file(r'world.shp') world_data.plot()",
"e": 5132,
"s": 5018,
"text": null
},
{
"code": null,
"e": 5140,
"s": 5132,
"text": "Output:"
},
{
"code": null,
"e": 5259,
"s": 5140,
"text": "If we see the “world_data” GeoDataFrame there are many columns(Geoseries) shown, you can choose specific Geoseries by:"
},
{
"code": null,
"e": 5267,
"s": 5259,
"text": "Syntax:"
},
{
"code": null,
"e": 5304,
"s": 5267,
"text": "data[[‘attribute 1’, ‘attribute 2’]]"
},
{
"code": null,
"e": 5313,
"s": 5304,
"text": "Example:"
},
{
"code": null,
"e": 5321,
"s": 5313,
"text": "Python3"
},
{
"code": "import geopandas as gpd # Reading the world shapefileworld_data = gpd.read_file(r'world.shp') world_data = world_data[['NAME', 'geometry']]",
"e": 5463,
"s": 5321,
"text": null
},
{
"code": null,
"e": 5471,
"s": 5463,
"text": "Output:"
},
{
"code": null,
"e": 5590,
"s": 5471,
"text": "We can calculate the area of each country using geopandas by creating a new column “area” and using the area property."
},
{
"code": null,
"e": 5598,
"s": 5590,
"text": "Syntax:"
},
{
"code": null,
"e": 5613,
"s": 5598,
"text": "GeoSeries.area"
},
{
"code": null,
"e": 5719,
"s": 5613,
"text": "Returns a Series containing the area of each geometry in the GeoSeries expressed in the units of the CRS."
},
{
"code": null,
"e": 5728,
"s": 5719,
"text": "Example:"
},
{
"code": null,
"e": 5736,
"s": 5728,
"text": "Python3"
},
{
"code": "import geopandas as gpd # Reading the world shapefileworld_data = gpd.read_file(r'world.shp') world_data = world_data[['NAME', 'geometry']] # Calculating the area of each countryworld_data['area'] = world_data.area",
"e": 5954,
"s": 5736,
"text": null
},
{
"code": null,
"e": 5962,
"s": 5954,
"text": "Output:"
},
{
"code": null,
"e": 6096,
"s": 5962,
"text": "We can remove a specific element from the Geoseries. Here we are removing the continent named “Antarctica” from the “Name” Geoseries."
},
{
"code": null,
"e": 6104,
"s": 6096,
"text": "Syntax:"
},
{
"code": null,
"e": 6141,
"s": 6104,
"text": "data[data[‘attribute’] != ‘element’]"
},
{
"code": null,
"e": 6150,
"s": 6141,
"text": "Example:"
},
{
"code": null,
"e": 6158,
"s": 6150,
"text": "Python3"
},
{
"code": "import geopandas as gpd # Reading the world shapefileworld_data = gpd.read_file(r'world.shp') world_data = world_data[['NAME', 'geometry']] # Calculating the area of each countryworld_data['area'] = world_data.area # Removing Antarctica from GeoPandas GeoDataframeworld_data = world_data[world_data['NAME'] != 'Antarctica']world_data.plot()",
"e": 6503,
"s": 6158,
"text": null
},
{
"code": null,
"e": 6511,
"s": 6503,
"text": "Output:"
},
{
"code": null,
"e": 6640,
"s": 6511,
"text": "We can visualize/plot a specific country by selecting it. In the below example, we are selecting “India” from the “NAME” column."
},
{
"code": null,
"e": 6648,
"s": 6640,
"text": "Syntax:"
},
{
"code": null,
"e": 6687,
"s": 6648,
"text": "data[data.attribute==”element”].plot()"
},
{
"code": null,
"e": 6696,
"s": 6687,
"text": "Example:"
},
{
"code": null,
"e": 6704,
"s": 6696,
"text": "Python3"
},
{
"code": "import geopandas as gpdimport matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable # Reading the world shapefile world_data = gpd.read_file(r'world.shp')world_data = world_data[['NAME', 'geometry']] # Calculating the area of each country world_data['area'] = world_data.area # Removing Antarctica from GeoPandas GeoDataframeworld_data = world_data[world_data['NAME'] != 'Antarctica']world_data[world_data.NAME==\"India\"].plot()",
"e": 7163,
"s": 6704,
"text": null
},
{
"code": null,
"e": 7171,
"s": 7163,
"text": "Output:"
},
{
"code": null,
"e": 7458,
"s": 7171,
"text": "We can check our current Coordinate System using Geopandas CRS i.e Coordinates Reference System. Also, we can change it to a projection coordination system. The Coordinate Reference System (CRS) is represented as a pyproj.CRS object. We can check current CRS using the following syntax."
},
{
"code": null,
"e": 7466,
"s": 7458,
"text": "Syntax:"
},
{
"code": null,
"e": 7483,
"s": 7466,
"text": "GeoDataFrame.crs"
},
{
"code": null,
"e": 8052,
"s": 7483,
"text": "to_crs() method transform geometries to a new coordinate reference system. Transform all geometries in an active geometry column to a different coordinate reference system. The CRS attribute on the current GeoSeries must be set. Either CRS or epsg may be specified for output. This method will transform all points in all objects. It has no notion or projecting entire geometries. All segment joining points are assumed to be lined in the current projection, not geodesics. Objects crossing the dateline (or another projection boundary) will have undesirable behavior."
},
{
"code": null,
"e": 8116,
"s": 8052,
"text": "Syntax: GeoDataFrame.to_crs(crs=None, epsg=None, inplace=False)"
},
{
"code": null,
"e": 8127,
"s": 8116,
"text": "Parameters"
},
{
"code": null,
"e": 8305,
"s": 8127,
"text": "crs: pyproj.CRS, optional if epsg is specified. The value can be anything accepted by pyproj.CRS.from_user_input(), such as an authority string (eg “EPSG:4326”) or a WKT string."
},
{
"code": null,
"e": 8386,
"s": 8305,
"text": "epsg: int, optional if crs is specified. EPSG code specifying output projection."
},
{
"code": null,
"e": 8499,
"s": 8386,
"text": "inplace: bool, optional, default: False. Whether to return a new GeoDataFrame or do the transformation in place."
},
{
"code": null,
"e": 8508,
"s": 8499,
"text": "Example:"
},
{
"code": null,
"e": 8516,
"s": 8508,
"text": "Python3"
},
{
"code": "import geopandas as gpd # Reading the world shapefileworld_data = gpd.read_file(r'world.shp') world_data = world_data[['NAME', 'geometry']] # Calculating the area of each countryworld_data['area'] = world_data.area # Removing Antarctica from GeoPandas GeoDataframeworld_data = world_data[world_data['NAME'] != 'Antarctica'] # Changing the projectioncurrent_crs = world_data.crsworld_data.to_crs(epsg=3857, inplace=True) world.plot()",
"e": 8955,
"s": 8516,
"text": null
},
{
"code": null,
"e": 8963,
"s": 8955,
"text": "Output:"
},
{
"code": null,
"e": 9249,
"s": 8963,
"text": "We can color each country in the world using a head column and cmap. To find out head column type “world_data.head()” in console. We can choose different color maps(cmap) available in matplotlib. In the following code, we have colored countries using plot() arguments column and cmap. "
},
{
"code": null,
"e": 9258,
"s": 9249,
"text": "Example:"
},
{
"code": null,
"e": 9266,
"s": 9258,
"text": "Python3"
},
{
"code": "import geopandas as gpd # Reading the world shapefileworld_data = gpd.read_file(r'world.shp') world_data = world_data[['NAME', 'geometry']] # Calculating the area of each countryworld_data['area'] = world_data.area # Removing Antarctica from GeoPandas GeoDataframeworld_data = world_data[world_data['NAME'] != 'Antarctica'] # Changing the projectioncurrent_crs = world_data.crsworld_data.to_crs(epsg=3857, inplace=True) world_data.plot(column='NAME', cmap='hsv')",
"e": 9735,
"s": 9266,
"text": null
},
{
"code": null,
"e": 9743,
"s": 9735,
"text": "Output:"
},
{
"code": null,
"e": 9900,
"s": 9743,
"text": "Next, we are going to convert the area in sq. km by dividing it to 10^6 i.e (1000000). Output can be seen in variable explorer in the “world_data” variable."
},
{
"code": null,
"e": 9979,
"s": 9900,
"text": "We can add a legend to our world map along with a label using plot() arguments"
},
{
"code": null,
"e": 10077,
"s": 9979,
"text": "legend: bool (default False). Plot a legend. Ignored if no column is given, or if color is given."
},
{
"code": null,
"e": 10701,
"s": 10077,
"text": "legend_kwds: dict (default None). Keyword arguments to pass to matplotlib.pyplot.legend() or matplotlib.pyplot.colorbar(). Additional accepted keywords when scheme is specified:fmt: string. A formatting specification for the bin edges of the classes in the legend. For example, to have no decimals: {“fmt”: “{:.0f}”}.labels: list-like. A list of legend labels to override the auto-generated labels. Needs to have the same number of elements as the number of classes (k).interval: boolean (default False). An option to control brackets from mapclassify legend. If True, open/closed interval brackets are shown in the legend."
},
{
"code": null,
"e": 10842,
"s": 10701,
"text": "fmt: string. A formatting specification for the bin edges of the classes in the legend. For example, to have no decimals: {“fmt”: “{:.0f}”}."
},
{
"code": null,
"e": 10996,
"s": 10842,
"text": "labels: list-like. A list of legend labels to override the auto-generated labels. Needs to have the same number of elements as the number of classes (k)."
},
{
"code": null,
"e": 11150,
"s": 10996,
"text": "interval: boolean (default False). An option to control brackets from mapclassify legend. If True, open/closed interval brackets are shown in the legend."
},
{
"code": null,
"e": 11159,
"s": 11150,
"text": "Example:"
},
{
"code": null,
"e": 11167,
"s": 11159,
"text": "Python3"
},
{
"code": "import geopandas as gpd # Reading the world shapefileworld_data = gpd.read_file(r'world.shp') world_data = world_data[['NAME', 'geometry']] # Calculating the area of each countryworld_data['area'] = world_data.area # Removing Antarctica from GeoPandas GeoDataframeworld_data = world_data[world_data['NAME'] != 'Antarctica']world_data.plot() # Changing the projectioncurrent_crs = world_data.crsworld_data.to_crs(epsg=3857, inplace=True)world_data.plot(column='NAME', cmap='hsv') # Re-calculate the areas in Sq. Km.world_data['area'] = world_data.area/1000000 # Adding a legendworld_data.plot(column='area', cmap='hsv', legend=True, legend_kwds={'label': \"Area of the country (Sq. Km.)\"}, figsize=(7, 7))",
"e": 11909,
"s": 11167,
"text": null
},
{
"code": null,
"e": 11917,
"s": 11909,
"text": "Output:"
},
{
"code": null,
"e": 11986,
"s": 11917,
"text": "We can also resize the legend using ax and cax arguments of plot(). "
},
{
"code": null,
"e": 12064,
"s": 11986,
"text": "ax: matplotlib.pyplot. Artist (default None). axes on which to draw the plot."
},
{
"code": null,
"e": 12165,
"s": 12064,
"text": "cax: matplotlib.pyplot Artist (default None). axes on which to draw the legend in case of color map."
},
{
"code": null,
"e": 12203,
"s": 12165,
"text": "For this, we need matplotlib library."
},
{
"code": null,
"e": 12573,
"s": 12203,
"text": "The axes_divider.make_axes_locatable function takes an existing axes, adds it to a new AxesDivider, and returns the AxesDivider. The append_axes method of the AxesDivider can then be used to create new axes on a given side (“top”, “right”, “bottom”, or “left”) of the original axes. To create axes at the given position with the same height (or width) of the main axes-"
},
{
"code": null,
"e": 12581,
"s": 12573,
"text": "Syntax:"
},
{
"code": null,
"e": 12655,
"s": 12581,
"text": "append_axes(self, position, size, pad=None, add_to_figure=True, **kwargs)"
},
{
"code": null,
"e": 12725,
"s": 12655,
"text": "position can take any value from: “left”, “right”, “bottom” or “top”."
},
{
"code": null,
"e": 12780,
"s": 12725,
"text": "size and pad should be axes_grid.axes_size compatible."
},
{
"code": null,
"e": 12789,
"s": 12780,
"text": "Example:"
},
{
"code": null,
"e": 12797,
"s": 12789,
"text": "Python3"
},
{
"code": "import geopandas as gpdimport matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1 import make_axes_locatable # Reading the world shapefileworld_data = gpd.read_file(r'world.shp') world_data = world_data[['NAME', 'geometry']] # Calculating the area of each countryworld_data['area'] = world_data.area # Removing Antarctica from GeoPandas GeoDataframeworld_data = world_data[world_data['NAME'] != 'Antarctica']world_data.plot() # Changing the projectioncurrent_crs = world_data.crsworld_data.to_crs(epsg=3857, inplace=True)world_data.plot(column='NAME', cmap='hsv') # Re-calculate the areas in Sq. Km.world_data['area'] = world_data.area/1000000 # Adding a legendworld_data.plot(column='area', cmap='hsv', legend=True, legend_kwds={'label': \"Area of the country (Sq. Km.)\"}, figsize=(7, 7)) # Resizing the legendfig, ax = plt.subplots(figsize=(10, 10))divider = make_axes_locatable(ax) cax = divider.append_axes(\"right\", size=\"7%\", pad=0.1)world_data.plot(column='area', cmap='hsv', legend=True, legend_kwds={'label': \"Area of the country (Sq. Km.)\"}, ax=ax, cax=cax)",
"e": 13934,
"s": 12797,
"text": null
},
{
"code": null,
"e": 13942,
"s": 13934,
"text": "Output:"
},
{
"code": null,
"e": 14245,
"s": 13942,
"text": "First, we will import Geoplot library. Next, we will load one of the sample datasets(geojson file) present in geoplot. In the below example, we are going to use “world” ,”contiguous_usa”,”usa_cities”,”melbourne” and “melbourne_schools” datasets. List of datasets present in geoplot are mentioned below:"
},
{
"code": null,
"e": 14256,
"s": 14245,
"text": "usa_cities"
},
{
"code": null,
"e": 14271,
"s": 14256,
"text": "contiguous_usa"
},
{
"code": null,
"e": 14293,
"s": 14271,
"text": "nyc_collision_factors"
},
{
"code": null,
"e": 14306,
"s": 14293,
"text": "nyc_boroughs"
},
{
"code": null,
"e": 14316,
"s": 14306,
"text": "ny_census"
},
{
"code": null,
"e": 14333,
"s": 14316,
"text": "obesity_by_state"
},
{
"code": null,
"e": 14344,
"s": 14333,
"text": "la_flights"
},
{
"code": null,
"e": 14353,
"s": 14344,
"text": "dc_roads"
},
{
"code": null,
"e": 14374,
"s": 14353,
"text": "nyc_map_pluto_sample"
},
{
"code": null,
"e": 14396,
"s": 14374,
"text": "nyc_collisions_sample"
},
{
"code": null,
"e": 14413,
"s": 14396,
"text": "boston_zip_codes"
},
{
"code": null,
"e": 14436,
"s": 14413,
"text": "boston_airbnb_listings"
},
{
"code": null,
"e": 14461,
"s": 14436,
"text": "napoleon_troop_movements"
},
{
"code": null,
"e": 14482,
"s": 14461,
"text": "nyc_fatal_collisions"
},
{
"code": null,
"e": 14507,
"s": 14482,
"text": "nyc_injurious_collisions"
},
{
"code": null,
"e": 14528,
"s": 14507,
"text": "nyc_police_precincts"
},
{
"code": null,
"e": 14548,
"s": 14528,
"text": "nyc_parking_tickets"
},
{
"code": null,
"e": 14554,
"s": 14548,
"text": "world"
},
{
"code": null,
"e": 14564,
"s": 14554,
"text": "melbourne"
},
{
"code": null,
"e": 14582,
"s": 14564,
"text": "melbourne_schools"
},
{
"code": null,
"e": 14596,
"s": 14582,
"text": "san_francisco"
},
{
"code": null,
"e": 14630,
"s": 14596,
"text": "san_francisco_street_trees_sample"
},
{
"code": null,
"e": 14665,
"s": 14630,
"text": "california_congressional_districts"
},
{
"code": null,
"e": 14769,
"s": 14665,
"text": "We can add our own datasets by editing the datasets.py file. Click here for some free sample datasets. "
},
{
"code": null,
"e": 14841,
"s": 14769,
"text": "If you have polygonal data, you can plot that using a geoplot polyplot."
},
{
"code": null,
"e": 14939,
"s": 14841,
"text": "If your data consists of a bunch of points instead, you can display those points using pointplot."
},
{
"code": null,
"e": 14948,
"s": 14939,
"text": "Syntax :"
},
{
"code": null,
"e": 14979,
"s": 14948,
"text": "geoplot.datasets.get_path(str)"
},
{
"code": null,
"e": 15000,
"s": 14979,
"text": "Syntax for plotting:"
},
{
"code": null,
"e": 15045,
"s": 15000,
"text": "geoplot.polyplot(var)\ngeoplot.pointplot(var)"
},
{
"code": null,
"e": 15054,
"s": 15045,
"text": "Example:"
},
{
"code": null,
"e": 15062,
"s": 15054,
"text": "Python3"
},
{
"code": "import geoplot as gpltimport geopandas as gpd # Reading the world shapefilepath = gplt.datasets.get_path(\"world\")world = gpd.read_file(path)gplt.polyplot(world) path = gplt.datasets.get_path(\"contiguous_usa\")contiguous_usa = gpd.read_file(path)gplt.polyplot(contiguous_usa) path = gplt.datasets.get_path(\"usa_cities\")usa_cities = gpd.read_file(path)gplt.pointplot(usa_cities) path = gplt.datasets.get_path(\"melbourne\")melbourne = gpd.read_file(path)gplt.polyplot(melbourne) path = gplt.datasets.get_path(\"melbourne_schools\")melbourne_schools = gpd.read_file(path)gplt.pointplot(melbourne_schools)",
"e": 15664,
"s": 15062,
"text": null
},
{
"code": null,
"e": 15679,
"s": 15664,
"text": "World Dataset:"
},
{
"code": null,
"e": 15692,
"s": 15679,
"text": "USA Dataset:"
},
{
"code": null,
"e": 15712,
"s": 15692,
"text": "USA Cities Dataset:"
},
{
"code": null,
"e": 15731,
"s": 15712,
"text": "Melbourne Dataset:"
},
{
"code": null,
"e": 15758,
"s": 15731,
"text": "Melbourne Schools Dataset:"
},
{
"code": null,
"e": 15947,
"s": 15758,
"text": "We can combine these two plots using overplotting. Overplotting is the act of stacking several different plots on top of one another, useful for providing additional context for our plots:"
},
{
"code": null,
"e": 15956,
"s": 15947,
"text": "Example:"
},
{
"code": null,
"e": 15964,
"s": 15956,
"text": "Python3"
},
{
"code": "import geoplot as gpltimport geopandas as gpd # Reading the world shapefile path = gplt.datasets.get_path(\"usa_cities\")usa_cities = gpd.read_file(path) path = gplt.datasets.get_path(\"contiguous_usa\")contiguous_usa = gpd.read_file(path) path = gplt.datasets.get_path(\"melbourne\")melbourne = gpd.read_file(path) path = gplt.datasets.get_path(\"melbourne_schools\")melbourne_schools = gpd.read_file(path) ax = gplt.polyplot(contiguous_usa)gplt.pointplot(usa_cities, ax=ax) ax = gplt.polyplot(melbourne)gplt.pointplot(melbourne_schools, ax=ax)",
"e": 16508,
"s": 15964,
"text": null
},
{
"code": null,
"e": 16516,
"s": 16508,
"text": "Output:"
},
{
"code": null,
"e": 17038,
"s": 16516,
"text": "You may have noticed that this map of the United States appears to be odd. Because the Earth is a sphere, it is difficult to depict it in two dimensions. As a result, we use some type of projection, or means of flattening the sphere, whenever we take data off the sphere and place it on a map. When you plot data without a projection, or “carte blanche,” your map will be distorted. We can “correct” the distortions by picking up a projection method. Here we are going to use Albers equal-area and WebMercator projection."
},
{
"code": null,
"e": 17141,
"s": 17038,
"text": "Along with this, we are also going to add some other parameters such as hue, legend, cmap, and scheme."
},
{
"code": null,
"e": 17196,
"s": 17141,
"text": "The hue parameter applies a colormap to a data column."
},
{
"code": null,
"e": 17235,
"s": 17196,
"text": "The legend parameter toggles a legend."
},
{
"code": null,
"e": 17280,
"s": 17235,
"text": "Change the colormap using matplotlib’s cmap."
},
{
"code": null,
"e": 17322,
"s": 17280,
"text": "For a categorical colormap, use a scheme."
},
{
"code": null,
"e": 17331,
"s": 17322,
"text": "Example:"
},
{
"code": null,
"e": 17339,
"s": 17331,
"text": "Python3"
},
{
"code": "import geoplot as gpltimport geopandas as gpdimport geoplot.crs as gcrs # Reading the world shapefile path = gplt.datasets.get_path(\"contiguous_usa\")contiguous_usa = gpd.read_file(path) path = gplt.datasets.get_path(\"usa_cities\")usa_cities = gpd.read_file(path) ax = gplt.polyplot(contiguous_usa, projection=gcrs.AlbersEqualArea())gplt.pointplot(usa_cities, ax=ax, hue=\"ELEV_IN_FT\",cmap='rainbow', legend=True) ax = gplt.webmap(contiguous_usa, projection=gcrs.WebMercator())gplt.pointplot(usa_cities, ax=ax, hue='ELEV_IN_FT', cmap='terrain', legend=True)",
"e": 17928,
"s": 17339,
"text": null
},
{
"code": null,
"e": 17936,
"s": 17928,
"text": "Output:"
},
{
"code": null,
"e": 18382,
"s": 17936,
"text": "A choropleth takes data that has been aggregated on some meaningful polygonal level (e.g. census tract, state, country, or continent) and uses color to display it to the reader. It’s a well-known plot type, and it’s perhaps the most general-purpose and well-known of the spatial plot types. A basic choropleth requires polygonal geometries and a hue variable. Change the colormap using matplotlib’s cmap. The legend parameter toggles the legend."
},
{
"code": null,
"e": 18390,
"s": 18382,
"text": "Syntax:"
},
{
"code": null,
"e": 18414,
"s": 18390,
"text": "geoplot.choropleth(var)"
},
{
"code": null,
"e": 18423,
"s": 18414,
"text": "Example:"
},
{
"code": null,
"e": 18431,
"s": 18423,
"text": "Python3"
},
{
"code": "import geoplot as gpltimport geopandas as gpdimport geoplot.crs as gcrs # Reading the world shapefile boroughs = gpd.read_file(gplt.datasets.get_path('nyc_boroughs')) gplt.choropleth(boroughs, hue='Shape_Area', projection=gcrs.AlbersEqualArea(), cmap='RdPu', legend=True)",
"e": 18737,
"s": 18431,
"text": null
},
{
"code": null,
"e": 18745,
"s": 18737,
"text": "Output:"
},
{
"code": null,
"e": 19107,
"s": 18745,
"text": "To pass the keyword argument to the legend, use the legend_kwargs argument. To specify a categorical colormap, use a scheme. Use legend_labels and legend_values to customize the labels and values that appear in the legend. Here we are going to use mapclassify which is an open-source python library for Choropleth map classification. To install mapclassify use:"
},
{
"code": null,
"e": 19173,
"s": 19107,
"text": "mapclassify is available in on conda via the conda-forge channel:"
},
{
"code": null,
"e": 19181,
"s": 19173,
"text": "Syntax:"
},
{
"code": null,
"e": 19222,
"s": 19181,
"text": "conda install -c conda-forge mapclassify"
},
{
"code": null,
"e": 19281,
"s": 19222,
"text": "mapclassify is also available on the Python Package Index:"
},
{
"code": null,
"e": 19289,
"s": 19281,
"text": "Syntax:"
},
{
"code": null,
"e": 19316,
"s": 19289,
"text": "pip install -U mapclassify"
},
{
"code": null,
"e": 19325,
"s": 19316,
"text": "Example:"
},
{
"code": null,
"e": 19333,
"s": 19325,
"text": "Python3"
},
{
"code": "import geoplot as gpltimport geopandas as gpdimport geoplot.crs as gcrsimport mapclassify as mc # Reading the world shapefile contiguous_usa = gpd.read_file(gplt.datasets.get_path('contiguous_usa')) scheme = mc.FisherJenks(contiguous_usa['population'], k=5) gplt.choropleth( contiguous_usa, hue='population', projection=gcrs.AlbersEqualArea(), edgecolor='white', linewidth=1, cmap='Reds', legend=True, legend_kwargs={'loc': 'lower left'}, scheme=scheme, legend_labels=[ '<3 million', '3-6.7 million', '6.7-12.8 million', '12.8-25 million', '25-37 million' ])",
"e": 19926,
"s": 19333,
"text": null
},
{
"code": null,
"e": 19934,
"s": 19926,
"text": "Output:"
},
{
"code": null,
"e": 20266,
"s": 19934,
"text": "Kernel density estimation is a technique that non-parametrically estimates a distribution function for a set of point observations without using parameters. KDEs are a popular method for examining data distributions; in this figure, the technique is applied to a geospatial situation. A basic KDEplot takes pointwise data as input."
},
{
"code": null,
"e": 20274,
"s": 20266,
"text": "Syntax:"
},
{
"code": null,
"e": 20295,
"s": 20274,
"text": "geoplot.kdeplot(var)"
},
{
"code": null,
"e": 20304,
"s": 20295,
"text": "Example:"
},
{
"code": null,
"e": 20312,
"s": 20304,
"text": "Python3"
},
{
"code": "import geoplot as gpltimport geopandas as gpdimport geoplot.crs as gcrs # Reading the world shapefile boroughs = gpd.read_file(gplt.datasets.get_path('nyc_boroughs')) collisions = gpd.read_file(gplt.datasets.get_path('nyc_collision_factors')) ax = gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea()) gplt.kdeplot(collisions, ax=ax)",
"e": 20655,
"s": 20312,
"text": null
},
{
"code": null,
"e": 20663,
"s": 20655,
"text": "Output:"
},
{
"code": null,
"e": 21259,
"s": 20663,
"text": "A Sankey diagram depicts the flow of information through a network. It’s useful for displaying the magnitudes of data flowing through a system. This figure places the Sankey diagram in a geospatial context, making it helpful for monitoring traffic loads on a road network or travel volumes between airports, for example. A basic Sankey requires a GeoDataFrame of LineString or MultiPoint geometries. hue adds color gradation to the map. Use matplotlib’s cmap to control the colormap. For a categorical colormap, specify the scheme. legend toggles a legend. Here we are using Mollweide projection"
},
{
"code": null,
"e": 21267,
"s": 21259,
"text": "Syntax;"
},
{
"code": null,
"e": 21287,
"s": 21267,
"text": "geoplot.sankey(var)"
},
{
"code": null,
"e": 21296,
"s": 21287,
"text": "Example:"
},
{
"code": null,
"e": 21304,
"s": 21296,
"text": "Python3"
},
{
"code": "import geoplot as gpltimport geopandas as gpdimport geoplot.crs as gcrsimport mapclassify as mc # Reading the world shapefile la_flights = gpd.read_file(gplt.datasets.get_path('la_flights'))world = gpd.read_file(gplt.datasets.get_path('world'))scheme = mc.Quantiles(la_flights['Passengers'], k=5) ax = gplt.sankey(la_flights, projection=gcrs.Mollweide(), scale='Passengers', hue='Passengers', scheme=scheme, cmap='Oranges', legend=True) gplt.polyplot(world, ax=ax, facecolor='lightgray', edgecolor='white')ax.set_global(); ax.outline_patch.set_visible(True)",
"e": 21899,
"s": 21304,
"text": null
},
{
"code": null,
"e": 21907,
"s": 21899,
"text": "Output:"
},
{
"code": null,
"e": 21926,
"s": 21907,
"text": "Data Visualization"
},
{
"code": null,
"e": 21933,
"s": 21926,
"text": "Picked"
},
{
"code": null,
"e": 21940,
"s": 21933,
"text": "Python"
},
{
"code": null,
"e": 22038,
"s": 21940,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 22070,
"s": 22038,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 22097,
"s": 22070,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 22118,
"s": 22097,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 22141,
"s": 22118,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 22172,
"s": 22141,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 22228,
"s": 22172,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 22270,
"s": 22228,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 22312,
"s": 22270,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 22351,
"s": 22312,
"text": "Python | Get unique values from a list"
}
] |
Program to print the series 2, 1, 4, 3, 6, 5, .... up to N terms
|
18 Mar, 2021
Given a number N, the task is to print the below pattern upto N terms:
2, 1, 4, 3, 6, 5, .... N terms
Examples:
Input: N = 4
Output: 2, 1, 4, 3
Explanation:
Nth Term = (N % 2 == 0) ? (N - 1) : (N + 1)
1st term = (1 % 2 == 0) ? (1 - 1) : (1 + 1)
= (1 + 1)
= 2
2nd term = (2 % 2 == 0) ? (2 - 1) : (2 + 1)
= (2 - 1)
= 1
3rd term = (3 % 2 == 0) ? (3 - 1) : (3 + 1)
= (3 + 1)
= 4
4th term = (4 % 2 == 0) ? (4 - 1) : (4 + 1)
= (4 - 1)
= 3
Therefore, Series = 2, 1, 4, 3
Input: N = 7
Output: 2, 1, 4, 3, 6, 5, 8
Formula:
Nth Term = (N % 2 == 0) ? (N - 1) : (N + 1)
Below is the solution to above problem:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print the series// 2, 1, 4, 3, 6, 5, .... up to N terms#include <iostream>using namespace std; // Function to print the seriesvoid printPattern(int N){ for (int i = 1; i <= N; i++) { // Find and print the ith term cout <<" "<<((i % 2 == 0) ? (i - 1) : (i + 1)); }} // Driver codeint main(){ // Get the value of N int N = 10; // Print the Series printPattern(N); return 0;}
// Java Program to print the series// 2, 1, 4, 3, 6, 5, .... up to N terms import java.util.*;import java.lang.*;import java.io.*; class GFG{// Function to print the seriesstatic void printPattern(int N){ for (int i = 1; i <= N; i++) { // Find and print the ith term System.out.print(" "+((i % 2 == 0) ? (i - 1) : (i + 1))); }} // Driver codepublic static void main(String args[]){ // Get the value of N int N = 10; // Print the Series printPattern(N); }}
# Python program to print the series# 2, 1, 4, 3, 6, 5, .... up to N terms # Function to print the seriesdef printPattern(N): for i in range(1, N + 1): # Find and print the ith term print(i - 1 if i % 2 == 0 else i + 1, end = " ") # Driver codeN = 10printPattern(N) # This code is contributed by Shrikant13
// C# program to print the series// 2, 1, 4, 3, 6, 5, .... up to N termsusing System; class GFG{// Function to print the seriespublic void printPattern(int N){ for (int i = 1; i <= N; i++) { // Find and print the ith term int a = ((i % 2 == 0) ? (i - 1) : (i + 1)); Console.Write(" {0}", a); }} // Driver codepublic static void Main(){ GFG g = new GFG(); // Get the value of N int N = 10; // Print the Series g.printPattern(N);}} // This code is contributed// by Soumik
<?php// PHP program to print the series// 2, 1, 4, 3, 6, 5, .... up to N terms // Function to print the seriesfunction printPattern($N){ for ($i = 1; $i <= $N; $i++) { // Find and print the ith term echo " " . (($i % 2 == 0) ? ($i - 1) : ($i + 1)); }} // Driver code // Get the value of N$N = 10; // Print the SeriesprintPattern($N); // This code is contributed// by ChitraNayal?>
<script>// javascript program to print the series// 2, 1, 4, 3, 6, 5, .... up to N terms // Function to print the seriesfunction printPattern( N){ for (let i = 1; i <= N; i++) { // Find and print the ith term document.write(" " + ((i % 2 == 0) ? (i - 1) : (i + 1))); }} // Driver code // Get the value of N let N = 10; // Print the Series printPattern(N); // This code is contributed by Rajput-Ji </script>
2 1 4 3 6 5 8 7 10 9
tufan_gupta2000
SoumikMondal
shrikanth13
ukasp
mayank5326
Rajput-Ji
series
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Mar, 2021"
},
{
"code": null,
"e": 101,
"s": 28,
"text": "Given a number N, the task is to print the below pattern upto N terms: "
},
{
"code": null,
"e": 134,
"s": 101,
"text": "2, 1, 4, 3, 6, 5, .... N terms "
},
{
"code": null,
"e": 146,
"s": 134,
"text": "Examples: "
},
{
"code": null,
"e": 613,
"s": 146,
"text": "Input: N = 4\nOutput: 2, 1, 4, 3\n\nExplanation:\nNth Term = (N % 2 == 0) ? (N - 1) : (N + 1)\n1st term = (1 % 2 == 0) ? (1 - 1) : (1 + 1)\n = (1 + 1)\n = 2\n2nd term = (2 % 2 == 0) ? (2 - 1) : (2 + 1)\n = (2 - 1)\n = 1\n3rd term = (3 % 2 == 0) ? (3 - 1) : (3 + 1)\n = (3 + 1)\n = 4\n4th term = (4 % 2 == 0) ? (4 - 1) : (4 + 1)\n = (4 - 1)\n = 3\nTherefore, Series = 2, 1, 4, 3\n\nInput: N = 7\nOutput: 2, 1, 4, 3, 6, 5, 8"
},
{
"code": null,
"e": 626,
"s": 615,
"text": "Formula: "
},
{
"code": null,
"e": 670,
"s": 626,
"text": "Nth Term = (N % 2 == 0) ? (N - 1) : (N + 1)"
},
{
"code": null,
"e": 712,
"s": 670,
"text": "Below is the solution to above problem: "
},
{
"code": null,
"e": 716,
"s": 712,
"text": "C++"
},
{
"code": null,
"e": 721,
"s": 716,
"text": "Java"
},
{
"code": null,
"e": 729,
"s": 721,
"text": "Python3"
},
{
"code": null,
"e": 732,
"s": 729,
"text": "C#"
},
{
"code": null,
"e": 736,
"s": 732,
"text": "PHP"
},
{
"code": null,
"e": 747,
"s": 736,
"text": "Javascript"
},
{
"code": "// C++ program to print the series// 2, 1, 4, 3, 6, 5, .... up to N terms#include <iostream>using namespace std; // Function to print the seriesvoid printPattern(int N){ for (int i = 1; i <= N; i++) { // Find and print the ith term cout <<\" \"<<((i % 2 == 0) ? (i - 1) : (i + 1)); }} // Driver codeint main(){ // Get the value of N int N = 10; // Print the Series printPattern(N); return 0;}",
"e": 1178,
"s": 747,
"text": null
},
{
"code": "// Java Program to print the series// 2, 1, 4, 3, 6, 5, .... up to N terms import java.util.*;import java.lang.*;import java.io.*; class GFG{// Function to print the seriesstatic void printPattern(int N){ for (int i = 1; i <= N; i++) { // Find and print the ith term System.out.print(\" \"+((i % 2 == 0) ? (i - 1) : (i + 1))); }} // Driver codepublic static void main(String args[]){ // Get the value of N int N = 10; // Print the Series printPattern(N); }}",
"e": 1682,
"s": 1178,
"text": null
},
{
"code": "# Python program to print the series# 2, 1, 4, 3, 6, 5, .... up to N terms # Function to print the seriesdef printPattern(N): for i in range(1, N + 1): # Find and print the ith term print(i - 1 if i % 2 == 0 else i + 1, end = \" \") # Driver codeN = 10printPattern(N) # This code is contributed by Shrikant13",
"e": 2034,
"s": 1682,
"text": null
},
{
"code": "// C# program to print the series// 2, 1, 4, 3, 6, 5, .... up to N termsusing System; class GFG{// Function to print the seriespublic void printPattern(int N){ for (int i = 1; i <= N; i++) { // Find and print the ith term int a = ((i % 2 == 0) ? (i - 1) : (i + 1)); Console.Write(\" {0}\", a); }} // Driver codepublic static void Main(){ GFG g = new GFG(); // Get the value of N int N = 10; // Print the Series g.printPattern(N);}} // This code is contributed// by Soumik",
"e": 2578,
"s": 2034,
"text": null
},
{
"code": "<?php// PHP program to print the series// 2, 1, 4, 3, 6, 5, .... up to N terms // Function to print the seriesfunction printPattern($N){ for ($i = 1; $i <= $N; $i++) { // Find and print the ith term echo \" \" . (($i % 2 == 0) ? ($i - 1) : ($i + 1)); }} // Driver code // Get the value of N$N = 10; // Print the SeriesprintPattern($N); // This code is contributed// by ChitraNayal?>",
"e": 3003,
"s": 2578,
"text": null
},
{
"code": "<script>// javascript program to print the series// 2, 1, 4, 3, 6, 5, .... up to N terms // Function to print the seriesfunction printPattern( N){ for (let i = 1; i <= N; i++) { // Find and print the ith term document.write(\" \" + ((i % 2 == 0) ? (i - 1) : (i + 1))); }} // Driver code // Get the value of N let N = 10; // Print the Series printPattern(N); // This code is contributed by Rajput-Ji </script>",
"e": 3453,
"s": 3003,
"text": null
},
{
"code": null,
"e": 3474,
"s": 3453,
"text": "2 1 4 3 6 5 8 7 10 9"
},
{
"code": null,
"e": 3492,
"s": 3476,
"text": "tufan_gupta2000"
},
{
"code": null,
"e": 3505,
"s": 3492,
"text": "SoumikMondal"
},
{
"code": null,
"e": 3517,
"s": 3505,
"text": "shrikanth13"
},
{
"code": null,
"e": 3523,
"s": 3517,
"text": "ukasp"
},
{
"code": null,
"e": 3534,
"s": 3523,
"text": "mayank5326"
},
{
"code": null,
"e": 3544,
"s": 3534,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 3551,
"s": 3544,
"text": "series"
},
{
"code": null,
"e": 3564,
"s": 3551,
"text": "Mathematical"
},
{
"code": null,
"e": 3583,
"s": 3564,
"text": "School Programming"
},
{
"code": null,
"e": 3596,
"s": 3583,
"text": "Mathematical"
},
{
"code": null,
"e": 3603,
"s": 3596,
"text": "series"
},
{
"code": null,
"e": 3701,
"s": 3603,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3725,
"s": 3701,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 3746,
"s": 3725,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 3760,
"s": 3746,
"text": "Prime Numbers"
},
{
"code": null,
"e": 3813,
"s": 3760,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 3850,
"s": 3813,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 3868,
"s": 3850,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3893,
"s": 3868,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 3909,
"s": 3893,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 3932,
"s": 3909,
"text": "Introduction To PYTHON"
}
] |
RxJS - Join Operator forkJoin
|
This operator will take in an array or dict object as an input and will wait for the observable to complete and return the last values emitted from the given observable.
forkJoin(value: array or dict object): Observable
value − The value is the input which can be an array or dict object.
An observable is returned with last values emitted from the given observable.
import { of, forkJoin } from 'rxjs';
import { concat } from 'rxjs/operators';
let list1 = of(2, 3, 4, 5, 6);
let list2 = of(4, 9, 16, 25, 36)
let final_val = forkJoin([list1, list2]);
final_val.subscribe(x => console.log(x));
[6,36]
51 Lectures
4 hours
Daniel Stern
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1994,
"s": 1824,
"text": "This operator will take in an array or dict object as an input and will wait for the observable to complete and return the last values emitted from the given observable."
},
{
"code": null,
"e": 2045,
"s": 1994,
"text": "forkJoin(value: array or dict object): Observable\n"
},
{
"code": null,
"e": 2114,
"s": 2045,
"text": "value − The value is the input which can be an array or dict object."
},
{
"code": null,
"e": 2192,
"s": 2114,
"text": "An observable is returned with last values emitted from the given observable."
},
{
"code": null,
"e": 2419,
"s": 2192,
"text": "import { of, forkJoin } from 'rxjs';\nimport { concat } from 'rxjs/operators';\n\nlet list1 = of(2, 3, 4, 5, 6);\nlet list2 = of(4, 9, 16, 25, 36)\nlet final_val = forkJoin([list1, list2]);\nfinal_val.subscribe(x => console.log(x));"
},
{
"code": null,
"e": 2427,
"s": 2419,
"text": "[6,36]\n"
},
{
"code": null,
"e": 2460,
"s": 2427,
"text": "\n 51 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2474,
"s": 2460,
"text": " Daniel Stern"
},
{
"code": null,
"e": 2481,
"s": 2474,
"text": " Print"
},
{
"code": null,
"e": 2492,
"s": 2481,
"text": " Add Notes"
}
] |
Kotlin - Data Types
|
Kotlin data type is a classification of data which tells the compiler how the programmer intends to use the data. For example, Kotlin data could be numeric, string, boolean etc.
Kotlin treats everything as an object which means that we can call member functions and properties on any variable.
Kotlin is a statically typed language, which means that the data type of every expression should be known at compile time.
Kotlin built in data type can be categorized as follows:
Number
Number
Character
Character
String
String
Boolean
Boolean
Array
Array
Kotlin number data types are used to define variables which hold numeric values and they are divided into two groups: (a) Integer types store whole numbers, positive or negative (b) Floating point types represent numbers with a fractional part, containing one or more decimals.
Following table list down all the Kotlin number data types, keywords to define their variable types, size of the memory taken by the variables, and a value range which can be stored in those variables.
If we will try to store a value more than permitted value in a variable of particular data type, the Kotlin compiler will complain because an overflow would occur at runtime.
Following example shows how to define and access different Kotlin number data types:
fun main(args: Array<String>) {
val a: Int = 10000
val d: Double = 100.00
val f: Float = 100.00f
val l: Long = 1000000004
val s: Short = 10
val b: Byte = 1
println("Int Value is " + a)
println("Double Value is " + d)
println("Float Value is " + f)
println("Long Value is " + l )
println("Short Value is " + s)
println("Byte Value is " + b)
}
When you run the above Kotlin program, it will generate the following output:
Int Value is 10000
Double Value is 100.0
Float Value is 100.0
Long Value is 1000000004
Short Value is 10
Byte Value is 1
Kotlin character data type is used to store a single character and they are represented by the type Char keyword. A Char value must be surrounded by single quotes, like 'A' or '1'.
Following example shows how to define and access a Kotlin Char data type:
fun main(args: Array<String>) {
val letter: Char // defining a Char variable
letter = 'A' // Assigning a value to it
println("$letter")
}
When you run the above Kotlin program, it will generate the following output:
A
Kotlin supports a number of escape sequences of characters. When a character is preceded by a backslash (\), it is called an escape sequence and it has a special meaning to the compiler. For example, \n in the following statement is a valid character and it is called a new line character
println('\n') //prints a newline character
println('\$') //prints a dollar $ character
println('\\') //prints a back slash \ character
The following escape sequences are supported in Kotlin: \t, \b, \n, \r, \', \", \\ and \$.
The String data type is used to store a sequence of characters. String values must be surrounded by double quotes (" ") or triple quote (""" """).
We have two kinds of string available in Kotlin - one is called Escaped String and another is called Raw String.
Escaped string is declared within double quote (" ") and may contain escape characters like '\n', '\t', '\b' etc.
Escaped string is declared within double quote (" ") and may contain escape characters like '\n', '\t', '\b' etc.
Raw string is declared within triple quote (""" """) and may contain multiple lines of text without any escape characters.
Raw string is declared within triple quote (""" """) and may contain multiple lines of text without any escape characters.
fun main(args: Array<String>) {
val escapedString : String = "I am escaped String!\n"
var rawString :String = """This is going to be a
multi-line string and will
not have any escape sequence""";
print(escapedString)
println(rawString)
}
When you run the above Kotlin program, it will generate the following output:
I am escaped String!
This is going to be a
multi-line string and will
not have any escape sequence
Boolean is very simple like other programming languages. We have only two values for Boolean data type - either true or false.
fun main(args: Array<String>) {
val A: Boolean = true // defining a variable with true value
val B: Boolean = false // defining a variable with false value
println("Value of variable A "+ A )
println("Value of variable B "+ B )
}
When you run the above Kotlin program, it will generate the following output:
Value of variable A true
Value of variable B false
Boolean has a nullable counterpart Boolean? that can store a null value as below:
val boolNull: Boolean? = null
Kotlin arrays are a collection of homogeneous data. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
We will study array in a separate chapter, for now let's look at one example to define an array of integers and then access its one of the elements.
fun main(args: Array<String>) {
val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5)
println("Value at 3rd position : " + numbers[2])
}
When you run the above Kotlin program, it will generate the following output:
Value at 3rd position : 3
Type conversion is a process in which the value of one data type is converted into another type. Kotlin does not support direct conversion of one numeric data type to another, For example, it is not possible to convert an Int type to a Long type:
fun main(args: Array<String>) {
val x: Int = 100
val y: Long = x // Not valid assignment
println(y)
}
When you run the above Kotlin program, it will generate the following output:
main.kt:3:18: error: type mismatch: inferred type is Int but Long was expected
val y: Long = x // Not valid assignment
To convert a numeric data type to another type, Kotlin provides a set of functions:
toByte()
toByte()
toShort()
toShort()
toInt()
toInt()
toLong()
toLong()
toFloat()
toFloat()
toDouble()
toDouble()
toChar()
toChar()
Now let's rewrite above example once again and try to run it:
fun main(args: Array<String>) {
val x: Int = 100
val y: Long = x.toLong()
println(y)
}
When you run the above Kotlin program, it will generate the following output:
100
Q 1 - Can a Kotlin Boolean variable have a value of 0:
A - True
B - False
No Kotlin Boolean variable can store either true or false values, no integer value is allowed in Boolean variable.
Q 2 - Which of the data type is used to define a variable PI to store the value 3.14
A - Float
B - Double
C - Long
D - None of the above
We will use Double data type to define PI to store a value of 3.14. Floats are used to store values like 3.14F
Q 3 - What could be the minimum length of Kotlin String?
A - Zero character
B - 1 character
C - Null value
D - None of the above
We can define an empty string having zero characters.
Q 4 - Which of these are valid data types to hold integers in Kotlin?
A - Byte, Short, Int, Long
B - Byte, Int, Float, Long
C - Short, Int, Long, Boolean
D - None of the above
This is the set of data types which can be used to define an integer (Byte, Short, Int, Long). Float and Boolean are not used to define integer.
Q 5 - Which of the following statement is true about Kotlin Data Type:
A - Kotlin does not allow direct numeric data type conversion.
B - To convert a numeric data type to another type, you must use provided helper functions.
C - Int, Short, Float, Byte, Long, Double can be used to define Numeric Data types
D - All of the above
All the given statements are correct about Kotlin Data Types
68 Lectures
4.5 hours
Arnab Chakraborty
71 Lectures
5.5 hours
Frahaan Hussain
18 Lectures
1.5 hours
Mahmoud Ramadan
49 Lectures
6 hours
Catalin Stefan
49 Lectures
2.5 hours
Skillbakerystudios
22 Lectures
1 hours
CLEMENT OCHIENG
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2603,
"s": 2425,
"text": "Kotlin data type is a classification of data which tells the compiler how the programmer intends to use the data. For example, Kotlin data could be numeric, string, boolean etc."
},
{
"code": null,
"e": 2719,
"s": 2603,
"text": "Kotlin treats everything as an object which means that we can call member functions and properties on any variable."
},
{
"code": null,
"e": 2842,
"s": 2719,
"text": "Kotlin is a statically typed language, which means that the data type of every expression should be known at compile time."
},
{
"code": null,
"e": 2899,
"s": 2842,
"text": "Kotlin built in data type can be categorized as follows:"
},
{
"code": null,
"e": 2906,
"s": 2899,
"text": "Number"
},
{
"code": null,
"e": 2913,
"s": 2906,
"text": "Number"
},
{
"code": null,
"e": 2923,
"s": 2913,
"text": "Character"
},
{
"code": null,
"e": 2933,
"s": 2923,
"text": "Character"
},
{
"code": null,
"e": 2940,
"s": 2933,
"text": "String"
},
{
"code": null,
"e": 2947,
"s": 2940,
"text": "String"
},
{
"code": null,
"e": 2955,
"s": 2947,
"text": "Boolean"
},
{
"code": null,
"e": 2963,
"s": 2955,
"text": "Boolean"
},
{
"code": null,
"e": 2969,
"s": 2963,
"text": "Array"
},
{
"code": null,
"e": 2975,
"s": 2969,
"text": "Array"
},
{
"code": null,
"e": 3253,
"s": 2975,
"text": "Kotlin number data types are used to define variables which hold numeric values and they are divided into two groups: (a) Integer types store whole numbers, positive or negative (b) Floating point types represent numbers with a fractional part, containing one or more decimals."
},
{
"code": null,
"e": 3455,
"s": 3253,
"text": "Following table list down all the Kotlin number data types, keywords to define their variable types, size of the memory taken by the variables, and a value range which can be stored in those variables."
},
{
"code": null,
"e": 3630,
"s": 3455,
"text": "If we will try to store a value more than permitted value in a variable of particular data type, the Kotlin compiler will complain because an overflow would occur at runtime."
},
{
"code": null,
"e": 3715,
"s": 3630,
"text": "Following example shows how to define and access different Kotlin number data types:"
},
{
"code": null,
"e": 4096,
"s": 3715,
"text": "fun main(args: Array<String>) {\n val a: Int = 10000\n val d: Double = 100.00\n val f: Float = 100.00f\n val l: Long = 1000000004\n val s: Short = 10\n val b: Byte = 1\n\n println(\"Int Value is \" + a)\n println(\"Double Value is \" + d)\n println(\"Float Value is \" + f)\n println(\"Long Value is \" + l )\n println(\"Short Value is \" + s)\n println(\"Byte Value is \" + b)\n}\n"
},
{
"code": null,
"e": 4174,
"s": 4096,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 4297,
"s": 4174,
"text": "Int Value is 10000\nDouble Value is 100.0\nFloat Value is 100.0\nLong Value is 1000000004\nShort Value is 10\nByte Value is 1\n"
},
{
"code": null,
"e": 4478,
"s": 4297,
"text": "Kotlin character data type is used to store a single character and they are represented by the type Char keyword. A Char value must be surrounded by single quotes, like 'A' or '1'."
},
{
"code": null,
"e": 4552,
"s": 4478,
"text": "Following example shows how to define and access a Kotlin Char data type:"
},
{
"code": null,
"e": 4710,
"s": 4552,
"text": "fun main(args: Array<String>) {\n val letter: Char // defining a Char variable\n letter = 'A' // Assigning a value to it\n println(\"$letter\")\n}\n"
},
{
"code": null,
"e": 4788,
"s": 4710,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 4791,
"s": 4788,
"text": "A\n"
},
{
"code": null,
"e": 5080,
"s": 4791,
"text": "Kotlin supports a number of escape sequences of characters. When a character is preceded by a backslash (\\), it is called an escape sequence and it has a special meaning to the compiler. For example, \\n in the following statement is a valid character and it is called a new line character"
},
{
"code": null,
"e": 5218,
"s": 5080,
"text": "println('\\n') //prints a newline character\n\nprintln('\\$') //prints a dollar $ character\n\nprintln('\\\\') //prints a back slash \\ character\n"
},
{
"code": null,
"e": 5309,
"s": 5218,
"text": "The following escape sequences are supported in Kotlin: \\t, \\b, \\n, \\r, \\', \\\", \\\\ and \\$."
},
{
"code": null,
"e": 5457,
"s": 5309,
"text": "The String data type is used to store a sequence of characters. String values must be surrounded by double quotes (\" \") or triple quote (\"\"\" \"\"\")."
},
{
"code": null,
"e": 5570,
"s": 5457,
"text": "We have two kinds of string available in Kotlin - one is called Escaped String and another is called Raw String."
},
{
"code": null,
"e": 5684,
"s": 5570,
"text": "Escaped string is declared within double quote (\" \") and may contain escape characters like '\\n', '\\t', '\\b' etc."
},
{
"code": null,
"e": 5798,
"s": 5684,
"text": "Escaped string is declared within double quote (\" \") and may contain escape characters like '\\n', '\\t', '\\b' etc."
},
{
"code": null,
"e": 5921,
"s": 5798,
"text": "Raw string is declared within triple quote (\"\"\" \"\"\") and may contain multiple lines of text without any escape characters."
},
{
"code": null,
"e": 6044,
"s": 5921,
"text": "Raw string is declared within triple quote (\"\"\" \"\"\") and may contain multiple lines of text without any escape characters."
},
{
"code": null,
"e": 6303,
"s": 6044,
"text": "fun main(args: Array<String>) {\n val escapedString : String = \"I am escaped String!\\n\"\n var rawString :String = \"\"\"This is going to be a\n multi-line string and will\n not have any escape sequence\"\"\";\n\n print(escapedString)\n println(rawString)\n}\n"
},
{
"code": null,
"e": 6381,
"s": 6303,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 6487,
"s": 6381,
"text": "I am escaped String!\nThis is going to be a\n multi-line string and will\n not have any escape sequence\n"
},
{
"code": null,
"e": 6614,
"s": 6487,
"text": "Boolean is very simple like other programming languages. We have only two values for Boolean data type - either true or false."
},
{
"code": null,
"e": 6862,
"s": 6614,
"text": "fun main(args: Array<String>) {\n val A: Boolean = true // defining a variable with true value\n val B: Boolean = false // defining a variable with false value\n\n println(\"Value of variable A \"+ A )\n println(\"Value of variable B \"+ B )\n}\n"
},
{
"code": null,
"e": 6940,
"s": 6862,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 6992,
"s": 6940,
"text": "Value of variable A true\nValue of variable B false\n"
},
{
"code": null,
"e": 7074,
"s": 6992,
"text": "Boolean has a nullable counterpart Boolean? that can store a null value as below:"
},
{
"code": null,
"e": 7105,
"s": 7074,
"text": "val boolNull: Boolean? = null\n"
},
{
"code": null,
"e": 7276,
"s": 7105,
"text": "Kotlin arrays are a collection of homogeneous data. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value."
},
{
"code": null,
"e": 7425,
"s": 7276,
"text": "We will study array in a separate chapter, for now let's look at one example to define an array of integers and then access its one of the elements."
},
{
"code": null,
"e": 7565,
"s": 7425,
"text": "fun main(args: Array<String>) {\n val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5)\n println(\"Value at 3rd position : \" + numbers[2])\n}\n"
},
{
"code": null,
"e": 7643,
"s": 7565,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 7670,
"s": 7643,
"text": "Value at 3rd position : 3\n"
},
{
"code": null,
"e": 7917,
"s": 7670,
"text": "Type conversion is a process in which the value of one data type is converted into another type. Kotlin does not support direct conversion of one numeric data type to another, For example, it is not possible to convert an Int type to a Long type:"
},
{
"code": null,
"e": 8031,
"s": 7917,
"text": "fun main(args: Array<String>) {\n val x: Int = 100\n val y: Long = x // Not valid assignment\n\n println(y)\n}\n"
},
{
"code": null,
"e": 8109,
"s": 8031,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 8233,
"s": 8109,
"text": "main.kt:3:18: error: type mismatch: inferred type is Int but Long was expected\n val y: Long = x // Not valid assignment\n"
},
{
"code": null,
"e": 8317,
"s": 8233,
"text": "To convert a numeric data type to another type, Kotlin provides a set of functions:"
},
{
"code": null,
"e": 8326,
"s": 8317,
"text": "toByte()"
},
{
"code": null,
"e": 8335,
"s": 8326,
"text": "toByte()"
},
{
"code": null,
"e": 8345,
"s": 8335,
"text": "toShort()"
},
{
"code": null,
"e": 8355,
"s": 8345,
"text": "toShort()"
},
{
"code": null,
"e": 8363,
"s": 8355,
"text": "toInt()"
},
{
"code": null,
"e": 8371,
"s": 8363,
"text": "toInt()"
},
{
"code": null,
"e": 8380,
"s": 8371,
"text": "toLong()"
},
{
"code": null,
"e": 8389,
"s": 8380,
"text": "toLong()"
},
{
"code": null,
"e": 8399,
"s": 8389,
"text": "toFloat()"
},
{
"code": null,
"e": 8409,
"s": 8399,
"text": "toFloat()"
},
{
"code": null,
"e": 8420,
"s": 8409,
"text": "toDouble()"
},
{
"code": null,
"e": 8431,
"s": 8420,
"text": "toDouble()"
},
{
"code": null,
"e": 8440,
"s": 8431,
"text": "toChar()"
},
{
"code": null,
"e": 8449,
"s": 8440,
"text": "toChar()"
},
{
"code": null,
"e": 8511,
"s": 8449,
"text": "Now let's rewrite above example once again and try to run it:"
},
{
"code": null,
"e": 8609,
"s": 8511,
"text": "fun main(args: Array<String>) {\n val x: Int = 100\n val y: Long = x.toLong()\n\n println(y)\n}\n"
},
{
"code": null,
"e": 8687,
"s": 8609,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 8692,
"s": 8687,
"text": "100\n"
},
{
"code": null,
"e": 8747,
"s": 8692,
"text": "Q 1 - Can a Kotlin Boolean variable have a value of 0:"
},
{
"code": null,
"e": 8756,
"s": 8747,
"text": "A - True"
},
{
"code": null,
"e": 8766,
"s": 8756,
"text": "B - False"
},
{
"code": null,
"e": 8881,
"s": 8766,
"text": "No Kotlin Boolean variable can store either true or false values, no integer value is allowed in Boolean variable."
},
{
"code": null,
"e": 8966,
"s": 8881,
"text": "Q 2 - Which of the data type is used to define a variable PI to store the value 3.14"
},
{
"code": null,
"e": 8976,
"s": 8966,
"text": "A - Float"
},
{
"code": null,
"e": 8987,
"s": 8976,
"text": "B - Double"
},
{
"code": null,
"e": 8996,
"s": 8987,
"text": "C - Long"
},
{
"code": null,
"e": 9018,
"s": 8996,
"text": "D - None of the above"
},
{
"code": null,
"e": 9129,
"s": 9018,
"text": "We will use Double data type to define PI to store a value of 3.14. Floats are used to store values like 3.14F"
},
{
"code": null,
"e": 9186,
"s": 9129,
"text": "Q 3 - What could be the minimum length of Kotlin String?"
},
{
"code": null,
"e": 9205,
"s": 9186,
"text": "A - Zero character"
},
{
"code": null,
"e": 9221,
"s": 9205,
"text": "B - 1 character"
},
{
"code": null,
"e": 9236,
"s": 9221,
"text": "C - Null value"
},
{
"code": null,
"e": 9258,
"s": 9236,
"text": "D - None of the above"
},
{
"code": null,
"e": 9312,
"s": 9258,
"text": "We can define an empty string having zero characters."
},
{
"code": null,
"e": 9382,
"s": 9312,
"text": "Q 4 - Which of these are valid data types to hold integers in Kotlin?"
},
{
"code": null,
"e": 9409,
"s": 9382,
"text": "A - Byte, Short, Int, Long"
},
{
"code": null,
"e": 9436,
"s": 9409,
"text": "B - Byte, Int, Float, Long"
},
{
"code": null,
"e": 9466,
"s": 9436,
"text": "C - Short, Int, Long, Boolean"
},
{
"code": null,
"e": 9488,
"s": 9466,
"text": "D - None of the above"
},
{
"code": null,
"e": 9633,
"s": 9488,
"text": "This is the set of data types which can be used to define an integer (Byte, Short, Int, Long). Float and Boolean are not used to define integer."
},
{
"code": null,
"e": 9704,
"s": 9633,
"text": "Q 5 - Which of the following statement is true about Kotlin Data Type:"
},
{
"code": null,
"e": 9767,
"s": 9704,
"text": "A - Kotlin does not allow direct numeric data type conversion."
},
{
"code": null,
"e": 9859,
"s": 9767,
"text": "B - To convert a numeric data type to another type, you must use provided helper functions."
},
{
"code": null,
"e": 9942,
"s": 9859,
"text": "C - Int, Short, Float, Byte, Long, Double can be used to define Numeric Data types"
},
{
"code": null,
"e": 9963,
"s": 9942,
"text": "D - All of the above"
},
{
"code": null,
"e": 10024,
"s": 9963,
"text": "All the given statements are correct about Kotlin Data Types"
},
{
"code": null,
"e": 10059,
"s": 10024,
"text": "\n 68 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 10078,
"s": 10059,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 10113,
"s": 10078,
"text": "\n 71 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 10130,
"s": 10113,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 10165,
"s": 10130,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10182,
"s": 10165,
"text": " Mahmoud Ramadan"
},
{
"code": null,
"e": 10215,
"s": 10182,
"text": "\n 49 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 10231,
"s": 10215,
"text": " Catalin Stefan"
},
{
"code": null,
"e": 10266,
"s": 10231,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10286,
"s": 10266,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 10319,
"s": 10286,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10336,
"s": 10319,
"text": " CLEMENT OCHIENG"
},
{
"code": null,
"e": 10343,
"s": 10336,
"text": " Print"
},
{
"code": null,
"e": 10354,
"s": 10343,
"text": " Add Notes"
}
] |
Python | Split and Pass list as separate parameter - GeeksforGeeks
|
05 Sep, 2019
With the advent of programming paradigms, there has been need to modify the way one codes. One such paradigm is OOPS. In this, we have a technique called modularity, which stands for making different modules/functions which perform independent tasks in program. In this, we need to pass more than just variable, but a list as well. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using tuple()This task can be performed using the tuple(). In this, we convert the pair list to tuple and by this way we separate individual elements as variables, ready to be sent to function.
# Python3 code to demonstrate working of# Split and Pass list as separate parameter# using tuple() # Helper function for demonstrationdef pass_args(arg1, arg2): print("The first argument is : " + str(arg1)) print("The second argument is : " + str(arg2)) # initialize listtest_list = [4, 5] # printing original listprint("The original list is : " + str(test_list)) # Split and Pass list as separate parameter# using tuple()one, two = tuple(test_list)pass_args(one, two)
The original list is : [4, 5]
The first argument is : 4
The second argument is : 5
Method #2 : Using * operatorUsing * operator is the most recommended method to perform this task. The * operator unpacks the dual list into args and hence solving our problem.
# Python3 code to demonstrate working of# Split and Pass list as separate parameter# using * operator # Helper function for demonstrationdef pass_args(arg1, arg2): print("The first argument is : " + str(arg1)) print("The second argument is : " + str(arg2)) # initialize listtest_list = [4, 5] # printing original listprint("The original list is : " + str(test_list)) # Split and Pass list as separate parameter# using * operatorpass_args(*test_list)
The original list is : [4, 5]
The first argument is : 4
The second argument is : 5
Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
sum() function in Python
|
[
{
"code": null,
"e": 24296,
"s": 24268,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 24692,
"s": 24296,
"text": "With the advent of programming paradigms, there has been need to modify the way one codes. One such paradigm is OOPS. In this, we have a technique called modularity, which stands for making different modules/functions which perform independent tasks in program. In this, we need to pass more than just variable, but a list as well. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 24898,
"s": 24692,
"text": "Method #1 : Using tuple()This task can be performed using the tuple(). In this, we convert the pair list to tuple and by this way we separate individual elements as variables, ready to be sent to function."
},
{
"code": "# Python3 code to demonstrate working of# Split and Pass list as separate parameter# using tuple() # Helper function for demonstrationdef pass_args(arg1, arg2): print(\"The first argument is : \" + str(arg1)) print(\"The second argument is : \" + str(arg2)) # initialize listtest_list = [4, 5] # printing original listprint(\"The original list is : \" + str(test_list)) # Split and Pass list as separate parameter# using tuple()one, two = tuple(test_list)pass_args(one, two)",
"e": 25379,
"s": 24898,
"text": null
},
{
"code": null,
"e": 25463,
"s": 25379,
"text": "The original list is : [4, 5]\nThe first argument is : 4\nThe second argument is : 5\n"
},
{
"code": null,
"e": 25641,
"s": 25465,
"text": "Method #2 : Using * operatorUsing * operator is the most recommended method to perform this task. The * operator unpacks the dual list into args and hence solving our problem."
},
{
"code": "# Python3 code to demonstrate working of# Split and Pass list as separate parameter# using * operator # Helper function for demonstrationdef pass_args(arg1, arg2): print(\"The first argument is : \" + str(arg1)) print(\"The second argument is : \" + str(arg2)) # initialize listtest_list = [4, 5] # printing original listprint(\"The original list is : \" + str(test_list)) # Split and Pass list as separate parameter# using * operatorpass_args(*test_list)",
"e": 26103,
"s": 25641,
"text": null
},
{
"code": null,
"e": 26187,
"s": 26103,
"text": "The original list is : [4, 5]\nThe first argument is : 4\nThe second argument is : 5\n"
},
{
"code": null,
"e": 26208,
"s": 26187,
"text": "Python list-programs"
},
{
"code": null,
"e": 26215,
"s": 26208,
"text": "Python"
},
{
"code": null,
"e": 26313,
"s": 26215,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26322,
"s": 26313,
"text": "Comments"
},
{
"code": null,
"e": 26335,
"s": 26322,
"text": "Old Comments"
},
{
"code": null,
"e": 26353,
"s": 26335,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26385,
"s": 26353,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26407,
"s": 26385,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26449,
"s": 26407,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26475,
"s": 26449,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26512,
"s": 26475,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26556,
"s": 26512,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26612,
"s": 26556,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26667,
"s": 26612,
"text": "Selecting rows in pandas DataFrame based on conditions"
}
] |
Setting the same axis limits for all subplots in Matplotlib
|
To set the same axis limits for all subplots in matplotlib we can use subplot() method to create 4 subplots where nrows=2, ncols=2 having share of x and y axes.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Add a subplot to the current figure at index 1.
Add a subplot to the current figure at index 1.
Set the x and y axes view limit using set_xlim() and set_ylim() methods.
Set the x and y axes view limit using set_xlim() and set_ylim() methods.
Plot a line on axis 1 (step 2).
Plot a line on axis 1 (step 2).
Add a subplot to the current figure at index 2 with the same limit (step 3).
Add a subplot to the current figure at index 2 with the same limit (step 3).
Plot a line on axis 2.
Plot a line on axis 2.
Add a subplot to the current figure at index 3 with the same limit (step 3).
Add a subplot to the current figure at index 3 with the same limit (step 3).
Plot a line on axis 3.
Plot a line on axis 3.
Add a subplot to the current figure at index 4 with the same limit (step 3).
Add a subplot to the current figure at index 4 with the same limit (step 3).
Plot a line on axis 4.
Plot a line on axis 4.
To show the figure, use show() method.
To show the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
ax1 = plt.subplot(2, 2, 1)
ax1.set_xlim(left=0, right=5)
ax1.set_ylim(bottom=0, top=5)
ax1.plot([1, 4, 3])
ax2 = plt.subplot(2, 2, 2, sharey=ax1, sharex=ax1)
ax2.plot([3, 4, 1])
ax3 = plt.subplot(2, 2, 4, sharey=ax1, sharex=ax1)
ax3.plot([2, 4, 2])
ax4 = plt.subplot(2, 2, 3, sharey=ax1, sharex=ax1)
ax4.plot([4, 0, 4])
plt.show()
|
[
{
"code": null,
"e": 1223,
"s": 1062,
"text": "To set the same axis limits for all subplots in matplotlib we can use subplot() method to create 4 subplots where nrows=2, ncols=2 having share of x and y axes."
},
{
"code": null,
"e": 1299,
"s": 1223,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1375,
"s": 1299,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1423,
"s": 1375,
"text": "Add a subplot to the current figure at index 1."
},
{
"code": null,
"e": 1471,
"s": 1423,
"text": "Add a subplot to the current figure at index 1."
},
{
"code": null,
"e": 1544,
"s": 1471,
"text": "Set the x and y axes view limit using set_xlim() and set_ylim() methods."
},
{
"code": null,
"e": 1617,
"s": 1544,
"text": "Set the x and y axes view limit using set_xlim() and set_ylim() methods."
},
{
"code": null,
"e": 1649,
"s": 1617,
"text": "Plot a line on axis 1 (step 2)."
},
{
"code": null,
"e": 1681,
"s": 1649,
"text": "Plot a line on axis 1 (step 2)."
},
{
"code": null,
"e": 1758,
"s": 1681,
"text": "Add a subplot to the current figure at index 2 with the same limit (step 3)."
},
{
"code": null,
"e": 1835,
"s": 1758,
"text": "Add a subplot to the current figure at index 2 with the same limit (step 3)."
},
{
"code": null,
"e": 1858,
"s": 1835,
"text": "Plot a line on axis 2."
},
{
"code": null,
"e": 1881,
"s": 1858,
"text": "Plot a line on axis 2."
},
{
"code": null,
"e": 1958,
"s": 1881,
"text": "Add a subplot to the current figure at index 3 with the same limit (step 3)."
},
{
"code": null,
"e": 2035,
"s": 1958,
"text": "Add a subplot to the current figure at index 3 with the same limit (step 3)."
},
{
"code": null,
"e": 2058,
"s": 2035,
"text": "Plot a line on axis 3."
},
{
"code": null,
"e": 2081,
"s": 2058,
"text": "Plot a line on axis 3."
},
{
"code": null,
"e": 2158,
"s": 2081,
"text": "Add a subplot to the current figure at index 4 with the same limit (step 3)."
},
{
"code": null,
"e": 2235,
"s": 2158,
"text": "Add a subplot to the current figure at index 4 with the same limit (step 3)."
},
{
"code": null,
"e": 2258,
"s": 2235,
"text": "Plot a line on axis 4."
},
{
"code": null,
"e": 2281,
"s": 2258,
"text": "Plot a line on axis 4."
},
{
"code": null,
"e": 2320,
"s": 2281,
"text": "To show the figure, use show() method."
},
{
"code": null,
"e": 2359,
"s": 2320,
"text": "To show the figure, use show() method."
},
{
"code": null,
"e": 2814,
"s": 2359,
"text": "from matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nax1 = plt.subplot(2, 2, 1)\nax1.set_xlim(left=0, right=5)\nax1.set_ylim(bottom=0, top=5)\nax1.plot([1, 4, 3])\nax2 = plt.subplot(2, 2, 2, sharey=ax1, sharex=ax1)\nax2.plot([3, 4, 1])\nax3 = plt.subplot(2, 2, 4, sharey=ax1, sharex=ax1)\nax3.plot([2, 4, 2])\nax4 = plt.subplot(2, 2, 3, sharey=ax1, sharex=ax1)\nax4.plot([4, 0, 4])\nplt.show()"
}
] |
pthread_self() in C
|
Here we will see what will be the effect of pthread_self() in C. The pthread_self() function is used to get the ID of the current thread. This function can uniquely identify the existing threads. But if there are multiple threads, and one thread is completed, then that id can be reused. So for all running threads, the ids are unique.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* func(void* p) {
printf("From the function, the thread id = %d\n", pthread_self()); //get current thread id
pthread_exit(NULL);
return NULL;
}
main() {
pthread_t thread; // declare thread
pthread_create(&thread, NULL, func, NULL);
printf("From the main function, the thread id = %d\n", thread);
pthread_join(thread, NULL); //join with main thread
}
From the main function, the thread id = 1
From the function, the thread id = 1
|
[
{
"code": null,
"e": 1398,
"s": 1062,
"text": "Here we will see what will be the effect of pthread_self() in C. The pthread_self() function is used to get the ID of the current thread. This function can uniquely identify the existing threads. But if there are multiple threads, and one thread is completed, then that id can be reused. So for all running threads, the ids are unique."
},
{
"code": null,
"e": 1836,
"s": 1398,
"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <pthread.h>\nvoid* func(void* p) {\n printf(\"From the function, the thread id = %d\\n\", pthread_self()); //get current thread id\n pthread_exit(NULL);\n return NULL;\n}\nmain() {\n pthread_t thread; // declare thread\n pthread_create(&thread, NULL, func, NULL);\n printf(\"From the main function, the thread id = %d\\n\", thread);\n pthread_join(thread, NULL); //join with main thread\n}"
},
{
"code": null,
"e": 1915,
"s": 1836,
"text": "From the main function, the thread id = 1\nFrom the function, the thread id = 1"
}
] |
Installing Docker on Linux
|
To start the installation of Docker, we are going to use an Ubuntu instance. You can use Oracle Virtual Box to setup a virtual Linux instance, in case you don’t have it already.
The following screenshot shows a simple Ubuntu server which has been installed on Oracle Virtual Box. There is an OS user named demo which has been defined on the system having entire root access to the sever.
To install Docker, we need to follow the steps given below.
Step 1 − Before installing Docker, you first have to ensure that you have the right Linux kernel version running. Docker is only designed to run on Linux kernel version 3.8 and higher. We can do this by running the following command.
This method returns the system information about the Linux system.
uname -a
a − This is used to ensure that the system information is returned.
This method returns the following information on the Linux system −
kernel name
node name
kernel release
kernel version
machine
processor
hardware platform
operating system
uname –a
When we run above command, we will get the following result −
From the output, we can see that the Linux kernel version is 4.2.0-27 which is higher than version 3.8, so we are good to go.
Step 2 − You need to update the OS with the latest packages, which can be done via the following command −
apt-get
This method installs packages from the Internet on to the Linux system.
sudo apt-get update
sudo − The sudo command is used to ensure that the command runs with root access.
sudo − The sudo command is used to ensure that the command runs with root access.
update − The update option is used ensure that all packages are updated on the Linux system.
update − The update option is used ensure that all packages are updated on the Linux system.
None
sudo apt-get update
When we run the above command, we will get the following result −
This command will connect to the internet and download the latest system packages for Ubuntu.
Step 3 − The next step is to install the necessary certificates that will be required to work with the Docker site later on to download the necessary Docker packages. It can be done with the following command.
sudo apt-get install apt-transport-https ca-certificates
Step 4 − The next step is to add the new GPG key. This key is required to ensure that all data is encrypted when downloading the necessary packages for Docker.
The following command will download the key with the ID 58118E89F3A912897C070ADBF76221572C52609D from the keyserver hkp://ha.pool.sks-keyservers.net:80 and adds it to the adv keychain. Please note that this particular key is required to download the necessary Docker packages.
Step 5 − Next, depending on the version of Ubuntu you have, you will need to add the relevant site to the docker.list for the apt package manager, so that it will be able to detect the Docker packages from the Docker site and download them accordingly.
Precise 12.04 (LTS) ─ deb https://apt.dockerproject.org/repoubuntu-precise main
Precise 12.04 (LTS) ─ deb https://apt.dockerproject.org/repoubuntu-precise main
Trusty 14.04 (LTS) ─ deb https://apt.dockerproject.org/repo/ ubuntu-trusty main
Trusty 14.04 (LTS) ─ deb https://apt.dockerproject.org/repo/ ubuntu-trusty main
Wily 15.10 ─ deb https://apt.dockerproject.org/repo ubuntu-wily main
Wily 15.10 ─ deb https://apt.dockerproject.org/repo ubuntu-wily main
Xenial 16.04 (LTS) - https://apt.dockerproject.org/repo ubuntu-xenial main
Xenial 16.04 (LTS) - https://apt.dockerproject.org/repo ubuntu-xenial main
Since our OS is Ubuntu 14.04, we will use the Repository name as “deb https://apt.dockerproject.org/repoubuntu-trusty main”.
And then, we will need to add this repository to the docker.list as mentioned above.
echo "deb https://apt.dockerproject.org/repo ubuntu-trusty main”
| sudo tee /etc/apt/sources.list.d/docker.list
Step 6 − Next, we issue the apt-get update command to update the packages on the Ubuntu system.
Step 7 − If you want to verify that the package manager is pointing to the right repository, you can do it by issuing the apt-cache command.
apt-cache policy docker-engine
In the output, you will get the link to https://apt.dockerproject.org/repo/
Step 8 − Issue the apt-get update command to ensure all the packages on the local system are up to date.
Step 9 − For Ubuntu Trusty, Wily, and Xenial, we have to install the linux-image-extra-* kernel packages, which allows one to use the aufs storage driver. This driver is used by the newer versions of Docker.
It can be done by using the following command.
sudo apt-get install linux-image-extra-$(uname -r)
linux-image-extra-virtual
Step 10 − The final step is to install Docker and we can do this with the following command −
sudo apt-get install –y docker-engine
Here, apt-get uses the install option to download the Docker-engine image from the Docker website and get Docker installed.
The Docker-engine is the official package from the Docker Corporation for Ubuntu-based systems.
In the next section, we will see how to check for the version of Docker that was installed.
To see the version of Docker running, you can issue the following command −
docker version
version − It is used to ensure the Docker command returns the Docker version installed.
version − It is used to ensure the Docker command returns the Docker version installed.
The output will provide the various details of the Docker version installed on the system.
sudo docker version
When we run the above program, we will get the following result −
To see more information on the Docker running on the system, you can issue the following command −
docker info
info − It is used to ensure that the Docker command returns the detailed information on the Docker service installed.
info − It is used to ensure that the Docker command returns the detailed information on the Docker service installed.
The output will provide the various details of the Docker installed on the system such as −
Number of containers
Number of images
The storage driver used by Docker
The root directory used by Docker
The execution driver used by Docker
sudo docker info
When we run the above command, we will get the following result −
Docker has out-of-the-box support for Windows, but you need to have the following configuration in order to install Docker for Windows.
You can download Docker for Windows from − https://docs.docker.com/docker-for-windows/
Docker ToolBox has been designed for older versions of Windows, such as Windows 8.1 and Windows 7. You need to have the following configuration in order to install Docker for Windows.
You can download Docker ToolBox from − https://www.docker.com/products/docker-toolbox
70 Lectures
12 hours
Anshul Chauhan
41 Lectures
5 hours
AR Shankar
31 Lectures
3 hours
Abhilash Nelson
15 Lectures
2 hours
Harshit Srivastava, Pranjal Srivastava
33 Lectures
4 hours
Mumshad Mannambeth
13 Lectures
53 mins
Musab Zayadneh
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2518,
"s": 2340,
"text": "To start the installation of Docker, we are going to use an Ubuntu instance. You can use Oracle Virtual Box to setup a virtual Linux instance, in case you don’t have it already."
},
{
"code": null,
"e": 2728,
"s": 2518,
"text": "The following screenshot shows a simple Ubuntu server which has been installed on Oracle Virtual Box. There is an OS user named demo which has been defined on the system having entire root access to the sever."
},
{
"code": null,
"e": 2788,
"s": 2728,
"text": "To install Docker, we need to follow the steps given below."
},
{
"code": null,
"e": 3022,
"s": 2788,
"text": "Step 1 − Before installing Docker, you first have to ensure that you have the right Linux kernel version running. Docker is only designed to run on Linux kernel version 3.8 and higher. We can do this by running the following command."
},
{
"code": null,
"e": 3089,
"s": 3022,
"text": "This method returns the system information about the Linux system."
},
{
"code": null,
"e": 3099,
"s": 3089,
"text": "uname -a\n"
},
{
"code": null,
"e": 3167,
"s": 3099,
"text": "a − This is used to ensure that the system information is returned."
},
{
"code": null,
"e": 3235,
"s": 3167,
"text": "This method returns the following information on the Linux system −"
},
{
"code": null,
"e": 3247,
"s": 3235,
"text": "kernel name"
},
{
"code": null,
"e": 3257,
"s": 3247,
"text": "node name"
},
{
"code": null,
"e": 3272,
"s": 3257,
"text": "kernel release"
},
{
"code": null,
"e": 3287,
"s": 3272,
"text": "kernel version"
},
{
"code": null,
"e": 3295,
"s": 3287,
"text": "machine"
},
{
"code": null,
"e": 3305,
"s": 3295,
"text": "processor"
},
{
"code": null,
"e": 3323,
"s": 3305,
"text": "hardware platform"
},
{
"code": null,
"e": 3340,
"s": 3323,
"text": "operating system"
},
{
"code": null,
"e": 3350,
"s": 3340,
"text": "uname –a\n"
},
{
"code": null,
"e": 3412,
"s": 3350,
"text": "When we run above command, we will get the following result −"
},
{
"code": null,
"e": 3538,
"s": 3412,
"text": "From the output, we can see that the Linux kernel version is 4.2.0-27 which is higher than version 3.8, so we are good to go."
},
{
"code": null,
"e": 3645,
"s": 3538,
"text": "Step 2 − You need to update the OS with the latest packages, which can be done via the following command −"
},
{
"code": null,
"e": 3654,
"s": 3645,
"text": "apt-get\n"
},
{
"code": null,
"e": 3726,
"s": 3654,
"text": "This method installs packages from the Internet on to the Linux system."
},
{
"code": null,
"e": 3746,
"s": 3726,
"text": "sudo apt-get update"
},
{
"code": null,
"e": 3828,
"s": 3746,
"text": "sudo − The sudo command is used to ensure that the command runs with root access."
},
{
"code": null,
"e": 3910,
"s": 3828,
"text": "sudo − The sudo command is used to ensure that the command runs with root access."
},
{
"code": null,
"e": 4003,
"s": 3910,
"text": "update − The update option is used ensure that all packages are updated on the Linux system."
},
{
"code": null,
"e": 4096,
"s": 4003,
"text": "update − The update option is used ensure that all packages are updated on the Linux system."
},
{
"code": null,
"e": 4101,
"s": 4096,
"text": "None"
},
{
"code": null,
"e": 4122,
"s": 4101,
"text": "sudo apt-get update\n"
},
{
"code": null,
"e": 4188,
"s": 4122,
"text": "When we run the above command, we will get the following result −"
},
{
"code": null,
"e": 4282,
"s": 4188,
"text": "This command will connect to the internet and download the latest system packages for Ubuntu."
},
{
"code": null,
"e": 4492,
"s": 4282,
"text": "Step 3 − The next step is to install the necessary certificates that will be required to work with the Docker site later on to download the necessary Docker packages. It can be done with the following command."
},
{
"code": null,
"e": 4550,
"s": 4492,
"text": "sudo apt-get install apt-transport-https ca-certificates\n"
},
{
"code": null,
"e": 4710,
"s": 4550,
"text": "Step 4 − The next step is to add the new GPG key. This key is required to ensure that all data is encrypted when downloading the necessary packages for Docker."
},
{
"code": null,
"e": 4987,
"s": 4710,
"text": "The following command will download the key with the ID 58118E89F3A912897C070ADBF76221572C52609D from the keyserver hkp://ha.pool.sks-keyservers.net:80 and adds it to the adv keychain. Please note that this particular key is required to download the necessary Docker packages."
},
{
"code": null,
"e": 5240,
"s": 4987,
"text": "Step 5 − Next, depending on the version of Ubuntu you have, you will need to add the relevant site to the docker.list for the apt package manager, so that it will be able to detect the Docker packages from the Docker site and download them accordingly."
},
{
"code": null,
"e": 5320,
"s": 5240,
"text": "Precise 12.04 (LTS) ─ deb https://apt.dockerproject.org/repoubuntu-precise main"
},
{
"code": null,
"e": 5400,
"s": 5320,
"text": "Precise 12.04 (LTS) ─ deb https://apt.dockerproject.org/repoubuntu-precise main"
},
{
"code": null,
"e": 5480,
"s": 5400,
"text": "Trusty 14.04 (LTS) ─ deb https://apt.dockerproject.org/repo/ ubuntu-trusty main"
},
{
"code": null,
"e": 5560,
"s": 5480,
"text": "Trusty 14.04 (LTS) ─ deb https://apt.dockerproject.org/repo/ ubuntu-trusty main"
},
{
"code": null,
"e": 5631,
"s": 5560,
"text": "Wily 15.10 ─ deb https://apt.dockerproject.org/repo ubuntu-wily main "
},
{
"code": null,
"e": 5702,
"s": 5631,
"text": "Wily 15.10 ─ deb https://apt.dockerproject.org/repo ubuntu-wily main "
},
{
"code": null,
"e": 5777,
"s": 5702,
"text": "Xenial 16.04 (LTS) - https://apt.dockerproject.org/repo ubuntu-xenial main"
},
{
"code": null,
"e": 5852,
"s": 5777,
"text": "Xenial 16.04 (LTS) - https://apt.dockerproject.org/repo ubuntu-xenial main"
},
{
"code": null,
"e": 5977,
"s": 5852,
"text": "Since our OS is Ubuntu 14.04, we will use the Repository name as “deb https://apt.dockerproject.org/repoubuntu-trusty main”."
},
{
"code": null,
"e": 6062,
"s": 5977,
"text": "And then, we will need to add this repository to the docker.list as mentioned above."
},
{
"code": null,
"e": 6179,
"s": 6062,
"text": "echo \"deb https://apt.dockerproject.org/repo ubuntu-trusty main” \n | sudo tee /etc/apt/sources.list.d/docker.list\n"
},
{
"code": null,
"e": 6275,
"s": 6179,
"text": "Step 6 − Next, we issue the apt-get update command to update the packages on the Ubuntu system."
},
{
"code": null,
"e": 6416,
"s": 6275,
"text": "Step 7 − If you want to verify that the package manager is pointing to the right repository, you can do it by issuing the apt-cache command."
},
{
"code": null,
"e": 6448,
"s": 6416,
"text": "apt-cache policy docker-engine\n"
},
{
"code": null,
"e": 6524,
"s": 6448,
"text": "In the output, you will get the link to https://apt.dockerproject.org/repo/"
},
{
"code": null,
"e": 6630,
"s": 6524,
"text": "Step 8 − Issue the apt-get update command to ensure all the packages on the local system are up to date."
},
{
"code": null,
"e": 6838,
"s": 6630,
"text": "Step 9 − For Ubuntu Trusty, Wily, and Xenial, we have to install the linux-image-extra-* kernel packages, which allows one to use the aufs storage driver. This driver is used by the newer versions of Docker."
},
{
"code": null,
"e": 6885,
"s": 6838,
"text": "It can be done by using the following command."
},
{
"code": null,
"e": 6967,
"s": 6885,
"text": "sudo apt-get install linux-image-extra-$(uname -r) \n linux-image-extra-virtual\n"
},
{
"code": null,
"e": 7061,
"s": 6967,
"text": "Step 10 − The final step is to install Docker and we can do this with the following command −"
},
{
"code": null,
"e": 7100,
"s": 7061,
"text": "sudo apt-get install –y docker-engine\n"
},
{
"code": null,
"e": 7224,
"s": 7100,
"text": "Here, apt-get uses the install option to download the Docker-engine image from the Docker website and get Docker installed."
},
{
"code": null,
"e": 7320,
"s": 7224,
"text": "The Docker-engine is the official package from the Docker Corporation for Ubuntu-based systems."
},
{
"code": null,
"e": 7412,
"s": 7320,
"text": "In the next section, we will see how to check for the version of Docker that was installed."
},
{
"code": null,
"e": 7488,
"s": 7412,
"text": "To see the version of Docker running, you can issue the following command −"
},
{
"code": null,
"e": 7505,
"s": 7488,
"text": "docker version \n"
},
{
"code": null,
"e": 7593,
"s": 7505,
"text": "version − It is used to ensure the Docker command returns the Docker version installed."
},
{
"code": null,
"e": 7681,
"s": 7593,
"text": "version − It is used to ensure the Docker command returns the Docker version installed."
},
{
"code": null,
"e": 7772,
"s": 7681,
"text": "The output will provide the various details of the Docker version installed on the system."
},
{
"code": null,
"e": 7794,
"s": 7772,
"text": "sudo docker version \n"
},
{
"code": null,
"e": 7860,
"s": 7794,
"text": "When we run the above program, we will get the following result −"
},
{
"code": null,
"e": 7959,
"s": 7860,
"text": "To see more information on the Docker running on the system, you can issue the following command −"
},
{
"code": null,
"e": 7972,
"s": 7959,
"text": "docker info\n"
},
{
"code": null,
"e": 8090,
"s": 7972,
"text": "info − It is used to ensure that the Docker command returns the detailed information on the Docker service installed."
},
{
"code": null,
"e": 8208,
"s": 8090,
"text": "info − It is used to ensure that the Docker command returns the detailed information on the Docker service installed."
},
{
"code": null,
"e": 8300,
"s": 8208,
"text": "The output will provide the various details of the Docker installed on the system such as −"
},
{
"code": null,
"e": 8321,
"s": 8300,
"text": "Number of containers"
},
{
"code": null,
"e": 8338,
"s": 8321,
"text": "Number of images"
},
{
"code": null,
"e": 8372,
"s": 8338,
"text": "The storage driver used by Docker"
},
{
"code": null,
"e": 8406,
"s": 8372,
"text": "The root directory used by Docker"
},
{
"code": null,
"e": 8442,
"s": 8406,
"text": "The execution driver used by Docker"
},
{
"code": null,
"e": 8459,
"s": 8442,
"text": "sudo docker info"
},
{
"code": null,
"e": 8525,
"s": 8459,
"text": "When we run the above command, we will get the following result −"
},
{
"code": null,
"e": 8661,
"s": 8525,
"text": "Docker has out-of-the-box support for Windows, but you need to have the following configuration in order to install Docker for Windows."
},
{
"code": null,
"e": 8748,
"s": 8661,
"text": "You can download Docker for Windows from − https://docs.docker.com/docker-for-windows/"
},
{
"code": null,
"e": 8932,
"s": 8748,
"text": "Docker ToolBox has been designed for older versions of Windows, such as Windows 8.1 and Windows 7. You need to have the following configuration in order to install Docker for Windows."
},
{
"code": null,
"e": 9018,
"s": 8932,
"text": "You can download Docker ToolBox from − https://www.docker.com/products/docker-toolbox"
},
{
"code": null,
"e": 9052,
"s": 9018,
"text": "\n 70 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 9068,
"s": 9052,
"text": " Anshul Chauhan"
},
{
"code": null,
"e": 9101,
"s": 9068,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 9113,
"s": 9101,
"text": " AR Shankar"
},
{
"code": null,
"e": 9146,
"s": 9113,
"text": "\n 31 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 9163,
"s": 9146,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9196,
"s": 9163,
"text": "\n 15 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9236,
"s": 9196,
"text": " Harshit Srivastava, Pranjal Srivastava"
},
{
"code": null,
"e": 9269,
"s": 9236,
"text": "\n 33 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 9289,
"s": 9269,
"text": " Mumshad Mannambeth"
},
{
"code": null,
"e": 9321,
"s": 9289,
"text": "\n 13 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 9337,
"s": 9321,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 9344,
"s": 9337,
"text": " Print"
},
{
"code": null,
"e": 9355,
"s": 9344,
"text": " Add Notes"
}
] |
C# | IsNullOrEmpty() Method - GeeksforGeeks
|
01 Apr, 2019
In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.Empty (A constant for empty strings).
Syntax:
public static bool IsNullOrEmpty(String str)
Explanation: This method will take a parameter which is of type System.String and this method will returns a boolean value. If the str parameter is null or an empty string (“”) then return True otherwise return False.
Example:
Input : str = null // initialize by null value
String.IsNullOrEmpty(str)
Output: True
Input : str = String.Empty // initialize by empty value
String.IsNullOrEmpty(str)
Output: True
Program: To demonstrate the working of the IsNullOrEmpty() Method :
// C# program to illustrate // IsNullOrEmpty() Methodusing System;class Geeks { // Main Method public static void Main(string[] args) { string s1 = "GeeksforGeeks"; // or declare String s2.Empty; string s2 = ""; string s3 = null; // for String value Geeks, return true bool b1 = string.IsNullOrEmpty(s1); // For String value Empty or "", return true bool b2 = string.IsNullOrEmpty(s2); // For String value null, return true bool b3 = string.IsNullOrEmpty(s3); Console.WriteLine(b1); Console.WriteLine(b2); Console.WriteLine(b3); }}
False
True
True
Note: IsNullOrEmpty method enables to check whether a String is null or its value is Empty and its alternative code can be as follows:
return s == null || s == String.Empty;
Program: To demonstrate IsNullOrEmpty() method’s alternative
// C# program to illustrate the // similar method for IsNullOrEmpty()using System;class Geeks { // to make similar method as IsNullOrEmpty public static bool check(string s) { return (s == null || s == String.Empty) ? true : false; } // Main Method public static void Main(string[] args) { string s1 = "GeeksforGeeks"; // or declare String s2.Empty; string s2 = ""; string s3 = null; bool b1 = check(s1); bool b2 = check(s2); bool b3 = check(s3); // same output as above program Console.WriteLine(b1); Console.WriteLine(b2); Console.WriteLine(b3); }}
False
True
True
Reference: https://msdn.microsoft.com/en-us/library/system.string.isnullorempty(v=vs.110).aspx
AlanFitzgerald
CSharp-method
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Class and Object
Difference between Ref and Out keywords in C#
C# | Constructors
Introduction to .NET Framework
Extension Method in C#
C# | Delegates
C# | Abstract Classes
C# | Data Types
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
|
[
{
"code": null,
"e": 24371,
"s": 24343,
"text": "\n01 Apr, 2019"
},
{
"code": null,
"e": 24642,
"s": 24371,
"text": "In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.Empty (A constant for empty strings)."
},
{
"code": null,
"e": 24650,
"s": 24642,
"text": "Syntax:"
},
{
"code": null,
"e": 24698,
"s": 24650,
"text": "public static bool IsNullOrEmpty(String str) \n"
},
{
"code": null,
"e": 24916,
"s": 24698,
"text": "Explanation: This method will take a parameter which is of type System.String and this method will returns a boolean value. If the str parameter is null or an empty string (“”) then return True otherwise return False."
},
{
"code": null,
"e": 24925,
"s": 24916,
"text": "Example:"
},
{
"code": null,
"e": 25135,
"s": 24925,
"text": "Input : str = null // initialize by null value\n String.IsNullOrEmpty(str)\nOutput: True\n\nInput : str = String.Empty // initialize by empty value\n String.IsNullOrEmpty(str)\nOutput: True\n"
},
{
"code": null,
"e": 25203,
"s": 25135,
"text": "Program: To demonstrate the working of the IsNullOrEmpty() Method :"
},
{
"code": "// C# program to illustrate // IsNullOrEmpty() Methodusing System;class Geeks { // Main Method public static void Main(string[] args) { string s1 = \"GeeksforGeeks\"; // or declare String s2.Empty; string s2 = \"\"; string s3 = null; // for String value Geeks, return true bool b1 = string.IsNullOrEmpty(s1); // For String value Empty or \"\", return true bool b2 = string.IsNullOrEmpty(s2); // For String value null, return true bool b3 = string.IsNullOrEmpty(s3); Console.WriteLine(b1); Console.WriteLine(b2); Console.WriteLine(b3); }}",
"e": 25859,
"s": 25203,
"text": null
},
{
"code": null,
"e": 25876,
"s": 25859,
"text": "False\nTrue\nTrue\n"
},
{
"code": null,
"e": 26011,
"s": 25876,
"text": "Note: IsNullOrEmpty method enables to check whether a String is null or its value is Empty and its alternative code can be as follows:"
},
{
"code": null,
"e": 26052,
"s": 26011,
"text": "return s == null || s == String.Empty;\n"
},
{
"code": null,
"e": 26113,
"s": 26052,
"text": "Program: To demonstrate IsNullOrEmpty() method’s alternative"
},
{
"code": "// C# program to illustrate the // similar method for IsNullOrEmpty()using System;class Geeks { // to make similar method as IsNullOrEmpty public static bool check(string s) { return (s == null || s == String.Empty) ? true : false; } // Main Method public static void Main(string[] args) { string s1 = \"GeeksforGeeks\"; // or declare String s2.Empty; string s2 = \"\"; string s3 = null; bool b1 = check(s1); bool b2 = check(s2); bool b3 = check(s3); // same output as above program Console.WriteLine(b1); Console.WriteLine(b2); Console.WriteLine(b3); }}",
"e": 26783,
"s": 26113,
"text": null
},
{
"code": null,
"e": 26800,
"s": 26783,
"text": "False\nTrue\nTrue\n"
},
{
"code": null,
"e": 26895,
"s": 26800,
"text": "Reference: https://msdn.microsoft.com/en-us/library/system.string.isnullorempty(v=vs.110).aspx"
},
{
"code": null,
"e": 26910,
"s": 26895,
"text": "AlanFitzgerald"
},
{
"code": null,
"e": 26924,
"s": 26910,
"text": "CSharp-method"
},
{
"code": null,
"e": 26938,
"s": 26924,
"text": "CSharp-string"
},
{
"code": null,
"e": 26941,
"s": 26938,
"text": "C#"
},
{
"code": null,
"e": 27039,
"s": 26941,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27048,
"s": 27039,
"text": "Comments"
},
{
"code": null,
"e": 27061,
"s": 27048,
"text": "Old Comments"
},
{
"code": null,
"e": 27083,
"s": 27061,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 27129,
"s": 27083,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 27147,
"s": 27129,
"text": "C# | Constructors"
},
{
"code": null,
"e": 27178,
"s": 27147,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 27201,
"s": 27178,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27216,
"s": 27201,
"text": "C# | Delegates"
},
{
"code": null,
"e": 27238,
"s": 27216,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 27254,
"s": 27238,
"text": "C# | Data Types"
},
{
"code": null,
"e": 27282,
"s": 27254,
"text": "HashSet in C# with Examples"
}
] |
Finding 'k' such that its modulus with each array element is same - GeeksforGeeks
|
23 Jun, 2021
Given an array of n integers .We need to find all ‘k’ such that
arr[0] % k = arr[1] % k = ....... = arr[n-1] % k
Examples:
Input : arr[] = {6, 38, 34}
Output : 1 2 4
6%1 = 38%1 = 34%1 = 0
6%2 = 38%2 = 34%2 = 0
6%4 = 38%4 = 34%2 = 2
Input : arr[] = {3, 2}
Output : 1
Suppose the array contains only two elements a and b (b>a). So we can write b = a + d where d is a positive integer and ‘k’ be a number such that b%k = a%k.
(a + d)%k = a%k
a%k + d%k = a%k
d%k = 0
Now what we get from the above calculation is that ‘k’ should be a divisor of difference between the two numbers. Now what we have to do when we have an array of integers
Find out the difference ‘d’ between maximum and minimum element of the arrayFind out all the divisors of ‘d’Step 3: For each divisor check if arr[i]%divisor(d) is same or not .if it is same print it.
Find out the difference ‘d’ between maximum and minimum element of the array
Find out all the divisors of ‘d’
Step 3: For each divisor check if arr[i]%divisor(d) is same or not .if it is same print it.
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of finding all k// such that arr[i]%k is same for each i#include<bits/stdc++.h>using namespace std; // Prints all k such that arr[i]%k is same for all ivoid printEqualModNumbers (int arr[], int n){ // sort the numbers sort(arr, arr + n); // max difference will be the difference between // first and last element of sorted array int d = arr[n-1] - arr[0]; // Case when all the array elements are same if(d==0){ cout<<"Infinite solution"; return; } // Find all divisors of d and store in // a vector v[] vector <int> v; for (int i=1; i*i<=d; i++) { if (d%i == 0) { v.push_back(i); if (i != d/i) v.push_back(d/i); } } // check for each v[i] if its modulus with // each array element is same or not for (int i=0; i<v.size(); i++) { int temp = arr[0]%v[i]; // checking for each array element if // its modulus with k is equal to k or not int j; for (j=1; j<n; j++) if (arr[j] % v[i] != temp) break; // if check is true print v[i] if (j == n) cout << v[i] <<" "; }} // Driver functionint main(){ int arr[] = {38, 6, 34}; int n = sizeof(arr)/sizeof(arr[0]); printEqualModNumbers(arr, n); return 0;}
// Java implementation of finding all k// such that arr[i]%k is same for each i import java.util.Arrays;import java.util.Vector; class Test{ // Prints all k such that arr[i]%k is same for all i static void printEqualModNumbers (int arr[], int n) { // sort the numbers Arrays.sort(arr); // max difference will be the difference between // first and last element of sorted array int d = arr[n-1] - arr[0]; // Case when all the array elements are same if(d==0){ System.out.println("Infinite solution"); return; } // Find all divisors of d and store in // a vector v[] Vector<Integer> v = new Vector<>(); for (int i=1; i*i<=d; i++) { if (d%i == 0) { v.add(i); if (i != d/i) v.add(d/i); } } // check for each v[i] if its modulus with // each array element is same or not for (int i=0; i<v.size(); i++) { int temp = arr[0]%v.get(i); // checking for each array element if // its modulus with k is equal to k or not int j; for (j=1; j<n; j++) if (arr[j] % v.get(i) != temp) break; // if check is true print v[i] if (j == n) System.out.print(v.get(i) + " "); } } // Driver method public static void main(String args[]) { int arr[] = {38, 6, 34}; printEqualModNumbers(arr, arr.length); }}
# Python3 implementation of finding all k# such that arr[i]%k is same for each i # Prints all k such that arr[i]%k is# same for all idef printEqualModNumbers(arr, n): # sort the numbers arr.sort(); # max difference will be the difference # between first and last element of # sorted array d = arr[n - 1] - arr[0]; // Case when all the array elements are same if(d==0): print("Infinite solution") return # Find all divisors of d and store # in a vector v[] v = []; i = 1; while (i * i <= d): if (d % i == 0): v.append(i); if (i != d / i): v.append(d / i); i += 1; # check for each v[i] if its modulus with # each array element is same or not for i in range(len(v)): temp = arr[0] % v[i]; # checking for each array element if # its modulus with k is equal to k or not j = 1; while (j < n): if (arr[j] % v[i] != temp): break; j += 1; # if check is true print v[i] if (j == n): print(v[i], end = " "); # Driver Codearr = [38, 6, 34];printEqualModNumbers(arr, len(arr)); # This code is contributed by mits
// C# implementation of finding all k// such that arr[i]%k is same for each iusing System;using System.Collections;class Test{ // Prints all k such that arr[i]%k is same for all i static void printEqualModNumbers (int []arr, int n) { // sort the numbers Array.Sort(arr); // max difference will be the difference between // first and last element of sorted array int d = arr[n-1] - arr[0]; // Case when all the array elements are same if(d==0){ Console.write("Infinite solution"); return; } // Find all divisors of d and store in // a vector v[] ArrayList v = new ArrayList(); for (int i=1; i*i<=d; i++) { if (d%i == 0) { v.Add(i); if (i != d/i) v.Add(d/i); } } // check for each v[i] if its modulus with // each array element is same or not for (int i=0; i<v.Count; i++) { int temp = arr[0]%(int)v[i]; // checking for each array element if // its modulus with k is equal to k or not int j; for (j=1; j<n; j++) if (arr[j] % (int)v[i] != temp) break; // if check is true print v[i] if (j == n) Console.Write(v[i] + " "); } } // Driver method public static void Main() { int []arr = {38, 6, 34}; printEqualModNumbers(arr, arr.Length); }}// This code is contributed by mits
<?php// PHP implementation of finding all k// such that arr[i]%k is same for each i // Prints all k such that arr[i]%k is same for all i function printEqualModNumbers ($arr, $n) { // sort the numbers sort($arr); // max difference will be the difference between // first and last element of sorted array $d = $arr[$n-1] - $arr[0]; // Case when all the array elements are same if(d==0){ print("Infinite solution"); return; } // Find all divisors of d and store in // a vector v[] $v = array(); for ($i=1; $i*$i<=$d; $i++) { if ($d%$i == 0) { array_push($v,$i); if ($i != $d/$i) array_push($v,$d/$i); } } // check for each v[i] if its modulus with // each array element is same or not for ($i=0; $i<count($v); $i++) { $temp = $arr[0]%$v[$i]; // checking for each array element if // its modulus with k is equal to k or not $j=1; for (; $j<$n; $j++) if ($arr[$j] % $v[$i] != $temp) break; // if check is true print v[i] if ($j == $n) print($v[$i]." "); } } // Driver method $arr = array(38, 6, 34); printEqualModNumbers($arr, count($arr)); // This code is contributed by mits?>
<script> // JavaScript implementation of finding all k// such that arr[i]%k is same for each i // Prints all k such that arr[i]%k is same for all i function printEqualModNumbers (arr, n) { // sort the numbers arr.sort((a, b) => a - b); // max difference will be the difference between // first and last element of sorted array d = arr[n-1] - arr[0]; // Case when all the array elements are same if(d==0){ document.write("Infinite solution"); return; } // Find all divisors of d and store in // a vector v[] v = new Array(); for (i=1; i*i<=d; i++) { if (d%i == 0) { v.push(i); if (i != d/i) v.push(d/i); } } // check for each v[i] if its modulus with // each array element is same or not for (i=0; i< v.length; i++) { temp = arr[0]%v[i]; // checking for each array element if // its modulus with k is equal to k or not j=1; for (; j<n; j++) if (arr[j] % v[i] != temp) break; // if check is true print v[i] if (j == n) document.write(v[i] + " "); } } // Driver method let arr = new Array(38, 6, 34); printEqualModNumbers(arr, arr.length); // This code is contributed by _saurabh_jaiswal </script>
Output:
1 2 4
This article is contributed by Ayush Jha. 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.
Mithun Kumar
gjaiswal108
_saurabh_jaiswal
Modular Arithmetic
Arrays
Mathematical
Arrays
Mathematical
Modular Arithmetic
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
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
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": 25342,
"s": 25314,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 25407,
"s": 25342,
"text": "Given an array of n integers .We need to find all ‘k’ such that "
},
{
"code": null,
"e": 25457,
"s": 25407,
"text": "arr[0] % k = arr[1] % k = ....... = arr[n-1] % k "
},
{
"code": null,
"e": 25469,
"s": 25457,
"text": "Examples: "
},
{
"code": null,
"e": 25639,
"s": 25469,
"text": "Input : arr[] = {6, 38, 34}\nOutput : 1 2 4\n 6%1 = 38%1 = 34%1 = 0\n 6%2 = 38%2 = 34%2 = 0\n 6%4 = 38%4 = 34%2 = 2\n\nInput : arr[] = {3, 2}\nOutput : 1"
},
{
"code": null,
"e": 25799,
"s": 25641,
"text": "Suppose the array contains only two elements a and b (b>a). So we can write b = a + d where d is a positive integer and ‘k’ be a number such that b%k = a%k. "
},
{
"code": null,
"e": 25840,
"s": 25799,
"text": "(a + d)%k = a%k\na%k + d%k = a%k \nd%k = 0"
},
{
"code": null,
"e": 26013,
"s": 25840,
"text": "Now what we get from the above calculation is that ‘k’ should be a divisor of difference between the two numbers. Now what we have to do when we have an array of integers "
},
{
"code": null,
"e": 26213,
"s": 26013,
"text": "Find out the difference ‘d’ between maximum and minimum element of the arrayFind out all the divisors of ‘d’Step 3: For each divisor check if arr[i]%divisor(d) is same or not .if it is same print it."
},
{
"code": null,
"e": 26290,
"s": 26213,
"text": "Find out the difference ‘d’ between maximum and minimum element of the array"
},
{
"code": null,
"e": 26323,
"s": 26290,
"text": "Find out all the divisors of ‘d’"
},
{
"code": null,
"e": 26415,
"s": 26323,
"text": "Step 3: For each divisor check if arr[i]%divisor(d) is same or not .if it is same print it."
},
{
"code": null,
"e": 26421,
"s": 26417,
"text": "C++"
},
{
"code": null,
"e": 26426,
"s": 26421,
"text": "Java"
},
{
"code": null,
"e": 26434,
"s": 26426,
"text": "Python3"
},
{
"code": null,
"e": 26437,
"s": 26434,
"text": "C#"
},
{
"code": null,
"e": 26441,
"s": 26437,
"text": "PHP"
},
{
"code": null,
"e": 26452,
"s": 26441,
"text": "Javascript"
},
{
"code": "// C++ implementation of finding all k// such that arr[i]%k is same for each i#include<bits/stdc++.h>using namespace std; // Prints all k such that arr[i]%k is same for all ivoid printEqualModNumbers (int arr[], int n){ // sort the numbers sort(arr, arr + n); // max difference will be the difference between // first and last element of sorted array int d = arr[n-1] - arr[0]; // Case when all the array elements are same if(d==0){ cout<<\"Infinite solution\"; return; } // Find all divisors of d and store in // a vector v[] vector <int> v; for (int i=1; i*i<=d; i++) { if (d%i == 0) { v.push_back(i); if (i != d/i) v.push_back(d/i); } } // check for each v[i] if its modulus with // each array element is same or not for (int i=0; i<v.size(); i++) { int temp = arr[0]%v[i]; // checking for each array element if // its modulus with k is equal to k or not int j; for (j=1; j<n; j++) if (arr[j] % v[i] != temp) break; // if check is true print v[i] if (j == n) cout << v[i] <<\" \"; }} // Driver functionint main(){ int arr[] = {38, 6, 34}; int n = sizeof(arr)/sizeof(arr[0]); printEqualModNumbers(arr, n); return 0;}",
"e": 27804,
"s": 26452,
"text": null
},
{
"code": "// Java implementation of finding all k// such that arr[i]%k is same for each i import java.util.Arrays;import java.util.Vector; class Test{ // Prints all k such that arr[i]%k is same for all i static void printEqualModNumbers (int arr[], int n) { // sort the numbers Arrays.sort(arr); // max difference will be the difference between // first and last element of sorted array int d = arr[n-1] - arr[0]; // Case when all the array elements are same if(d==0){ System.out.println(\"Infinite solution\"); return; } // Find all divisors of d and store in // a vector v[] Vector<Integer> v = new Vector<>(); for (int i=1; i*i<=d; i++) { if (d%i == 0) { v.add(i); if (i != d/i) v.add(d/i); } } // check for each v[i] if its modulus with // each array element is same or not for (int i=0; i<v.size(); i++) { int temp = arr[0]%v.get(i); // checking for each array element if // its modulus with k is equal to k or not int j; for (j=1; j<n; j++) if (arr[j] % v.get(i) != temp) break; // if check is true print v[i] if (j == n) System.out.print(v.get(i) + \" \"); } } // Driver method public static void main(String args[]) { int arr[] = {38, 6, 34}; printEqualModNumbers(arr, arr.length); }}",
"e": 29423,
"s": 27804,
"text": null
},
{
"code": "# Python3 implementation of finding all k# such that arr[i]%k is same for each i # Prints all k such that arr[i]%k is# same for all idef printEqualModNumbers(arr, n): # sort the numbers arr.sort(); # max difference will be the difference # between first and last element of # sorted array d = arr[n - 1] - arr[0]; // Case when all the array elements are same if(d==0): print(\"Infinite solution\") return # Find all divisors of d and store # in a vector v[] v = []; i = 1; while (i * i <= d): if (d % i == 0): v.append(i); if (i != d / i): v.append(d / i); i += 1; # check for each v[i] if its modulus with # each array element is same or not for i in range(len(v)): temp = arr[0] % v[i]; # checking for each array element if # its modulus with k is equal to k or not j = 1; while (j < n): if (arr[j] % v[i] != temp): break; j += 1; # if check is true print v[i] if (j == n): print(v[i], end = \" \"); # Driver Codearr = [38, 6, 34];printEqualModNumbers(arr, len(arr)); # This code is contributed by mits",
"e": 30680,
"s": 29423,
"text": null
},
{
"code": "// C# implementation of finding all k// such that arr[i]%k is same for each iusing System;using System.Collections;class Test{ // Prints all k such that arr[i]%k is same for all i static void printEqualModNumbers (int []arr, int n) { // sort the numbers Array.Sort(arr); // max difference will be the difference between // first and last element of sorted array int d = arr[n-1] - arr[0]; // Case when all the array elements are same if(d==0){ Console.write(\"Infinite solution\"); return; } // Find all divisors of d and store in // a vector v[] ArrayList v = new ArrayList(); for (int i=1; i*i<=d; i++) { if (d%i == 0) { v.Add(i); if (i != d/i) v.Add(d/i); } } // check for each v[i] if its modulus with // each array element is same or not for (int i=0; i<v.Count; i++) { int temp = arr[0]%(int)v[i]; // checking for each array element if // its modulus with k is equal to k or not int j; for (j=1; j<n; j++) if (arr[j] % (int)v[i] != temp) break; // if check is true print v[i] if (j == n) Console.Write(v[i] + \" \"); } } // Driver method public static void Main() { int []arr = {38, 6, 34}; printEqualModNumbers(arr, arr.Length); }}// This code is contributed by mits",
"e": 32285,
"s": 30680,
"text": null
},
{
"code": "<?php// PHP implementation of finding all k// such that arr[i]%k is same for each i // Prints all k such that arr[i]%k is same for all i function printEqualModNumbers ($arr, $n) { // sort the numbers sort($arr); // max difference will be the difference between // first and last element of sorted array $d = $arr[$n-1] - $arr[0]; // Case when all the array elements are same if(d==0){ print(\"Infinite solution\"); return; } // Find all divisors of d and store in // a vector v[] $v = array(); for ($i=1; $i*$i<=$d; $i++) { if ($d%$i == 0) { array_push($v,$i); if ($i != $d/$i) array_push($v,$d/$i); } } // check for each v[i] if its modulus with // each array element is same or not for ($i=0; $i<count($v); $i++) { $temp = $arr[0]%$v[$i]; // checking for each array element if // its modulus with k is equal to k or not $j=1; for (; $j<$n; $j++) if ($arr[$j] % $v[$i] != $temp) break; // if check is true print v[i] if ($j == $n) print($v[$i].\" \"); } } // Driver method $arr = array(38, 6, 34); printEqualModNumbers($arr, count($arr)); // This code is contributed by mits?>",
"e": 33799,
"s": 32285,
"text": null
},
{
"code": "<script> // JavaScript implementation of finding all k// such that arr[i]%k is same for each i // Prints all k such that arr[i]%k is same for all i function printEqualModNumbers (arr, n) { // sort the numbers arr.sort((a, b) => a - b); // max difference will be the difference between // first and last element of sorted array d = arr[n-1] - arr[0]; // Case when all the array elements are same if(d==0){ document.write(\"Infinite solution\"); return; } // Find all divisors of d and store in // a vector v[] v = new Array(); for (i=1; i*i<=d; i++) { if (d%i == 0) { v.push(i); if (i != d/i) v.push(d/i); } } // check for each v[i] if its modulus with // each array element is same or not for (i=0; i< v.length; i++) { temp = arr[0]%v[i]; // checking for each array element if // its modulus with k is equal to k or not j=1; for (; j<n; j++) if (arr[j] % v[i] != temp) break; // if check is true print v[i] if (j == n) document.write(v[i] + \" \"); } } // Driver method let arr = new Array(38, 6, 34); printEqualModNumbers(arr, arr.length); // This code is contributed by _saurabh_jaiswal </script>",
"e": 35334,
"s": 33799,
"text": null
},
{
"code": null,
"e": 35344,
"s": 35334,
"text": "Output: "
},
{
"code": null,
"e": 35351,
"s": 35344,
"text": "1 2 4 "
},
{
"code": null,
"e": 35769,
"s": 35351,
"text": "This article is contributed by Ayush Jha. 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": 35782,
"s": 35769,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 35794,
"s": 35782,
"text": "gjaiswal108"
},
{
"code": null,
"e": 35811,
"s": 35794,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 35830,
"s": 35811,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 35837,
"s": 35830,
"text": "Arrays"
},
{
"code": null,
"e": 35850,
"s": 35837,
"text": "Mathematical"
},
{
"code": null,
"e": 35857,
"s": 35850,
"text": "Arrays"
},
{
"code": null,
"e": 35870,
"s": 35857,
"text": "Mathematical"
},
{
"code": null,
"e": 35889,
"s": 35870,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 35987,
"s": 35889,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36055,
"s": 35987,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 36103,
"s": 36055,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 36147,
"s": 36103,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 36179,
"s": 36147,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 36202,
"s": 36179,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 36232,
"s": 36202,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 36292,
"s": 36232,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 36307,
"s": 36292,
"text": "C++ Data Types"
},
{
"code": null,
"e": 36350,
"s": 36307,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Alternative to Multiple OR Operators in JavaScript - GeeksforGeeks
|
20 Oct, 2021
In this article, we will learn the alternatives to the use of multiple || (OR operator) in conditional statements. Multiple OR operators in conditional statements might cause poor readability of code and are often limited in functionality.
The below JavaScript code could be rewritten to perform the same task in the other ways:
javascript
let user = "motivated";let recommended_org = ""; /* If user is a geek or motivated or curious then the recommended organisation for him/her is GeeksforGeeks */if (user == "geek" || user == "motivated" || user == "curious") { recommended_org = "GeeksforGeeks"; console.log(recommended_org);}
Output:
GeeksforGeeks
Approach 1: This approach uses an if-else ladder to handle all the different possibilities.
In this approach, the syntax is heavily increased. As the outcome of each, if-statement is the same, it may be preferable to use the original method of using multiple OR operations.
However, as the program becomes more complex in options, the if-else ladder is preferred as it increases the readability of the code. It is also very flexible as one can add any number of conditions and even nested conditions, Due to such reasons, it may be used in complex conditions.
The example below demonstrates this approach:
javascript
/* If user is a geek or motivated or curious then the recommended organisation for him/her is GeeksforGeeks */if (user == "geek") { recommended_org = "GeeksforGeeks";}else if (user == "motivated") { recommended_org = "GeeksforGeeks";}else if (user == "curious") { recommended_org = "GeeksforGeeks";}else { recommended_org = "No recommendation"}console.log(recommended_org);
Output:
GeeksforGeeks
Approach 2: This approach uses switch-case statements to handle all the different possibilities.
Switch-case statements are powerful they increase the readability of the code and also the use of default and break statements make the code more efficient to write.
The syntax is increased in this case by the use of switch-case statements but there is less repetition of code as compared to the previous approach. In the if-else ladder, we used the assignment statement three times but in this approach, we use it a single time. But nesting switch case will make the code very complex and it is generally not preferred for problems having a lot of nested conditionals so it’s not that flexible as if-else.
The example below demonstrates this approach:
javascript
let user = "curious";let recommended_org = "No recommendation"; /* If user is a geek or motivated or curious then the recommended organisation for him/her is GeeksforGeeks */switch (user) { case "geek": case "motivated": case "curious": recommended_org = "GeeksforGeeks" break; default: recommended_org = "No Recommendation"} console.log(recommended_org);
Output:
GeeksforGeeks
Approach 3: This approach uses a map object to handle all the different possibilities.
This approach is very flexible like the if-else ladder and easy to scale as one needs to add more key-value pairs, but still, it cannot replace the above approaches in case of very complex examples.
The example below demonstrates this approach:
javascript
let user = "geek"; /* A recommended_org map object which consists the behaviour of the user as the key and the recommended organisation as the values */var recommended_org = { "geek": "GeeksforGeeks", "motivated": "GeeksforGeeks", "curious": "GeeksforGeeks", "other": "No Recommendation"} /* if user is a geek or motivated or curious then the recommended organisation for him/her is GeeksforGeeks */console.log(recommended_org[user] || recommended_org["other"]);
Output:
GeeksforGeeks
Any of the alternatives cannot be termed as superior as all have some pros and cons. It depends on the personal opinion of the programmer and the context where it is to be used. However, it is still a good practice to know about the available alternatives.
surindertarika1234
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 25827,
"s": 25799,
"text": "\n20 Oct, 2021"
},
{
"code": null,
"e": 26067,
"s": 25827,
"text": "In this article, we will learn the alternatives to the use of multiple || (OR operator) in conditional statements. Multiple OR operators in conditional statements might cause poor readability of code and are often limited in functionality."
},
{
"code": null,
"e": 26156,
"s": 26067,
"text": "The below JavaScript code could be rewritten to perform the same task in the other ways:"
},
{
"code": null,
"e": 26167,
"s": 26156,
"text": "javascript"
},
{
"code": "let user = \"motivated\";let recommended_org = \"\"; /* If user is a geek or motivated or curious then the recommended organisation for him/her is GeeksforGeeks */if (user == \"geek\" || user == \"motivated\" || user == \"curious\") { recommended_org = \"GeeksforGeeks\"; console.log(recommended_org);}",
"e": 26472,
"s": 26167,
"text": null
},
{
"code": null,
"e": 26481,
"s": 26472,
"text": "Output: "
},
{
"code": null,
"e": 26495,
"s": 26481,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 26589,
"s": 26497,
"text": "Approach 1: This approach uses an if-else ladder to handle all the different possibilities."
},
{
"code": null,
"e": 26771,
"s": 26589,
"text": "In this approach, the syntax is heavily increased. As the outcome of each, if-statement is the same, it may be preferable to use the original method of using multiple OR operations."
},
{
"code": null,
"e": 27058,
"s": 26771,
"text": "However, as the program becomes more complex in options, the if-else ladder is preferred as it increases the readability of the code. It is also very flexible as one can add any number of conditions and even nested conditions, Due to such reasons, it may be used in complex conditions. "
},
{
"code": null,
"e": 27104,
"s": 27058,
"text": "The example below demonstrates this approach:"
},
{
"code": null,
"e": 27115,
"s": 27104,
"text": "javascript"
},
{
"code": "/* If user is a geek or motivated or curious then the recommended organisation for him/her is GeeksforGeeks */if (user == \"geek\") { recommended_org = \"GeeksforGeeks\";}else if (user == \"motivated\") { recommended_org = \"GeeksforGeeks\";}else if (user == \"curious\") { recommended_org = \"GeeksforGeeks\";}else { recommended_org = \"No recommendation\"}console.log(recommended_org);",
"e": 27499,
"s": 27115,
"text": null
},
{
"code": null,
"e": 27509,
"s": 27499,
"text": " Output: "
},
{
"code": null,
"e": 27524,
"s": 27509,
"text": "GeeksforGeeks "
},
{
"code": null,
"e": 27621,
"s": 27524,
"text": "Approach 2: This approach uses switch-case statements to handle all the different possibilities."
},
{
"code": null,
"e": 27787,
"s": 27621,
"text": "Switch-case statements are powerful they increase the readability of the code and also the use of default and break statements make the code more efficient to write."
},
{
"code": null,
"e": 28229,
"s": 27787,
"text": "The syntax is increased in this case by the use of switch-case statements but there is less repetition of code as compared to the previous approach. In the if-else ladder, we used the assignment statement three times but in this approach, we use it a single time. But nesting switch case will make the code very complex and it is generally not preferred for problems having a lot of nested conditionals so it’s not that flexible as if-else. "
},
{
"code": null,
"e": 28275,
"s": 28229,
"text": "The example below demonstrates this approach:"
},
{
"code": null,
"e": 28286,
"s": 28275,
"text": "javascript"
},
{
"code": "let user = \"curious\";let recommended_org = \"No recommendation\"; /* If user is a geek or motivated or curious then the recommended organisation for him/her is GeeksforGeeks */switch (user) { case \"geek\": case \"motivated\": case \"curious\": recommended_org = \"GeeksforGeeks\" break; default: recommended_org = \"No Recommendation\"} console.log(recommended_org);",
"e": 28657,
"s": 28286,
"text": null
},
{
"code": null,
"e": 28667,
"s": 28657,
"text": " Output: "
},
{
"code": null,
"e": 28681,
"s": 28667,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 28768,
"s": 28681,
"text": "Approach 3: This approach uses a map object to handle all the different possibilities."
},
{
"code": null,
"e": 28968,
"s": 28768,
"text": "This approach is very flexible like the if-else ladder and easy to scale as one needs to add more key-value pairs, but still, it cannot replace the above approaches in case of very complex examples. "
},
{
"code": null,
"e": 29014,
"s": 28968,
"text": "The example below demonstrates this approach:"
},
{
"code": null,
"e": 29025,
"s": 29014,
"text": "javascript"
},
{
"code": "let user = \"geek\"; /* A recommended_org map object which consists the behaviour of the user as the key and the recommended organisation as the values */var recommended_org = { \"geek\": \"GeeksforGeeks\", \"motivated\": \"GeeksforGeeks\", \"curious\": \"GeeksforGeeks\", \"other\": \"No Recommendation\"} /* if user is a geek or motivated or curious then the recommended organisation for him/her is GeeksforGeeks */console.log(recommended_org[user] || recommended_org[\"other\"]);",
"e": 29509,
"s": 29025,
"text": null
},
{
"code": null,
"e": 29517,
"s": 29509,
"text": "Output:"
},
{
"code": null,
"e": 29532,
"s": 29517,
"text": "GeeksforGeeks "
},
{
"code": null,
"e": 29790,
"s": 29532,
"text": "Any of the alternatives cannot be termed as superior as all have some pros and cons. It depends on the personal opinion of the programmer and the context where it is to be used. However, it is still a good practice to know about the available alternatives. "
},
{
"code": null,
"e": 29809,
"s": 29790,
"text": "surindertarika1234"
},
{
"code": null,
"e": 29825,
"s": 29809,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 29832,
"s": 29825,
"text": "Picked"
},
{
"code": null,
"e": 29843,
"s": 29832,
"text": "JavaScript"
},
{
"code": null,
"e": 29860,
"s": 29843,
"text": "Web Technologies"
},
{
"code": null,
"e": 29887,
"s": 29860,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29985,
"s": 29887,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30025,
"s": 29985,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30070,
"s": 30025,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30131,
"s": 30070,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30203,
"s": 30131,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 30249,
"s": 30203,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 30289,
"s": 30249,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30322,
"s": 30289,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30367,
"s": 30322,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30410,
"s": 30367,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
SourceWolf – A CLI Web Crawler Tool in Linux - GeeksforGeeks
|
14 Sep, 2021
Web crawling is the process of indexing data on web pages by using a program or automated script and these automated scripts or programs are known by multiple names, that includes web crawler, spider, spider bot, and often shortened to the crawler. Manual crawling consumes a lot of time if the scope of the target is more. SourceWolf is an automated script developed in the Python Language that crawls the directories from the domain server and the status code. This can help the tester to test the pages whose responses are 200 or 301 quickly. SourceWolf is an open-source and free-to-use tool. SourceWolf tool supports custom word lists for brute-forcing. The output feature of SourceWolf is excellent as the output is stored in the leading directory, and the main directory contains sub-directories with separates status code directories.
SourceWolf tool can crawl the responses to identify the hidden endpoints of the target domain.
SourceWolf tool can create a verbose list of identified JavaScript sources variables.
SourceWolf tool supports brute-forcing of the files and directories by using the custom word list.
SourceWolf tool can display the status code of each director visited on the target server.
SourceWolf tool provides us with an option to crawl the responses files locally so that you aren’t sending requests again to an endpoint, whose response you already have a copy of.
1. Crawl response mode: In this Mode, the hidden endpoints are discovered and saved in the text file format.
python3 sourcewolf.py -l domains.txt -o output/ -c crawl_output
2. Brute force mode: In this Mode Brute Forcing attack is done for the detection of files and directories on the target domain. A wordlist is used to brute force.
python3 sourcewolf.py -b https://geeksforgeeks.org/FUZZ -w /usr/share/wordlists/dirb/common.txt -s status
3. Probing mode: In this Mode, the activeness of the target domain is checked. Whether is target host is live or not is verified in this mode.
python3 sourcewolf.py -l domains.txt -s live
SourceWolf tool can be very beneficial in our workflow. This tool has the support to filter out the live domains. So we can enumerate the subdomains from Amass, AssetFinder, and Sublist3r tool and pass the list to the SourceWolf tool. SourceWolf tool will filter out only responsive or live subdomains so we can test only the live subdomains rather than wasting the time on inactive subdomains. This tool can also be useful for finding the endpoint of the target domain.
To creep the files locally, we must follow some naming conventions rules. These conventions are in place for SourceWolf to directly identify the hostname, and thereby parse all the endpoints, including the relative ones.
Consider an URL https://geeksforgeeks.org/api/
Remove the https (protocol) and the trailing slash (//) (if any) from the URL –> geeksforgeeks.org/api
Replace ‘/’ with ‘@’ –> geeksforgeeks@api
Save the response as a text file with the file name obtained above.
So the file finally looks like geeksforgeeks@api.txt
Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux
Step 1: Check whether Python Environment is Established or not, use the following command.
python3
Step 2: Open up your Kali Linux terminal and move to Desktop using the following command.
cd Desktop
Step 3: You are on Desktop now create a new directory called SourceWolf using the following command. In this directory, we will complete the installation of the SourceWolf tool.
mkdir SourceWolf
Step 4: Now switch to the SourceWolf directory using the following command.
cd SourceWolf
Step 5: Now you have to install the tool. You have to clone the tool from GitHub.
git clone https://github.com/micha3lb3n/SourceWolf.git
Step 6: The tool has been downloaded successfully in the SourceWolf directory. Now list out the contents of the tool by using the below command.
ls
Step 7: You can observe that there is a new directory created of the SourceWolf tool that has been generated while we were installing the tool. Now move to that directory using the below command:
cd SourceWolf
Step 8: Once again to discover the contents of the tool, use the below command.
ls
Step 9: Download the required packages for running the tool, use the following command.
pip3 install -r requirements.txt
Step 10: Now we are done with our installation, Use the below command to view the help (gives a better understanding of the tool) index of the tool.
python3 sourcewolf.py -h
Example 1: Simple Usage
python3 sourcewolf.py --url http://geeksforgeeks.org/wp-admin
In this example, We are testing only a single directory on the target domain geeksforgeeks.org. We have got 500 as a status code which defines that there is a generic error response from the server.
Example 2: Brute force
python3 sourcewolf.py -b http://geeksforgeeks.org/FUZZ
1. In this example, We will be brute-forcing directories on the geeksforgeeks.org domain. We are using a custom or default word list for brute-forcing.
2. In the below Screenshot, We have got the results with the server response status.
Example 3: Verbose
python3 sourcewolf.py -b http://geeksforgeeks.org/FUZZ -v
1. In this example, We will be printing the results in a more realistic way or in more detail. We have used -v tag for verbose mode.
2. In the below Screenshot, We have got the results in real-time and all the directories tested are shown in the terminal with the status code returned from the server.
Example 4: Wordlist
python3 sourcewolf.py -b http://geeksforgeeks.org/FUZZ -w /usr/share/wordlists/dirb/common.txt
1. In this example, We will be using the custom word list which is specified in the -w tag.
2. In the below Screenshot, We have specified the command for using the custom word list.
3. In the below Screenshot, We have got the results of our fuzz and we are trying to open the http://geeksforgeeks.org/About URL whose status code is 200 (Ok).
4. In the below Screenshot, We have opened the About page URL on the web browser.
Example 5: Output
python3 sourcewolf.py -b http://geeksforgeeks.org/FUZZ -w /usr/share/wordlists/dirb/common.txt -o ok
1. In this Example, We are saving the results on our disk for further use. We are using the -o tag along with the name of the directory where results will be saved.
2. In the below Screenshot, We have got the results of our scan.
3. In the below Screenshot, New directories are created with the name of status codes. In this directory, the associated status code web page information will be saved.
4. In the below Screenshot, We have opened the 2xx directory which contains all the web pages whose response is 200 from the server.
5. In the below Screenshot, We have opened the file whose status code is 200. All the HTML, JS code data is stored in the file.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Netstat command in Linux
Network configuration and trouble shooting commands in Linux
uniq Command in LINUX with examples
Absolute and Relative Pathnames in UNIX
Linux File Hierarchy Structure
Basic Operators in Shell Scripting
Thread functions in C/C++
scp command in Linux with Examples
Linux system call in Detail
How to setup cron jobs in Ubuntu
|
[
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 26494,
"s": 25651,
"text": "Web crawling is the process of indexing data on web pages by using a program or automated script and these automated scripts or programs are known by multiple names, that includes web crawler, spider, spider bot, and often shortened to the crawler. Manual crawling consumes a lot of time if the scope of the target is more. SourceWolf is an automated script developed in the Python Language that crawls the directories from the domain server and the status code. This can help the tester to test the pages whose responses are 200 or 301 quickly. SourceWolf is an open-source and free-to-use tool. SourceWolf tool supports custom word lists for brute-forcing. The output feature of SourceWolf is excellent as the output is stored in the leading directory, and the main directory contains sub-directories with separates status code directories."
},
{
"code": null,
"e": 26589,
"s": 26494,
"text": "SourceWolf tool can crawl the responses to identify the hidden endpoints of the target domain."
},
{
"code": null,
"e": 26675,
"s": 26589,
"text": "SourceWolf tool can create a verbose list of identified JavaScript sources variables."
},
{
"code": null,
"e": 26774,
"s": 26675,
"text": "SourceWolf tool supports brute-forcing of the files and directories by using the custom word list."
},
{
"code": null,
"e": 26865,
"s": 26774,
"text": "SourceWolf tool can display the status code of each director visited on the target server."
},
{
"code": null,
"e": 27046,
"s": 26865,
"text": "SourceWolf tool provides us with an option to crawl the responses files locally so that you aren’t sending requests again to an endpoint, whose response you already have a copy of."
},
{
"code": null,
"e": 27155,
"s": 27046,
"text": "1. Crawl response mode: In this Mode, the hidden endpoints are discovered and saved in the text file format."
},
{
"code": null,
"e": 27219,
"s": 27155,
"text": "python3 sourcewolf.py -l domains.txt -o output/ -c crawl_output"
},
{
"code": null,
"e": 27382,
"s": 27219,
"text": "2. Brute force mode: In this Mode Brute Forcing attack is done for the detection of files and directories on the target domain. A wordlist is used to brute force."
},
{
"code": null,
"e": 27488,
"s": 27382,
"text": "python3 sourcewolf.py -b https://geeksforgeeks.org/FUZZ -w /usr/share/wordlists/dirb/common.txt -s status"
},
{
"code": null,
"e": 27631,
"s": 27488,
"text": "3. Probing mode: In this Mode, the activeness of the target domain is checked. Whether is target host is live or not is verified in this mode."
},
{
"code": null,
"e": 27676,
"s": 27631,
"text": "python3 sourcewolf.py -l domains.txt -s live"
},
{
"code": null,
"e": 28147,
"s": 27676,
"text": "SourceWolf tool can be very beneficial in our workflow. This tool has the support to filter out the live domains. So we can enumerate the subdomains from Amass, AssetFinder, and Sublist3r tool and pass the list to the SourceWolf tool. SourceWolf tool will filter out only responsive or live subdomains so we can test only the live subdomains rather than wasting the time on inactive subdomains. This tool can also be useful for finding the endpoint of the target domain."
},
{
"code": null,
"e": 28368,
"s": 28147,
"text": "To creep the files locally, we must follow some naming conventions rules. These conventions are in place for SourceWolf to directly identify the hostname, and thereby parse all the endpoints, including the relative ones."
},
{
"code": null,
"e": 28415,
"s": 28368,
"text": "Consider an URL https://geeksforgeeks.org/api/"
},
{
"code": null,
"e": 28518,
"s": 28415,
"text": "Remove the https (protocol) and the trailing slash (//) (if any) from the URL –> geeksforgeeks.org/api"
},
{
"code": null,
"e": 28560,
"s": 28518,
"text": "Replace ‘/’ with ‘@’ –> geeksforgeeks@api"
},
{
"code": null,
"e": 28628,
"s": 28560,
"text": "Save the response as a text file with the file name obtained above."
},
{
"code": null,
"e": 28681,
"s": 28628,
"text": "So the file finally looks like geeksforgeeks@api.txt"
},
{
"code": null,
"e": 28847,
"s": 28681,
"text": "Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux"
},
{
"code": null,
"e": 28938,
"s": 28847,
"text": "Step 1: Check whether Python Environment is Established or not, use the following command."
},
{
"code": null,
"e": 28946,
"s": 28938,
"text": "python3"
},
{
"code": null,
"e": 29036,
"s": 28946,
"text": "Step 2: Open up your Kali Linux terminal and move to Desktop using the following command."
},
{
"code": null,
"e": 29047,
"s": 29036,
"text": "cd Desktop"
},
{
"code": null,
"e": 29225,
"s": 29047,
"text": "Step 3: You are on Desktop now create a new directory called SourceWolf using the following command. In this directory, we will complete the installation of the SourceWolf tool."
},
{
"code": null,
"e": 29243,
"s": 29225,
"text": "mkdir SourceWolf "
},
{
"code": null,
"e": 29319,
"s": 29243,
"text": "Step 4: Now switch to the SourceWolf directory using the following command."
},
{
"code": null,
"e": 29334,
"s": 29319,
"text": "cd SourceWolf "
},
{
"code": null,
"e": 29416,
"s": 29334,
"text": "Step 5: Now you have to install the tool. You have to clone the tool from GitHub."
},
{
"code": null,
"e": 29471,
"s": 29416,
"text": "git clone https://github.com/micha3lb3n/SourceWolf.git"
},
{
"code": null,
"e": 29616,
"s": 29471,
"text": "Step 6: The tool has been downloaded successfully in the SourceWolf directory. Now list out the contents of the tool by using the below command."
},
{
"code": null,
"e": 29619,
"s": 29616,
"text": "ls"
},
{
"code": null,
"e": 29815,
"s": 29619,
"text": "Step 7: You can observe that there is a new directory created of the SourceWolf tool that has been generated while we were installing the tool. Now move to that directory using the below command:"
},
{
"code": null,
"e": 29830,
"s": 29815,
"text": "cd SourceWolf "
},
{
"code": null,
"e": 29910,
"s": 29830,
"text": "Step 8: Once again to discover the contents of the tool, use the below command."
},
{
"code": null,
"e": 29913,
"s": 29910,
"text": "ls"
},
{
"code": null,
"e": 30001,
"s": 29913,
"text": "Step 9: Download the required packages for running the tool, use the following command."
},
{
"code": null,
"e": 30034,
"s": 30001,
"text": "pip3 install -r requirements.txt"
},
{
"code": null,
"e": 30183,
"s": 30034,
"text": "Step 10: Now we are done with our installation, Use the below command to view the help (gives a better understanding of the tool) index of the tool."
},
{
"code": null,
"e": 30208,
"s": 30183,
"text": "python3 sourcewolf.py -h"
},
{
"code": null,
"e": 30232,
"s": 30208,
"text": "Example 1: Simple Usage"
},
{
"code": null,
"e": 30294,
"s": 30232,
"text": "python3 sourcewolf.py --url http://geeksforgeeks.org/wp-admin"
},
{
"code": null,
"e": 30493,
"s": 30294,
"text": "In this example, We are testing only a single directory on the target domain geeksforgeeks.org. We have got 500 as a status code which defines that there is a generic error response from the server."
},
{
"code": null,
"e": 30516,
"s": 30493,
"text": "Example 2: Brute force"
},
{
"code": null,
"e": 30571,
"s": 30516,
"text": "python3 sourcewolf.py -b http://geeksforgeeks.org/FUZZ"
},
{
"code": null,
"e": 30723,
"s": 30571,
"text": "1. In this example, We will be brute-forcing directories on the geeksforgeeks.org domain. We are using a custom or default word list for brute-forcing."
},
{
"code": null,
"e": 30808,
"s": 30723,
"text": "2. In the below Screenshot, We have got the results with the server response status."
},
{
"code": null,
"e": 30827,
"s": 30808,
"text": "Example 3: Verbose"
},
{
"code": null,
"e": 30885,
"s": 30827,
"text": "python3 sourcewolf.py -b http://geeksforgeeks.org/FUZZ -v"
},
{
"code": null,
"e": 31018,
"s": 30885,
"text": "1. In this example, We will be printing the results in a more realistic way or in more detail. We have used -v tag for verbose mode."
},
{
"code": null,
"e": 31187,
"s": 31018,
"text": "2. In the below Screenshot, We have got the results in real-time and all the directories tested are shown in the terminal with the status code returned from the server."
},
{
"code": null,
"e": 31207,
"s": 31187,
"text": "Example 4: Wordlist"
},
{
"code": null,
"e": 31302,
"s": 31207,
"text": "python3 sourcewolf.py -b http://geeksforgeeks.org/FUZZ -w /usr/share/wordlists/dirb/common.txt"
},
{
"code": null,
"e": 31394,
"s": 31302,
"text": "1. In this example, We will be using the custom word list which is specified in the -w tag."
},
{
"code": null,
"e": 31484,
"s": 31394,
"text": "2. In the below Screenshot, We have specified the command for using the custom word list."
},
{
"code": null,
"e": 31644,
"s": 31484,
"text": "3. In the below Screenshot, We have got the results of our fuzz and we are trying to open the http://geeksforgeeks.org/About URL whose status code is 200 (Ok)."
},
{
"code": null,
"e": 31726,
"s": 31644,
"text": "4. In the below Screenshot, We have opened the About page URL on the web browser."
},
{
"code": null,
"e": 31744,
"s": 31726,
"text": "Example 5: Output"
},
{
"code": null,
"e": 31845,
"s": 31744,
"text": "python3 sourcewolf.py -b http://geeksforgeeks.org/FUZZ -w /usr/share/wordlists/dirb/common.txt -o ok"
},
{
"code": null,
"e": 32010,
"s": 31845,
"text": "1. In this Example, We are saving the results on our disk for further use. We are using the -o tag along with the name of the directory where results will be saved."
},
{
"code": null,
"e": 32075,
"s": 32010,
"text": "2. In the below Screenshot, We have got the results of our scan."
},
{
"code": null,
"e": 32244,
"s": 32075,
"text": "3. In the below Screenshot, New directories are created with the name of status codes. In this directory, the associated status code web page information will be saved."
},
{
"code": null,
"e": 32377,
"s": 32244,
"text": "4. In the below Screenshot, We have opened the 2xx directory which contains all the web pages whose response is 200 from the server."
},
{
"code": null,
"e": 32505,
"s": 32377,
"text": "5. In the below Screenshot, We have opened the file whose status code is 200. All the HTML, JS code data is stored in the file."
},
{
"code": null,
"e": 32516,
"s": 32505,
"text": "Kali-Linux"
},
{
"code": null,
"e": 32528,
"s": 32516,
"text": "Linux-Tools"
},
{
"code": null,
"e": 32539,
"s": 32528,
"text": "Linux-Unix"
},
{
"code": null,
"e": 32637,
"s": 32539,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32662,
"s": 32637,
"text": "Netstat command in Linux"
},
{
"code": null,
"e": 32723,
"s": 32662,
"text": "Network configuration and trouble shooting commands in Linux"
},
{
"code": null,
"e": 32759,
"s": 32723,
"text": "uniq Command in LINUX with examples"
},
{
"code": null,
"e": 32799,
"s": 32759,
"text": "Absolute and Relative Pathnames in UNIX"
},
{
"code": null,
"e": 32830,
"s": 32799,
"text": "Linux File Hierarchy Structure"
},
{
"code": null,
"e": 32865,
"s": 32830,
"text": "Basic Operators in Shell Scripting"
},
{
"code": null,
"e": 32891,
"s": 32865,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 32926,
"s": 32891,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 32954,
"s": 32926,
"text": "Linux system call in Detail"
}
] |
C# Program to Check a Specified City Exists in the List Collection using LINQ - GeeksforGeeks
|
09 Dec, 2021
Given a list, we need to check if a specified city exists in the given list using LINQ. So we can do this task using contains() method. This method is used to check whether a sequence contains a specified element or not. The method overloads in the following ways:
Contains<TSource>(IEnumerable<TSource>, TSource): It is used to check whether the specified sequence or list holds the given element by using the default equality comparer.
Contains<TSource>(IEnumerable<TSource>, TSource, IEqualityComparer<TSource>): It is used to check whether the specified sequence or list holds the given element by using a specified IEqualityComparer<T>.
Syntax:
public static bool Contains<TSource> (this System.Collections.Generic.IEnumerable<TSource> Mylist, TSource element);
Return Type: The return type is Boolean. It will return true if the given element is present in the list. Otherwise, it will return false.
Example:
Input : ["Mumbai", "Pune", "Bangalore", "Hyderabad"]
search_city : "Mumbai"
Output : True
Input : ["Chennai", "Vizag", "Delhi"]
search_city : "Hyderabad"
Output : False
Approach:
Create a method isPresent() that takes city list and name of the city to be searched as arguments.
In isPresent() method, Using contains() check if the city is present in list or not.
bool isExist = City_List.AsEnumerable().Contains(city);
If the city is present it will return true, else it will return false. By using an if condition check if it is true or false and print the result.
In main method, create a list of city names using arrayList.
Calling isPresent() method with two parameters one is list and another one is the name of city that we want to check is present or not.
isPresent(City_List, "Mumbai");
C#
// C# program to check if the given city // is available in the list or notusing System;using System.Collections.Generic;using System.Linq; class GFG{ // Method to check the given city is present in the list or notstatic void isPresent(List<string> City_List, string city){ bool isExist = City_List.AsEnumerable().Contains(city); if (isExist) Console.WriteLine(city + " is present in list"); else Console.WriteLine(city + " is not present in list");} // Driver codestatic void Main(string[] args){ // Creating a list List<string> City_List = new List<string>(){ "Mumbai", "Pune", "Bangalore", "Hyderabad" }; // Calling method isPresent(City_List, "Mumbai"); isPresent(City_List, "Chennai");}}
Output:
Mumbai is present in list
Chennai is not present in list
Explanation: In the above example, first of all, we create an isPresent() method. In this method, we use contains() method to check if the city is present in the list or not and store the result in isExist variable. Now when the if statement is true then it will return “City_name is present in the list” otherwise return “City_name is not present in the list”. Now in the main method, we create a list that contains city names and then call isPresent() method with the city list and name of the city, that is isPresent(City_List, “Mumbai”); and isPresent(City_List, “Chennai”);. As the 1st specified city name is Mumbai and it is present in the list so it returned true, the second specified city name is Chennai which is not there in the list so it returned false.
CSharp LINQ
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Convert String to Character Array in C#
Getting a Month Name Using Month Number in C#
Program to Print a New Line in C#
Socket Programming in C#
Program to find absolute value of a given number
|
[
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 25812,
"s": 25547,
"text": "Given a list, we need to check if a specified city exists in the given list using LINQ. So we can do this task using contains() method. This method is used to check whether a sequence contains a specified element or not. The method overloads in the following ways:"
},
{
"code": null,
"e": 25985,
"s": 25812,
"text": "Contains<TSource>(IEnumerable<TSource>, TSource): It is used to check whether the specified sequence or list holds the given element by using the default equality comparer."
},
{
"code": null,
"e": 26189,
"s": 25985,
"text": "Contains<TSource>(IEnumerable<TSource>, TSource, IEqualityComparer<TSource>): It is used to check whether the specified sequence or list holds the given element by using a specified IEqualityComparer<T>."
},
{
"code": null,
"e": 26197,
"s": 26189,
"text": "Syntax:"
},
{
"code": null,
"e": 26314,
"s": 26197,
"text": "public static bool Contains<TSource> (this System.Collections.Generic.IEnumerable<TSource> Mylist, TSource element);"
},
{
"code": null,
"e": 26453,
"s": 26314,
"text": "Return Type: The return type is Boolean. It will return true if the given element is present in the list. Otherwise, it will return false."
},
{
"code": null,
"e": 26462,
"s": 26453,
"text": "Example:"
},
{
"code": null,
"e": 26634,
"s": 26462,
"text": "Input : [\"Mumbai\", \"Pune\", \"Bangalore\", \"Hyderabad\"]\nsearch_city : \"Mumbai\"\nOutput : True\n\nInput : [\"Chennai\", \"Vizag\", \"Delhi\"]\nsearch_city : \"Hyderabad\"\nOutput : False"
},
{
"code": null,
"e": 26644,
"s": 26634,
"text": "Approach:"
},
{
"code": null,
"e": 26743,
"s": 26644,
"text": "Create a method isPresent() that takes city list and name of the city to be searched as arguments."
},
{
"code": null,
"e": 26828,
"s": 26743,
"text": "In isPresent() method, Using contains() check if the city is present in list or not."
},
{
"code": null,
"e": 26884,
"s": 26828,
"text": "bool isExist = City_List.AsEnumerable().Contains(city);"
},
{
"code": null,
"e": 27031,
"s": 26884,
"text": "If the city is present it will return true, else it will return false. By using an if condition check if it is true or false and print the result."
},
{
"code": null,
"e": 27092,
"s": 27031,
"text": "In main method, create a list of city names using arrayList."
},
{
"code": null,
"e": 27228,
"s": 27092,
"text": "Calling isPresent() method with two parameters one is list and another one is the name of city that we want to check is present or not."
},
{
"code": null,
"e": 27260,
"s": 27228,
"text": "isPresent(City_List, \"Mumbai\");"
},
{
"code": null,
"e": 27263,
"s": 27260,
"text": "C#"
},
{
"code": "// C# program to check if the given city // is available in the list or notusing System;using System.Collections.Generic;using System.Linq; class GFG{ // Method to check the given city is present in the list or notstatic void isPresent(List<string> City_List, string city){ bool isExist = City_List.AsEnumerable().Contains(city); if (isExist) Console.WriteLine(city + \" is present in list\"); else Console.WriteLine(city + \" is not present in list\");} // Driver codestatic void Main(string[] args){ // Creating a list List<string> City_List = new List<string>(){ \"Mumbai\", \"Pune\", \"Bangalore\", \"Hyderabad\" }; // Calling method isPresent(City_List, \"Mumbai\"); isPresent(City_List, \"Chennai\");}}",
"e": 28068,
"s": 27263,
"text": null
},
{
"code": null,
"e": 28076,
"s": 28068,
"text": "Output:"
},
{
"code": null,
"e": 28133,
"s": 28076,
"text": "Mumbai is present in list\nChennai is not present in list"
},
{
"code": null,
"e": 28900,
"s": 28133,
"text": "Explanation: In the above example, first of all, we create an isPresent() method. In this method, we use contains() method to check if the city is present in the list or not and store the result in isExist variable. Now when the if statement is true then it will return “City_name is present in the list” otherwise return “City_name is not present in the list”. Now in the main method, we create a list that contains city names and then call isPresent() method with the city list and name of the city, that is isPresent(City_List, “Mumbai”); and isPresent(City_List, “Chennai”);. As the 1st specified city name is Mumbai and it is present in the list so it returned true, the second specified city name is Chennai which is not there in the list so it returned false."
},
{
"code": null,
"e": 28912,
"s": 28900,
"text": "CSharp LINQ"
},
{
"code": null,
"e": 28919,
"s": 28912,
"text": "Picked"
},
{
"code": null,
"e": 28922,
"s": 28919,
"text": "C#"
},
{
"code": null,
"e": 28934,
"s": 28922,
"text": "C# Programs"
},
{
"code": null,
"e": 29032,
"s": 28934,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29055,
"s": 29032,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29083,
"s": 29055,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 29100,
"s": 29083,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 29122,
"s": 29100,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 29151,
"s": 29122,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 29191,
"s": 29151,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 29237,
"s": 29191,
"text": "Getting a Month Name Using Month Number in C#"
},
{
"code": null,
"e": 29271,
"s": 29237,
"text": "Program to Print a New Line in C#"
},
{
"code": null,
"e": 29296,
"s": 29271,
"text": "Socket Programming in C#"
}
] |
tac command in Linux with Examples - GeeksforGeeks
|
27 May, 2019
tac command in Linux is used to concatenate and print files in reverse. This command will write each FILE to standard output, the last line first. When no file is specified then this command will read the standard input.
Syntax:
tac [OPTION]... [FILE]...
Example: It will print files in reverse.
Options:
tac -b: This option attach the separator before instead of after.Example:tac -b concat.txt tacexample.txt
Example:
tac -b concat.txt tacexample.txt
tac -r: This option will interpret the separator as a regular expression.Example:tac -r concat.txt tacexample.txt
Example:
tac -r concat.txt tacexample.txt
tac -s : This option use STRING as the separator instead of newline.Example:tac -s concat.txt tacexample.txt
Example:
tac -s concat.txt tacexample.txt
tac –help : This option will display the help text and exit.tac --help
tac --help
tac –version: This option will give the version information and exit.tac --version
tac --version
linux-command
Linux-file-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
|
[
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n27 May, 2019"
},
{
"code": null,
"e": 25872,
"s": 25651,
"text": "tac command in Linux is used to concatenate and print files in reverse. This command will write each FILE to standard output, the last line first. When no file is specified then this command will read the standard input."
},
{
"code": null,
"e": 25880,
"s": 25872,
"text": "Syntax:"
},
{
"code": null,
"e": 25907,
"s": 25880,
"text": "tac [OPTION]... [FILE]...\n"
},
{
"code": null,
"e": 25948,
"s": 25907,
"text": "Example: It will print files in reverse."
},
{
"code": null,
"e": 25957,
"s": 25948,
"text": "Options:"
},
{
"code": null,
"e": 26063,
"s": 25957,
"text": "tac -b: This option attach the separator before instead of after.Example:tac -b concat.txt tacexample.txt"
},
{
"code": null,
"e": 26072,
"s": 26063,
"text": "Example:"
},
{
"code": null,
"e": 26105,
"s": 26072,
"text": "tac -b concat.txt tacexample.txt"
},
{
"code": null,
"e": 26219,
"s": 26105,
"text": "tac -r: This option will interpret the separator as a regular expression.Example:tac -r concat.txt tacexample.txt"
},
{
"code": null,
"e": 26228,
"s": 26219,
"text": "Example:"
},
{
"code": null,
"e": 26261,
"s": 26228,
"text": "tac -r concat.txt tacexample.txt"
},
{
"code": null,
"e": 26370,
"s": 26261,
"text": "tac -s : This option use STRING as the separator instead of newline.Example:tac -s concat.txt tacexample.txt"
},
{
"code": null,
"e": 26379,
"s": 26370,
"text": "Example:"
},
{
"code": null,
"e": 26412,
"s": 26379,
"text": "tac -s concat.txt tacexample.txt"
},
{
"code": null,
"e": 26483,
"s": 26412,
"text": "tac –help : This option will display the help text and exit.tac --help"
},
{
"code": null,
"e": 26494,
"s": 26483,
"text": "tac --help"
},
{
"code": null,
"e": 26577,
"s": 26494,
"text": "tac –version: This option will give the version information and exit.tac --version"
},
{
"code": null,
"e": 26591,
"s": 26577,
"text": "tac --version"
},
{
"code": null,
"e": 26605,
"s": 26591,
"text": "linux-command"
},
{
"code": null,
"e": 26625,
"s": 26605,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 26636,
"s": 26625,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26734,
"s": 26636,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26769,
"s": 26734,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 26803,
"s": 26769,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 26829,
"s": 26803,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 26858,
"s": 26829,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 26895,
"s": 26858,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26932,
"s": 26895,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26974,
"s": 26932,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 27000,
"s": 26974,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 27036,
"s": 27000,
"text": "uniq Command in LINUX with examples"
}
] |
Score of Parentheses using Tree - GeeksforGeeks
|
13 Oct, 2021
Given a string str which contains pairs of balanced parentheses, the task is to calculate the score of the given string based on the given rules:
“()” has a score of 1.“x y” has a score of x + y where x and y are individual pairs of balanced parentheses.“(x)” has a score twice of x (i.e), the score is 2 * score of x.
“()” has a score of 1.
“x y” has a score of x + y where x and y are individual pairs of balanced parentheses.
“(x)” has a score twice of x (i.e), the score is 2 * score of x.
Examples:
Input: str = “()()” Output: 2 Explanation: Here input is of the form “xy” which makes the total score = score of x + score of y and hence, score = 1 + 1 = 2
Input: str = “(())” Output: 2 Explanation: Here input is of the form “(x)” which makes the total score = 2 * score of x and hence, score = 2 * 1 = 2
Input: str = “(()()())” Output: 6 Explanation: Here input is of the form “(xyz)” which makes the total score = 2 * (score of x + score of y + score of z) and hence 2*(1 + 1 + 1) = 6
Approach: The idea is to use a tree data structure to solve this problem along with Recursion.
The root node of our tree structure will represent the outermost pair of our input parentheses.
For every pair of balanced parentheses included inside the outermost parentheses, we will add a child to our root node.
This process of declaring a child to a root node will be recursive and hence it will create a node in our tree structure for every pair of balanced parentheses in a hierarchy.
Every balanced pair of parentheses will be considered as outermost (recursively) and generate a node and hence will allow us to calculate the score.
When computing score, each leaf node of our tree will be considered with a score of 1 and to get the score of its respective root node we need to add the scores of each child node and double that aggregate.
The diagram below shows the recursive structure of the tree generated and we start from the bottom to calculate the scores at each level until we reach the outermost ending parentheses.
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ program to find the score of// parentheses using Tree #include <iostream>#include <vector> using namespace std; // Customized tree class or struct,// contains all required methods.class TreeNode { TreeNode* parent = NULL; vector<TreeNode*> children; public: // Function to add a child into // the list of children void addChild(TreeNode* node) { children.push_back(node); } // Function to change the parent // pointer to the node passed void setParent(TreeNode* node) { parent = node; } // Function to return the parent // of the current node TreeNode* getParent() { return parent; } // Function to compute the score recursively. int computeScore() { // Base case if (children.size() == 0) return 1; int res = 0; // Adds scores of all children for (TreeNode* curr : children) res += curr->computeScore(); if (parent == NULL) return res; else return 2 * res; }}; // Function to create the tree structureTreeNode* computeTree(string s){ TreeNode* current = new TreeNode(); TreeNode* root = current; // Creating a node for every "()" for (int i = 0; i < s.size(); i++) { // If we find "(" we add a node as // a child if (s[i] == '(') { TreeNode* child = new TreeNode(); child->setParent(current); current->addChild(child); current = child; } // On finding ")" which confirms that // a pair is closed, we go back // to the parent else { current = current->getParent(); } } return root;} // Driver codeint main(){ string s = "(()(()))"; // Generating the tree TreeNode* root = computeTree(s); // Computing the score cout << root->computeScore(); return 0;}
// Java program to find the score of// parentheses using Treeimport java.util.*;public class Main{ // Customized tree class or struct, // contains all required methods. static class TreeNode { public TreeNode parent = null; public Vector<TreeNode> children = new Vector<TreeNode>(); // Function to add a child into // the list of children public void addChild(TreeNode node) { children.add(node); } // Function to change the parent // pointer to the node passed public void setParent(TreeNode node) { parent = node; } // Function to return the parent // of the current node public TreeNode getParent() { return parent; } // Function to compute the score // recursively. public int computeScore() { // Base case if (children.size() == 0) return 1; int res = 0; // Adds scores of all children for(TreeNode curr : children) res += curr.computeScore(); if (parent == null) return res; else return 2 * res; } } // Function to create the tree structure static TreeNode computeTree(String s) { TreeNode current = new TreeNode(); TreeNode root = current; // Creating a node for every "()" for(int i = 0; i < s.length(); i++) { // If we find "(" we add a node as // a child if (s.charAt(i) == '(') { TreeNode child = new TreeNode(); child.setParent(current); current.addChild(child); current = child; } // On finding ")" which confirms that // a pair is closed, we go back // to the parent else { current = current.getParent(); } } return root; } public static void main(String[] args) { String s = "(()(()))"; // Generating the tree TreeNode root = computeTree(s); // Computing the score System.out.print(root.computeScore()); }} // This code is contributed by suresh07.
# Python3 program to find the score of# parentheses using Tree # Customized tree class or struct,# contains all required methods.class TreeNode: def __init__(self): self.parent = None self.children = [] # Function to add a child into # the list of children def addChild(self, node): self.children.append(node); # Function to change the parent # pointer to the node passed def setParent(self, node): self.parent = node; # Function to return the parent # of the current node def getParent(self): return self.parent; # Function to compute the score recursively. def computeScore(self): # Base case if (len(self.children) == 0): return 1; res = 0; # Adds scores of all children for curr in self.children: res += curr.computeScore(); if (self.parent == None): return res; else: return 2 * res; # Function to create the tree structuredef computeTree(s): current = TreeNode(); root = current; # Creating a node for every "()" for i in range(len(s)): # If we find "(" we add a node as # a child if (s[i] == '('): child = TreeNode(); child.setParent(current); current.addChild(child); current = child; # On finding ")" which confirms that # a pair is closed, we go back # to the parent else: current = current.getParent(); return root; # Driver codeif __name__=='__main__': s = "(()(()))"; # Generating the tree root = computeTree(s); # Computing the score print(root.computeScore()) # This code is contributed by rutvik_56
// C# program to find the score of// parentheses using Treeusing System;using System.Collections; class GFG{ // Customized tree class or struct,// contains all required methods.class TreeNode{ public TreeNode parent = null; public ArrayList children = new ArrayList(); // Function to add a child into // the list of children public void addChild(TreeNode node) { children.Add(node); } // Function to change the parent // pointer to the node passed public void setParent(TreeNode node) { parent = node; } // Function to return the parent // of the current node public TreeNode getParent() { return parent; } // Function to compute the score // recursively. public int computeScore() { // Base case if (children.Count == 0) return 1; int res = 0; // Adds scores of all children foreach(TreeNode curr in children) res += curr.computeScore(); if (parent == null) return res; else return 2 * res; }}; // Function to create the tree structurestatic TreeNode computeTree(string s){ TreeNode current = new TreeNode(); TreeNode root = current; // Creating a node for every "()" for(int i = 0; i < s.Length; i++) { // If we find "(" we add a node as // a child if (s[i] == '(') { TreeNode child = new TreeNode(); child.setParent(current); current.addChild(child); current = child; } // On finding ")" which confirms that // a pair is closed, we go back // to the parent else { current = current.getParent(); } } return root;} // Driver codepublic static void Main(){ string s = "(()(()))"; // Generating the tree TreeNode root = computeTree(s); // Computing the score Console.Write(root.computeScore());}} // This code is contributed by pratham76
6
Time Complexity: O(N), where N is the length of the input string. Space Complexity: O(N), where N is the length of the input string.
rutvik_56
pratham76
suresh07
Advanced Data Structure
Competitive Programming
Recursion
Strings
Tree
Strings
Recursion
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ordered Set and GNU C++ PBDS
2-3 Trees | (Search, Insert and Deletion)
Extendible Hashing (Dynamic approach to DBMS)
Suffix Array | Set 1 (Introduction)
Interval Tree
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming
Fast I/O for Competitive Programming
|
[
{
"code": null,
"e": 25733,
"s": 25705,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 25880,
"s": 25733,
"text": "Given a string str which contains pairs of balanced parentheses, the task is to calculate the score of the given string based on the given rules: "
},
{
"code": null,
"e": 26053,
"s": 25880,
"text": "“()” has a score of 1.“x y” has a score of x + y where x and y are individual pairs of balanced parentheses.“(x)” has a score twice of x (i.e), the score is 2 * score of x."
},
{
"code": null,
"e": 26076,
"s": 26053,
"text": "“()” has a score of 1."
},
{
"code": null,
"e": 26163,
"s": 26076,
"text": "“x y” has a score of x + y where x and y are individual pairs of balanced parentheses."
},
{
"code": null,
"e": 26228,
"s": 26163,
"text": "“(x)” has a score twice of x (i.e), the score is 2 * score of x."
},
{
"code": null,
"e": 26239,
"s": 26228,
"text": "Examples: "
},
{
"code": null,
"e": 26396,
"s": 26239,
"text": "Input: str = “()()” Output: 2 Explanation: Here input is of the form “xy” which makes the total score = score of x + score of y and hence, score = 1 + 1 = 2"
},
{
"code": null,
"e": 26545,
"s": 26396,
"text": "Input: str = “(())” Output: 2 Explanation: Here input is of the form “(x)” which makes the total score = 2 * score of x and hence, score = 2 * 1 = 2"
},
{
"code": null,
"e": 26728,
"s": 26545,
"text": "Input: str = “(()()())” Output: 6 Explanation: Here input is of the form “(xyz)” which makes the total score = 2 * (score of x + score of y + score of z) and hence 2*(1 + 1 + 1) = 6 "
},
{
"code": null,
"e": 26825,
"s": 26728,
"text": "Approach: The idea is to use a tree data structure to solve this problem along with Recursion. "
},
{
"code": null,
"e": 26921,
"s": 26825,
"text": "The root node of our tree structure will represent the outermost pair of our input parentheses."
},
{
"code": null,
"e": 27041,
"s": 26921,
"text": "For every pair of balanced parentheses included inside the outermost parentheses, we will add a child to our root node."
},
{
"code": null,
"e": 27217,
"s": 27041,
"text": "This process of declaring a child to a root node will be recursive and hence it will create a node in our tree structure for every pair of balanced parentheses in a hierarchy."
},
{
"code": null,
"e": 27366,
"s": 27217,
"text": "Every balanced pair of parentheses will be considered as outermost (recursively) and generate a node and hence will allow us to calculate the score."
},
{
"code": null,
"e": 27573,
"s": 27366,
"text": "When computing score, each leaf node of our tree will be considered with a score of 1 and to get the score of its respective root node we need to add the scores of each child node and double that aggregate."
},
{
"code": null,
"e": 27759,
"s": 27573,
"text": "The diagram below shows the recursive structure of the tree generated and we start from the bottom to calculate the scores at each level until we reach the outermost ending parentheses."
},
{
"code": null,
"e": 27811,
"s": 27759,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27815,
"s": 27811,
"text": "C++"
},
{
"code": null,
"e": 27820,
"s": 27815,
"text": "Java"
},
{
"code": null,
"e": 27828,
"s": 27820,
"text": "Python3"
},
{
"code": null,
"e": 27831,
"s": 27828,
"text": "C#"
},
{
"code": "// C++ program to find the score of// parentheses using Tree #include <iostream>#include <vector> using namespace std; // Customized tree class or struct,// contains all required methods.class TreeNode { TreeNode* parent = NULL; vector<TreeNode*> children; public: // Function to add a child into // the list of children void addChild(TreeNode* node) { children.push_back(node); } // Function to change the parent // pointer to the node passed void setParent(TreeNode* node) { parent = node; } // Function to return the parent // of the current node TreeNode* getParent() { return parent; } // Function to compute the score recursively. int computeScore() { // Base case if (children.size() == 0) return 1; int res = 0; // Adds scores of all children for (TreeNode* curr : children) res += curr->computeScore(); if (parent == NULL) return res; else return 2 * res; }}; // Function to create the tree structureTreeNode* computeTree(string s){ TreeNode* current = new TreeNode(); TreeNode* root = current; // Creating a node for every \"()\" for (int i = 0; i < s.size(); i++) { // If we find \"(\" we add a node as // a child if (s[i] == '(') { TreeNode* child = new TreeNode(); child->setParent(current); current->addChild(child); current = child; } // On finding \")\" which confirms that // a pair is closed, we go back // to the parent else { current = current->getParent(); } } return root;} // Driver codeint main(){ string s = \"(()(()))\"; // Generating the tree TreeNode* root = computeTree(s); // Computing the score cout << root->computeScore(); return 0;}",
"e": 29735,
"s": 27831,
"text": null
},
{
"code": "// Java program to find the score of// parentheses using Treeimport java.util.*;public class Main{ // Customized tree class or struct, // contains all required methods. static class TreeNode { public TreeNode parent = null; public Vector<TreeNode> children = new Vector<TreeNode>(); // Function to add a child into // the list of children public void addChild(TreeNode node) { children.add(node); } // Function to change the parent // pointer to the node passed public void setParent(TreeNode node) { parent = node; } // Function to return the parent // of the current node public TreeNode getParent() { return parent; } // Function to compute the score // recursively. public int computeScore() { // Base case if (children.size() == 0) return 1; int res = 0; // Adds scores of all children for(TreeNode curr : children) res += curr.computeScore(); if (parent == null) return res; else return 2 * res; } } // Function to create the tree structure static TreeNode computeTree(String s) { TreeNode current = new TreeNode(); TreeNode root = current; // Creating a node for every \"()\" for(int i = 0; i < s.length(); i++) { // If we find \"(\" we add a node as // a child if (s.charAt(i) == '(') { TreeNode child = new TreeNode(); child.setParent(current); current.addChild(child); current = child; } // On finding \")\" which confirms that // a pair is closed, we go back // to the parent else { current = current.getParent(); } } return root; } public static void main(String[] args) { String s = \"(()(()))\"; // Generating the tree TreeNode root = computeTree(s); // Computing the score System.out.print(root.computeScore()); }} // This code is contributed by suresh07.",
"e": 32187,
"s": 29735,
"text": null
},
{
"code": "# Python3 program to find the score of# parentheses using Tree # Customized tree class or struct,# contains all required methods.class TreeNode: def __init__(self): self.parent = None self.children = [] # Function to add a child into # the list of children def addChild(self, node): self.children.append(node); # Function to change the parent # pointer to the node passed def setParent(self, node): self.parent = node; # Function to return the parent # of the current node def getParent(self): return self.parent; # Function to compute the score recursively. def computeScore(self): # Base case if (len(self.children) == 0): return 1; res = 0; # Adds scores of all children for curr in self.children: res += curr.computeScore(); if (self.parent == None): return res; else: return 2 * res; # Function to create the tree structuredef computeTree(s): current = TreeNode(); root = current; # Creating a node for every \"()\" for i in range(len(s)): # If we find \"(\" we add a node as # a child if (s[i] == '('): child = TreeNode(); child.setParent(current); current.addChild(child); current = child; # On finding \")\" which confirms that # a pair is closed, we go back # to the parent else: current = current.getParent(); return root; # Driver codeif __name__=='__main__': s = \"(()(()))\"; # Generating the tree root = computeTree(s); # Computing the score print(root.computeScore()) # This code is contributed by rutvik_56",
"e": 34016,
"s": 32187,
"text": null
},
{
"code": "// C# program to find the score of// parentheses using Treeusing System;using System.Collections; class GFG{ // Customized tree class or struct,// contains all required methods.class TreeNode{ public TreeNode parent = null; public ArrayList children = new ArrayList(); // Function to add a child into // the list of children public void addChild(TreeNode node) { children.Add(node); } // Function to change the parent // pointer to the node passed public void setParent(TreeNode node) { parent = node; } // Function to return the parent // of the current node public TreeNode getParent() { return parent; } // Function to compute the score // recursively. public int computeScore() { // Base case if (children.Count == 0) return 1; int res = 0; // Adds scores of all children foreach(TreeNode curr in children) res += curr.computeScore(); if (parent == null) return res; else return 2 * res; }}; // Function to create the tree structurestatic TreeNode computeTree(string s){ TreeNode current = new TreeNode(); TreeNode root = current; // Creating a node for every \"()\" for(int i = 0; i < s.Length; i++) { // If we find \"(\" we add a node as // a child if (s[i] == '(') { TreeNode child = new TreeNode(); child.setParent(current); current.addChild(child); current = child; } // On finding \")\" which confirms that // a pair is closed, we go back // to the parent else { current = current.getParent(); } } return root;} // Driver codepublic static void Main(){ string s = \"(()(()))\"; // Generating the tree TreeNode root = computeTree(s); // Computing the score Console.Write(root.computeScore());}} // This code is contributed by pratham76",
"e": 36083,
"s": 34016,
"text": null
},
{
"code": null,
"e": 36085,
"s": 36083,
"text": "6"
},
{
"code": null,
"e": 36221,
"s": 36087,
"text": "Time Complexity: O(N), where N is the length of the input string. Space Complexity: O(N), where N is the length of the input string. "
},
{
"code": null,
"e": 36231,
"s": 36221,
"text": "rutvik_56"
},
{
"code": null,
"e": 36241,
"s": 36231,
"text": "pratham76"
},
{
"code": null,
"e": 36250,
"s": 36241,
"text": "suresh07"
},
{
"code": null,
"e": 36274,
"s": 36250,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 36298,
"s": 36274,
"text": "Competitive Programming"
},
{
"code": null,
"e": 36308,
"s": 36298,
"text": "Recursion"
},
{
"code": null,
"e": 36316,
"s": 36308,
"text": "Strings"
},
{
"code": null,
"e": 36321,
"s": 36316,
"text": "Tree"
},
{
"code": null,
"e": 36329,
"s": 36321,
"text": "Strings"
},
{
"code": null,
"e": 36339,
"s": 36329,
"text": "Recursion"
},
{
"code": null,
"e": 36344,
"s": 36339,
"text": "Tree"
},
{
"code": null,
"e": 36442,
"s": 36344,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36471,
"s": 36442,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 36513,
"s": 36471,
"text": "2-3 Trees | (Search, Insert and Deletion)"
},
{
"code": null,
"e": 36559,
"s": 36513,
"text": "Extendible Hashing (Dynamic approach to DBMS)"
},
{
"code": null,
"e": 36595,
"s": 36559,
"text": "Suffix Array | Set 1 (Introduction)"
},
{
"code": null,
"e": 36609,
"s": 36595,
"text": "Interval Tree"
},
{
"code": null,
"e": 36652,
"s": 36609,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 36695,
"s": 36652,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 36736,
"s": 36695,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 36814,
"s": 36736,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
}
] |
What are inline conditional expressions in ReactJS ? - GeeksforGeeks
|
19 Jan, 2022
In the react, conditional rendering is the process to show components based on a particular condition. For example, While building the to-do list app, developers should show a task only if any pending task is available otherwise they can show a message like “There is no pending task available.”
In this tutorial, we will go through the concept of inline conditional rendering in React. As the inline condition suggests, we can write the condition in a single line. There are several methods for inline conditional rendering in React.
Users need to first set up the react project environment on their local computer.
Creating new react project
Step 1: To create a new react app, run the below command to your terminal.
npx create-react-app testapp
Step 2: Now, move inside the project directory using the below command.
cd testapp
Project Directory: It should look like the below image.
Method 1: Inline if-else conditional (ternary) operatorProgrammers can use the ternary operator ( ? : ) as a short if-else statement. The ternary operator is a simple javascript operator which takes 3 operands.
Syntax:
While working with the ternary operator, developers need to wrap the whole expression in curly braces. To improve the readability of the code, users can wrap the operands inside the parenthesis.
{
condition ? ("condition is true") : ("condition is false")
}
When the condition is true, it returns “condition is true” otherwise it returns “condition is false“. Here, developers can include components as an operand instead of an HTML element.
Example:
Now, edit the App.js file and add the below code to it.
Filename: App.js
In this file, we will declare a variable name ‘totalTask’ and assign a value to this. Next, we will use the ternary operator to show the different messages according to the value of the ‘totalTask‘ variable.
Javascript
import React, { Component } from 'react'; // rendering different message according to the// value of total task variableclass App extends Component { render() { const todoList = ['write article', 'read article', 'Review article']; const totalTask = todoList.length; return ( <div> <h1 style={{color: "green"}}>GeeksForGeeks</h1> <b>{totalTask > 0 ? (<h2>The user has total {totalTask} task pending</h2>) : (<h2>The user has not any task pending</h2>) }</b> </div> ); }} export default App;
Command to run:
npm start
Output:
In the above output image, the user can see that it shows “user has 3 pending tasks” as the user has a total of 3 tasks to do.
Here, Logical && operator is a boolean operator which works the same in React as it works in Javascript. It takes 2 conditions as operands. If the first condition is True, it only evaluates the second condition. Here, instead of adding condition as a second operand, we can add react component. So, if the first condition becomes true, it only renders react component.
Syntax:
Developers need to embed expression with the curly braces. If they need, they can wrap operands inside the parenthesis to keep the code clean.
{
(condition) && (React component or HTML code)
}
When the condition evaluates True, It returns the right part (react component or HTML code) as an output...
Example:
Filename: App.js
In this file, we will write a code to render the message according to the value of the ‘totalTask’ variable.
Javascript
import React, { Component } from 'react'; // using inline if with logical && operatorclass App extends Component { render() { const todoList = []; const totalTask = todoList.length; return ( <div> <h1 style={{color: "green"}}>GeeksForGeeks</h1> { (totalTask > 0) && (<h2>The user has total {totalTask} task pending</h2>) } { (totalTask === 0) && (<h2>The user has not any pending task.</h2>) } </div> ); }} export default App;export default App;
Command to run:
npm start
Output:
In the above image, the user can see that it show the message ‘User has no pending task’ as it evaluates (totalTask === 0) condition True.
sagartomar9927
adnanirshad158
sagar0719kumar
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26071,
"s": 26043,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 26367,
"s": 26071,
"text": "In the react, conditional rendering is the process to show components based on a particular condition. For example, While building the to-do list app, developers should show a task only if any pending task is available otherwise they can show a message like “There is no pending task available.”"
},
{
"code": null,
"e": 26607,
"s": 26367,
"text": "In this tutorial, we will go through the concept of inline conditional rendering in React. As the inline condition suggests, we can write the condition in a single line. There are several methods for inline conditional rendering in React. "
},
{
"code": null,
"e": 26689,
"s": 26607,
"text": "Users need to first set up the react project environment on their local computer."
},
{
"code": null,
"e": 26716,
"s": 26689,
"text": "Creating new react project"
},
{
"code": null,
"e": 26791,
"s": 26716,
"text": "Step 1: To create a new react app, run the below command to your terminal."
},
{
"code": null,
"e": 26820,
"s": 26791,
"text": "npx create-react-app testapp"
},
{
"code": null,
"e": 26892,
"s": 26820,
"text": "Step 2: Now, move inside the project directory using the below command."
},
{
"code": null,
"e": 26903,
"s": 26892,
"text": "cd testapp"
},
{
"code": null,
"e": 26959,
"s": 26903,
"text": "Project Directory: It should look like the below image."
},
{
"code": null,
"e": 27171,
"s": 26959,
"text": "Method 1: Inline if-else conditional (ternary) operatorProgrammers can use the ternary operator ( ? : ) as a short if-else statement. The ternary operator is a simple javascript operator which takes 3 operands. "
},
{
"code": null,
"e": 27179,
"s": 27171,
"text": "Syntax:"
},
{
"code": null,
"e": 27375,
"s": 27179,
"text": "While working with the ternary operator, developers need to wrap the whole expression in curly braces. To improve the readability of the code, users can wrap the operands inside the parenthesis. "
},
{
"code": null,
"e": 27440,
"s": 27375,
"text": "{\n condition ? (\"condition is true\") : (\"condition is false\")\n}"
},
{
"code": null,
"e": 27626,
"s": 27440,
"text": "When the condition is true, it returns “condition is true” otherwise it returns “condition is false“. Here, developers can include components as an operand instead of an HTML element. "
},
{
"code": null,
"e": 27635,
"s": 27626,
"text": "Example:"
},
{
"code": null,
"e": 27691,
"s": 27635,
"text": "Now, edit the App.js file and add the below code to it."
},
{
"code": null,
"e": 27708,
"s": 27691,
"text": "Filename: App.js"
},
{
"code": null,
"e": 27917,
"s": 27708,
"text": "In this file, we will declare a variable name ‘totalTask’ and assign a value to this. Next, we will use the ternary operator to show the different messages according to the value of the ‘totalTask‘ variable. "
},
{
"code": null,
"e": 27928,
"s": 27917,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react'; // rendering different message according to the// value of total task variableclass App extends Component { render() { const todoList = ['write article', 'read article', 'Review article']; const totalTask = todoList.length; return ( <div> <h1 style={{color: \"green\"}}>GeeksForGeeks</h1> <b>{totalTask > 0 ? (<h2>The user has total {totalTask} task pending</h2>) : (<h2>The user has not any task pending</h2>) }</b> </div> ); }} export default App;",
"e": 28481,
"s": 27928,
"text": null
},
{
"code": null,
"e": 28498,
"s": 28481,
"text": "Command to run: "
},
{
"code": null,
"e": 28508,
"s": 28498,
"text": "npm start"
},
{
"code": null,
"e": 28517,
"s": 28508,
"text": "Output: "
},
{
"code": null,
"e": 28645,
"s": 28517,
"text": "In the above output image, the user can see that it shows “user has 3 pending tasks” as the user has a total of 3 tasks to do. "
},
{
"code": null,
"e": 29015,
"s": 28645,
"text": "Here, Logical && operator is a boolean operator which works the same in React as it works in Javascript. It takes 2 conditions as operands. If the first condition is True, it only evaluates the second condition. Here, instead of adding condition as a second operand, we can add react component. So, if the first condition becomes true, it only renders react component. "
},
{
"code": null,
"e": 29023,
"s": 29015,
"text": "Syntax:"
},
{
"code": null,
"e": 29167,
"s": 29023,
"text": "Developers need to embed expression with the curly braces. If they need, they can wrap operands inside the parenthesis to keep the code clean. "
},
{
"code": null,
"e": 29220,
"s": 29167,
"text": "{\n (condition) && (React component or HTML code)\n}"
},
{
"code": null,
"e": 29328,
"s": 29220,
"text": "When the condition evaluates True, It returns the right part (react component or HTML code) as an output..."
},
{
"code": null,
"e": 29337,
"s": 29328,
"text": "Example:"
},
{
"code": null,
"e": 29354,
"s": 29337,
"text": "Filename: App.js"
},
{
"code": null,
"e": 29464,
"s": 29354,
"text": "In this file, we will write a code to render the message according to the value of the ‘totalTask’ variable. "
},
{
"code": null,
"e": 29475,
"s": 29464,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react'; // using inline if with logical && operatorclass App extends Component { render() { const todoList = []; const totalTask = todoList.length; return ( <div> <h1 style={{color: \"green\"}}>GeeksForGeeks</h1> { (totalTask > 0) && (<h2>The user has total {totalTask} task pending</h2>) } { (totalTask === 0) && (<h2>The user has not any pending task.</h2>) } </div> ); }} export default App;export default App;",
"e": 30029,
"s": 29475,
"text": null
},
{
"code": null,
"e": 30046,
"s": 30029,
"text": "Command to run: "
},
{
"code": null,
"e": 30056,
"s": 30046,
"text": "npm start"
},
{
"code": null,
"e": 30065,
"s": 30056,
"text": "Output: "
},
{
"code": null,
"e": 30204,
"s": 30065,
"text": "In the above image, the user can see that it show the message ‘User has no pending task’ as it evaluates (totalTask === 0) condition True."
},
{
"code": null,
"e": 30221,
"s": 30206,
"text": "sagartomar9927"
},
{
"code": null,
"e": 30236,
"s": 30221,
"text": "adnanirshad158"
},
{
"code": null,
"e": 30251,
"s": 30236,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 30258,
"s": 30251,
"text": "Picked"
},
{
"code": null,
"e": 30274,
"s": 30258,
"text": "React-Questions"
},
{
"code": null,
"e": 30282,
"s": 30274,
"text": "ReactJS"
},
{
"code": null,
"e": 30299,
"s": 30282,
"text": "Web Technologies"
},
{
"code": null,
"e": 30397,
"s": 30299,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30424,
"s": 30397,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 30466,
"s": 30424,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 30504,
"s": 30466,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 30539,
"s": 30504,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 30597,
"s": 30539,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 30637,
"s": 30597,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30670,
"s": 30637,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30715,
"s": 30670,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30777,
"s": 30715,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Matplotlib.figure.Figure.get_edgecolor() in Python - GeeksforGeeks
|
30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The get_edgecolor() method figure module of matplotlib library is used to get the edge color of the Figure rectangle.
Syntax: get_edgecolor(self)
Parameters: This method does not accept any parameters.
Returns: This method return the edge color of the Figure rectangle.
Below examples illustrate the matplotlib.figure.Figure.get_edgecolor() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np fig = plt.figure(edgecolor ="green") ax = Subplot(fig, 111) fig.add_subplot(ax) w = fig.get_edgecolor()ax.text(0.2, 0.5, "Value Return by get_edgecolor() :\n" +str(w), fontweight ="bold") fig.canvas.draw()fig.suptitle('matplotlib.figure.Figure.get_edgecolor() \function Example', fontweight ="bold") plt.show()
Output:
Example 2:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np fig = plt.figure(edgecolor = "red", figsize =(7, 6)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx)) w = fig.get_edgecolor()ax.text(2, 0, "Value Return by get_edgecolor() :\n" + str(w), fontweight ="bold") fig.canvas.draw()fig.suptitle('matplotlib.figure.Figure.get_edgecolor()\ function Example', fontweight ="bold") plt.show()
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Defaultdict in Python
How to Install PIP on Windows ?
Deque in Python
Bar Plot in Matplotlib
Check if element exists in list in Python
Python math function | sqrt()
Python | Output Formatting
Python - Pandas dataframe.append()
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n30 Apr, 2020"
},
{
"code": null,
"e": 25848,
"s": 25537,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements."
},
{
"code": null,
"e": 25966,
"s": 25848,
"text": "The get_edgecolor() method figure module of matplotlib library is used to get the edge color of the Figure rectangle."
},
{
"code": null,
"e": 25994,
"s": 25966,
"text": "Syntax: get_edgecolor(self)"
},
{
"code": null,
"e": 26050,
"s": 25994,
"text": "Parameters: This method does not accept any parameters."
},
{
"code": null,
"e": 26118,
"s": 26050,
"text": "Returns: This method return the edge color of the Figure rectangle."
},
{
"code": null,
"e": 26220,
"s": 26118,
"text": "Below examples illustrate the matplotlib.figure.Figure.get_edgecolor() function in matplotlib.figure:"
},
{
"code": null,
"e": 26231,
"s": 26220,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np fig = plt.figure(edgecolor =\"green\") ax = Subplot(fig, 111) fig.add_subplot(ax) w = fig.get_edgecolor()ax.text(0.2, 0.5, \"Value Return by get_edgecolor() :\\n\" +str(w), fontweight =\"bold\") fig.canvas.draw()fig.suptitle('matplotlib.figure.Figure.get_edgecolor() \\function Example', fontweight =\"bold\") plt.show()",
"e": 26759,
"s": 26231,
"text": null
},
{
"code": null,
"e": 26767,
"s": 26759,
"text": "Output:"
},
{
"code": null,
"e": 26778,
"s": 26767,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np fig = plt.figure(edgecolor = \"red\", figsize =(7, 6)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx)) w = fig.get_edgecolor()ax.text(2, 0, \"Value Return by get_edgecolor() :\\n\" + str(w), fontweight =\"bold\") fig.canvas.draw()fig.suptitle('matplotlib.figure.Figure.get_edgecolor()\\ function Example', fontweight =\"bold\") plt.show()",
"e": 27324,
"s": 26778,
"text": null
},
{
"code": null,
"e": 27332,
"s": 27324,
"text": "Output:"
},
{
"code": null,
"e": 27356,
"s": 27332,
"text": "Matplotlib figure-class"
},
{
"code": null,
"e": 27374,
"s": 27356,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 27381,
"s": 27374,
"text": "Python"
},
{
"code": null,
"e": 27479,
"s": 27381,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27501,
"s": 27479,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27533,
"s": 27501,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27549,
"s": 27533,
"text": "Deque in Python"
},
{
"code": null,
"e": 27572,
"s": 27549,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 27614,
"s": 27572,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27644,
"s": 27614,
"text": "Python math function | sqrt()"
},
{
"code": null,
"e": 27671,
"s": 27644,
"text": "Python | Output Formatting"
},
{
"code": null,
"e": 27706,
"s": 27671,
"text": "Python - Pandas dataframe.append()"
},
{
"code": null,
"e": 27762,
"s": 27706,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
How to add Mean and Median to Histogram in R ? - GeeksforGeeks
|
21 Apr, 2021
Visualizing data can help gather insights from it that descriptive statistics can’t. Anscombe’s Quartet shows us how those statistics could be misleading, hence it becomes to analyze the data visually. Histograms are a way to visualize the data distribution of a continuous variable. Histograms are similar to bar plots, but bar plots visualize categorical data and histograms visualize continuous data. In this article, we’ll see how we can create histograms in R Programming Language and how to add mean and median lines to them.
Before learning the code to create histograms, let’s go ahead and understand how to make them. The process to create a histogram is simple, you start by deciding a bin size let’s take the bin size as 5 for now. Next, we’ll find the frequency of the no. that lie in the bins(0-5, 5-10,10-15,..). So if we have sample data as [2, 3, 7, 8, 10, 13, 14, 15, 17, 18, 20, 22, 25, 26, 27, 28] and bin size as 5 then we’ll get the following histogram:-
Let’s understand the above plot. In our sample data, we have 2 values in the range 0-5 hence the bar for 0-5 is of the height 2 units on the y axis. Similarly, we have 3 values in the range 5-10 hence the height of that bar is 3. Histogram change with change in bin size. The same data of bin size 3 will give the following histogram:-
So it’s important to set the correct bin size in order to get valuable insights from the data. There are many formulas to find correct bin size like Sturge’s Rule, Rice Rule, Scott’s Rule, etc.
Histograms in R can be created using the hist() function. All you do is just pass the data to the function and it’ll plot it for you. Let’s go ahead and create a histogram.
R
l <- c(2, 3, 7, 8, 10, 13, 14, 15, 18, 18, 20, 26, 25, 26, 27, 28)hist(l)
Output:
Now that we have created our histogram let’s add mean and median lines to it. To find the mean and median lines to it. But before adding them let’s find them to find the mean and median of data in R we can use mean() and median() functions.
mean <- mean(l) # Mean: 16.25
med <- median(l) # Meadian: 16.5
Now that we have the mean and median let’s add mean to the plot by using abline() function and set its color as blue.
abline(v = mean, col = 'blue')
Example 1: Add Mean to Histogram in R
R
l <- c(2, 3, 7, 8, 10, 13, 14, 15, 18, 18, 20, 26, 25, 26, 27, 28) # Mean of lmean <- mean(l) # Plotting histogram and Adding# Mean line to Histogramhist(l)abline(v = mean, col = 'blue')
Output:
Example 2: Add Median to Histogram in R
Let’s add median to the plot by using abline() function and set its color as red.
abline(v = med, col = 'red')
R
l <- c(2, 3, 7, 8, 10, 13, 14, 15, 18, 18, 20, 26, 25, 26, 27, 28) # Median of lmed <- median(l) # Plotting histogram and Adding # Median line to Histogramhist(l)abline(v = med, col = 'red')
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions?
|
[
{
"code": null,
"e": 26512,
"s": 26484,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 27044,
"s": 26512,
"text": "Visualizing data can help gather insights from it that descriptive statistics can’t. Anscombe’s Quartet shows us how those statistics could be misleading, hence it becomes to analyze the data visually. Histograms are a way to visualize the data distribution of a continuous variable. Histograms are similar to bar plots, but bar plots visualize categorical data and histograms visualize continuous data. In this article, we’ll see how we can create histograms in R Programming Language and how to add mean and median lines to them."
},
{
"code": null,
"e": 27488,
"s": 27044,
"text": "Before learning the code to create histograms, let’s go ahead and understand how to make them. The process to create a histogram is simple, you start by deciding a bin size let’s take the bin size as 5 for now. Next, we’ll find the frequency of the no. that lie in the bins(0-5, 5-10,10-15,..). So if we have sample data as [2, 3, 7, 8, 10, 13, 14, 15, 17, 18, 20, 22, 25, 26, 27, 28] and bin size as 5 then we’ll get the following histogram:-"
},
{
"code": null,
"e": 27824,
"s": 27488,
"text": "Let’s understand the above plot. In our sample data, we have 2 values in the range 0-5 hence the bar for 0-5 is of the height 2 units on the y axis. Similarly, we have 3 values in the range 5-10 hence the height of that bar is 3. Histogram change with change in bin size. The same data of bin size 3 will give the following histogram:-"
},
{
"code": null,
"e": 28018,
"s": 27824,
"text": "So it’s important to set the correct bin size in order to get valuable insights from the data. There are many formulas to find correct bin size like Sturge’s Rule, Rice Rule, Scott’s Rule, etc."
},
{
"code": null,
"e": 28191,
"s": 28018,
"text": "Histograms in R can be created using the hist() function. All you do is just pass the data to the function and it’ll plot it for you. Let’s go ahead and create a histogram."
},
{
"code": null,
"e": 28193,
"s": 28191,
"text": "R"
},
{
"code": "l <- c(2, 3, 7, 8, 10, 13, 14, 15, 18, 18, 20, 26, 25, 26, 27, 28)hist(l)",
"e": 28273,
"s": 28193,
"text": null
},
{
"code": null,
"e": 28281,
"s": 28273,
"text": "Output:"
},
{
"code": null,
"e": 28522,
"s": 28281,
"text": "Now that we have created our histogram let’s add mean and median lines to it. To find the mean and median lines to it. But before adding them let’s find them to find the mean and median of data in R we can use mean() and median() functions."
},
{
"code": null,
"e": 28592,
"s": 28522,
"text": "mean <- mean(l) # Mean: 16.25\nmed <- median(l) # Meadian: 16.5"
},
{
"code": null,
"e": 28710,
"s": 28592,
"text": "Now that we have the mean and median let’s add mean to the plot by using abline() function and set its color as blue."
},
{
"code": null,
"e": 28741,
"s": 28710,
"text": "abline(v = mean, col = 'blue')"
},
{
"code": null,
"e": 28779,
"s": 28741,
"text": "Example 1: Add Mean to Histogram in R"
},
{
"code": null,
"e": 28781,
"s": 28779,
"text": "R"
},
{
"code": "l <- c(2, 3, 7, 8, 10, 13, 14, 15, 18, 18, 20, 26, 25, 26, 27, 28) # Mean of lmean <- mean(l) # Plotting histogram and Adding# Mean line to Histogramhist(l)abline(v = mean, col = 'blue')",
"e": 28976,
"s": 28781,
"text": null
},
{
"code": null,
"e": 28984,
"s": 28976,
"text": "Output:"
},
{
"code": null,
"e": 29024,
"s": 28984,
"text": "Example 2: Add Median to Histogram in R"
},
{
"code": null,
"e": 29106,
"s": 29024,
"text": "Let’s add median to the plot by using abline() function and set its color as red."
},
{
"code": null,
"e": 29135,
"s": 29106,
"text": "abline(v = med, col = 'red')"
},
{
"code": null,
"e": 29137,
"s": 29135,
"text": "R"
},
{
"code": "l <- c(2, 3, 7, 8, 10, 13, 14, 15, 18, 18, 20, 26, 25, 26, 27, 28) # Median of lmed <- median(l) # Plotting histogram and Adding # Median line to Histogramhist(l)abline(v = med, col = 'red')",
"e": 29336,
"s": 29137,
"text": null
},
{
"code": null,
"e": 29343,
"s": 29336,
"text": "Picked"
},
{
"code": null,
"e": 29352,
"s": 29343,
"text": "R-Charts"
},
{
"code": null,
"e": 29361,
"s": 29352,
"text": "R-Graphs"
},
{
"code": null,
"e": 29369,
"s": 29361,
"text": "R-plots"
},
{
"code": null,
"e": 29380,
"s": 29369,
"text": "R Language"
},
{
"code": null,
"e": 29478,
"s": 29380,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29530,
"s": 29478,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29565,
"s": 29530,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29603,
"s": 29565,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29661,
"s": 29603,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29704,
"s": 29661,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29753,
"s": 29704,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29790,
"s": 29753,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 29816,
"s": 29790,
"text": "Time Series Analysis in R"
},
{
"code": null,
"e": 29833,
"s": 29816,
"text": "R - if statement"
}
] |
Python Plotly: How to set the range of the y axis? - GeeksforGeeks
|
30 Nov, 2021
In this article, we will learn how to set the range of the y-axis of a graph using plotly in Python.
To install this module type the below command in the terminal:
pip install plotly
Example 1: Using layout_yaxis_range as a parameter
In this example, we have first import the required libraries i.e pandas,numpy and plotly.objs, then we generated some list of numbers of plotting on the x-axis and y-axis, Further, we have used go.Scatter() function to make a scatter plot. The go.Figure() function takes in data as input where we set the mode as ‘lines’ using mode=’lines’.We have used the magic underscore notation i.e layout_yaxis_range=[-8,8] to set the y-axis range from -8 to 8. At last we display the figure using the show() function.
Python3
# Importing Librariesimport pandas as pdimport plotly.graph_objs as goimport numpy as np # generating numbers ranging from 1 to 20# on x-axisx = list(range(1,20)) # generating random numbers on y-axisy = np.random.randn(20) # plotting scatter plot on x and y data with 'lines'# as mode and setting the y-axis range from -8 to 8fig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines'), layout_yaxis_range=[-8,8]) # to display the figure in the output screenfig.show()
Output:
Example 2: Using update_layout() function to set the y-axis range later
In the following example, Here we have built the plot without setting the y-axis range at first.Further, we set the y-axis range using update_layout() function i.e fig.update_layout(yaxis_range=[-3,3]) to set the range from -3 to 3.
Python3
# Importing Librariesimport pandas as pdimport plotly.graph_objs as goimport numpy as np np.random.seed(5) # generating numbers ranging from 1 to 20# on x-axisx = list(range(1,20)) # generating random numbers on y-axisy = np.random.randn(20) # plotting scatter plot on x and y data with# 'lines' as modefig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines')) # setting the y-axis range from -3 to 3fig.update_layout(yaxis_range=[-3,3]) # to display the figure in the output screenfig.show()
Output:
Example 3:
Similarly here we passed dict(range=[-4,4]) as a dictionary of numbers to parameter yaxis inside update_layout() function.
Python3
# Importing Librariesimport numpy as npimport pandas as pdimport plotly.graph_objs as go np.random.seed(5) # generating numbers ranging from 1 to 20# on x-axisx = list(range(1,20)) # generating random numbers on y-axisy = np.random.randn(20) # plotting scatter plot on x and y data with# 'lines' as modefig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines')) # and setting the y-axis range from -4 to 4fig.update_layout(yaxis=dict(range=[-4,4])) # to display the figure in the output screenfig.show()
Output:
singghakshay
Picked
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 25638,
"s": 25537,
"text": "In this article, we will learn how to set the range of the y-axis of a graph using plotly in Python."
},
{
"code": null,
"e": 25701,
"s": 25638,
"text": "To install this module type the below command in the terminal:"
},
{
"code": null,
"e": 25720,
"s": 25701,
"text": "pip install plotly"
},
{
"code": null,
"e": 25772,
"s": 25720,
"text": "Example 1: Using layout_yaxis_range as a parameter "
},
{
"code": null,
"e": 26280,
"s": 25772,
"text": "In this example, we have first import the required libraries i.e pandas,numpy and plotly.objs, then we generated some list of numbers of plotting on the x-axis and y-axis, Further, we have used go.Scatter() function to make a scatter plot. The go.Figure() function takes in data as input where we set the mode as ‘lines’ using mode=’lines’.We have used the magic underscore notation i.e layout_yaxis_range=[-8,8] to set the y-axis range from -8 to 8. At last we display the figure using the show() function."
},
{
"code": null,
"e": 26288,
"s": 26280,
"text": "Python3"
},
{
"code": "# Importing Librariesimport pandas as pdimport plotly.graph_objs as goimport numpy as np # generating numbers ranging from 1 to 20# on x-axisx = list(range(1,20)) # generating random numbers on y-axisy = np.random.randn(20) # plotting scatter plot on x and y data with 'lines'# as mode and setting the y-axis range from -8 to 8fig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines'), layout_yaxis_range=[-8,8]) # to display the figure in the output screenfig.show()",
"e": 26769,
"s": 26288,
"text": null
},
{
"code": null,
"e": 26777,
"s": 26769,
"text": "Output:"
},
{
"code": null,
"e": 26849,
"s": 26777,
"text": "Example 2: Using update_layout() function to set the y-axis range later"
},
{
"code": null,
"e": 27082,
"s": 26849,
"text": "In the following example, Here we have built the plot without setting the y-axis range at first.Further, we set the y-axis range using update_layout() function i.e fig.update_layout(yaxis_range=[-3,3]) to set the range from -3 to 3."
},
{
"code": null,
"e": 27090,
"s": 27082,
"text": "Python3"
},
{
"code": "# Importing Librariesimport pandas as pdimport plotly.graph_objs as goimport numpy as np np.random.seed(5) # generating numbers ranging from 1 to 20# on x-axisx = list(range(1,20)) # generating random numbers on y-axisy = np.random.randn(20) # plotting scatter plot on x and y data with# 'lines' as modefig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines')) # setting the y-axis range from -3 to 3fig.update_layout(yaxis_range=[-3,3]) # to display the figure in the output screenfig.show()",
"e": 27582,
"s": 27090,
"text": null
},
{
"code": null,
"e": 27590,
"s": 27582,
"text": "Output:"
},
{
"code": null,
"e": 27601,
"s": 27590,
"text": "Example 3:"
},
{
"code": null,
"e": 27724,
"s": 27601,
"text": "Similarly here we passed dict(range=[-4,4]) as a dictionary of numbers to parameter yaxis inside update_layout() function."
},
{
"code": null,
"e": 27732,
"s": 27724,
"text": "Python3"
},
{
"code": "# Importing Librariesimport numpy as npimport pandas as pdimport plotly.graph_objs as go np.random.seed(5) # generating numbers ranging from 1 to 20# on x-axisx = list(range(1,20)) # generating random numbers on y-axisy = np.random.randn(20) # plotting scatter plot on x and y data with# 'lines' as modefig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines')) # and setting the y-axis range from -4 to 4fig.update_layout(yaxis=dict(range=[-4,4])) # to display the figure in the output screenfig.show()",
"e": 28234,
"s": 27732,
"text": null
},
{
"code": null,
"e": 28242,
"s": 28234,
"text": "Output:"
},
{
"code": null,
"e": 28255,
"s": 28242,
"text": "singghakshay"
},
{
"code": null,
"e": 28262,
"s": 28255,
"text": "Picked"
},
{
"code": null,
"e": 28276,
"s": 28262,
"text": "Python-Plotly"
},
{
"code": null,
"e": 28283,
"s": 28276,
"text": "Python"
},
{
"code": null,
"e": 28381,
"s": 28283,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28413,
"s": 28381,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28455,
"s": 28413,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28497,
"s": 28455,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28553,
"s": 28497,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28580,
"s": 28553,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28619,
"s": 28580,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28650,
"s": 28619,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28672,
"s": 28650,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28701,
"s": 28672,
"text": "Create a directory in Python"
}
] |
Lex program to take input from file and remove multiple spaces, lines and tabs - GeeksforGeeks
|
30 Apr, 2019
FLEX (Fast Lexical Analyzer Generator) is a tool/computer program for generating lexical analyzers (scanners or lexers) written by Vern Paxson in C around 1987. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. The function yylex() is the main flex function which runs the Rule Section.
Prerequisite: FLEX (Fast Lexical Analyzer Generator)
Example:
Input:
hello how
are
you?
Output:
hellohowareyou?
Input:
Welcome to
Geeks for
Geeks
Output:
WelcometoGeeksforGeeks
Approach:Open input file in read mode and whenever parser encounters newline (\n), space ( ) or tab (\t) remove it and write all the other characters in output file.
Input File: Input.txt (Input File used in this program)
Below is the implementation program:
/*Lex program to take input from file and remove multiple spaces, newline and taband write output in a separate file*/ % { /*Definition section */ %} /* Rule: whenever space, tab or newline is encounterd, remove it*/% %[ \n\t]+ {fprintf(yyout, "");}. { fprintf(yyout, "%s", yytext); }% % int yywrap(){} // driver code int main(){ /* yyin and yyout as pointer of File type */ extern FILE *yyin, *yyout; /* yyin points to the file input.txt and opens it in read mode*/ yyin = fopen("Input.txt", "r"); /* yyout points to the file output.txt and opens it in write mode*/ yyout = fopen("Output.txt", "w"); yylex(); return 0;}
Output:
Lex program
C Language
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Converting Strings to Numbers in C/C++
Function Pointer in C
Compiler Design | Syntax Directed Definition
Predictive Parser in Compiler Design
Difference between Source Code and Object Code
Lex program to identify the identifier
Optimization of Basic Blocks
|
[
{
"code": null,
"e": 26063,
"s": 26035,
"text": "\n30 Apr, 2019"
},
{
"code": null,
"e": 26436,
"s": 26063,
"text": "FLEX (Fast Lexical Analyzer Generator) is a tool/computer program for generating lexical analyzers (scanners or lexers) written by Vern Paxson in C around 1987. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. The function yylex() is the main flex function which runs the Rule Section."
},
{
"code": null,
"e": 26489,
"s": 26436,
"text": "Prerequisite: FLEX (Fast Lexical Analyzer Generator)"
},
{
"code": null,
"e": 26498,
"s": 26489,
"text": "Example:"
},
{
"code": null,
"e": 26647,
"s": 26498,
"text": "Input:\nhello how\n are \nyou?\n\nOutput:\nhellohowareyou?\n\nInput:\nWelcome to\nGeeks for\n Geeks\n\nOutput:\nWelcometoGeeksforGeeks\n"
},
{
"code": null,
"e": 26813,
"s": 26647,
"text": "Approach:Open input file in read mode and whenever parser encounters newline (\\n), space ( ) or tab (\\t) remove it and write all the other characters in output file."
},
{
"code": null,
"e": 26869,
"s": 26813,
"text": "Input File: Input.txt (Input File used in this program)"
},
{
"code": null,
"e": 26906,
"s": 26869,
"text": "Below is the implementation program:"
},
{
"code": "/*Lex program to take input from file and remove multiple spaces, newline and taband write output in a separate file*/ % { /*Definition section */ %} /* Rule: whenever space, tab or newline is encounterd, remove it*/% %[ \\n\\t]+ {fprintf(yyout, \"\");}. { fprintf(yyout, \"%s\", yytext); }% % int yywrap(){} // driver code int main(){ /* yyin and yyout as pointer of File type */ extern FILE *yyin, *yyout; /* yyin points to the file input.txt and opens it in read mode*/ yyin = fopen(\"Input.txt\", \"r\"); /* yyout points to the file output.txt and opens it in write mode*/ yyout = fopen(\"Output.txt\", \"w\"); yylex(); return 0;}",
"e": 27584,
"s": 26906,
"text": null
},
{
"code": null,
"e": 27592,
"s": 27584,
"text": "Output:"
},
{
"code": null,
"e": 27604,
"s": 27592,
"text": "Lex program"
},
{
"code": null,
"e": 27615,
"s": 27604,
"text": "C Language"
},
{
"code": null,
"e": 27631,
"s": 27615,
"text": "Compiler Design"
},
{
"code": null,
"e": 27729,
"s": 27631,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27746,
"s": 27729,
"text": "Substring in C++"
},
{
"code": null,
"e": 27781,
"s": 27746,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 27827,
"s": 27781,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 27866,
"s": 27827,
"text": "Converting Strings to Numbers in C/C++"
},
{
"code": null,
"e": 27888,
"s": 27866,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27933,
"s": 27888,
"text": "Compiler Design | Syntax Directed Definition"
},
{
"code": null,
"e": 27970,
"s": 27933,
"text": "Predictive Parser in Compiler Design"
},
{
"code": null,
"e": 28017,
"s": 27970,
"text": "Difference between Source Code and Object Code"
},
{
"code": null,
"e": 28056,
"s": 28017,
"text": "Lex program to identify the identifier"
}
] |
Python - Conditional String Append - GeeksforGeeks
|
01 Mar, 2020
Sometimes, while working with data, we have a problem in which we need to perform append operation in string on a particular condition. This kind of problem is common in web development and day-day programming. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is brute force way to perform this task. In this, we run a loop and check for the condition and according to that append the string to original string.
# Python3 code to demonstrate # Conditional String Append# using loop def append_str(item, boy_str, girl_str): if len(item) > 4 and item[-5] == ' ': return item + girl_str return item + boy_str # initializing list test_list = ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur'] # initializing append string boy_str = " Boy"girl_str = " Girl" # printing original listprint ("The original list is : " + str(test_list)) # Conditional String Append# using loopres = [append_str(item, boy_str, girl_str) for item in test_list] # printing result print ("The filtered strings are : " + str(res))
The original list is : ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur']
The filtered strings are : ['Manjeet Singh Boy', 'Harsimran Kaur Girl', 'Sarbjeet Kaur Girl']
Method #2 : Using list comprehensionList comprehension is shorthand to longer method of loops. This solved problem in similar way but in shorter constructs.
# Python3 code to demonstrate # Conditional String Append# using list comprehension # initializing list test_list = ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur'] # initializing append string boy_str = " Boy"girl_str = " Girl" # printing original listprint ("The original list is : " + str(test_list)) # Conditional String Append# using list comprehensionres = [ele + girl_str if ele[-5] == ' ' else ele + boy_str for ele in test_list] # printing result print ("The filtered strings are : " + str(res))
The original list is : ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur']
The filtered strings are : ['Manjeet Singh Boy', 'Harsimran Kaur Girl', 'Sarbjeet Kaur Girl']
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n01 Mar, 2020"
},
{
"code": null,
"e": 25812,
"s": 25537,
"text": "Sometimes, while working with data, we have a problem in which we need to perform append operation in string on a particular condition. This kind of problem is common in web development and day-day programming. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 25991,
"s": 25812,
"text": "Method #1 : Using loopThis is brute force way to perform this task. In this, we run a loop and check for the condition and according to that append the string to original string."
},
{
"code": "# Python3 code to demonstrate # Conditional String Append# using loop def append_str(item, boy_str, girl_str): if len(item) > 4 and item[-5] == ' ': return item + girl_str return item + boy_str # initializing list test_list = ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur'] # initializing append string boy_str = \" Boy\"girl_str = \" Girl\" # printing original listprint (\"The original list is : \" + str(test_list)) # Conditional String Append# using loopres = [append_str(item, boy_str, girl_str) for item in test_list] # printing result print (\"The filtered strings are : \" + str(res))",
"e": 26604,
"s": 25991,
"text": null
},
{
"code": null,
"e": 26775,
"s": 26604,
"text": "The original list is : ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur']\nThe filtered strings are : ['Manjeet Singh Boy', 'Harsimran Kaur Girl', 'Sarbjeet Kaur Girl']\n"
},
{
"code": null,
"e": 26934,
"s": 26777,
"text": "Method #2 : Using list comprehensionList comprehension is shorthand to longer method of loops. This solved problem in similar way but in shorter constructs."
},
{
"code": "# Python3 code to demonstrate # Conditional String Append# using list comprehension # initializing list test_list = ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur'] # initializing append string boy_str = \" Boy\"girl_str = \" Girl\" # printing original listprint (\"The original list is : \" + str(test_list)) # Conditional String Append# using list comprehensionres = [ele + girl_str if ele[-5] == ' ' else ele + boy_str for ele in test_list] # printing result print (\"The filtered strings are : \" + str(res))",
"e": 27448,
"s": 26934,
"text": null
},
{
"code": null,
"e": 27619,
"s": 27448,
"text": "The original list is : ['Manjeet Singh', 'Harsimran Kaur', 'Sarbjeet Kaur']\nThe filtered strings are : ['Manjeet Singh Boy', 'Harsimran Kaur Girl', 'Sarbjeet Kaur Girl']\n"
},
{
"code": null,
"e": 27640,
"s": 27619,
"text": "Python list-programs"
},
{
"code": null,
"e": 27647,
"s": 27640,
"text": "Python"
},
{
"code": null,
"e": 27663,
"s": 27647,
"text": "Python Programs"
},
{
"code": null,
"e": 27761,
"s": 27663,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27793,
"s": 27761,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27835,
"s": 27793,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27877,
"s": 27835,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27933,
"s": 27877,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27960,
"s": 27933,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27982,
"s": 27960,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28021,
"s": 27982,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28067,
"s": 28021,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28105,
"s": 28067,
"text": "Python | Convert a list to dictionary"
}
] |
How to wrap text around circular carousel in Bootstrap 4 ? - GeeksforGeeks
|
28 Apr, 2021
Wrapping up a circular carousel is quite hectic compare to wrapping up a circular image or any shape of the image. In this article first, we have to create a carousel to make that circular, then we can use the text to wrap the carousel. First, you have to create Bootstrap Carousel. To make that carousel circular you can use CSS border-radius property. Then write down your wrapping text and use the CSS Circle() function on the main div. This will wrap your circular carousel in proper way:Below example illustrates the above approach: Example:
html
<!DOCTYPE html><html lang="en"> <head> <title> How to wrap text around circular carousel in Bootstrap 4 ? </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.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <style> h1{ color: green; } .container { margin: 15px 10px 0px; width: 200px; height: 200px; float: left; shape-outside: circle(); } .carousel { border-radius: 50% ; overflow: hidden; } .text { font-size: 18px; text-align: justify; margin: 0px 15px; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <b> A Computer Science Portal for Geeks </b> <div class="container"> <div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> <div class="item active"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200120171114/logo10.png" alt="" style="width:100%;"> </div> <div class="item"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200120152724/gfg_icon.png" alt="" style="width:100%;"> </div> </div> <!-- Left and right controls --> <a class="left carousel-control" href="#myCarousel" > </a> <a class="right carousel-control" href="#myCarousel" > </a> </div> </div> <div class="text"> <b> How many times were you frustrated while looking out for a good collection of programming/ algorithm/ interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </b> </div> <center></body> </html>
Output:
arorakashish0911
Bootstrap-4
Bootstrap-Misc
CSS-Misc
HTML-Misc
Picked
Bootstrap
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to pass data into a bootstrap modal?
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
How to change the background color of the active nav-item?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 26179,
"s": 26151,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 26728,
"s": 26179,
"text": "Wrapping up a circular carousel is quite hectic compare to wrapping up a circular image or any shape of the image. In this article first, we have to create a carousel to make that circular, then we can use the text to wrap the carousel. First, you have to create Bootstrap Carousel. To make that carousel circular you can use CSS border-radius property. Then write down your wrapping text and use the CSS Circle() function on the main div. This will wrap your circular carousel in proper way:Below example illustrates the above approach: Example: "
},
{
"code": null,
"e": 26733,
"s": 26728,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> How to wrap text around circular carousel in Bootstrap 4 ? </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.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <style> h1{ color: green; } .container { margin: 15px 10px 0px; width: 200px; height: 200px; float: left; shape-outside: circle(); } .carousel { border-radius: 50% ; overflow: hidden; } .text { font-size: 18px; text-align: justify; margin: 0px 15px; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <b> A Computer Science Portal for Geeks </b> <div class=\"container\"> <div id=\"myCarousel\" class=\"carousel slide\" data-ride=\"carousel\"> <!-- Indicators --> <ol class=\"carousel-indicators\"> <li data-target=\"#myCarousel\" data-slide-to=\"0\" class=\"active\"></li> <li data-target=\"#myCarousel\" data-slide-to=\"1\"></li> </ol> <!-- Wrapper for slides --> <div class=\"carousel-inner\"> <div class=\"item active\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200120171114/logo10.png\" alt=\"\" style=\"width:100%;\"> </div> <div class=\"item\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200120152724/gfg_icon.png\" alt=\"\" style=\"width:100%;\"> </div> </div> <!-- Left and right controls --> <a class=\"left carousel-control\" href=\"#myCarousel\" > </a> <a class=\"right carousel-control\" href=\"#myCarousel\" > </a> </div> </div> <div class=\"text\"> <b> How many times were you frustrated while looking out for a good collection of programming/ algorithm/ interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </b> </div> <center></body> </html>",
"e": 30383,
"s": 26733,
"text": null
},
{
"code": null,
"e": 30393,
"s": 30383,
"text": "Output: "
},
{
"code": null,
"e": 30412,
"s": 30395,
"text": "arorakashish0911"
},
{
"code": null,
"e": 30424,
"s": 30412,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 30439,
"s": 30424,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 30448,
"s": 30439,
"text": "CSS-Misc"
},
{
"code": null,
"e": 30458,
"s": 30448,
"text": "HTML-Misc"
},
{
"code": null,
"e": 30465,
"s": 30458,
"text": "Picked"
},
{
"code": null,
"e": 30475,
"s": 30465,
"text": "Bootstrap"
},
{
"code": null,
"e": 30492,
"s": 30475,
"text": "Web Technologies"
},
{
"code": null,
"e": 30519,
"s": 30492,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30617,
"s": 30519,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30658,
"s": 30617,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 30699,
"s": 30658,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 30762,
"s": 30699,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 30795,
"s": 30762,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 30854,
"s": 30795,
"text": "How to change the background color of the active nav-item?"
},
{
"code": null,
"e": 30894,
"s": 30854,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30927,
"s": 30894,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30972,
"s": 30927,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31015,
"s": 30972,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python | Pandas DataFrame.nlargest() - GeeksforGeeks
|
17 Sep, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas nlargest() method is used to get n largest values from a data frame or a series.
Syntax:
DataFrame.nlargest(n, columns, keep='first')
Parameters:
n: int, Number of values to selectcolumns: Column to check for values or user can select column while calling too. [For example: data[“age”].nsmallest(3) OR data.nsmallest(3, “age”)]
keep: object to set which value to select if duplicates exit. Options are ‘first’ or ‘last’
To download the CSV file used, Click Here.
Code #1: Extracting Largest 5 valuesIn this example, Largest 5 values are extracted and then compared to the other sorted by the sort_values() function. NaN values are removed before trying this method.
Refer sort_values and dropna() function.
# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("employees.csv") # removing null valuesdata.dropna(inplace = True) # extracting greatest 5large5 = data.nlargest(5, "Salary") # displaylarge5
Output:
Code #2: Sorting by sort_values()
# importing pandas packageimport pandas as pd # making data frame from csv file data = pd.read_csv("employees.csv") # removing null valuesdata.dropna(inplace = True) # sorting in descending orderdata.sort_values("Salary", ascending = False, inplace = True) # displaying top 5 valuesdata.head()
Output:
As shown in the output image, the values returned by both functions is similar.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
|
[
{
"code": null,
"e": 25751,
"s": 25723,
"text": "\n17 Sep, 2018"
},
{
"code": null,
"e": 25965,
"s": 25751,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 26053,
"s": 25965,
"text": "Pandas nlargest() method is used to get n largest values from a data frame or a series."
},
{
"code": null,
"e": 26061,
"s": 26053,
"text": "Syntax:"
},
{
"code": null,
"e": 26106,
"s": 26061,
"text": "DataFrame.nlargest(n, columns, keep='first')"
},
{
"code": null,
"e": 26118,
"s": 26106,
"text": "Parameters:"
},
{
"code": null,
"e": 26301,
"s": 26118,
"text": "n: int, Number of values to selectcolumns: Column to check for values or user can select column while calling too. [For example: data[“age”].nsmallest(3) OR data.nsmallest(3, “age”)]"
},
{
"code": null,
"e": 26393,
"s": 26301,
"text": "keep: object to set which value to select if duplicates exit. Options are ‘first’ or ‘last’"
},
{
"code": null,
"e": 26436,
"s": 26393,
"text": "To download the CSV file used, Click Here."
},
{
"code": null,
"e": 26639,
"s": 26436,
"text": "Code #1: Extracting Largest 5 valuesIn this example, Largest 5 values are extracted and then compared to the other sorted by the sort_values() function. NaN values are removed before trying this method."
},
{
"code": null,
"e": 26680,
"s": 26639,
"text": "Refer sort_values and dropna() function."
},
{
"code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"employees.csv\") # removing null valuesdata.dropna(inplace = True) # extracting greatest 5large5 = data.nlargest(5, \"Salary\") # displaylarge5",
"e": 26924,
"s": 26680,
"text": null
},
{
"code": null,
"e": 26932,
"s": 26924,
"text": "Output:"
},
{
"code": null,
"e": 26968,
"s": 26934,
"text": "Code #2: Sorting by sort_values()"
},
{
"code": "# importing pandas packageimport pandas as pd # making data frame from csv file data = pd.read_csv(\"employees.csv\") # removing null valuesdata.dropna(inplace = True) # sorting in descending orderdata.sort_values(\"Salary\", ascending = False, inplace = True) # displaying top 5 valuesdata.head()",
"e": 27266,
"s": 26968,
"text": null
},
{
"code": null,
"e": 27274,
"s": 27266,
"text": "Output:"
},
{
"code": null,
"e": 27354,
"s": 27274,
"text": "As shown in the output image, the values returned by both functions is similar."
},
{
"code": null,
"e": 27378,
"s": 27354,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 27410,
"s": 27378,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 27424,
"s": 27410,
"text": "Python-pandas"
},
{
"code": null,
"e": 27431,
"s": 27424,
"text": "Python"
},
{
"code": null,
"e": 27529,
"s": 27431,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27547,
"s": 27529,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27582,
"s": 27547,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27614,
"s": 27582,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27656,
"s": 27614,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27682,
"s": 27656,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27711,
"s": 27682,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27755,
"s": 27711,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27792,
"s": 27755,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27828,
"s": 27792,
"text": "Convert integer to string in Python"
}
] |
PyQt5 - Setting current index in ComboBox - GeeksforGeeks
|
22 Apr, 2020
In this article we will see how we can select the item at the specific index. By default when we create a combo box it shows the first item to be selected but we can change the index, in order to do this we will use setCurrentIndex method.
Syntax : combo_box.setCurrentIndex(index)
Argument : It takes integer as argument
Action performed : It will set item of given index
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 ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 120, 30) # geek list geek_list = ["Geek", "Geeky Geek", "Legend Geek", "Ultra Legend Geek"] # adding list of items to combo box self.combo_box.addItems(geek_list) # setting current index self.combo_box.setCurrentIndex(2) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Convert integer to string in Python
How To Convert Python Dictionary To JSON?
sum() function in Python
isupper(), islower(), lower(), upper() in Python and their applications
Python Classes and Objects
|
[
{
"code": null,
"e": 26071,
"s": 26043,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 26311,
"s": 26071,
"text": "In this article we will see how we can select the item at the specific index. By default when we create a combo box it shows the first item to be selected but we can change the index, in order to do this we will use setCurrentIndex method."
},
{
"code": null,
"e": 26353,
"s": 26311,
"text": "Syntax : combo_box.setCurrentIndex(index)"
},
{
"code": null,
"e": 26393,
"s": 26353,
"text": "Argument : It takes integer as argument"
},
{
"code": null,
"e": 26444,
"s": 26393,
"text": "Action performed : It will set item of given index"
},
{
"code": null,
"e": 26474,
"s": 26444,
"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 \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 120, 30) # geek list geek_list = [\"Geek\", \"Geeky Geek\", \"Legend Geek\", \"Ultra Legend Geek\"] # adding list of items to combo box self.combo_box.addItems(geek_list) # setting current index self.combo_box.setCurrentIndex(2) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 27570,
"s": 26474,
"text": null
},
{
"code": null,
"e": 27579,
"s": 27570,
"text": "Output :"
},
{
"code": null,
"e": 27601,
"s": 27579,
"text": "Python PyQt5-ComboBox"
},
{
"code": null,
"e": 27612,
"s": 27601,
"text": "Python-gui"
},
{
"code": null,
"e": 27624,
"s": 27612,
"text": "Python-PyQt"
},
{
"code": null,
"e": 27631,
"s": 27624,
"text": "Python"
},
{
"code": null,
"e": 27729,
"s": 27631,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27761,
"s": 27729,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27803,
"s": 27761,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27832,
"s": 27803,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27869,
"s": 27832,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27911,
"s": 27869,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27947,
"s": 27911,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 27989,
"s": 27947,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28014,
"s": 27989,
"text": "sum() function in Python"
},
{
"code": null,
"e": 28086,
"s": 28014,
"text": "isupper(), islower(), lower(), upper() in Python and their applications"
}
] |
Deprecated Linux Networking Commands and Their Replacements - GeeksforGeeks
|
09 May, 2022
In this article, let us have a close look at some networking commands that are deprecated. That means they are not provided by default and replaced by other commands that serve the same purpose.
But please note that these commands can still be executed by first downloading the net-tools package onto the machine.
sudo apt-get install net-tools
These commands(except iwconfig) are included in the net-tools package and that is the reason why you can see the output of these commands in this article, as we installed the net-tools package on our Linux machine, but if you try these commands on your machine without executing the above-mentioned, command you will receive “Command: not found” error.
We will show outputs of both depreciated and their respective replacements in order to get you better insights about their use.
So let us understand for what purpose each depreciated command is used and also see what their existing versions are, we can use on behalf of these depreciated commands.
Let’s have a brief description of the deprecated commands and their replacements.
1. arp: arp command is used mainly for altering the system’s ARP cache. The full-form for ARP is Address Resolution Protocol and its job is to resolve the IP address of a system to its mac address.
Command:
$ arp
Output:
ip n (ip neighbour): This Command is the depreciated version of arp command. Here, generally, IP stands for internet protocol. This command is mainly used for routing devices and tunnels.
Command :
$ ip n
Output :
2. ifconfig: The main job of this command is to check the configuration of kernel-resident network interfaces. At boot time, its main use is to set up interfaces as required.
Command :
$ ifconfig
Output :
ip a(ip addr): This command is used for looking at the IP configuration of the machine.
Command:
$ ip a
Output:
ip link: This command assists users in viewing and modifying network interfaces.
Command :
$ip link
Output :
3. iwconfig: This command functions similarly to ifconfig but is solely dedicated to wireless interfaces and is used to configure parameters for network interfaces that work specifically for wireless operations.
Command :
$ iwconfig
Output :
iw: This is a newer command which performs the same operations executed by iwconfig.
Command:
$ iw
Output:
4. nameif: This command is used for renaming interfaces based on mac addresses when no arguments given, /etc/mactab is read.
Command:
$ nameif
Output:
ip link: This Command has replaced the version of nameif which is used to display and modify network interfaces.
Command:
$ ip link
Output:
5. netstat: This Command is used for printing out the Linux networking subsystem. By default, it prints out the list of open sockets.
Command :
$ netstat
Output:
ss: This command is used to dump socket statistics, it allows showing information similar to netstat command.
Command:
$ ss
Output:
6. route: The main job of this command is to match packets based on routing table entries. This filter centers around the possibility of assigning a realm around routing table entries.
Command:
$ route
Output:
ip r: This command is a replaced version of the route command which shows table routes.
Command :
$ ip r
Output:
7. iptunnel: This command is used for the creation of configured tunnels for transmission of IPV6 or IPV4 packets (both sending and receiving), which are encapsulated in the form of a payload for an IPV4 diagram.
Command:
$ iptunnel
Output:
ip tunnel: This command is the replaced version of the iptunnel command, which performs the same operations i.e configuring tunnels to allow seamless transportation of IPV6 or IPV4 packets.
Command :
$ip tunnel add
Output:
rkbhola5
linux-command
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
|
[
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n09 May, 2022"
},
{
"code": null,
"e": 25846,
"s": 25651,
"text": "In this article, let us have a close look at some networking commands that are deprecated. That means they are not provided by default and replaced by other commands that serve the same purpose."
},
{
"code": null,
"e": 25965,
"s": 25846,
"text": "But please note that these commands can still be executed by first downloading the net-tools package onto the machine."
},
{
"code": null,
"e": 25996,
"s": 25965,
"text": "sudo apt-get install net-tools"
},
{
"code": null,
"e": 26349,
"s": 25996,
"text": "These commands(except iwconfig) are included in the net-tools package and that is the reason why you can see the output of these commands in this article, as we installed the net-tools package on our Linux machine, but if you try these commands on your machine without executing the above-mentioned, command you will receive “Command: not found” error."
},
{
"code": null,
"e": 26477,
"s": 26349,
"text": "We will show outputs of both depreciated and their respective replacements in order to get you better insights about their use."
},
{
"code": null,
"e": 26647,
"s": 26477,
"text": "So let us understand for what purpose each depreciated command is used and also see what their existing versions are, we can use on behalf of these depreciated commands."
},
{
"code": null,
"e": 26729,
"s": 26647,
"text": "Let’s have a brief description of the deprecated commands and their replacements."
},
{
"code": null,
"e": 26927,
"s": 26729,
"text": "1. arp: arp command is used mainly for altering the system’s ARP cache. The full-form for ARP is Address Resolution Protocol and its job is to resolve the IP address of a system to its mac address."
},
{
"code": null,
"e": 26936,
"s": 26927,
"text": "Command:"
},
{
"code": null,
"e": 26942,
"s": 26936,
"text": "$ arp"
},
{
"code": null,
"e": 26950,
"s": 26942,
"text": "Output:"
},
{
"code": null,
"e": 27138,
"s": 26950,
"text": "ip n (ip neighbour): This Command is the depreciated version of arp command. Here, generally, IP stands for internet protocol. This command is mainly used for routing devices and tunnels."
},
{
"code": null,
"e": 27148,
"s": 27138,
"text": "Command :"
},
{
"code": null,
"e": 27155,
"s": 27148,
"text": "$ ip n"
},
{
"code": null,
"e": 27164,
"s": 27155,
"text": "Output :"
},
{
"code": null,
"e": 27339,
"s": 27164,
"text": "2. ifconfig: The main job of this command is to check the configuration of kernel-resident network interfaces. At boot time, its main use is to set up interfaces as required."
},
{
"code": null,
"e": 27349,
"s": 27339,
"text": "Command :"
},
{
"code": null,
"e": 27362,
"s": 27349,
"text": "$ ifconfig "
},
{
"code": null,
"e": 27372,
"s": 27362,
"text": "Output : "
},
{
"code": null,
"e": 27460,
"s": 27372,
"text": "ip a(ip addr): This command is used for looking at the IP configuration of the machine."
},
{
"code": null,
"e": 27469,
"s": 27460,
"text": "Command:"
},
{
"code": null,
"e": 27477,
"s": 27469,
"text": "$ ip a "
},
{
"code": null,
"e": 27485,
"s": 27477,
"text": "Output:"
},
{
"code": null,
"e": 27566,
"s": 27485,
"text": "ip link: This command assists users in viewing and modifying network interfaces."
},
{
"code": null,
"e": 27576,
"s": 27566,
"text": "Command :"
},
{
"code": null,
"e": 27585,
"s": 27576,
"text": "$ip link"
},
{
"code": null,
"e": 27594,
"s": 27585,
"text": "Output :"
},
{
"code": null,
"e": 27806,
"s": 27594,
"text": "3. iwconfig: This command functions similarly to ifconfig but is solely dedicated to wireless interfaces and is used to configure parameters for network interfaces that work specifically for wireless operations."
},
{
"code": null,
"e": 27816,
"s": 27806,
"text": "Command :"
},
{
"code": null,
"e": 27828,
"s": 27816,
"text": "$ iwconfig "
},
{
"code": null,
"e": 27837,
"s": 27828,
"text": "Output :"
},
{
"code": null,
"e": 27922,
"s": 27837,
"text": "iw: This is a newer command which performs the same operations executed by iwconfig."
},
{
"code": null,
"e": 27931,
"s": 27922,
"text": "Command:"
},
{
"code": null,
"e": 27937,
"s": 27931,
"text": "$ iw "
},
{
"code": null,
"e": 27945,
"s": 27937,
"text": "Output:"
},
{
"code": null,
"e": 28070,
"s": 27945,
"text": "4. nameif: This command is used for renaming interfaces based on mac addresses when no arguments given, /etc/mactab is read."
},
{
"code": null,
"e": 28079,
"s": 28070,
"text": "Command:"
},
{
"code": null,
"e": 28089,
"s": 28079,
"text": "$ nameif "
},
{
"code": null,
"e": 28097,
"s": 28089,
"text": "Output:"
},
{
"code": null,
"e": 28210,
"s": 28097,
"text": "ip link: This Command has replaced the version of nameif which is used to display and modify network interfaces."
},
{
"code": null,
"e": 28219,
"s": 28210,
"text": "Command:"
},
{
"code": null,
"e": 28231,
"s": 28219,
"text": "$ ip link "
},
{
"code": null,
"e": 28239,
"s": 28231,
"text": "Output:"
},
{
"code": null,
"e": 28373,
"s": 28239,
"text": "5. netstat: This Command is used for printing out the Linux networking subsystem. By default, it prints out the list of open sockets."
},
{
"code": null,
"e": 28383,
"s": 28373,
"text": "Command :"
},
{
"code": null,
"e": 28394,
"s": 28383,
"text": "$ netstat "
},
{
"code": null,
"e": 28402,
"s": 28394,
"text": "Output:"
},
{
"code": null,
"e": 28512,
"s": 28402,
"text": "ss: This command is used to dump socket statistics, it allows showing information similar to netstat command."
},
{
"code": null,
"e": 28521,
"s": 28512,
"text": "Command:"
},
{
"code": null,
"e": 28527,
"s": 28521,
"text": "$ ss "
},
{
"code": null,
"e": 28536,
"s": 28527,
"text": "Output: "
},
{
"code": null,
"e": 28723,
"s": 28536,
"text": "6. route: The main job of this command is to match packets based on routing table entries. This filter centers around the possibility of assigning a realm around routing table entries. "
},
{
"code": null,
"e": 28732,
"s": 28723,
"text": "Command:"
},
{
"code": null,
"e": 28741,
"s": 28732,
"text": "$ route "
},
{
"code": null,
"e": 28749,
"s": 28741,
"text": "Output:"
},
{
"code": null,
"e": 28837,
"s": 28749,
"text": "ip r: This command is a replaced version of the route command which shows table routes."
},
{
"code": null,
"e": 28847,
"s": 28837,
"text": "Command :"
},
{
"code": null,
"e": 28855,
"s": 28847,
"text": "$ ip r "
},
{
"code": null,
"e": 28863,
"s": 28855,
"text": "Output:"
},
{
"code": null,
"e": 29077,
"s": 28863,
"text": "7. iptunnel: This command is used for the creation of configured tunnels for transmission of IPV6 or IPV4 packets (both sending and receiving), which are encapsulated in the form of a payload for an IPV4 diagram. "
},
{
"code": null,
"e": 29086,
"s": 29077,
"text": "Command:"
},
{
"code": null,
"e": 29098,
"s": 29086,
"text": "$ iptunnel "
},
{
"code": null,
"e": 29106,
"s": 29098,
"text": "Output:"
},
{
"code": null,
"e": 29297,
"s": 29106,
"text": "ip tunnel: This command is the replaced version of the iptunnel command, which performs the same operations i.e configuring tunnels to allow seamless transportation of IPV6 or IPV4 packets. "
},
{
"code": null,
"e": 29308,
"s": 29297,
"text": "Command : "
},
{
"code": null,
"e": 29325,
"s": 29308,
"text": "$ip tunnel add "
},
{
"code": null,
"e": 29333,
"s": 29325,
"text": "Output:"
},
{
"code": null,
"e": 29342,
"s": 29333,
"text": "rkbhola5"
},
{
"code": null,
"e": 29356,
"s": 29342,
"text": "linux-command"
},
{
"code": null,
"e": 29363,
"s": 29356,
"text": "Picked"
},
{
"code": null,
"e": 29374,
"s": 29363,
"text": "Linux-Unix"
},
{
"code": null,
"e": 29472,
"s": 29374,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29507,
"s": 29472,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 29541,
"s": 29507,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 29567,
"s": 29541,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 29596,
"s": 29567,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 29633,
"s": 29596,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 29670,
"s": 29633,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 29712,
"s": 29670,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 29738,
"s": 29712,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 29774,
"s": 29738,
"text": "uniq Command in LINUX with examples"
}
] |
How to Create Expandable RecyclerView items in Android using Kotlin? - GeeksforGeeks
|
24 Mar, 2021
RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item that can be customized vastly while improving the efficiency of ListViews and GridViews. This improvement is achieved by recycling the views which are out of the visibility of the user. For example, if a user scrolled down to a position where items 4 and 5 are visible; items 1, 2, and 3 would be cleared from the memory to reduce memory consumption. In this article, we will explain how to create Expandable Recycler View items in android. Below is the sample video to show what we are going to build. Note that we are going to implement this project using the Kotlin 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 Kotlin as the programming language.
Step 2: Add view binding dependency
Go to build.gradle(app) and the following dependency inside the android tag and click sync now.
buildFeatures {
viewBinding true
}
Step 3: Working with the activity_main.xml
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. It has only a single Recycler view which we will use to show our data.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:background="#F5F8FD" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Add recycler view to main activity--> <androidx.recyclerview.widget.RecyclerView android:id="@+id/rv_list" android:layout_width="match_parent" android:layout_height="match_parent" tools:listitem="@layout/single_item" app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 4: Create a new layout file and name it as single_item.xml file
Go to the single_item.xml file and refer to the following code. Below is the code for the single_item.xml file. It is the single item layout that we will use in RecyclerView.
XML
<?xml version="1.0" encoding="utf-8"?><com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/card_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="5dp" android:layout_marginEnd="5dp" android:layout_marginBottom="10dp"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <!--Text view for showing the language name--> <TextView android:id="@+id/tv_lang_name" android:layout_width="wrap_content" android:layout_height="40dp" android:layout_marginStart="20dp" android:layout_marginTop="10dp" android:text="Language" android:textColor="@color/black" android:textSize="20sp" android:textStyle="bold" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toTopOf="parent" /> <!--This is the layout "expanded_view" we will hide initially and show as expanded layout when user clicks on any of the item--> <RelativeLayout android:id="@+id/expanded_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@id/tv_lang_name"> <!--It has a text view which we will use in our case as a description text for the languages--> <TextView android:id="@+id/tv_description" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:text="Description Text" android:textSize="18sp" /> </RelativeLayout> </androidx.constraintlayout.widget.ConstraintLayout> </com.google.android.material.card.MaterialCardView>
Step 5: Create a new model class
Create a new class Language.kt we will use data of custom generic “Language” to pass in the list that will be shown in RecyclerView.
Kotlin
// this is the Language model classclass Language( val name : String ="", val description : String= "", var expand : Boolean = false)
Step 6: Working with adapter class
Create a new class RvAdapter.kt this will act as an Adapter class for the recycler view. The logic behind the expandable recycler view is that initially, we will make the visibility of layout with id “expanded_view” of “single_item.xml” to GONE and once the user clicks on any item of recycler view we will make its visibility VISIBLE. Comments are added before the code for better understanding.
Kotlin
import android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport androidx.recyclerview.widget.RecyclerViewimport com.geeksforgeeks.rvadapterviewbinding.databinding.SingleItemBinding class RvAdapter( private var languageList: List<Language>) : RecyclerView.Adapter<RvAdapter.ViewHolder>() { // create an inner class with name ViewHolder // It takes a view argument, in which pass the generated class of single_item.xml // ie SingleItemBinding and in the RecyclerView.ViewHolder(binding.root) pass it like this inner class ViewHolder(val binding: SingleItemBinding) : RecyclerView.ViewHolder(binding.root) // inside the onCreateViewHolder inflate the view of SingleItemBinding // and return new ViewHolder object containing this layout override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = SingleItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(binding) } // bind the items with each item of the list languageList which than will be // shown in recycler view // to keep it simple we are not setting any image data to view override fun onBindViewHolder(holder: ViewHolder, position: Int) { with(holder){ with(languageList[position]){ // set name of the language from the list binding.tvLangName.text = this.name // set description to the text // since this is inside "expandedView" its visibility will be gone initially // after click on the item we will make the visibility of the "expandedView" visible // which will also make the visibility of desc also visible binding.tvDescription.text = this.description // check if boolean property "extend" is true or false // if it is true make the "extendedView" Visible binding.expandedView.visibility = if (this.expand) View.VISIBLE else View.GONE // on Click of the item take parent card view in our case // revert the boolean "expand" binding.cardLayout.setOnClickListener { this.expand = !this.expand notifyDataSetChanged() } } } } // return the size of languageList override fun getItemCount(): Int { return languageList.size }}
Step 7: Working with MainActivity.kt
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport androidx.recyclerview.widget.LinearLayoutManagerimport com.geeksforgeeks.rvadapterviewbinding.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { // view binding for the activity private var _binding: ActivityMainBinding? = null private val binding get() = _binding!! // get reference to the adapter class private var languageList = ArrayList<Language>() private lateinit var rvAdapter: RvAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // define layout manager for the Recycler view binding.rvList.layoutManager = LinearLayoutManager(this) // attach adapter to the recycler view rvAdapter = RvAdapter(languageList) binding.rvList.adapter = rvAdapter // create new objects // add some row data val language1 = Language( "Java", "Java is an Object Oriented Programming language." + " Java is used in all kind of applications like Mobile Applications (Android is Java based), " + "desktop applications, web applications, client server applications, enterprise applications and many more. ", false ) val language2 = Language( "Kotlin", "Kotlin is a statically typed, general-purpose programming language" + " developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc.", false ) val language3 = Language( "Python", "Python is a high-level, general-purpose and a very popular programming language." + " Python programming language (latest Python 3) is being used in web development, Machine Learning applications, " + "along with all cutting edge technology in Software Industry.", false ) val language4 = Language( "CPP", "C++ is a general purpose programming language and widely used now a days for " + "competitive programming. It has imperative, object-oriented and generic programming features. ", false ) // add items to list languageList.add(language1) languageList.add(language2) languageList.add(language3) languageList.add(language4) rvAdapter.notifyDataSetChanged() } // on destroy of view make the binding reference to null override fun onDestroy() { super.onDestroy() _binding = null }}
Output:
Github Repo here.
Kotlin Android
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Kotlin Setters and Getters
|
[
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n24 Mar, 2021"
},
{
"code": null,
"e": 27243,
"s": 26381,
"text": "RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item that can be customized vastly while improving the efficiency of ListViews and GridViews. This improvement is achieved by recycling the views which are out of the visibility of the user. For example, if a user scrolled down to a position where items 4 and 5 are visible; items 1, 2, and 3 would be cleared from the memory to reduce memory consumption. In this article, we will explain how to create Expandable Recycler View items in android. Below is the sample video to show what we are going to build. Note that we are going to implement this project using the Kotlin language. "
},
{
"code": null,
"e": 27272,
"s": 27243,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 27436,
"s": 27272,
"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 Kotlin as the programming language."
},
{
"code": null,
"e": 27472,
"s": 27436,
"text": "Step 2: Add view binding dependency"
},
{
"code": null,
"e": 27568,
"s": 27472,
"text": "Go to build.gradle(app) and the following dependency inside the android tag and click sync now."
},
{
"code": null,
"e": 27585,
"s": 27568,
"text": " buildFeatures {"
},
{
"code": null,
"e": 27608,
"s": 27585,
"text": " viewBinding true"
},
{
"code": null,
"e": 27612,
"s": 27608,
"text": " }"
},
{
"code": null,
"e": 27655,
"s": 27612,
"text": "Step 3: Working with the activity_main.xml"
},
{
"code": null,
"e": 27842,
"s": 27655,
"text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. It has only a single Recycler view which we will use to show our data."
},
{
"code": null,
"e": 27846,
"s": 27842,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:background=\"#F5F8FD\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Add recycler view to main activity--> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/rv_list\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:listitem=\"@layout/single_item\" app:layoutManager=\"androidx.recyclerview.widget.LinearLayoutManager\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 28638,
"s": 27846,
"text": null
},
{
"code": null,
"e": 28707,
"s": 28638,
"text": "Step 4: Create a new layout file and name it as single_item.xml file"
},
{
"code": null,
"e": 28882,
"s": 28707,
"text": "Go to the single_item.xml file and refer to the following code. Below is the code for the single_item.xml file. It is the single item layout that we will use in RecyclerView."
},
{
"code": null,
"e": 28886,
"s": 28882,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><com.google.android.material.card.MaterialCardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:id=\"@+id/card_layout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"5dp\" android:layout_marginEnd=\"5dp\" android:layout_marginBottom=\"10dp\"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <!--Text view for showing the language name--> <TextView android:id=\"@+id/tv_lang_name\" android:layout_width=\"wrap_content\" android:layout_height=\"40dp\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"10dp\" android:text=\"Language\" android:textColor=\"@color/black\" android:textSize=\"20sp\" android:textStyle=\"bold\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <!--This is the layout \"expanded_view\" we will hide initially and show as expanded layout when user clicks on any of the item--> <RelativeLayout android:id=\"@+id/expanded_view\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"10dp\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@id/tv_lang_name\"> <!--It has a text view which we will use in our case as a description text for the languages--> <TextView android:id=\"@+id/tv_description\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:text=\"Description Text\" android:textSize=\"18sp\" /> </RelativeLayout> </androidx.constraintlayout.widget.ConstraintLayout> </com.google.android.material.card.MaterialCardView>",
"e": 31149,
"s": 28886,
"text": null
},
{
"code": null,
"e": 31182,
"s": 31149,
"text": "Step 5: Create a new model class"
},
{
"code": null,
"e": 31315,
"s": 31182,
"text": "Create a new class Language.kt we will use data of custom generic “Language” to pass in the list that will be shown in RecyclerView."
},
{
"code": null,
"e": 31322,
"s": 31315,
"text": "Kotlin"
},
{
"code": "// this is the Language model classclass Language( val name : String =\"\", val description : String= \"\", var expand : Boolean = false)",
"e": 31465,
"s": 31322,
"text": null
},
{
"code": null,
"e": 31500,
"s": 31465,
"text": "Step 6: Working with adapter class"
},
{
"code": null,
"e": 31897,
"s": 31500,
"text": "Create a new class RvAdapter.kt this will act as an Adapter class for the recycler view. The logic behind the expandable recycler view is that initially, we will make the visibility of layout with id “expanded_view” of “single_item.xml” to GONE and once the user clicks on any item of recycler view we will make its visibility VISIBLE. Comments are added before the code for better understanding."
},
{
"code": null,
"e": 31904,
"s": 31897,
"text": "Kotlin"
},
{
"code": "import android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport androidx.recyclerview.widget.RecyclerViewimport com.geeksforgeeks.rvadapterviewbinding.databinding.SingleItemBinding class RvAdapter( private var languageList: List<Language>) : RecyclerView.Adapter<RvAdapter.ViewHolder>() { // create an inner class with name ViewHolder // It takes a view argument, in which pass the generated class of single_item.xml // ie SingleItemBinding and in the RecyclerView.ViewHolder(binding.root) pass it like this inner class ViewHolder(val binding: SingleItemBinding) : RecyclerView.ViewHolder(binding.root) // inside the onCreateViewHolder inflate the view of SingleItemBinding // and return new ViewHolder object containing this layout override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = SingleItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(binding) } // bind the items with each item of the list languageList which than will be // shown in recycler view // to keep it simple we are not setting any image data to view override fun onBindViewHolder(holder: ViewHolder, position: Int) { with(holder){ with(languageList[position]){ // set name of the language from the list binding.tvLangName.text = this.name // set description to the text // since this is inside \"expandedView\" its visibility will be gone initially // after click on the item we will make the visibility of the \"expandedView\" visible // which will also make the visibility of desc also visible binding.tvDescription.text = this.description // check if boolean property \"extend\" is true or false // if it is true make the \"extendedView\" Visible binding.expandedView.visibility = if (this.expand) View.VISIBLE else View.GONE // on Click of the item take parent card view in our case // revert the boolean \"expand\" binding.cardLayout.setOnClickListener { this.expand = !this.expand notifyDataSetChanged() } } } } // return the size of languageList override fun getItemCount(): Int { return languageList.size }}",
"e": 34353,
"s": 31904,
"text": null
},
{
"code": null,
"e": 34390,
"s": 34353,
"text": "Step 7: Working with MainActivity.kt"
},
{
"code": null,
"e": 34576,
"s": 34390,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 34583,
"s": 34576,
"text": "Kotlin"
},
{
"code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport androidx.recyclerview.widget.LinearLayoutManagerimport com.geeksforgeeks.rvadapterviewbinding.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { // view binding for the activity private var _binding: ActivityMainBinding? = null private val binding get() = _binding!! // get reference to the adapter class private var languageList = ArrayList<Language>() private lateinit var rvAdapter: RvAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // define layout manager for the Recycler view binding.rvList.layoutManager = LinearLayoutManager(this) // attach adapter to the recycler view rvAdapter = RvAdapter(languageList) binding.rvList.adapter = rvAdapter // create new objects // add some row data val language1 = Language( \"Java\", \"Java is an Object Oriented Programming language.\" + \" Java is used in all kind of applications like Mobile Applications (Android is Java based), \" + \"desktop applications, web applications, client server applications, enterprise applications and many more. \", false ) val language2 = Language( \"Kotlin\", \"Kotlin is a statically typed, general-purpose programming language\" + \" developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc.\", false ) val language3 = Language( \"Python\", \"Python is a high-level, general-purpose and a very popular programming language.\" + \" Python programming language (latest Python 3) is being used in web development, Machine Learning applications, \" + \"along with all cutting edge technology in Software Industry.\", false ) val language4 = Language( \"CPP\", \"C++ is a general purpose programming language and widely used now a days for \" + \"competitive programming. It has imperative, object-oriented and generic programming features. \", false ) // add items to list languageList.add(language1) languageList.add(language2) languageList.add(language3) languageList.add(language4) rvAdapter.notifyDataSetChanged() } // on destroy of view make the binding reference to null override fun onDestroy() { super.onDestroy() _binding = null }}",
"e": 37342,
"s": 34583,
"text": null
},
{
"code": null,
"e": 37350,
"s": 37342,
"text": "Output:"
},
{
"code": null,
"e": 37368,
"s": 37350,
"text": "Github Repo here."
},
{
"code": null,
"e": 37383,
"s": 37368,
"text": "Kotlin Android"
},
{
"code": null,
"e": 37391,
"s": 37383,
"text": "Android"
},
{
"code": null,
"e": 37398,
"s": 37391,
"text": "Kotlin"
},
{
"code": null,
"e": 37406,
"s": 37398,
"text": "Android"
},
{
"code": null,
"e": 37504,
"s": 37406,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37542,
"s": 37504,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 37581,
"s": 37542,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 37631,
"s": 37581,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 37673,
"s": 37631,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 37724,
"s": 37673,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 37743,
"s": 37724,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 37756,
"s": 37743,
"text": "Kotlin Array"
},
{
"code": null,
"e": 37798,
"s": 37756,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 37838,
"s": 37798,
"text": "How to Get Current Location in Android?"
}
] |
Python | Pandas dataframe.cummax() - GeeksforGeeks
|
16 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.cummax() is used to find the cumulative maximum value over any axis. Each cell is populated with the maximum value seen so far.
Syntax: DataFrame.cummax(axis=None, skipna=True, *args, **kwargs)
Parameters:axis : {index (0), columns (1)}skipna : Exclude NA/null values. If an entire row/column is NA, the result will be NA
Returns: cummax : Series
Example #1: Use cummax() function to find the cumulative maximum value along the index axis.
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[5, 3, 6, 4], "B":[11, 2, 4, 3], "C":[4, 3, 8, 5], "D":[5, 4, 2, 8]}) # Print the dataframedf
Output :
Now find the cumulative maximum value over the index axis
# To find the cumulative maxdf.cummax(axis = 0)
Output :
Example #2: Use cummax() function to find the cumulative maximum value along the column axis.
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[5, 3, 6, 4], "B":[11, 2, 4, 3], "C":[4, 3, 8, 5], "D":[5, 4, 2, 8]}) # To find the cumulative max along column axisdf.cummax(axis = 1)
Output :
Example #3: Use cummax() function to find the cumulative maximum value along the index axis in a data frame with NaN value.
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[5, 3, None, 4], "B":[None, 2, 4, 3], "C":[4, 3, 8, 5], "D":[5, 4, 2, None]}) # To find the cumulative maxdf.cummax(axis = 0, skipna = True)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Check if element exists in list in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 26135,
"s": 26107,
"text": "\n16 Nov, 2018"
},
{
"code": null,
"e": 26349,
"s": 26135,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 26494,
"s": 26349,
"text": "Pandas dataframe.cummax() is used to find the cumulative maximum value over any axis. Each cell is populated with the maximum value seen so far."
},
{
"code": null,
"e": 26560,
"s": 26494,
"text": "Syntax: DataFrame.cummax(axis=None, skipna=True, *args, **kwargs)"
},
{
"code": null,
"e": 26688,
"s": 26560,
"text": "Parameters:axis : {index (0), columns (1)}skipna : Exclude NA/null values. If an entire row/column is NA, the result will be NA"
},
{
"code": null,
"e": 26713,
"s": 26688,
"text": "Returns: cummax : Series"
},
{
"code": null,
"e": 26806,
"s": 26713,
"text": "Example #1: Use cummax() function to find the cumulative maximum value along the index axis."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[5, 3, 6, 4], \"B\":[11, 2, 4, 3], \"C\":[4, 3, 8, 5], \"D\":[5, 4, 2, 8]}) # Print the dataframedf",
"e": 27048,
"s": 26806,
"text": null
},
{
"code": null,
"e": 27057,
"s": 27048,
"text": "Output :"
},
{
"code": null,
"e": 27115,
"s": 27057,
"text": "Now find the cumulative maximum value over the index axis"
},
{
"code": "# To find the cumulative maxdf.cummax(axis = 0)",
"e": 27163,
"s": 27115,
"text": null
},
{
"code": null,
"e": 27172,
"s": 27163,
"text": "Output :"
},
{
"code": null,
"e": 27268,
"s": 27174,
"text": "Example #2: Use cummax() function to find the cumulative maximum value along the column axis."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[5, 3, 6, 4], \"B\":[11, 2, 4, 3], \"C\":[4, 3, 8, 5], \"D\":[5, 4, 2, 8]}) # To find the cumulative max along column axisdf.cummax(axis = 1)",
"e": 27552,
"s": 27268,
"text": null
},
{
"code": null,
"e": 27561,
"s": 27552,
"text": "Output :"
},
{
"code": null,
"e": 27687,
"s": 27563,
"text": "Example #3: Use cummax() function to find the cumulative maximum value along the index axis in a data frame with NaN value."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[5, 3, None, 4], \"B\":[None, 2, 4, 3], \"C\":[4, 3, 8, 5], \"D\":[5, 4, 2, None]}) # To find the cumulative maxdf.cummax(axis = 0, skipna = True)",
"e": 27976,
"s": 27687,
"text": null
},
{
"code": null,
"e": 27985,
"s": 27976,
"text": "Output :"
},
{
"code": null,
"e": 28009,
"s": 27985,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 28041,
"s": 28009,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 28055,
"s": 28041,
"text": "Python-pandas"
},
{
"code": null,
"e": 28062,
"s": 28055,
"text": "Python"
},
{
"code": null,
"e": 28160,
"s": 28062,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28178,
"s": 28160,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28210,
"s": 28178,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28232,
"s": 28210,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28274,
"s": 28232,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28300,
"s": 28274,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28344,
"s": 28300,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28373,
"s": 28344,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28409,
"s": 28373,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 28451,
"s": 28409,
"text": "Check if element exists in list in Python"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.