title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
jQuery | Flipping Gallery Plugin
|
28 May, 2020
jQuery provides a simple, beautiful, and interactive flipping gallery plugin which helps programmers to flip many images in a gallery in various directions with the autoplay feature. The plugin is implemented by using HTML markups and simple javascript function call.
Please download the Flipping gallery plugin in your working folder and include all the relevant files in the head section of your landing web page.Download link: https://github.com/peachananr/flipping_gallery
Example 1: In the following program, the simple call of flipping_gallery() function is shown for basic usage. Previous and Next buttons are provided for handling of flipping images in forward or backward movements.
<!doctype html><html><head> <meta charset="utf-8"> <title>jQuery Flipping Gallery Plugin </title> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300, 400, 700' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Noto+Serif:400, 700, 400italic, 700italic' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'> <link href='flipping_gallery.css' rel='stylesheet' type='text/css'> <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"> </script> <script type="text/javascript" src="jquery.flipping_gallery.js"> </script> <style> html { height: 90%; } body { padding: 0; text-align: center; font-family: 'open sans'; position: relative; margin: 0; height: 80%; } .wrapper { height: auto !important; height: 60%; margin: 0 auto; overflow: hidden; } a { text-decoration: none; } .btn { display: inline-block; border: 4px solid black; border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; background: green; display: inline-block; line-height: 100%; padding: 0.6em; text-decoration: none; color: #0d2633; width: 100px; line-height: 100%; font-size: 14px; font-family: open sans; font-weight: bold; border: none; margin-left: 10px; } .btns { width: 200px; margin: 20px auto; } .page-container { max-width: 700px; margin: auto; position: relative; } .gallery { height: 300px; width: 500px; margin: 150px auto 100px; } img { border : 1px solid black; } </style> <script> $(document).ready( function() { $(".gallery").flipping_gallery(); $(".next").click(function() { $(".gallery").flipForward(); return false; }); $(".prev").click(function() { $(".gallery").flipBackward(); return false; }); }); </script></head><body> <h3 style="color:green"> GeeksForGeeks - jQuery Flipping gallery </h3> <div class="wrapper"> <div class="page-container"> <div class="gallery"> <a href="#" data-caption=""> <img src="images/geeksimage1.png" border="2"></a> <a href="#" data-caption=""> <img src="images/geeksimage2.png" border="2"></a> <a href="#" data-caption=""> <img src="images/geeksimage3.png" border="2"></a> <a href="#" data-caption=""> <img src="images/gfg2.jpg" border="2"></a> <a href="#" data-caption=""> <img src="images/gfg6.png" border="2"></a> <a href="#" data-caption=""> <img src="images/background.jpg" border="2"></a> <a href="#" data-caption=""> <img src="images/background2.jpg" border="2"></a> <a href="#" data-caption=""> <img src="images/background3.jpg" border="2"></a> </div> <div class="navigation"> <a href="#" class="btn prev">Previous</a> <a href="#" class="btn next">Next</a> </div> </div> </div></body></html>
Output :
Example 2: In the following program, various options setting are implemented using javascript function call.The programmer can make use of various options depending on the application’s requirement. Please read the comments for each option values and use accordingly. Programmer can make use of data-caption attribute to add captions.
<!doctype html><html><head> <meta charset="utf-8"> <title>jQuery Flipping Gallery Plugin </title> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300, 400, 700' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Noto+Serif:400, 700, 400italic, 700italic' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'> <link href='flipping_gallery.css' rel='stylesheet' type='text/css'> <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"> </script> <script type="text/javascript" src="jquery.flipping_gallery.js"> </script> <style> html { height: 90%; } body { padding: 0; text-align: center; font-family: 'open sans'; position: relative; margin: 0; height: 80%; } .wrapper { height: auto !important; height: 60%; margin: 0 auto; overflow: hidden; } a { text-decoration: none; } .btn { display: inline-block; border: 4px solid black; border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; background: green; display: inline-block; line-height: 100%; padding: 0.6em; text-decoration: none; color: #0d2633; width: 100px; line-height: 100%; font-size: 14px; font-family: open sans; font-weight: bold; border: none; margin-left: 10px; } .btns { width: 200px; margin: 20px auto; } .page-container { max-width: 700px; margin: auto; position: relative; } .gallery { height: 310px; width: 500px; margin: 150px auto 100px; } img { border : 1px solid black; } .navigation { margin-bottom: 150px; } </style> <script> $(document).ready( function() { $(".gallery").flipping_gallery({/* The options for the flipping direction are "forward", or "backward". Default value is forward.*/ direction: "forward", // Default selector is set for generation of the gallery. selector: "> a", /* Spacing between each photo in pixels in the gallery. Default value is 10.*/ spacing: 20, // Limit the number of photos in the viewport. showMaximum: 5, // Set the scrolling behavior. Default value is true. enableScroll: true, /* Direction to flip picture. Options are "left", "right", "top", "bottom". Default value is bottom.*/ flipDirection: "left", // Autoplay time interval. Default value is false. autoplay: 1200 }); $(".next").click(function() { $(".gallery").flipForward(); return false; }); $(".prev").click(function() { $(".gallery").flipBackward(); return false; }); }); </script></head><body> <h3 style="color:green"> GeeksForGeeks - jQuery Flipping gallery </h3> <div class="wrapper"> <div class="page-container"> <div class="gallery"> <a href="#" data-caption="GeeksForGeeks Logo"> <img src="images/geeksimage1.png" border="2"></a> <a href="#" data-caption="Learning computer science!"> <img src="images/geeksimage2.png" border="2"></a> <a href="#" data-caption="jQuery is fun."> <img src="images/geeksimage3.png" border="2"></a> <a href="#" data-caption="Geeks week contest"> <img src="images/gfg2.jpg" border="2"></a> <a href="#" data-caption="WebTechnology classes"> <img src="images/gfg6.png" border="2"></a> <a href="#" data-caption="Going thr links and hyperlinks"> <img src="images/background.jpg" border="2"></a> <a href="#" data-caption="HTML fundamentals"> <img src="images/background2.jpg" border="2"></a> <a href="#" data-caption="CSS tutorials"> <img src="images/background3.jpg" border="2"></a> </div> <div class="navigation"> <a href="#" class="btn prev">Previous</a> <a href="#" class="btn next">Next</a> </div> </div> </div></body></html>
Output:
In the following script, the option setting for flipping in top direction is shown. The programmers can similarly make use of other options as well for different flipping options.
$(document).ready( function() { $(".gallery").flipping_gallery({ flipDirection: "top", autoplay: false });});
Output:
jQuery-Plugin
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
jQuery | children() with Examples
Scroll to the top of the page using JavaScript/jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
How to get the value in an input text box using jQuery ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 296,
"s": 28,
"text": "jQuery provides a simple, beautiful, and interactive flipping gallery plugin which helps programmers to flip many images in a gallery in various directions with the autoplay feature. The plugin is implemented by using HTML markups and simple javascript function call."
},
{
"code": null,
"e": 505,
"s": 296,
"text": "Please download the Flipping gallery plugin in your working folder and include all the relevant files in the head section of your landing web page.Download link: https://github.com/peachananr/flipping_gallery"
},
{
"code": null,
"e": 720,
"s": 505,
"text": "Example 1: In the following program, the simple call of flipping_gallery() function is shown for basic usage. Previous and Next buttons are provided for handling of flipping images in forward or backward movements."
},
{
"code": "<!doctype html><html><head> <meta charset=\"utf-8\"> <title>jQuery Flipping Gallery Plugin </title> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300, 400, 700' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Noto+Serif:400, 700, 400italic, 700italic' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'> <link href='flipping_gallery.css' rel='stylesheet' type='text/css'> <script type=\"text/javascript\" src=\"http://code.jquery.com/jquery-1.9.1.js\"> </script> <script type=\"text/javascript\" src=\"jquery.flipping_gallery.js\"> </script> <style> html { height: 90%; } body { padding: 0; text-align: center; font-family: 'open sans'; position: relative; margin: 0; height: 80%; } .wrapper { height: auto !important; height: 60%; margin: 0 auto; overflow: hidden; } a { text-decoration: none; } .btn { display: inline-block; border: 4px solid black; border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; background: green; display: inline-block; line-height: 100%; padding: 0.6em; text-decoration: none; color: #0d2633; width: 100px; line-height: 100%; font-size: 14px; font-family: open sans; font-weight: bold; border: none; margin-left: 10px; } .btns { width: 200px; margin: 20px auto; } .page-container { max-width: 700px; margin: auto; position: relative; } .gallery { height: 300px; width: 500px; margin: 150px auto 100px; } img { border : 1px solid black; } </style> <script> $(document).ready( function() { $(\".gallery\").flipping_gallery(); $(\".next\").click(function() { $(\".gallery\").flipForward(); return false; }); $(\".prev\").click(function() { $(\".gallery\").flipBackward(); return false; }); }); </script></head><body> <h3 style=\"color:green\"> GeeksForGeeks - jQuery Flipping gallery </h3> <div class=\"wrapper\"> <div class=\"page-container\"> <div class=\"gallery\"> <a href=\"#\" data-caption=\"\"> <img src=\"images/geeksimage1.png\" border=\"2\"></a> <a href=\"#\" data-caption=\"\"> <img src=\"images/geeksimage2.png\" border=\"2\"></a> <a href=\"#\" data-caption=\"\"> <img src=\"images/geeksimage3.png\" border=\"2\"></a> <a href=\"#\" data-caption=\"\"> <img src=\"images/gfg2.jpg\" border=\"2\"></a> <a href=\"#\" data-caption=\"\"> <img src=\"images/gfg6.png\" border=\"2\"></a> <a href=\"#\" data-caption=\"\"> <img src=\"images/background.jpg\" border=\"2\"></a> <a href=\"#\" data-caption=\"\"> <img src=\"images/background2.jpg\" border=\"2\"></a> <a href=\"#\" data-caption=\"\"> <img src=\"images/background3.jpg\" border=\"2\"></a> </div> <div class=\"navigation\"> <a href=\"#\" class=\"btn prev\">Previous</a> <a href=\"#\" class=\"btn next\">Next</a> </div> </div> </div></body></html>",
"e": 4299,
"s": 720,
"text": null
},
{
"code": null,
"e": 4308,
"s": 4299,
"text": "Output :"
},
{
"code": null,
"e": 4643,
"s": 4308,
"text": "Example 2: In the following program, various options setting are implemented using javascript function call.The programmer can make use of various options depending on the application’s requirement. Please read the comments for each option values and use accordingly. Programmer can make use of data-caption attribute to add captions."
},
{
"code": "<!doctype html><html><head> <meta charset=\"utf-8\"> <title>jQuery Flipping Gallery Plugin </title> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300, 400, 700' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Noto+Serif:400, 700, 400italic, 700italic' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'> <link href='flipping_gallery.css' rel='stylesheet' type='text/css'> <script type=\"text/javascript\" src=\"http://code.jquery.com/jquery-1.9.1.js\"> </script> <script type=\"text/javascript\" src=\"jquery.flipping_gallery.js\"> </script> <style> html { height: 90%; } body { padding: 0; text-align: center; font-family: 'open sans'; position: relative; margin: 0; height: 80%; } .wrapper { height: auto !important; height: 60%; margin: 0 auto; overflow: hidden; } a { text-decoration: none; } .btn { display: inline-block; border: 4px solid black; border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; background: green; display: inline-block; line-height: 100%; padding: 0.6em; text-decoration: none; color: #0d2633; width: 100px; line-height: 100%; font-size: 14px; font-family: open sans; font-weight: bold; border: none; margin-left: 10px; } .btns { width: 200px; margin: 20px auto; } .page-container { max-width: 700px; margin: auto; position: relative; } .gallery { height: 310px; width: 500px; margin: 150px auto 100px; } img { border : 1px solid black; } .navigation { margin-bottom: 150px; } </style> <script> $(document).ready( function() { $(\".gallery\").flipping_gallery({/* The options for the flipping direction are \"forward\", or \"backward\". Default value is forward.*/ direction: \"forward\", // Default selector is set for generation of the gallery. selector: \"> a\", /* Spacing between each photo in pixels in the gallery. Default value is 10.*/ spacing: 20, // Limit the number of photos in the viewport. showMaximum: 5, // Set the scrolling behavior. Default value is true. enableScroll: true, /* Direction to flip picture. Options are \"left\", \"right\", \"top\", \"bottom\". Default value is bottom.*/ flipDirection: \"left\", // Autoplay time interval. Default value is false. autoplay: 1200 }); $(\".next\").click(function() { $(\".gallery\").flipForward(); return false; }); $(\".prev\").click(function() { $(\".gallery\").flipBackward(); return false; }); }); </script></head><body> <h3 style=\"color:green\"> GeeksForGeeks - jQuery Flipping gallery </h3> <div class=\"wrapper\"> <div class=\"page-container\"> <div class=\"gallery\"> <a href=\"#\" data-caption=\"GeeksForGeeks Logo\"> <img src=\"images/geeksimage1.png\" border=\"2\"></a> <a href=\"#\" data-caption=\"Learning computer science!\"> <img src=\"images/geeksimage2.png\" border=\"2\"></a> <a href=\"#\" data-caption=\"jQuery is fun.\"> <img src=\"images/geeksimage3.png\" border=\"2\"></a> <a href=\"#\" data-caption=\"Geeks week contest\"> <img src=\"images/gfg2.jpg\" border=\"2\"></a> <a href=\"#\" data-caption=\"WebTechnology classes\"> <img src=\"images/gfg6.png\" border=\"2\"></a> <a href=\"#\" data-caption=\"Going thr links and hyperlinks\"> <img src=\"images/background.jpg\" border=\"2\"></a> <a href=\"#\" data-caption=\"HTML fundamentals\"> <img src=\"images/background2.jpg\" border=\"2\"></a> <a href=\"#\" data-caption=\"CSS tutorials\"> <img src=\"images/background3.jpg\" border=\"2\"></a> </div> <div class=\"navigation\"> <a href=\"#\" class=\"btn prev\">Previous</a> <a href=\"#\" class=\"btn next\">Next</a> </div> </div> </div></body></html>",
"e": 9112,
"s": 4643,
"text": null
},
{
"code": null,
"e": 9120,
"s": 9112,
"text": "Output:"
},
{
"code": null,
"e": 9300,
"s": 9120,
"text": "In the following script, the option setting for flipping in top direction is shown. The programmers can similarly make use of other options as well for different flipping options."
},
{
"code": "$(document).ready( function() { $(\".gallery\").flipping_gallery({ flipDirection: \"top\", autoplay: false });});",
"e": 9432,
"s": 9300,
"text": null
},
{
"code": null,
"e": 9440,
"s": 9432,
"text": "Output:"
},
{
"code": null,
"e": 9454,
"s": 9440,
"text": "jQuery-Plugin"
},
{
"code": null,
"e": 9461,
"s": 9454,
"text": "JQuery"
},
{
"code": null,
"e": 9478,
"s": 9461,
"text": "Web Technologies"
},
{
"code": null,
"e": 9576,
"s": 9478,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9605,
"s": 9576,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 9639,
"s": 9605,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 9693,
"s": 9639,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 9749,
"s": 9693,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 9806,
"s": 9749,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 9868,
"s": 9806,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 9901,
"s": 9868,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 9962,
"s": 9901,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 10012,
"s": 9962,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
MVC (Model View Controller) Architecture Pattern in Android with Example
|
27 Oct, 2020
Developing an android application by applying a software architecture pattern is always preferred by the developers. An architecture pattern gives modularity to the project files and assures that all the codes get covered in Unit testing. It makes the task easy for developers to maintain the software and to expand the features of the application in the future. There are some architectures that are very popular among developers and one of them is the Model—View—Controller(MVC) Pattern. The MVC pattern suggests splitting the code into 3 components. While creating the class/file of the application, the developer must categorize it into one of the following three layers:
Model: This component stores the application data. It has no knowledge about the interface. The model is responsible for handling the domain logic(real-world business rules) and communication with the database and network layers.
View: It is the UI(User Interface) layer that holds components that are visible on the screen. Moreover, it provides the visualization of the data stored in the Model and offers interaction to the user.
Controller: This component establishes the relationship between the View and the Model. It contains the core application logic and gets informed of the user’s behavior and updates the Model as per the need.
In spite of applying MVC schema to give a modular design to the application, code layers do depend on each other. In this pattern, View and Controller both depend upon the Model. Multiple approaches are possible to apply the MVC pattern in the project:
Approach 1: Activities and fragments can perform the role of Controller and are responsible for updating the View.
Approach 2: Use activity or fragments as views and controller while Model will be a separate class that does not extend any Android class.
In MVC architecture, application data is updated by the controller and View gets the data. Since the Model component is separated, it could be tested independently of the UI. Further, if the View layer respects the single responsibility principle then their role is just to update the Controller for every user event and just display data from the Model, without implementing any business logic. In this case, UI tests should be enough to cover the functionalities of the View.
To understand the implementation of the MVC architecture pattern more clearly, here is a simple example of an android application. This application will have 3 buttons and each one of them displays the count that how many times the user has clicked that particular button. To develop this application the code has been separated in the following manner:
Controller and View will be handled by the Activity. Whenever the user clicks the buttons, activity directs the Model to handle the further operations. The activity will act as an observer.
The Model will be a separate class that contains the data to be displayed. The operations on the data will be performed by functions of this class and after updating the values of the data this Observable class notifies the Observer(Activity) about the change.
Below is the complete step-by-step implementation of this android application using the MVC architecture pattern:
Note: Following steps are performed on Android Studio version 4.0
Step 1: Create a new project
Click on File, then New => New Project.Choose Empty activitySelect language as Java/KotlinSelect the minimum SDK as per your need.
Click on File, then New => New Project.
Choose Empty activity
Select language as Java/Kotlin
Select the minimum SDK as per your need.
Step 2: Modify String.xml file
All the strings which are used in the activity are listed in this file.
XML
<resources> <string name="app_name">GfG | MVC Architecture</string> <string name="Heading">MVC Architecture Pattern</string> <string name="Text1">Button_1</string> <string name="count">Count:0</string></resources>
Step 3: Working with the activity_main.xml file
Open the activity_main.xml file and add 3 Buttons to it which will display the count values as per the number of times the user clicks it. Below is the code for designing a proper activity layout.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#168BC34A" tools:context=".MainActivity" > <!-- Provided Linear layout for the activity. --> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <!-- TextView to display heading of the activity. --> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:layout_marginBottom="60dp" android:fontFamily="@font/roboto" android:text="@string/Heading" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="30sp" android:textStyle="bold" /> <!-- First Button of the activity. --> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginTop="30dp" android:layout_marginEnd="20dp" android:layout_marginBottom="20dp" android:background="#4CAF50" android:fontFamily="@font/roboto" android:text="@string/count" android:textColor="@android:color/background_light" android:textSize="24sp" android:textStyle="bold" /> <!-- Second Button of the activity. --> <Button android:id="@+id/button2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginTop="50dp" android:layout_marginEnd="20dp" android:layout_marginBottom="20dp" android:background="#4CAF50" android:fontFamily="@font/roboto" android:text="@string/count" android:textColor="@android:color/background_light" android:textSize="24sp" android:textStyle="bold" /> <!-- Third Button of the activity. --> <Button android:id="@+id/button3" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginTop="50dp" android:layout_marginEnd="20dp" android:layout_marginBottom="20dp" android:background="#4CAF50" android:fontFamily="@font/roboto" android:text="@string/count" android:textColor="@android:color/background_light" android:textSize="24sp" android:textStyle="bold" /> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" app:srcCompat="@drawable/banner" /> </LinearLayout></androidx.constraintlayout.widget.ConstraintLayout>
Step 4: Creating the Model class
Create a new class named Model to separate all data and its operations. This class will not know the existence of View Class.
Java
Kotlin
import java.util.*; public class Model extends Observable { // declaring a list of integer private List<Integer> List; // constructor to initialize the list public Model(){ // reserving the space for list elements List = new ArrayList<Integer>(3); // adding elements into the list List.add(0); List.add(0); List.add(0); } // defining getter and setter functions // function to return appropriate count // value at correct index public int getValueAtIndex(final int the_index) throws IndexOutOfBoundsException{ return List.get(the_index); } // function to make changes in the activity button's // count value when user touch it public void setValueAtIndex(final int the_index) throws IndexOutOfBoundsException{ List.set(the_index,List.get(the_index) + 1); setChanged(); notifyObservers(); } }
import java.util.*import kotlin.collections.ArrayList class Model : Observable() { // declaring a list of integer val List: MutableList<Int> // constructor to initialize the list init { // reserving the space for list elements List = ArrayList(3) // adding elements into the list List.add(0) List.add(0) List.add(0) } // defining getter and setter functions // function to return appropriate count // value at correct index @Throws(IndexOutOfBoundsException::class) fun getValueAtIndex(the_index: Int): Int { return List[the_index] } // function to make changes in the activity button's // count value when user touch it @Throws(IndexOutOfBoundsException::class) fun setValueAtIndex(the_index: Int) { List[the_index] = List[the_index] + 1 setChanged() notifyObservers() }}
Step 5: Define functionalities of View and Controller in the MainActivity file
This class will establish the relationship between View and Model. The data provided by the Model will be used by View and the appropriate changes will be made in the activity.
Java
Kotlin
import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import java.util.Observable;import java.util.Observer; public class MainActivity extends AppCompatActivity implements Observer, View.OnClickListener { // creating object of Model class private Model myModel; // creating object of Button class private Button Button1; private Button Button2; private Button Button3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // creating relationship between the // observable Model and the // observer Activity myModel = new Model(); myModel.addObserver(this); // assigning button IDs to the objects Button1 = findViewById(R.id.button); Button2 = findViewById(R.id.button2); Button3 = findViewById(R.id.button3); // transfer the control to Onclick() method // when a button is clicked by passing // argument "this" Button1.setOnClickListener(this); Button2.setOnClickListener(this); Button3.setOnClickListener(this); } @Override // calling setValueAtIndex() method // by passing appropriate arguments // for different buttons public void onClick(View v) { switch(v.getId()){ case R.id.button: myModel.setValueAtIndex(0); break; case R.id.button2: myModel.setValueAtIndex(1); break; case R.id.button3: myModel.setValueAtIndex(2); break; } } @Override // function to update the view after // the values are modified by the model public void update(Observable arg0, Object arg1) { // changing text of the buttons // according to updated values Button1.setText("Count: "+myModel.getValueAtIndex(0)); Button2.setText("Count: "+myModel.getValueAtIndex(1)); Button3.setText("Count: "+myModel.getValueAtIndex(2)); }}
import android.os.Bundleimport android.view.Viewimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivityimport java.util.* class MainActivity : AppCompatActivity(), Observer, View.OnClickListener { // creating object of Model class var myModel: Model? = null // creating object of Button class var Button1: Button? = null var Button2: Button? = null var Button3: Button? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // creating relationship between the // observable Model and the // observer Activity myModel = Model() myModel!!.addObserver(this) // assigning button IDs to the objects Button1 = findViewById(R.id.button) Button2 = findViewById(R.id.button2) Button3 = findViewById(R.id.button3) // transfer the control to Onclick() method // when a button is clicked by passing // argument "this" Button1?.setOnClickListener(this) Button2?.setOnClickListener(this) Button3?.setOnClickListener(this) } // calling setValueAtIndex() method // by passing appropriate arguments // for different buttons override fun onClick(v: View) { when (v.id) { R.id.button -> myModel?.setValueAtIndex(0) R.id.button2 -> myModel?.setValueAtIndex(1) R.id.button3 -> myModel?.setValueAtIndex(2) } } // function to update the view after // the values are modified by the model override fun update(arg0: Observable, arg1: Any?) { // changing text of the buttons // according to updated values Button1!!.text = "Count: " + myModel!!.getValueAtIndex(0) Button2!!.text = "Count: " + myModel!!.getValueAtIndex(1) Button3!!.text = "Count: " + myModel!!.getValueAtIndex(2) }}
MVC pattern increases the code testability and makes it easier to implement new features as it highly supports the separation of concerns.
Unit testing of Model and Controller is possible as they do not extend or use any Android class.
Functionalities of the View can be checked through UI tests if the View respect the single responsibility principle(update controller and display data from the model without implementing domain logic)
Code layers depend on each other even if MVC is applied correctly.
No parameter to handle UI logic i.e., how to display the data.
android
Technical Scripter 2020
Android
Java
Kotlin
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Android SDK and it's Components
Navigation Drawer in Android
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Oct, 2020"
},
{
"code": null,
"e": 728,
"s": 52,
"text": "Developing an android application by applying a software architecture pattern is always preferred by the developers. An architecture pattern gives modularity to the project files and assures that all the codes get covered in Unit testing. It makes the task easy for developers to maintain the software and to expand the features of the application in the future. There are some architectures that are very popular among developers and one of them is the Model—View—Controller(MVC) Pattern. The MVC pattern suggests splitting the code into 3 components. While creating the class/file of the application, the developer must categorize it into one of the following three layers:"
},
{
"code": null,
"e": 958,
"s": 728,
"text": "Model: This component stores the application data. It has no knowledge about the interface. The model is responsible for handling the domain logic(real-world business rules) and communication with the database and network layers."
},
{
"code": null,
"e": 1161,
"s": 958,
"text": "View: It is the UI(User Interface) layer that holds components that are visible on the screen. Moreover, it provides the visualization of the data stored in the Model and offers interaction to the user."
},
{
"code": null,
"e": 1368,
"s": 1161,
"text": "Controller: This component establishes the relationship between the View and the Model. It contains the core application logic and gets informed of the user’s behavior and updates the Model as per the need."
},
{
"code": null,
"e": 1621,
"s": 1368,
"text": "In spite of applying MVC schema to give a modular design to the application, code layers do depend on each other. In this pattern, View and Controller both depend upon the Model. Multiple approaches are possible to apply the MVC pattern in the project:"
},
{
"code": null,
"e": 1736,
"s": 1621,
"text": "Approach 1: Activities and fragments can perform the role of Controller and are responsible for updating the View."
},
{
"code": null,
"e": 1875,
"s": 1736,
"text": "Approach 2: Use activity or fragments as views and controller while Model will be a separate class that does not extend any Android class."
},
{
"code": null,
"e": 2353,
"s": 1875,
"text": "In MVC architecture, application data is updated by the controller and View gets the data. Since the Model component is separated, it could be tested independently of the UI. Further, if the View layer respects the single responsibility principle then their role is just to update the Controller for every user event and just display data from the Model, without implementing any business logic. In this case, UI tests should be enough to cover the functionalities of the View."
},
{
"code": null,
"e": 2707,
"s": 2353,
"text": "To understand the implementation of the MVC architecture pattern more clearly, here is a simple example of an android application. This application will have 3 buttons and each one of them displays the count that how many times the user has clicked that particular button. To develop this application the code has been separated in the following manner:"
},
{
"code": null,
"e": 2897,
"s": 2707,
"text": "Controller and View will be handled by the Activity. Whenever the user clicks the buttons, activity directs the Model to handle the further operations. The activity will act as an observer."
},
{
"code": null,
"e": 3158,
"s": 2897,
"text": "The Model will be a separate class that contains the data to be displayed. The operations on the data will be performed by functions of this class and after updating the values of the data this Observable class notifies the Observer(Activity) about the change."
},
{
"code": null,
"e": 3272,
"s": 3158,
"text": "Below is the complete step-by-step implementation of this android application using the MVC architecture pattern:"
},
{
"code": null,
"e": 3338,
"s": 3272,
"text": "Note: Following steps are performed on Android Studio version 4.0"
},
{
"code": null,
"e": 3367,
"s": 3338,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 3498,
"s": 3367,
"text": "Click on File, then New => New Project.Choose Empty activitySelect language as Java/KotlinSelect the minimum SDK as per your need."
},
{
"code": null,
"e": 3538,
"s": 3498,
"text": "Click on File, then New => New Project."
},
{
"code": null,
"e": 3560,
"s": 3538,
"text": "Choose Empty activity"
},
{
"code": null,
"e": 3591,
"s": 3560,
"text": "Select language as Java/Kotlin"
},
{
"code": null,
"e": 3632,
"s": 3591,
"text": "Select the minimum SDK as per your need."
},
{
"code": null,
"e": 3663,
"s": 3632,
"text": "Step 2: Modify String.xml file"
},
{
"code": null,
"e": 3735,
"s": 3663,
"text": "All the strings which are used in the activity are listed in this file."
},
{
"code": null,
"e": 3739,
"s": 3735,
"text": "XML"
},
{
"code": "<resources> <string name=\"app_name\">GfG | MVC Architecture</string> <string name=\"Heading\">MVC Architecture Pattern</string> <string name=\"Text1\">Button_1</string> <string name=\"count\">Count:0</string></resources>",
"e": 3965,
"s": 3739,
"text": null
},
{
"code": null,
"e": 4013,
"s": 3965,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 4210,
"s": 4013,
"text": "Open the activity_main.xml file and add 3 Buttons to it which will display the count values as per the number of times the user clicks it. Below is the code for designing a proper activity layout."
},
{
"code": null,
"e": 4214,
"s": 4210,
"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:layout_height=\"match_parent\" android:background=\"#168BC34A\" tools:context=\".MainActivity\" > <!-- Provided Linear layout for the activity. --> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"> <!-- TextView to display heading of the activity. --> <TextView android:id=\"@+id/textView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"40dp\" android:layout_marginBottom=\"60dp\" android:fontFamily=\"@font/roboto\" android:text=\"@string/Heading\" android:textAlignment=\"center\" android:textColor=\"@android:color/holo_green_dark\" android:textSize=\"30sp\" android:textStyle=\"bold\" /> <!-- First Button of the activity. --> <Button android:id=\"@+id/button\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"30dp\" android:layout_marginEnd=\"20dp\" android:layout_marginBottom=\"20dp\" android:background=\"#4CAF50\" android:fontFamily=\"@font/roboto\" android:text=\"@string/count\" android:textColor=\"@android:color/background_light\" android:textSize=\"24sp\" android:textStyle=\"bold\" /> <!-- Second Button of the activity. --> <Button android:id=\"@+id/button2\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"50dp\" android:layout_marginEnd=\"20dp\" android:layout_marginBottom=\"20dp\" android:background=\"#4CAF50\" android:fontFamily=\"@font/roboto\" android:text=\"@string/count\" android:textColor=\"@android:color/background_light\" android:textSize=\"24sp\" android:textStyle=\"bold\" /> <!-- Third Button of the activity. --> <Button android:id=\"@+id/button3\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"50dp\" android:layout_marginEnd=\"20dp\" android:layout_marginBottom=\"20dp\" android:background=\"#4CAF50\" android:fontFamily=\"@font/roboto\" android:text=\"@string/count\" android:textColor=\"@android:color/background_light\" android:textSize=\"24sp\" android:textStyle=\"bold\" /> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"30dp\" app:srcCompat=\"@drawable/banner\" /> </LinearLayout></androidx.constraintlayout.widget.ConstraintLayout>",
"e": 7815,
"s": 4214,
"text": null
},
{
"code": null,
"e": 7848,
"s": 7815,
"text": "Step 4: Creating the Model class"
},
{
"code": null,
"e": 7975,
"s": 7848,
"text": " Create a new class named Model to separate all data and its operations. This class will not know the existence of View Class."
},
{
"code": null,
"e": 7980,
"s": 7975,
"text": "Java"
},
{
"code": null,
"e": 7987,
"s": 7980,
"text": "Kotlin"
},
{
"code": "import java.util.*; public class Model extends Observable { // declaring a list of integer private List<Integer> List; // constructor to initialize the list public Model(){ // reserving the space for list elements List = new ArrayList<Integer>(3); // adding elements into the list List.add(0); List.add(0); List.add(0); } // defining getter and setter functions // function to return appropriate count // value at correct index public int getValueAtIndex(final int the_index) throws IndexOutOfBoundsException{ return List.get(the_index); } // function to make changes in the activity button's // count value when user touch it public void setValueAtIndex(final int the_index) throws IndexOutOfBoundsException{ List.set(the_index,List.get(the_index) + 1); setChanged(); notifyObservers(); } }",
"e": 8902,
"s": 7987,
"text": null
},
{
"code": "import java.util.*import kotlin.collections.ArrayList class Model : Observable() { // declaring a list of integer val List: MutableList<Int> // constructor to initialize the list init { // reserving the space for list elements List = ArrayList(3) // adding elements into the list List.add(0) List.add(0) List.add(0) } // defining getter and setter functions // function to return appropriate count // value at correct index @Throws(IndexOutOfBoundsException::class) fun getValueAtIndex(the_index: Int): Int { return List[the_index] } // function to make changes in the activity button's // count value when user touch it @Throws(IndexOutOfBoundsException::class) fun setValueAtIndex(the_index: Int) { List[the_index] = List[the_index] + 1 setChanged() notifyObservers() }}",
"e": 9802,
"s": 8902,
"text": null
},
{
"code": null,
"e": 9881,
"s": 9802,
"text": "Step 5: Define functionalities of View and Controller in the MainActivity file"
},
{
"code": null,
"e": 10058,
"s": 9881,
"text": "This class will establish the relationship between View and Model. The data provided by the Model will be used by View and the appropriate changes will be made in the activity."
},
{
"code": null,
"e": 10063,
"s": 10058,
"text": "Java"
},
{
"code": null,
"e": 10070,
"s": 10063,
"text": "Kotlin"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import java.util.Observable;import java.util.Observer; public class MainActivity extends AppCompatActivity implements Observer, View.OnClickListener { // creating object of Model class private Model myModel; // creating object of Button class private Button Button1; private Button Button2; private Button Button3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // creating relationship between the // observable Model and the // observer Activity myModel = new Model(); myModel.addObserver(this); // assigning button IDs to the objects Button1 = findViewById(R.id.button); Button2 = findViewById(R.id.button2); Button3 = findViewById(R.id.button3); // transfer the control to Onclick() method // when a button is clicked by passing // argument \"this\" Button1.setOnClickListener(this); Button2.setOnClickListener(this); Button3.setOnClickListener(this); } @Override // calling setValueAtIndex() method // by passing appropriate arguments // for different buttons public void onClick(View v) { switch(v.getId()){ case R.id.button: myModel.setValueAtIndex(0); break; case R.id.button2: myModel.setValueAtIndex(1); break; case R.id.button3: myModel.setValueAtIndex(2); break; } } @Override // function to update the view after // the values are modified by the model public void update(Observable arg0, Object arg1) { // changing text of the buttons // according to updated values Button1.setText(\"Count: \"+myModel.getValueAtIndex(0)); Button2.setText(\"Count: \"+myModel.getValueAtIndex(1)); Button3.setText(\"Count: \"+myModel.getValueAtIndex(2)); }}",
"e": 12226,
"s": 10070,
"text": null
},
{
"code": "import android.os.Bundleimport android.view.Viewimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivityimport java.util.* class MainActivity : AppCompatActivity(), Observer, View.OnClickListener { // creating object of Model class var myModel: Model? = null // creating object of Button class var Button1: Button? = null var Button2: Button? = null var Button3: Button? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // creating relationship between the // observable Model and the // observer Activity myModel = Model() myModel!!.addObserver(this) // assigning button IDs to the objects Button1 = findViewById(R.id.button) Button2 = findViewById(R.id.button2) Button3 = findViewById(R.id.button3) // transfer the control to Onclick() method // when a button is clicked by passing // argument \"this\" Button1?.setOnClickListener(this) Button2?.setOnClickListener(this) Button3?.setOnClickListener(this) } // calling setValueAtIndex() method // by passing appropriate arguments // for different buttons override fun onClick(v: View) { when (v.id) { R.id.button -> myModel?.setValueAtIndex(0) R.id.button2 -> myModel?.setValueAtIndex(1) R.id.button3 -> myModel?.setValueAtIndex(2) } } // function to update the view after // the values are modified by the model override fun update(arg0: Observable, arg1: Any?) { // changing text of the buttons // according to updated values Button1!!.text = \"Count: \" + myModel!!.getValueAtIndex(0) Button2!!.text = \"Count: \" + myModel!!.getValueAtIndex(1) Button3!!.text = \"Count: \" + myModel!!.getValueAtIndex(2) }}",
"e": 14160,
"s": 12226,
"text": null
},
{
"code": null,
"e": 14299,
"s": 14160,
"text": "MVC pattern increases the code testability and makes it easier to implement new features as it highly supports the separation of concerns."
},
{
"code": null,
"e": 14396,
"s": 14299,
"text": "Unit testing of Model and Controller is possible as they do not extend or use any Android class."
},
{
"code": null,
"e": 14597,
"s": 14396,
"text": "Functionalities of the View can be checked through UI tests if the View respect the single responsibility principle(update controller and display data from the model without implementing domain logic)"
},
{
"code": null,
"e": 14664,
"s": 14597,
"text": "Code layers depend on each other even if MVC is applied correctly."
},
{
"code": null,
"e": 14727,
"s": 14664,
"text": "No parameter to handle UI logic i.e., how to display the data."
},
{
"code": null,
"e": 14735,
"s": 14727,
"text": "android"
},
{
"code": null,
"e": 14759,
"s": 14735,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 14767,
"s": 14759,
"text": "Android"
},
{
"code": null,
"e": 14772,
"s": 14767,
"text": "Java"
},
{
"code": null,
"e": 14779,
"s": 14772,
"text": "Kotlin"
},
{
"code": null,
"e": 14798,
"s": 14779,
"text": "Technical Scripter"
},
{
"code": null,
"e": 14803,
"s": 14798,
"text": "Java"
},
{
"code": null,
"e": 14811,
"s": 14803,
"text": "Android"
},
{
"code": null,
"e": 14909,
"s": 14811,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14978,
"s": 14909,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 15009,
"s": 14978,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 15052,
"s": 15009,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 15084,
"s": 15052,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 15113,
"s": 15084,
"text": "Navigation Drawer in Android"
},
{
"code": null,
"e": 15128,
"s": 15113,
"text": "Arrays in Java"
},
{
"code": null,
"e": 15172,
"s": 15128,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 15208,
"s": 15172,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 15233,
"s": 15208,
"text": "Reverse a string in Java"
}
] |
How to generate byte code file in python ?
|
01 Nov, 2017
Whenever the Python script compiles, it automatically generates a compiled code called as byte code. The byte-code is not actually interpreted to machine code, unless there is some exotic implementation such as PyPy.
The byte-code is loaded into the Python run-time and interpreted by a virtual machine, which is a piece of code that reads each instruction in the byte-code and executes whatever operation is indicated.
Byte Code is automatically created in the same directory as .py file, when a module of python is imported for the first time, or when the source is more recent than the current compiled file. Next time, when the program is run, python interpretator use this file to skip the compilation step.
Running a script is not considered an import and no .pyc file will be created. For instance, let’s write a script file abc.py that imports another module xyz.py. Now run abc.py file, xyz.pyc will be created since xyz is imported, but no abc.pyc file will be created since abc.py isn’t being imported.
But there exist an inbuilt py_compile and compileall modules and commands which facilitate the creation of .pyc file.
Using py_compile.compile function: The py_compile module can manually compile any module. One way is to use the py_compile.compile function in that module interactively:>>> import py_compile
>>> py_compile.compile('abc.py')
This will write the .pyc to the same location as abc.py.Using py_compile.main() function: It compiles several files at a time.>>> import py_compile
>>> py_compile.main(['File1.py','File2.py','File3.py'])
Using compileall.compile_dir() function: It compiles every single python file present in the directory supplied.>>> import compileall
>>> compileall.compile_dir(directoryname)
Using py_compile in Terminal:$ python -m py_compile File1.py File2.py File3.py ...
Or, for Interactive Compilation of files$ python -m py_compile -
File1.py
File2.py
File3.py
.
.
.
Using compileall in Terminal: This command will automatically go recursively into sub directories and make .pyc files for all the python files it finds.$ python -m compileall
Using py_compile.compile function: The py_compile module can manually compile any module. One way is to use the py_compile.compile function in that module interactively:>>> import py_compile
>>> py_compile.compile('abc.py')
This will write the .pyc to the same location as abc.py.
>>> import py_compile
>>> py_compile.compile('abc.py')
This will write the .pyc to the same location as abc.py.
Using py_compile.main() function: It compiles several files at a time.>>> import py_compile
>>> py_compile.main(['File1.py','File2.py','File3.py'])
>>> import py_compile
>>> py_compile.main(['File1.py','File2.py','File3.py'])
Using compileall.compile_dir() function: It compiles every single python file present in the directory supplied.>>> import compileall
>>> compileall.compile_dir(directoryname)
>>> import compileall
>>> compileall.compile_dir(directoryname)
Using py_compile in Terminal:$ python -m py_compile File1.py File2.py File3.py ...
Or, for Interactive Compilation of files$ python -m py_compile -
File1.py
File2.py
File3.py
.
.
.
$ python -m py_compile File1.py File2.py File3.py ...
Or, for Interactive Compilation of files
$ python -m py_compile -
File1.py
File2.py
File3.py
.
.
.
Using compileall in Terminal: This command will automatically go recursively into sub directories and make .pyc files for all the python files it finds.$ python -m compileall
$ python -m compileall
Note: The compileall and py_compile module is part of the python standard library, so there is no need to install anything extra to use it.
References:1. https://docs.python.org/3/library/py_compile.html2. https://docs.python.org/2/library/compileall.html3. Effbot
This article is contributed by Shubham Bansal. 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.
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Nov, 2017"
},
{
"code": null,
"e": 269,
"s": 52,
"text": "Whenever the Python script compiles, it automatically generates a compiled code called as byte code. The byte-code is not actually interpreted to machine code, unless there is some exotic implementation such as PyPy."
},
{
"code": null,
"e": 472,
"s": 269,
"text": "The byte-code is loaded into the Python run-time and interpreted by a virtual machine, which is a piece of code that reads each instruction in the byte-code and executes whatever operation is indicated."
},
{
"code": null,
"e": 765,
"s": 472,
"text": "Byte Code is automatically created in the same directory as .py file, when a module of python is imported for the first time, or when the source is more recent than the current compiled file. Next time, when the program is run, python interpretator use this file to skip the compilation step."
},
{
"code": null,
"e": 1066,
"s": 765,
"text": "Running a script is not considered an import and no .pyc file will be created. For instance, let’s write a script file abc.py that imports another module xyz.py. Now run abc.py file, xyz.pyc will be created since xyz is imported, but no abc.pyc file will be created since abc.py isn’t being imported."
},
{
"code": null,
"e": 1184,
"s": 1066,
"text": "But there exist an inbuilt py_compile and compileall modules and commands which facilitate the creation of .pyc file."
},
{
"code": null,
"e": 2161,
"s": 1184,
"text": "Using py_compile.compile function: The py_compile module can manually compile any module. One way is to use the py_compile.compile function in that module interactively:>>> import py_compile\n>>> py_compile.compile('abc.py')\nThis will write the .pyc to the same location as abc.py.Using py_compile.main() function: It compiles several files at a time.>>> import py_compile\n>>> py_compile.main(['File1.py','File2.py','File3.py'])\nUsing compileall.compile_dir() function: It compiles every single python file present in the directory supplied.>>> import compileall\n>>> compileall.compile_dir(directoryname)\nUsing py_compile in Terminal:$ python -m py_compile File1.py File2.py File3.py ...\nOr, for Interactive Compilation of files$ python -m py_compile -\n File1.py\n File2.py\n File3.py\n .\n .\n .\nUsing compileall in Terminal: This command will automatically go recursively into sub directories and make .pyc files for all the python files it finds.$ python -m compileall \n"
},
{
"code": null,
"e": 2442,
"s": 2161,
"text": "Using py_compile.compile function: The py_compile module can manually compile any module. One way is to use the py_compile.compile function in that module interactively:>>> import py_compile\n>>> py_compile.compile('abc.py')\nThis will write the .pyc to the same location as abc.py."
},
{
"code": null,
"e": 2498,
"s": 2442,
"text": ">>> import py_compile\n>>> py_compile.compile('abc.py')\n"
},
{
"code": null,
"e": 2555,
"s": 2498,
"text": "This will write the .pyc to the same location as abc.py."
},
{
"code": null,
"e": 2704,
"s": 2555,
"text": "Using py_compile.main() function: It compiles several files at a time.>>> import py_compile\n>>> py_compile.main(['File1.py','File2.py','File3.py'])\n"
},
{
"code": null,
"e": 2783,
"s": 2704,
"text": ">>> import py_compile\n>>> py_compile.main(['File1.py','File2.py','File3.py'])\n"
},
{
"code": null,
"e": 2960,
"s": 2783,
"text": "Using compileall.compile_dir() function: It compiles every single python file present in the directory supplied.>>> import compileall\n>>> compileall.compile_dir(directoryname)\n"
},
{
"code": null,
"e": 3025,
"s": 2960,
"text": ">>> import compileall\n>>> compileall.compile_dir(directoryname)\n"
},
{
"code": null,
"e": 3222,
"s": 3025,
"text": "Using py_compile in Terminal:$ python -m py_compile File1.py File2.py File3.py ...\nOr, for Interactive Compilation of files$ python -m py_compile -\n File1.py\n File2.py\n File3.py\n .\n .\n .\n"
},
{
"code": null,
"e": 3277,
"s": 3222,
"text": "$ python -m py_compile File1.py File2.py File3.py ...\n"
},
{
"code": null,
"e": 3318,
"s": 3277,
"text": "Or, for Interactive Compilation of files"
},
{
"code": null,
"e": 3392,
"s": 3318,
"text": "$ python -m py_compile -\n File1.py\n File2.py\n File3.py\n .\n .\n .\n"
},
{
"code": null,
"e": 3569,
"s": 3392,
"text": "Using compileall in Terminal: This command will automatically go recursively into sub directories and make .pyc files for all the python files it finds.$ python -m compileall \n"
},
{
"code": null,
"e": 3594,
"s": 3569,
"text": "$ python -m compileall \n"
},
{
"code": null,
"e": 3734,
"s": 3594,
"text": "Note: The compileall and py_compile module is part of the python standard library, so there is no need to install anything extra to use it."
},
{
"code": null,
"e": 3859,
"s": 3734,
"text": "References:1. https://docs.python.org/3/library/py_compile.html2. https://docs.python.org/2/library/compileall.html3. Effbot"
},
{
"code": null,
"e": 4161,
"s": 3859,
"text": "This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4168,
"s": 4161,
"text": "Python"
},
{
"code": null,
"e": 4266,
"s": 4168,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4284,
"s": 4266,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4326,
"s": 4284,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4348,
"s": 4326,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4374,
"s": 4348,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4406,
"s": 4374,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4435,
"s": 4406,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4462,
"s": 4435,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4483,
"s": 4462,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4506,
"s": 4483,
"text": "Introduction To PYTHON"
}
] |
Sort an array when two halves are sorted
|
06 Jul, 2022
Given an integer array of which both first half and second half are sorted. Task is to merge two sorted halves of array into single sorted array.
Examples:
Input : A[] = { 2, 3, 8, -1, 7, 10 }
Output : -1, 2, 3, 7, 8, 10
Input : A[] = {-4, 6, 9, -1, 3 }
Output : -4, -1, 3, 6, 9
Method 1: A Simple Solution is to sort the array using built in functions (generally an implementation of quick sort).
Below is the implementation of above method:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to Merge two sorted halves of// array Into Single Sorted Array#include <bits/stdc++.h>using namespace std; void mergeTwoHalf(int A[], int n){ // Sort the given array using sort STL sort(A, A + n);} // Driver codeint main(){ int A[] = { 2, 3, 8, -1, 7, 10 }; int n = sizeof(A) / sizeof(A[0]); mergeTwoHalf(A, n); // Print sorted Array for (int i = 0; i < n; i++) cout << A[i] << " "; return 0;}
// Java program to Merge two sorted halves of// array Into Single Sorted Arrayimport java.io.*;import java.util.*; class GFG { static void mergeTwoHalf(int[] A, int n) { // Sort the given array using sort STL Arrays.sort(A); } // Driver code static public void main(String[] args) { int[] A = { 2, 3, 8, -1, 7, 10 }; int n = A.length; mergeTwoHalf(A, n); // Print sorted Array for (int i = 0; i < n; i++) System.out.print(A[i] + " "); }} // This code is contributed by vt_m .
# Python program to Merge two sorted# halves of array Into Single Sorted Array def mergeTwoHalf(A, n): # Sort the given array using sort STL A.sort() # Driver Codeif __name__ == '__main__': A = [2, 3, 8, -1, 7, 10] n = len(A) mergeTwoHalf(A, n) # Print sorted Array for i in range(n): print(A[i], end=" ") # This code is contributed by 29AjayKumar
// C# program to Merge two sorted halves of// array Into Single Sorted Arrayusing System; class GFG { static void mergeTwoHalf(int[] A, int n) { // Sort the given array using sort STL Array.Sort(A); } // Driver code static public void Main() { int[] A = { 2, 3, 8, -1, 7, 10 }; int n = A.Length; mergeTwoHalf(A, n); // Print sorted Array for (int i = 0; i < n; i++) Console.Write(A[i] + " "); }} // This code is contributed by vt_m .
<?php// PHP program to Merge two sorted halves// of array Into Single Sorted Array function mergeTwoHalf(&$A, $n){ // Sort the given array using sort STL sort($A, 0);} // Driver Code$A = array(2, 3, 8, -1, 7, 10);$n = sizeof($A);mergeTwoHalf($A, $n); // Print sorted Arrayfor ($i = 0; $i < $n; $i++) echo $A[$i] . " "; // This code is contributed// by Akanksha Rai?>
<script> // Javascript program to Merge two sorted halves of// array Into Single Sorted Array function mergeTwoHalf(A, n){ // Sort the given array using sort function A.sort((a,b) => a-b);} // Driver codevar A = [ 2, 3, 8, -1, 7, 10 ];var n = A.length;mergeTwoHalf(A, n); // Print sorted Arrayfor (var i = 0; i < n; i++) document.write( A[i] + " "); // This code is contributed by itsok.</script>
-1 2 3 7 8 10
Time Complexity:
*** QuickLaTeX cannot compile formula:
*** Error message:
Error: Nothing to show, formula is empty
best & average case, worst case (for quicksort)Space Complexity:
*** QuickLaTeX cannot compile formula:
*** Error message:
Error: Nothing to show, formula is empty
to
*** QuickLaTeX cannot compile formula:
*** Error message:
Error: Nothing to show, formula is empty
depending on the case & implementation (for quicksort)
For more details, check out the GFG article on Quicksort.
Method 2: A more efficient solution is to use an auxiliary array which is very similar to the Merge Function of Merge sort.
Below is the implementation of above approach :
C++
Java
Python3
C#
Javascript
// C++ program to Merge Two Sorted Halves Of// Array Into Single Sorted Array#include <bits/stdc++.h>using namespace std; // Merge two sorted halves of Array into single// sorted arrayvoid mergeTwoHalf(int A[], int n){ int half_i = 0; // starting index of second half // Temp Array store sorted resultant array int temp[n]; // First Find the point where array is divide // into two half for (int i = 0; i < n - 1; i++) { if (A[i] > A[i + 1]) { half_i = i + 1; break; } } // If Given array is all-ready sorted if (half_i == 0) return; // Merge two sorted arrays in single sorted array int i = 0, j = half_i, k = 0; while (i < half_i && j < n) { if (A[i] < A[j]) temp[k++] = A[i++]; else temp[k++] = A[j++]; } // Copy the remaining elements of A[i to half_! ] while (i < half_i) temp[k++] = A[i++]; // Copy the remaining elements of A[ half_! to n ] while (j < n) temp[k++] = A[j++]; for (int i = 0; i < n; i++) A[i] = temp[i];} // Driver codeint main(){ int A[] = { 2, 3, 8, -1, 7, 10 }; int n = sizeof(A) / sizeof(A[0]); mergeTwoHalf(A, n); // Print sorted Array for (int i = 0; i < n; i++) cout << A[i] << " "; return 0;}
// Java program to Merge Two Sorted Halves Of// Array Into Single Sorted Arrayimport java.io.*; class GFG { // Merge two sorted halves of Array // into single sorted array static void mergeTwoHalf(int[] A, int n) { int half_i = 0; // starting index of second half int i; // Temp Array store sorted resultant array int[] temp = new int[n]; // First Find the point where array is divide // into two half for (i = 0; i < n - 1; i++) { if (A[i] > A[i + 1]) { half_i = i + 1; break; } } // If Given array is all-ready sorted if (half_i == 0) return; // Merge two sorted arrays in single sorted array i = 0; int j = half_i; int k = 0; while (i < half_i && j < n) { if (A[i] < A[j]) temp[k++] = A[i++]; else temp[k++] = A[j++]; } // Copy the remaining elements of A[i to half_! ] while (i < half_i) temp[k++] = A[i++]; // Copy the remaining elements of A[ half_! to n ] while (j < n) temp[k++] = A[j++]; for (i = 0; i < n; i++) A[i] = temp[i]; } // Driver code static public void main(String[] args) { int[] A = { 2, 3, 8, -1, 7, 10 }; int n = A.length; mergeTwoHalf(A, n); // Print sorted Array for (int i = 0; i < n; i++) System.out.print(A[i] + " "); }} // This code is contributed by vt_m .
# Python3 program to Merge Two Sorted Halves Of# Array Into Single Sorted Array # Merge two sorted halves of Array into single# sorted arraydef mergeTwoHalf(A, n): # Starting index of second half half_i = 0 # Temp Array store sorted resultant array temp = [0 for i in range(n)] # First Find the point where array is # divide into two half for i in range(n - 1): if (A[i] > A[i + 1]): half_i = i + 1 break # If Given array is all-ready sorted if (half_i == 0): return # Merge two sorted arrays in single # sorted array i = 0 j = half_i k = 0 while (i < half_i and j < n): if (A[i] < A[j]): temp[k] = A[i] k += 1 i += 1 else: temp[k] = A[j] k += 1 j += 1 # Copy the remaining elements of A[i to half_! ] while i < half_i: temp[k] = A[i] k += 1 i += 1 # Copy the remaining elements of A[ half_! to n ] while (j < n): temp[k] = A[j] k += 1 j += 1 for i in range(n): A[i] = temp[i] # Driver codeA = [ 2, 3, 8, -1, 7, 10 ]n = len(A) mergeTwoHalf(A, n) # Print sorted Arrayprint(*A, sep = ' ') # This code is contributed by avanitrachhadiya2155
// C# program to Merge Two Sorted Halves Of// Array Into Single Sorted Arrayusing System class GFG { // Merge two sorted halves of Array // into single sorted array static void mergeTwoHalf(int[] A, int n) { int half_i = 0 // starting index of second half int i // Temp Array store sorted resultant array int[] temp = new int[n] // First Find the point where array is divide // into two half for (i = 0 i < n - 1 i++) { if (A[i] > A[i + 1]) { half_i = i + 1 break } } // If Given array is all-ready sorted if (half_i == 0) return // Merge two sorted arrays in single sorted // array i = 0 int j = half_i int k = 0 while (i < half_i & &j < n) { if (A[i] < A[j]) temp[k++] = A[i++] else temp[k++] = A[j++] } // Copy the remaining elements of A[i to half_!] while (i < half_i) temp[k++] = A[i++] // Copy the remaining elements of A[half_! // to n] while (j < n) temp[k++] = A[j++] for (i = 0 i < n i++) A[i] = temp[i] } // Driver code static public void Main() { int[] A = { 2, 3, 8, -1, 7, 10 } int n = A.Length mergeTwoHalf(A, n) // Print sorted Array for (int i = 0 i < n i++) Console.Write(A[i] + " ") }} // This code is contributed by vt_m .
<script> // JavaScript program to Merge Two Sorted Halves Of // Array Into Single Sorted Array // Merge two sorted halves of Array into single // sorted array function mergeTwoHalf(A, n) { let half_i = 0; // starting index of second half // Temp Array store sorted resultant array let temp = new Array(n); temp.fill(0); // First Find the point where array is divide // into two half for (let i = 0; i < n - 1; i++) { if (A[i] > A[i + 1]) { half_i = i + 1; break; } } // If Given array is all-ready sorted if (half_i == 0) return; // Merge two sorted arrays in single sorted array let i = 0, j = half_i, k = 0; while (i < half_i && j < n) { if (A[i] < A[j]) temp[k++] = A[i++]; else temp[k++] = A[j++]; } // Copy the remaining elements of A[i to half_! ] while (i < half_i) temp[k++] = A[i++]; // Copy the remaining elements of A[ half_! to n ] while (j < n) temp[k++] = A[j++]; for (let i = 0; i < n; i++) A[i] = temp[i]; } let A = [ 2, 3, 8, -1, 7, 10 ]; let n = A.length; mergeTwoHalf(A, n); // Print sorted Array for (let i = 0; i < n; i++) document.write(A[i] + " "); </script>
-1 2 3 7 8 10
Time Complexity:
*** QuickLaTeX cannot compile formula:
*** Error message:
Error: Nothing to show, formula is empty
Space Complexity:
*** QuickLaTeX cannot compile formula:
*** Error message:
Error: Nothing to show, formula is empty
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.
vt_m
29AjayKumar
Akanksha_Rai
Es
jelodar
parascoding
divyeshrabadiya07
divyesh072019
avanitrachhadiya2155
splevel62
mukesh07
itsok
surindertarika1234
rub1cks
amartyaghoshgfg
hardikkoriintern
Merge Sort
Arrays
Sorting
Arrays
Sorting
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Python | Using 2D arrays/lists the right way
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 198,
"s": 52,
"text": "Given an integer array of which both first half and second half are sorted. Task is to merge two sorted halves of array into single sorted array."
},
{
"code": null,
"e": 209,
"s": 198,
"text": "Examples: "
},
{
"code": null,
"e": 334,
"s": 209,
"text": "Input : A[] = { 2, 3, 8, -1, 7, 10 }\nOutput : -1, 2, 3, 7, 8, 10 \n\nInput : A[] = {-4, 6, 9, -1, 3 }\nOutput : -4, -1, 3, 6, 9"
},
{
"code": null,
"e": 454,
"s": 334,
"text": "Method 1: A Simple Solution is to sort the array using built in functions (generally an implementation of quick sort). "
},
{
"code": null,
"e": 499,
"s": 454,
"text": "Below is the implementation of above method:"
},
{
"code": null,
"e": 503,
"s": 499,
"text": "C++"
},
{
"code": null,
"e": 508,
"s": 503,
"text": "Java"
},
{
"code": null,
"e": 516,
"s": 508,
"text": "Python3"
},
{
"code": null,
"e": 519,
"s": 516,
"text": "C#"
},
{
"code": null,
"e": 523,
"s": 519,
"text": "PHP"
},
{
"code": null,
"e": 534,
"s": 523,
"text": "Javascript"
},
{
"code": "// C++ program to Merge two sorted halves of// array Into Single Sorted Array#include <bits/stdc++.h>using namespace std; void mergeTwoHalf(int A[], int n){ // Sort the given array using sort STL sort(A, A + n);} // Driver codeint main(){ int A[] = { 2, 3, 8, -1, 7, 10 }; int n = sizeof(A) / sizeof(A[0]); mergeTwoHalf(A, n); // Print sorted Array for (int i = 0; i < n; i++) cout << A[i] << \" \"; return 0;}",
"e": 975,
"s": 534,
"text": null
},
{
"code": "// Java program to Merge two sorted halves of// array Into Single Sorted Arrayimport java.io.*;import java.util.*; class GFG { static void mergeTwoHalf(int[] A, int n) { // Sort the given array using sort STL Arrays.sort(A); } // Driver code static public void main(String[] args) { int[] A = { 2, 3, 8, -1, 7, 10 }; int n = A.length; mergeTwoHalf(A, n); // Print sorted Array for (int i = 0; i < n; i++) System.out.print(A[i] + \" \"); }} // This code is contributed by vt_m .",
"e": 1535,
"s": 975,
"text": null
},
{
"code": "# Python program to Merge two sorted# halves of array Into Single Sorted Array def mergeTwoHalf(A, n): # Sort the given array using sort STL A.sort() # Driver Codeif __name__ == '__main__': A = [2, 3, 8, -1, 7, 10] n = len(A) mergeTwoHalf(A, n) # Print sorted Array for i in range(n): print(A[i], end=\" \") # This code is contributed by 29AjayKumar",
"e": 1915,
"s": 1535,
"text": null
},
{
"code": "// C# program to Merge two sorted halves of// array Into Single Sorted Arrayusing System; class GFG { static void mergeTwoHalf(int[] A, int n) { // Sort the given array using sort STL Array.Sort(A); } // Driver code static public void Main() { int[] A = { 2, 3, 8, -1, 7, 10 }; int n = A.Length; mergeTwoHalf(A, n); // Print sorted Array for (int i = 0; i < n; i++) Console.Write(A[i] + \" \"); }} // This code is contributed by vt_m .",
"e": 2433,
"s": 1915,
"text": null
},
{
"code": "<?php// PHP program to Merge two sorted halves// of array Into Single Sorted Array function mergeTwoHalf(&$A, $n){ // Sort the given array using sort STL sort($A, 0);} // Driver Code$A = array(2, 3, 8, -1, 7, 10);$n = sizeof($A);mergeTwoHalf($A, $n); // Print sorted Arrayfor ($i = 0; $i < $n; $i++) echo $A[$i] . \" \"; // This code is contributed// by Akanksha Rai?>",
"e": 2809,
"s": 2433,
"text": null
},
{
"code": "<script> // Javascript program to Merge two sorted halves of// array Into Single Sorted Array function mergeTwoHalf(A, n){ // Sort the given array using sort function A.sort((a,b) => a-b);} // Driver codevar A = [ 2, 3, 8, -1, 7, 10 ];var n = A.length;mergeTwoHalf(A, n); // Print sorted Arrayfor (var i = 0; i < n; i++) document.write( A[i] + \" \"); // This code is contributed by itsok.</script>",
"e": 3215,
"s": 2809,
"text": null
},
{
"code": null,
"e": 3230,
"s": 3215,
"text": "-1 2 3 7 8 10 "
},
{
"code": null,
"e": 3248,
"s": 3230,
"text": "Time Complexity: "
},
{
"code": null,
"e": 3351,
"s": 3248,
"text": "*** QuickLaTeX cannot compile formula:\n \n\n*** Error message:\nError: Nothing to show, formula is empty\n"
},
{
"code": null,
"e": 3417,
"s": 3351,
"text": "best & average case, worst case (for quicksort)Space Complexity: "
},
{
"code": null,
"e": 3520,
"s": 3417,
"text": "*** QuickLaTeX cannot compile formula:\n \n\n*** Error message:\nError: Nothing to show, formula is empty\n"
},
{
"code": null,
"e": 3524,
"s": 3520,
"text": "to "
},
{
"code": null,
"e": 3627,
"s": 3524,
"text": "*** QuickLaTeX cannot compile formula:\n \n\n*** Error message:\nError: Nothing to show, formula is empty\n"
},
{
"code": null,
"e": 3682,
"s": 3627,
"text": "depending on the case & implementation (for quicksort)"
},
{
"code": null,
"e": 3740,
"s": 3682,
"text": "For more details, check out the GFG article on Quicksort."
},
{
"code": null,
"e": 3865,
"s": 3740,
"text": "Method 2: A more efficient solution is to use an auxiliary array which is very similar to the Merge Function of Merge sort. "
},
{
"code": null,
"e": 3914,
"s": 3865,
"text": "Below is the implementation of above approach : "
},
{
"code": null,
"e": 3918,
"s": 3914,
"text": "C++"
},
{
"code": null,
"e": 3923,
"s": 3918,
"text": "Java"
},
{
"code": null,
"e": 3931,
"s": 3923,
"text": "Python3"
},
{
"code": null,
"e": 3934,
"s": 3931,
"text": "C#"
},
{
"code": null,
"e": 3945,
"s": 3934,
"text": "Javascript"
},
{
"code": "// C++ program to Merge Two Sorted Halves Of// Array Into Single Sorted Array#include <bits/stdc++.h>using namespace std; // Merge two sorted halves of Array into single// sorted arrayvoid mergeTwoHalf(int A[], int n){ int half_i = 0; // starting index of second half // Temp Array store sorted resultant array int temp[n]; // First Find the point where array is divide // into two half for (int i = 0; i < n - 1; i++) { if (A[i] > A[i + 1]) { half_i = i + 1; break; } } // If Given array is all-ready sorted if (half_i == 0) return; // Merge two sorted arrays in single sorted array int i = 0, j = half_i, k = 0; while (i < half_i && j < n) { if (A[i] < A[j]) temp[k++] = A[i++]; else temp[k++] = A[j++]; } // Copy the remaining elements of A[i to half_! ] while (i < half_i) temp[k++] = A[i++]; // Copy the remaining elements of A[ half_! to n ] while (j < n) temp[k++] = A[j++]; for (int i = 0; i < n; i++) A[i] = temp[i];} // Driver codeint main(){ int A[] = { 2, 3, 8, -1, 7, 10 }; int n = sizeof(A) / sizeof(A[0]); mergeTwoHalf(A, n); // Print sorted Array for (int i = 0; i < n; i++) cout << A[i] << \" \"; return 0;}",
"e": 5255,
"s": 3945,
"text": null
},
{
"code": "// Java program to Merge Two Sorted Halves Of// Array Into Single Sorted Arrayimport java.io.*; class GFG { // Merge two sorted halves of Array // into single sorted array static void mergeTwoHalf(int[] A, int n) { int half_i = 0; // starting index of second half int i; // Temp Array store sorted resultant array int[] temp = new int[n]; // First Find the point where array is divide // into two half for (i = 0; i < n - 1; i++) { if (A[i] > A[i + 1]) { half_i = i + 1; break; } } // If Given array is all-ready sorted if (half_i == 0) return; // Merge two sorted arrays in single sorted array i = 0; int j = half_i; int k = 0; while (i < half_i && j < n) { if (A[i] < A[j]) temp[k++] = A[i++]; else temp[k++] = A[j++]; } // Copy the remaining elements of A[i to half_! ] while (i < half_i) temp[k++] = A[i++]; // Copy the remaining elements of A[ half_! to n ] while (j < n) temp[k++] = A[j++]; for (i = 0; i < n; i++) A[i] = temp[i]; } // Driver code static public void main(String[] args) { int[] A = { 2, 3, 8, -1, 7, 10 }; int n = A.length; mergeTwoHalf(A, n); // Print sorted Array for (int i = 0; i < n; i++) System.out.print(A[i] + \" \"); }} // This code is contributed by vt_m .",
"e": 6821,
"s": 5255,
"text": null
},
{
"code": "# Python3 program to Merge Two Sorted Halves Of# Array Into Single Sorted Array # Merge two sorted halves of Array into single# sorted arraydef mergeTwoHalf(A, n): # Starting index of second half half_i = 0 # Temp Array store sorted resultant array temp = [0 for i in range(n)] # First Find the point where array is # divide into two half for i in range(n - 1): if (A[i] > A[i + 1]): half_i = i + 1 break # If Given array is all-ready sorted if (half_i == 0): return # Merge two sorted arrays in single # sorted array i = 0 j = half_i k = 0 while (i < half_i and j < n): if (A[i] < A[j]): temp[k] = A[i] k += 1 i += 1 else: temp[k] = A[j] k += 1 j += 1 # Copy the remaining elements of A[i to half_! ] while i < half_i: temp[k] = A[i] k += 1 i += 1 # Copy the remaining elements of A[ half_! to n ] while (j < n): temp[k] = A[j] k += 1 j += 1 for i in range(n): A[i] = temp[i] # Driver codeA = [ 2, 3, 8, -1, 7, 10 ]n = len(A) mergeTwoHalf(A, n) # Print sorted Arrayprint(*A, sep = ' ') # This code is contributed by avanitrachhadiya2155",
"e": 8108,
"s": 6821,
"text": null
},
{
"code": "// C# program to Merge Two Sorted Halves Of// Array Into Single Sorted Arrayusing System class GFG { // Merge two sorted halves of Array // into single sorted array static void mergeTwoHalf(int[] A, int n) { int half_i = 0 // starting index of second half int i // Temp Array store sorted resultant array int[] temp = new int[n] // First Find the point where array is divide // into two half for (i = 0 i < n - 1 i++) { if (A[i] > A[i + 1]) { half_i = i + 1 break } } // If Given array is all-ready sorted if (half_i == 0) return // Merge two sorted arrays in single sorted // array i = 0 int j = half_i int k = 0 while (i < half_i & &j < n) { if (A[i] < A[j]) temp[k++] = A[i++] else temp[k++] = A[j++] } // Copy the remaining elements of A[i to half_!] while (i < half_i) temp[k++] = A[i++] // Copy the remaining elements of A[half_! // to n] while (j < n) temp[k++] = A[j++] for (i = 0 i < n i++) A[i] = temp[i] } // Driver code static public void Main() { int[] A = { 2, 3, 8, -1, 7, 10 } int n = A.Length mergeTwoHalf(A, n) // Print sorted Array for (int i = 0 i < n i++) Console.Write(A[i] + \" \") }} // This code is contributed by vt_m .",
"e": 9865,
"s": 8108,
"text": null
},
{
"code": "<script> // JavaScript program to Merge Two Sorted Halves Of // Array Into Single Sorted Array // Merge two sorted halves of Array into single // sorted array function mergeTwoHalf(A, n) { let half_i = 0; // starting index of second half // Temp Array store sorted resultant array let temp = new Array(n); temp.fill(0); // First Find the point where array is divide // into two half for (let i = 0; i < n - 1; i++) { if (A[i] > A[i + 1]) { half_i = i + 1; break; } } // If Given array is all-ready sorted if (half_i == 0) return; // Merge two sorted arrays in single sorted array let i = 0, j = half_i, k = 0; while (i < half_i && j < n) { if (A[i] < A[j]) temp[k++] = A[i++]; else temp[k++] = A[j++]; } // Copy the remaining elements of A[i to half_! ] while (i < half_i) temp[k++] = A[i++]; // Copy the remaining elements of A[ half_! to n ] while (j < n) temp[k++] = A[j++]; for (let i = 0; i < n; i++) A[i] = temp[i]; } let A = [ 2, 3, 8, -1, 7, 10 ]; let n = A.length; mergeTwoHalf(A, n); // Print sorted Array for (let i = 0; i < n; i++) document.write(A[i] + \" \"); </script>",
"e": 11303,
"s": 9865,
"text": null
},
{
"code": null,
"e": 11318,
"s": 11303,
"text": "-1 2 3 7 8 10 "
},
{
"code": null,
"e": 11336,
"s": 11318,
"text": "Time Complexity: "
},
{
"code": null,
"e": 11439,
"s": 11336,
"text": "*** QuickLaTeX cannot compile formula:\n \n\n*** Error message:\nError: Nothing to show, formula is empty\n"
},
{
"code": null,
"e": 11458,
"s": 11439,
"text": "Space Complexity: "
},
{
"code": null,
"e": 11561,
"s": 11458,
"text": "*** QuickLaTeX cannot compile formula:\n \n\n*** Error message:\nError: Nothing to show, formula is empty\n"
},
{
"code": null,
"e": 11812,
"s": 11561,
"text": "If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 11817,
"s": 11812,
"text": "vt_m"
},
{
"code": null,
"e": 11829,
"s": 11817,
"text": "29AjayKumar"
},
{
"code": null,
"e": 11842,
"s": 11829,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 11845,
"s": 11842,
"text": "Es"
},
{
"code": null,
"e": 11853,
"s": 11845,
"text": "jelodar"
},
{
"code": null,
"e": 11865,
"s": 11853,
"text": "parascoding"
},
{
"code": null,
"e": 11883,
"s": 11865,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 11897,
"s": 11883,
"text": "divyesh072019"
},
{
"code": null,
"e": 11918,
"s": 11897,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 11928,
"s": 11918,
"text": "splevel62"
},
{
"code": null,
"e": 11937,
"s": 11928,
"text": "mukesh07"
},
{
"code": null,
"e": 11943,
"s": 11937,
"text": "itsok"
},
{
"code": null,
"e": 11962,
"s": 11943,
"text": "surindertarika1234"
},
{
"code": null,
"e": 11970,
"s": 11962,
"text": "rub1cks"
},
{
"code": null,
"e": 11986,
"s": 11970,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 12003,
"s": 11986,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 12014,
"s": 12003,
"text": "Merge Sort"
},
{
"code": null,
"e": 12021,
"s": 12014,
"text": "Arrays"
},
{
"code": null,
"e": 12029,
"s": 12021,
"text": "Sorting"
},
{
"code": null,
"e": 12036,
"s": 12029,
"text": "Arrays"
},
{
"code": null,
"e": 12044,
"s": 12036,
"text": "Sorting"
},
{
"code": null,
"e": 12055,
"s": 12044,
"text": "Merge Sort"
},
{
"code": null,
"e": 12153,
"s": 12055,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12185,
"s": 12153,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 12208,
"s": 12185,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 12264,
"s": 12208,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 12291,
"s": 12264,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 12336,
"s": 12291,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 12347,
"s": 12336,
"text": "Merge Sort"
},
{
"code": null,
"e": 12369,
"s": 12347,
"text": "Bubble Sort Algorithm"
},
{
"code": null,
"e": 12379,
"s": 12369,
"text": "QuickSort"
},
{
"code": null,
"e": 12394,
"s": 12379,
"text": "Insertion Sort"
}
] |
Python | First occurrence of True number
|
06 Apr, 2022
Many times we require to find the first occurring non-zero number to begin the processing with. This has mostly use case in Machine Learning domain in which we require to process data excluding None or 0 values. Let’s discuss certain ways in which this can be performed. Method #1 : Using next() + enumerate() The next function can be used to iterate through the list and enumerate along with it checks for the list if the number is a non zero element and returns the number of 0s before a True value i.e a non zero value.
Python3
# Python3 code to demonstrate# finding first True value# using next() and enumerate() # initializing listtest_list = [ 0, 0, 5, 6, 0] # printing original listprint ("The original list is : " + str(test_list)) # finding first True value# using next() and enumerate()res = next((i for i, j in enumerate(test_list) if j), None) # printing resultprint ("The values till first True value : " + str(res))
The original list is : [0, 0, 5, 6, 0]
The values till first True value : 2
Method #2 : Using filter() + lambda + index() Using the combination of the above functions, one can easily perform this particular task. The filter function can be used to screen out the True value that is processed by the lambda functions and index function returns the first occurrence of this.
Python3
# Python3 code to demonstrate# finding first True value# using filter() + lambda + index() # initializing listtest_list = [ 0, 0, 5, 6, 0] # printing original listprint ("The original list is : " + str(test_list)) # finding first True value# using filter() + lambda + index()res = test_list.index(next(filter(lambda i: i != 0, test_list))) # printing resultprint ("The values till first True value : " + str(res))
The original list is : [0, 0, 5, 6, 0]
The values till first True value : 2
sagartomar9927
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Apr, 2022"
},
{
"code": null,
"e": 552,
"s": 28,
"text": "Many times we require to find the first occurring non-zero number to begin the processing with. This has mostly use case in Machine Learning domain in which we require to process data excluding None or 0 values. Let’s discuss certain ways in which this can be performed. Method #1 : Using next() + enumerate() The next function can be used to iterate through the list and enumerate along with it checks for the list if the number is a non zero element and returns the number of 0s before a True value i.e a non zero value. "
},
{
"code": null,
"e": 560,
"s": 552,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# finding first True value# using next() and enumerate() # initializing listtest_list = [ 0, 0, 5, 6, 0] # printing original listprint (\"The original list is : \" + str(test_list)) # finding first True value# using next() and enumerate()res = next((i for i, j in enumerate(test_list) if j), None) # printing resultprint (\"The values till first True value : \" + str(res))",
"e": 959,
"s": 560,
"text": null
},
{
"code": null,
"e": 1035,
"s": 959,
"text": "The original list is : [0, 0, 5, 6, 0]\nThe values till first True value : 2"
},
{
"code": null,
"e": 1335,
"s": 1035,
"text": " Method #2 : Using filter() + lambda + index() Using the combination of the above functions, one can easily perform this particular task. The filter function can be used to screen out the True value that is processed by the lambda functions and index function returns the first occurrence of this. "
},
{
"code": null,
"e": 1343,
"s": 1335,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# finding first True value# using filter() + lambda + index() # initializing listtest_list = [ 0, 0, 5, 6, 0] # printing original listprint (\"The original list is : \" + str(test_list)) # finding first True value# using filter() + lambda + index()res = test_list.index(next(filter(lambda i: i != 0, test_list))) # printing resultprint (\"The values till first True value : \" + str(res))",
"e": 1757,
"s": 1343,
"text": null
},
{
"code": null,
"e": 1833,
"s": 1757,
"text": "The original list is : [0, 0, 5, 6, 0]\nThe values till first True value : 2"
},
{
"code": null,
"e": 1848,
"s": 1833,
"text": "sagartomar9927"
},
{
"code": null,
"e": 1869,
"s": 1848,
"text": "Python list-programs"
},
{
"code": null,
"e": 1876,
"s": 1869,
"text": "Python"
},
{
"code": null,
"e": 1892,
"s": 1876,
"text": "Python Programs"
},
{
"code": null,
"e": 1990,
"s": 1892,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2032,
"s": 1990,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2054,
"s": 2032,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2089,
"s": 2054,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2115,
"s": 2089,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2147,
"s": 2115,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2190,
"s": 2147,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2212,
"s": 2190,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2251,
"s": 2212,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2289,
"s": 2251,
"text": "Python | Convert a list to dictionary"
}
] |
Check if two strings are same ignoring their cases
|
19 Jul, 2021
Given two strings str1 and str2. The task is to check if the two given strings are same if a case-insensitive comparison is followed, i.e., the cases of the strings are ignored in Java.Examples:
Input: str1 = "Geeks", str2 = "geeks"
Output: Same
Input: str1 = "Geek", str2 = "geeksforgeeks"
Output: Not Same
Method 1: Naive Approach
Compare each character of the first string with the corresponding character of the second string.
if it is matched, compare next character.
If it does not match check if it is matched by ignoring their cases.
If matched, compare next character.
If all characters matched, return true
If any character is not matched, return false.
The implementation is given below.
C++
Java
Python3
C#
Javascript
#include <iostream>using namespace std; // Function to compare two strings// ignoring their casesbool equalIgnoreCase(string str1, string str2){ int i = 0; // length of first string int len1 = str1.size(); // length of second string int len2 = str2.size(); // if length is not same // simply return false since both string // can not be same if length is not equal if (len1 != len2) return false; // loop to match one by one // all characters of both string while (i < len1) { // if current characters of both string are same, // increase value of i to compare next character if (str1[i] == str2[i]) { i++; } // if any character of first string // is some special character // or numeric character and // not same as corresponding character // of second string then return false else if (!((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= 'A' && str1[i] <= 'Z'))) { return false; } // do the same for second string else if (!((str2[i] >= 'a' && str2[i] <= 'z') || (str2[i] >= 'A' && str2[i] <= 'Z'))) { return false; } // this block of code will be executed // if characters of both strings // are of different cases else { // compare characters by ASCII value if (str1[i] >= 'a' && str1[i] <= 'z') { if (str1[i] - 32 != str2[i]) return false; } else if (str1[i] >= 'A' && str1[i] <= 'Z') { if (str1[i] + 32 != str2[i]) return false; } // if characters matched, // increase the value of i to compare next char i++; } // end of outer else block } // end of while loop // if all characters of the first string // are matched with corresponding // characters of the second string, // then return true return true; } // end of equalIgnoreCase function // Function to print the same or not same// if strings are equal or not equalvoid equalIgnoreCaseUtil(string str1, string str2){ bool res = equalIgnoreCase(str1, str2); if (res == true) cout << "Same" << endl; else cout << "Not Same" << endl;} // Driver Codeint main(){ string str1, str2; str1 = "Geeks"; str2 = "geeks"; equalIgnoreCaseUtil(str1, str2); str1 = "Geek"; str2 = "geeksforgeeks"; equalIgnoreCaseUtil(str1, str2); return 0;}
class GFG{// Function to compare two strings// ignoring their casesstatic boolean equalIgnoreCase(String str1, String str2){ int i = 0; // length of first string int len1 = str1.length(); // length of second string int len2 = str2.length(); // if length is not same // simply return false since both string // can not be same if length is not equal if (len1 != len2) return false; // loop to match one by one // all characters of both string while (i < len1) { // if current characters of both string are same, // increase value of i to compare next character if (str1.charAt(i) == str2.charAt(i)) { i++; } // if any character of first string // is some special character // or numeric character and // not same as corresponding character // of second string then return false else if (!((str1.charAt(i) >= 'a' && str1.charAt(i) <= 'z') || (str1.charAt(i) >= 'A' && str1.charAt(i) <= 'Z'))) { return false; } // do the same for second string else if (!((str2.charAt(i) >= 'a' && str2.charAt(i) <= 'z') || (str2.charAt(i) >= 'A' && str2.charAt(i) <= 'Z'))) { return false; } // this block of code will be executed // if characters of both strings // are of different cases else { // compare characters by ASCII value if (str1.charAt(i) >= 'a' && str1.charAt(i) <= 'z') { if (str1.charAt(i) - 32 != str2.charAt(i)) return false; } else if (str1.charAt(i) >= 'A' && str1.charAt(i) <= 'Z') { if (str1.charAt(i) + 32 != str2.charAt(i)) return false; } // if characters matched, // increase the value of i to compare next char i++; } // end of outer else block } // end of while loop // if all characters of the first string // are matched with corresponding // characters of the second string, // then return true return true; } // end of equalIgnoreCase function // Function to print the same or not same// if strings are equal or not equalstatic void equalIgnoreCaseUtil(String str1, String str2){ boolean res = equalIgnoreCase(str1, str2); if (res == true) System.out.println( "Same" ); else System.out.println( "Not Same" );} // Driver Codepublic static void main(String args[]){ String str1, str2; str1 = "Geeks"; str2 = "geeks"; equalIgnoreCaseUtil(str1, str2); str1 = "Geek"; str2 = "geeksforgeeks"; equalIgnoreCaseUtil(str1, str2);}} // This code is contributed by Arnab Kundu
# Function to compare two strings# ignoring their casesdef equalIgnoreCase(str1, str2): i = 0 # length of first string len1 = len(str1) # length of second string len2 = len(str2) # if length is not same # simply return false since both string # can not be same if length is not equal if (len1 != len2): return False # loop to match one by one # all characters of both string while (i < len1): # if current characters of both string are same, # increase value of i to compare next character if (str1[i] == str2[i]): i += 1 # if any character of first string # is some special character # or numeric character and # not same as corresponding character # of second string then return false elif (((str1[i] >= 'a' and str1[i] <= 'z') or (str1[i] >= 'A' and str1[i] <= 'Z')) == False): return False # do the same for second string elif (((str2[i] >= 'a' and str2[i] <= 'z') or (str2[i] >= 'A' and str2[i] <= 'Z')) == False): return False # this block of code will be executed # if characters of both strings # are of different cases else: # compare characters by ASCII value if (str1[i] >= 'a' and str1[i] <= 'z'): if (ord(str1[i]) - 32 != ord(str2[i])): return False elif (str1[i] >= 'A' and str1[i] <= 'Z'): if (ord(str1[i]) + 32 != ord(str2[i])): return False # if characters matched, # increase the value of i # to compare next char i += 1 # end of outer else block # end of while loop # if all characters of the first string # are matched with corresponding # characters of the second string, # then return true return True # end of equalIgnoreCase function # Function to print the same or not same# if strings are equal or not equaldef equalIgnoreCaseUtil(str1, str2): res = equalIgnoreCase(str1, str2) if (res == True): print("Same") else: print("Not Same") # Driver Codeif __name__ == '__main__': str1 = "Geeks" str2 = "geeks" equalIgnoreCaseUtil(str1, str2) str1 = "Geek" str2 = "geeksforgeeks" equalIgnoreCaseUtil(str1, str2) # This code is contributed by# Surendra_Gangwar
using System;class GFG{// Function to compare two strings// ignoring their casesstatic bool equalIgnoreCase(string str1, string str2){ int i = 0; // length of first string int len1 = str1.Length; // length of second string int len2 = str2.Length; // if length is not same // simply return false since both string // can not be same if length is not equal if (len1 != len2) return false; // loop to match one by one // all characters of both string while (i < len1) { // if current characters of both string are same, // increase value of i to compare next character if (str1[i] == str2[i]) { i++; } // if any character of first string // is some special character // or numeric character and // not same as corresponding character // of second string then return false else if (!((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= 'A' && str1[i] <= 'Z'))) { return false; } // do the same for second string else if (!((str2[i] >= 'a' && str2[i] <= 'z') || (str2[i] >= 'A' && str2[i] <= 'Z'))) { return false; } // this block of code will be executed // if characters of both strings // are of different cases else { // compare characters by ASCII value if (str1[i] >= 'a' && str1[i] <= 'z') { if (str1[i] - 32 != str2[i]) return false; } else if (str1[i] >= 'A' && str1[i] <= 'Z') { if (str1[i] + 32 != str2[i]) return false; } // if characters matched, // increase the value of i to compare next char i++; } // end of outer else block } // end of while loop // if all characters of the first string // are matched with corresponding // characters of the second string, // then return true return true; } // end of equalIgnoreCase function // Function to print the same or not same// if strings are equal or not equalstatic void equalIgnoreCaseUtil(string str1, string str2){ bool res = equalIgnoreCase(str1, str2); if (res == true) Console.WriteLine( "Same" ); else Console.WriteLine( "Not Same" );} // Driver Codepublic static void Main(){ string str1, str2; str1 = "Geeks"; str2 = "geeks"; equalIgnoreCaseUtil(str1, str2); str1 = "Geek"; str2 = "geeksforgeeks"; equalIgnoreCaseUtil(str1, str2);}} // This code is contributed by ihritik
<script> // Function to compare two strings // ignoring their cases function equalIgnoreCase(str1, str2) { let i = 0; // length of first string let len1 = str1.length; // length of second string let len2 = str2.length; // if length is not same // simply return false since both string // can not be same if length is not equal if (len1 != len2) return false; // loop to match one by one // all characters of both string while (i < len1) { // if current characters of both string are same, // increase value of i to compare next character if (str1[i] == str2[i]) { i++; } // if any character of first string // is some special character // or numeric character and // not same as corresponding character // of second string then return false else if (!((str1[i].charCodeAt() >= 'a'.charCodeAt() && str1[i].charCodeAt() <= 'z'.charCodeAt()) || (str1[i].charCodeAt() >= 'A'.charCodeAt() && str1[i].charCodeAt() <= 'Z'.charCodeAt()))) { return false; } // do the same for second string else if (!((str2[i].charCodeAt() >= 'a'.charCodeAt() && str2[i].charCodeAt() <= 'z'.charCodeAt()) || (str2[i].charCodeAt() >= 'A'.charCodeAt() && str2[i].charCodeAt() <= 'Z'.charCodeAt()))) { return false; } // this block of code will be executed // if characters of both strings // are of different cases else { // compare characters by ASCII value if (str1[i].charCodeAt() >= 'a'.charCodeAt() && str1[i].charCodeAt() <= 'z'.charCodeAt()) { if (str1[i].charCodeAt() - 32 != str2[i].charCodeAt()) return false; } else if (str1[i].charCodeAt() >= 'A'.charCodeAt() && str1[i].charCodeAt() <= 'Z'.charCodeAt()) { if (str1[i].charCodeAt() + 32 != str2[i].charCodeAt()) return false; } // if characters matched, // increase the value of i to compare next char i++; } // end of outer else block } // end of while loop // if all characters of the first string // are matched with corresponding // characters of the second string, // then return true return true; } // end of equalIgnoreCase function // Function to print the same or not same // if strings are equal or not equal function equalIgnoreCaseUtil(str1, str2) { let res = equalIgnoreCase(str1, str2); if (res == true) document.write( "Same" + "</br>"); else document.write( "Not Same" + "</br>"); } let str1, str2; str1 = "Geeks"; str2 = "geeks"; equalIgnoreCaseUtil(str1, str2); str1 = "Geek"; str2 = "geeksforgeeks"; equalIgnoreCaseUtil(str1, str2); // This code is contributed by diveshrabadiya07.</script>
Same
Not Same
Method 2: Using toUpperCase() function
Change all lowercase characters of both string to uppercase and compare them.If they are equal, print “same” otherwise print “Not Same”.
Change all lowercase characters of both string to uppercase and compare them.
If they are equal, print “same” otherwise print “Not Same”.
The implementation is given below.
C++
Java
Python3
C#
Javascript
#include<bits/stdc++.h>using namespace std; // Function to compare two strings ignoring their casesbool equalIgnoreCase(string str1, string str2){ int i = 0; // Convert to uppercase // using transform() function and ::toupper in STL transform(str1.begin(), str1.end(), str1.begin(), ::toupper); transform(str2.begin(), str2.end(), str2.begin(), ::toupper); // Comparing both using inbuilt function int x = str1.compare(str2); // if strings are equal, // return true otherwise false if (x != 0) return false; else return true;} // Function to print the same or not same// if strings are equal or not equalvoid equalIgnoreCaseUtil(string str1, string str2){ bool res = equalIgnoreCase(str1, str2); if (res == true) cout << "Same" << endl; else cout << "Not Same" << endl;} // Driver Codeint main(){ string str1, str2; str1 = "Geeks"; str2 = "geeks"; equalIgnoreCaseUtil(str1, str2); str1 = "Geek"; str2 = "geeksforgeeks"; equalIgnoreCaseUtil(str1, str2); return 0;}
class GFG{ // Function to compare two Strings ignoring their cases static boolean equalIgnoreCase(String str1, String str2) { int i = 0; // Convert to lowercase // using toUpperCase function str1 = str1.toUpperCase(); str2 = str2.toUpperCase(); // Comparing both using inbuilt function int x = str1.compareTo(str2); // if Strings are equal, // return true otherwise false if (x != 0) { return false; } else { return true; } } // Function to print the same or not same // if Strings are equal or not equal static void equalIgnoreCaseUtil(String str1, String str2) { boolean res = equalIgnoreCase(str1, str2); if (res == true) { System.out.println("Same"); } else { System.out.println("Not Same"); } } // Driver Code public static void main(String[] args) { String str1, str2; str1 = "Geeks"; str2 = "geeks"; equalIgnoreCaseUtil(str1, str2); str1 = "Geek"; str2 = "geeksforgeeks"; equalIgnoreCaseUtil(str1, str2); }} // This code has been contributed by 29AjayKumar
# Python 3 Code for above approach # Function to compare two strings# ignoring their casesdef equalIgnoreCase(str1, str2) : # Convert to uppercase str1 = str1.upper(); str2 = str2.upper(); # if strings are equal, # return true otherwise false x = str1 == str2; return x; # Function to print the same or not same# if strings are equal or not equaldef equalIgnoreCaseUtil(str1, str2) : res = equalIgnoreCase(str1, str2); if (res == True) : print("Same"); else : print("Not Same"); # Driver Codeif __name__ == "__main__" : str1 = "Geeks"; str2 = "geeks"; equalIgnoreCaseUtil(str1, str2); str1 = "Geek"; str2 = "geeksforgeeks"; equalIgnoreCaseUtil(str1, str2); # This code is contributed by Ryuga
using System;public class GFG{ // Function to compare two Strings ignoring their cases static bool equalIgnoreCase(String str1, String str2) { // Convert to lowercase // using toUpperCase function str1 = str1.ToUpper(); str2 = str2.ToUpper(); // Comparing both using inbuilt function int x = str1.CompareTo(str2); // if Strings are equal, // return true otherwise false if (x != 0) { return false; } else { return true; } } // Function to print the same or not same // if Strings are equal or not equal static void equalIgnoreCaseUtil(String str1, String str2) { bool res = equalIgnoreCase(str1, str2); if (res == true) { Console.WriteLine("Same"); } else { Console.WriteLine("Not Same"); } } // Driver Code public static void Main() { String str1, str2; str1 = "Geeks"; str2 = "geeks"; equalIgnoreCaseUtil(str1, str2); str1 = "Geek"; str2 = "geeksforgeeks"; equalIgnoreCaseUtil(str1, str2); }} /* This code contributed by PrinciRaj1992 */
<script> // Function to compare two Strings ignoring their casesfunction equalIgnoreCase(str1,str2){ let i = 0; // Convert to lowercase // using toUpperCase function str1 = str1.toUpperCase(); str2 = str2.toUpperCase(); // Comparing both using inbuilt function let x = str1 == (str2); // if Strings are equal, // return true otherwise false if (!x) { return false; } else { return true; }} // Function to print the same or not same // if Strings are equal or not equalfunction equalIgnoreCaseUtil(str1,str2){ let res = equalIgnoreCase(str1, str2); if (res == true) { document.write("Same<br>"); } else { document.write("Not Same<br>"); }} // Driver Codelet str1, str2; str1 = "Geeks";str2 = "geeks";equalIgnoreCaseUtil(str1, str2); str1 = "Geek";str2 = "geeksforgeeks";equalIgnoreCaseUtil(str1, str2); // This code is contributed by avanitrachhadiya2155</script>
Same
Not Same
Method 3: Using toLowerCase() function
Change all characters of both string to lowercase and compare them.If they are equal, print “same” otherwise print “Not Same”.
Change all characters of both string to lowercase and compare them.
If they are equal, print “same” otherwise print “Not Same”.
The implementation is given below.
C++
Java
Python3
C#
Javascript
#include<bits/stdc++.h>using namespace std; // Function to compare two strings ignoring their casesbool equalIgnoreCase(string str1, string str2){ int i = 0; // Convert to lowercase // using transform() function and ::tolower in STL transform(str1.begin(), str1.end(), str1.begin(), ::tolower); transform(str2.begin(), str2.end(), str2.begin(), ::tolower); // Comparing both using inbuilt function int x = str1.compare(str2); // if strings are equal, // return true otherwise false if (x != 0) return false; else return true;} // Function to print the same or not same// if strings are equal or not equalvoid equalIgnoreCaseUtil(string str1, string str2){ bool res = equalIgnoreCase(str1, str2); if (res == true) cout << "Same" << endl; else cout << "Not Same" << endl;} // Driver Codeint main(){ string str1, str2; str1 = "Geeks"; str2 = "geeks"; equalIgnoreCaseUtil(str1, str2); str1 = "Geek"; str2 = "geeksforgeeks"; equalIgnoreCaseUtil(str1, str2); return 0;}
// A Java Program to find the longest common prefixclass GFG{ // Function to compare two strings ignoring their casesstatic boolean equalIgnoreCase(String str1, String str2){ int i = 0; // Convert to lowercase // using toLowerCase function str1 = str1.toLowerCase(); str2 = str2.toLowerCase(); // Comparing both using inbuilt function int x = str1.compareTo(str2); // if strings are equal, // return true otherwise false return x == 0;} // Function to print the same or not same// if strings are equal or not equalstatic void equalIgnoreCaseUtil(String str1, String str2){ boolean res = equalIgnoreCase(str1, str2); if (res == true) System.out.println("Same"); else System.out.println("Not Same");} // Driver Codepublic static void main(String[] args){ String str1, str2; str1 = "Geeks"; str2 = "geeks"; equalIgnoreCaseUtil(str1, str2); str1 = "Geek"; str2 = "geeksforgeeks"; equalIgnoreCaseUtil(str1, str2);}} // This code contributed by Rajput-Ji
# Python 3 Code for above approach # Function to compare two strings# ignoring their casesdef equalIgnoreCase(str1, str2) : # Convert to lower case str1 = str1.lower(); str2 = str2.lower(); # if strings are equal, # return true otherwise false x = str1 == str2; return x; # Function to print the same or not same# if strings are equal or not equaldef equalIgnoreCaseUtil(str1, str2) : res = equalIgnoreCase(str1, str2); if (res == True) : print("Same"); else : print("Not Same"); # Driver Codeif __name__ == "__main__" : str1 = "Geeks"; str2 = "geeks"; equalIgnoreCaseUtil(str1, str2); str1 = "Geek"; str2 = "geeksforgeeks"; equalIgnoreCaseUtil(str1, str2); # This code is contributed by ihritik
using System; class GFG{ // Function to compare two Strings ignoring their cases static bool equalIgnoreCase(String str1, String str2) { // Convert to lowercase // using toUpperCase function str1 = str1.ToUpper(); str2 = str2.ToUpper(); // Comparing both using inbuilt function int x = str1.CompareTo(str2); // if Strings are equal, // return true otherwise false if (x != 0) { return false; } else { return true; } } // Function to print the same or not same // if Strings are equal or not equal static void equalIgnoreCaseUtil(String str1, String str2) { bool res = equalIgnoreCase(str1, str2); if (res == true) { Console.WriteLine("Same"); } else { Console.WriteLine("Not Same"); } } // Driver Code public static void Main() { String str1, str2; str1 = "Geeks"; str2 = "geeks"; equalIgnoreCaseUtil(str1, str2); str1 = "Geek"; str2 = "geeksforgeeks"; equalIgnoreCaseUtil(str1, str2); }} /* This code contributed by PrinciRaj1992 */
<script>// A Javascript Program to find the longest common prefix // Function to compare two strings ignoring their casesfunction equalIgnoreCase(str1,str2){ let i = 0; // Convert to lowercase // using toLowerCase function str1 = str1.toLowerCase(); str2 = str2.toLowerCase(); // Comparing both using inbuilt function let x = (str1 == (str2)); // if strings are equal, // return true otherwise false return x == true;} // Function to print the same or not same// if strings are equal or not equalfunction equalIgnoreCaseUtil(str1,str2){ let res = equalIgnoreCase(str1, str2); if (res == true) document.write("Same<br>"); else document.write("Not Same<br>");} // Driver Codelet str1, str2; str1 = "Geeks";str2 = "geeks";equalIgnoreCaseUtil(str1, str2); str1 = "Geek";str2 = "geeksforgeeks";equalIgnoreCaseUtil(str1, str2); // This code is contributed by rag2127</script>
Same
Not Same
ankthon
andrew1234
SURENDRA_GANGWAR
ihritik
Rajput-Ji
princiraj1992
29AjayKumar
Shivam_k
ManasChhabra2
divyeshrabadiya07
avanitrachhadiya2155
rag2127
Java-Functions
Java-String-Programs
Java Programs
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jul, 2021"
},
{
"code": null,
"e": 225,
"s": 28,
"text": "Given two strings str1 and str2. The task is to check if the two given strings are same if a case-insensitive comparison is followed, i.e., the cases of the strings are ignored in Java.Examples: "
},
{
"code": null,
"e": 339,
"s": 225,
"text": "Input: str1 = \"Geeks\", str2 = \"geeks\"\nOutput: Same\n\nInput: str1 = \"Geek\", str2 = \"geeksforgeeks\"\nOutput: Not Same"
},
{
"code": null,
"e": 366,
"s": 339,
"text": "Method 1: Naive Approach "
},
{
"code": null,
"e": 464,
"s": 366,
"text": "Compare each character of the first string with the corresponding character of the second string."
},
{
"code": null,
"e": 506,
"s": 464,
"text": "if it is matched, compare next character."
},
{
"code": null,
"e": 575,
"s": 506,
"text": "If it does not match check if it is matched by ignoring their cases."
},
{
"code": null,
"e": 611,
"s": 575,
"text": "If matched, compare next character."
},
{
"code": null,
"e": 650,
"s": 611,
"text": "If all characters matched, return true"
},
{
"code": null,
"e": 697,
"s": 650,
"text": "If any character is not matched, return false."
},
{
"code": null,
"e": 734,
"s": 697,
"text": "The implementation is given below. "
},
{
"code": null,
"e": 738,
"s": 734,
"text": "C++"
},
{
"code": null,
"e": 743,
"s": 738,
"text": "Java"
},
{
"code": null,
"e": 751,
"s": 743,
"text": "Python3"
},
{
"code": null,
"e": 754,
"s": 751,
"text": "C#"
},
{
"code": null,
"e": 765,
"s": 754,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; // Function to compare two strings// ignoring their casesbool equalIgnoreCase(string str1, string str2){ int i = 0; // length of first string int len1 = str1.size(); // length of second string int len2 = str2.size(); // if length is not same // simply return false since both string // can not be same if length is not equal if (len1 != len2) return false; // loop to match one by one // all characters of both string while (i < len1) { // if current characters of both string are same, // increase value of i to compare next character if (str1[i] == str2[i]) { i++; } // if any character of first string // is some special character // or numeric character and // not same as corresponding character // of second string then return false else if (!((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= 'A' && str1[i] <= 'Z'))) { return false; } // do the same for second string else if (!((str2[i] >= 'a' && str2[i] <= 'z') || (str2[i] >= 'A' && str2[i] <= 'Z'))) { return false; } // this block of code will be executed // if characters of both strings // are of different cases else { // compare characters by ASCII value if (str1[i] >= 'a' && str1[i] <= 'z') { if (str1[i] - 32 != str2[i]) return false; } else if (str1[i] >= 'A' && str1[i] <= 'Z') { if (str1[i] + 32 != str2[i]) return false; } // if characters matched, // increase the value of i to compare next char i++; } // end of outer else block } // end of while loop // if all characters of the first string // are matched with corresponding // characters of the second string, // then return true return true; } // end of equalIgnoreCase function // Function to print the same or not same// if strings are equal or not equalvoid equalIgnoreCaseUtil(string str1, string str2){ bool res = equalIgnoreCase(str1, str2); if (res == true) cout << \"Same\" << endl; else cout << \"Not Same\" << endl;} // Driver Codeint main(){ string str1, str2; str1 = \"Geeks\"; str2 = \"geeks\"; equalIgnoreCaseUtil(str1, str2); str1 = \"Geek\"; str2 = \"geeksforgeeks\"; equalIgnoreCaseUtil(str1, str2); return 0;}",
"e": 3334,
"s": 765,
"text": null
},
{
"code": "class GFG{// Function to compare two strings// ignoring their casesstatic boolean equalIgnoreCase(String str1, String str2){ int i = 0; // length of first string int len1 = str1.length(); // length of second string int len2 = str2.length(); // if length is not same // simply return false since both string // can not be same if length is not equal if (len1 != len2) return false; // loop to match one by one // all characters of both string while (i < len1) { // if current characters of both string are same, // increase value of i to compare next character if (str1.charAt(i) == str2.charAt(i)) { i++; } // if any character of first string // is some special character // or numeric character and // not same as corresponding character // of second string then return false else if (!((str1.charAt(i) >= 'a' && str1.charAt(i) <= 'z') || (str1.charAt(i) >= 'A' && str1.charAt(i) <= 'Z'))) { return false; } // do the same for second string else if (!((str2.charAt(i) >= 'a' && str2.charAt(i) <= 'z') || (str2.charAt(i) >= 'A' && str2.charAt(i) <= 'Z'))) { return false; } // this block of code will be executed // if characters of both strings // are of different cases else { // compare characters by ASCII value if (str1.charAt(i) >= 'a' && str1.charAt(i) <= 'z') { if (str1.charAt(i) - 32 != str2.charAt(i)) return false; } else if (str1.charAt(i) >= 'A' && str1.charAt(i) <= 'Z') { if (str1.charAt(i) + 32 != str2.charAt(i)) return false; } // if characters matched, // increase the value of i to compare next char i++; } // end of outer else block } // end of while loop // if all characters of the first string // are matched with corresponding // characters of the second string, // then return true return true; } // end of equalIgnoreCase function // Function to print the same or not same// if strings are equal or not equalstatic void equalIgnoreCaseUtil(String str1, String str2){ boolean res = equalIgnoreCase(str1, str2); if (res == true) System.out.println( \"Same\" ); else System.out.println( \"Not Same\" );} // Driver Codepublic static void main(String args[]){ String str1, str2; str1 = \"Geeks\"; str2 = \"geeks\"; equalIgnoreCaseUtil(str1, str2); str1 = \"Geek\"; str2 = \"geeksforgeeks\"; equalIgnoreCaseUtil(str1, str2);}} // This code is contributed by Arnab Kundu",
"e": 6141,
"s": 3334,
"text": null
},
{
"code": "# Function to compare two strings# ignoring their casesdef equalIgnoreCase(str1, str2): i = 0 # length of first string len1 = len(str1) # length of second string len2 = len(str2) # if length is not same # simply return false since both string # can not be same if length is not equal if (len1 != len2): return False # loop to match one by one # all characters of both string while (i < len1): # if current characters of both string are same, # increase value of i to compare next character if (str1[i] == str2[i]): i += 1 # if any character of first string # is some special character # or numeric character and # not same as corresponding character # of second string then return false elif (((str1[i] >= 'a' and str1[i] <= 'z') or (str1[i] >= 'A' and str1[i] <= 'Z')) == False): return False # do the same for second string elif (((str2[i] >= 'a' and str2[i] <= 'z') or (str2[i] >= 'A' and str2[i] <= 'Z')) == False): return False # this block of code will be executed # if characters of both strings # are of different cases else: # compare characters by ASCII value if (str1[i] >= 'a' and str1[i] <= 'z'): if (ord(str1[i]) - 32 != ord(str2[i])): return False elif (str1[i] >= 'A' and str1[i] <= 'Z'): if (ord(str1[i]) + 32 != ord(str2[i])): return False # if characters matched, # increase the value of i # to compare next char i += 1 # end of outer else block # end of while loop # if all characters of the first string # are matched with corresponding # characters of the second string, # then return true return True # end of equalIgnoreCase function # Function to print the same or not same# if strings are equal or not equaldef equalIgnoreCaseUtil(str1, str2): res = equalIgnoreCase(str1, str2) if (res == True): print(\"Same\") else: print(\"Not Same\") # Driver Codeif __name__ == '__main__': str1 = \"Geeks\" str2 = \"geeks\" equalIgnoreCaseUtil(str1, str2) str1 = \"Geek\" str2 = \"geeksforgeeks\" equalIgnoreCaseUtil(str1, str2) # This code is contributed by# Surendra_Gangwar",
"e": 8577,
"s": 6141,
"text": null
},
{
"code": "using System;class GFG{// Function to compare two strings// ignoring their casesstatic bool equalIgnoreCase(string str1, string str2){ int i = 0; // length of first string int len1 = str1.Length; // length of second string int len2 = str2.Length; // if length is not same // simply return false since both string // can not be same if length is not equal if (len1 != len2) return false; // loop to match one by one // all characters of both string while (i < len1) { // if current characters of both string are same, // increase value of i to compare next character if (str1[i] == str2[i]) { i++; } // if any character of first string // is some special character // or numeric character and // not same as corresponding character // of second string then return false else if (!((str1[i] >= 'a' && str1[i] <= 'z') || (str1[i] >= 'A' && str1[i] <= 'Z'))) { return false; } // do the same for second string else if (!((str2[i] >= 'a' && str2[i] <= 'z') || (str2[i] >= 'A' && str2[i] <= 'Z'))) { return false; } // this block of code will be executed // if characters of both strings // are of different cases else { // compare characters by ASCII value if (str1[i] >= 'a' && str1[i] <= 'z') { if (str1[i] - 32 != str2[i]) return false; } else if (str1[i] >= 'A' && str1[i] <= 'Z') { if (str1[i] + 32 != str2[i]) return false; } // if characters matched, // increase the value of i to compare next char i++; } // end of outer else block } // end of while loop // if all characters of the first string // are matched with corresponding // characters of the second string, // then return true return true; } // end of equalIgnoreCase function // Function to print the same or not same// if strings are equal or not equalstatic void equalIgnoreCaseUtil(string str1, string str2){ bool res = equalIgnoreCase(str1, str2); if (res == true) Console.WriteLine( \"Same\" ); else Console.WriteLine( \"Not Same\" );} // Driver Codepublic static void Main(){ string str1, str2; str1 = \"Geeks\"; str2 = \"geeks\"; equalIgnoreCaseUtil(str1, str2); str1 = \"Geek\"; str2 = \"geeksforgeeks\"; equalIgnoreCaseUtil(str1, str2);}} // This code is contributed by ihritik",
"e": 11242,
"s": 8577,
"text": null
},
{
"code": "<script> // Function to compare two strings // ignoring their cases function equalIgnoreCase(str1, str2) { let i = 0; // length of first string let len1 = str1.length; // length of second string let len2 = str2.length; // if length is not same // simply return false since both string // can not be same if length is not equal if (len1 != len2) return false; // loop to match one by one // all characters of both string while (i < len1) { // if current characters of both string are same, // increase value of i to compare next character if (str1[i] == str2[i]) { i++; } // if any character of first string // is some special character // or numeric character and // not same as corresponding character // of second string then return false else if (!((str1[i].charCodeAt() >= 'a'.charCodeAt() && str1[i].charCodeAt() <= 'z'.charCodeAt()) || (str1[i].charCodeAt() >= 'A'.charCodeAt() && str1[i].charCodeAt() <= 'Z'.charCodeAt()))) { return false; } // do the same for second string else if (!((str2[i].charCodeAt() >= 'a'.charCodeAt() && str2[i].charCodeAt() <= 'z'.charCodeAt()) || (str2[i].charCodeAt() >= 'A'.charCodeAt() && str2[i].charCodeAt() <= 'Z'.charCodeAt()))) { return false; } // this block of code will be executed // if characters of both strings // are of different cases else { // compare characters by ASCII value if (str1[i].charCodeAt() >= 'a'.charCodeAt() && str1[i].charCodeAt() <= 'z'.charCodeAt()) { if (str1[i].charCodeAt() - 32 != str2[i].charCodeAt()) return false; } else if (str1[i].charCodeAt() >= 'A'.charCodeAt() && str1[i].charCodeAt() <= 'Z'.charCodeAt()) { if (str1[i].charCodeAt() + 32 != str2[i].charCodeAt()) return false; } // if characters matched, // increase the value of i to compare next char i++; } // end of outer else block } // end of while loop // if all characters of the first string // are matched with corresponding // characters of the second string, // then return true return true; } // end of equalIgnoreCase function // Function to print the same or not same // if strings are equal or not equal function equalIgnoreCaseUtil(str1, str2) { let res = equalIgnoreCase(str1, str2); if (res == true) document.write( \"Same\" + \"</br>\"); else document.write( \"Not Same\" + \"</br>\"); } let str1, str2; str1 = \"Geeks\"; str2 = \"geeks\"; equalIgnoreCaseUtil(str1, str2); str1 = \"Geek\"; str2 = \"geeksforgeeks\"; equalIgnoreCaseUtil(str1, str2); // This code is contributed by diveshrabadiya07.</script>",
"e": 14532,
"s": 11242,
"text": null
},
{
"code": null,
"e": 14546,
"s": 14532,
"text": "Same\nNot Same"
},
{
"code": null,
"e": 14588,
"s": 14548,
"text": "Method 2: Using toUpperCase() function "
},
{
"code": null,
"e": 14725,
"s": 14588,
"text": "Change all lowercase characters of both string to uppercase and compare them.If they are equal, print “same” otherwise print “Not Same”."
},
{
"code": null,
"e": 14803,
"s": 14725,
"text": "Change all lowercase characters of both string to uppercase and compare them."
},
{
"code": null,
"e": 14863,
"s": 14803,
"text": "If they are equal, print “same” otherwise print “Not Same”."
},
{
"code": null,
"e": 14900,
"s": 14863,
"text": "The implementation is given below. "
},
{
"code": null,
"e": 14904,
"s": 14900,
"text": "C++"
},
{
"code": null,
"e": 14909,
"s": 14904,
"text": "Java"
},
{
"code": null,
"e": 14917,
"s": 14909,
"text": "Python3"
},
{
"code": null,
"e": 14920,
"s": 14917,
"text": "C#"
},
{
"code": null,
"e": 14931,
"s": 14920,
"text": "Javascript"
},
{
"code": "#include<bits/stdc++.h>using namespace std; // Function to compare two strings ignoring their casesbool equalIgnoreCase(string str1, string str2){ int i = 0; // Convert to uppercase // using transform() function and ::toupper in STL transform(str1.begin(), str1.end(), str1.begin(), ::toupper); transform(str2.begin(), str2.end(), str2.begin(), ::toupper); // Comparing both using inbuilt function int x = str1.compare(str2); // if strings are equal, // return true otherwise false if (x != 0) return false; else return true;} // Function to print the same or not same// if strings are equal or not equalvoid equalIgnoreCaseUtil(string str1, string str2){ bool res = equalIgnoreCase(str1, str2); if (res == true) cout << \"Same\" << endl; else cout << \"Not Same\" << endl;} // Driver Codeint main(){ string str1, str2; str1 = \"Geeks\"; str2 = \"geeks\"; equalIgnoreCaseUtil(str1, str2); str1 = \"Geek\"; str2 = \"geeksforgeeks\"; equalIgnoreCaseUtil(str1, str2); return 0;}",
"e": 15996,
"s": 14931,
"text": null
},
{
"code": "class GFG{ // Function to compare two Strings ignoring their cases static boolean equalIgnoreCase(String str1, String str2) { int i = 0; // Convert to lowercase // using toUpperCase function str1 = str1.toUpperCase(); str2 = str2.toUpperCase(); // Comparing both using inbuilt function int x = str1.compareTo(str2); // if Strings are equal, // return true otherwise false if (x != 0) { return false; } else { return true; } } // Function to print the same or not same // if Strings are equal or not equal static void equalIgnoreCaseUtil(String str1, String str2) { boolean res = equalIgnoreCase(str1, str2); if (res == true) { System.out.println(\"Same\"); } else { System.out.println(\"Not Same\"); } } // Driver Code public static void main(String[] args) { String str1, str2; str1 = \"Geeks\"; str2 = \"geeks\"; equalIgnoreCaseUtil(str1, str2); str1 = \"Geek\"; str2 = \"geeksforgeeks\"; equalIgnoreCaseUtil(str1, str2); }} // This code has been contributed by 29AjayKumar",
"e": 17254,
"s": 15996,
"text": null
},
{
"code": "# Python 3 Code for above approach # Function to compare two strings# ignoring their casesdef equalIgnoreCase(str1, str2) : # Convert to uppercase str1 = str1.upper(); str2 = str2.upper(); # if strings are equal, # return true otherwise false x = str1 == str2; return x; # Function to print the same or not same# if strings are equal or not equaldef equalIgnoreCaseUtil(str1, str2) : res = equalIgnoreCase(str1, str2); if (res == True) : print(\"Same\"); else : print(\"Not Same\"); # Driver Codeif __name__ == \"__main__\" : str1 = \"Geeks\"; str2 = \"geeks\"; equalIgnoreCaseUtil(str1, str2); str1 = \"Geek\"; str2 = \"geeksforgeeks\"; equalIgnoreCaseUtil(str1, str2); # This code is contributed by Ryuga",
"e": 18020,
"s": 17254,
"text": null
},
{
"code": "using System;public class GFG{ // Function to compare two Strings ignoring their cases static bool equalIgnoreCase(String str1, String str2) { // Convert to lowercase // using toUpperCase function str1 = str1.ToUpper(); str2 = str2.ToUpper(); // Comparing both using inbuilt function int x = str1.CompareTo(str2); // if Strings are equal, // return true otherwise false if (x != 0) { return false; } else { return true; } } // Function to print the same or not same // if Strings are equal or not equal static void equalIgnoreCaseUtil(String str1, String str2) { bool res = equalIgnoreCase(str1, str2); if (res == true) { Console.WriteLine(\"Same\"); } else { Console.WriteLine(\"Not Same\"); } } // Driver Code public static void Main() { String str1, str2; str1 = \"Geeks\"; str2 = \"geeks\"; equalIgnoreCaseUtil(str1, str2); str1 = \"Geek\"; str2 = \"geeksforgeeks\"; equalIgnoreCaseUtil(str1, str2); }} /* This code contributed by PrinciRaj1992 */",
"e": 19247,
"s": 18020,
"text": null
},
{
"code": "<script> // Function to compare two Strings ignoring their casesfunction equalIgnoreCase(str1,str2){ let i = 0; // Convert to lowercase // using toUpperCase function str1 = str1.toUpperCase(); str2 = str2.toUpperCase(); // Comparing both using inbuilt function let x = str1 == (str2); // if Strings are equal, // return true otherwise false if (!x) { return false; } else { return true; }} // Function to print the same or not same // if Strings are equal or not equalfunction equalIgnoreCaseUtil(str1,str2){ let res = equalIgnoreCase(str1, str2); if (res == true) { document.write(\"Same<br>\"); } else { document.write(\"Not Same<br>\"); }} // Driver Codelet str1, str2; str1 = \"Geeks\";str2 = \"geeks\";equalIgnoreCaseUtil(str1, str2); str1 = \"Geek\";str2 = \"geeksforgeeks\";equalIgnoreCaseUtil(str1, str2); // This code is contributed by avanitrachhadiya2155</script>",
"e": 20321,
"s": 19247,
"text": null
},
{
"code": null,
"e": 20335,
"s": 20321,
"text": "Same\nNot Same"
},
{
"code": null,
"e": 20378,
"s": 20337,
"text": "Method 3: Using toLowerCase() function "
},
{
"code": null,
"e": 20505,
"s": 20378,
"text": "Change all characters of both string to lowercase and compare them.If they are equal, print “same” otherwise print “Not Same”."
},
{
"code": null,
"e": 20573,
"s": 20505,
"text": "Change all characters of both string to lowercase and compare them."
},
{
"code": null,
"e": 20633,
"s": 20573,
"text": "If they are equal, print “same” otherwise print “Not Same”."
},
{
"code": null,
"e": 20670,
"s": 20633,
"text": "The implementation is given below. "
},
{
"code": null,
"e": 20674,
"s": 20670,
"text": "C++"
},
{
"code": null,
"e": 20679,
"s": 20674,
"text": "Java"
},
{
"code": null,
"e": 20687,
"s": 20679,
"text": "Python3"
},
{
"code": null,
"e": 20690,
"s": 20687,
"text": "C#"
},
{
"code": null,
"e": 20701,
"s": 20690,
"text": "Javascript"
},
{
"code": "#include<bits/stdc++.h>using namespace std; // Function to compare two strings ignoring their casesbool equalIgnoreCase(string str1, string str2){ int i = 0; // Convert to lowercase // using transform() function and ::tolower in STL transform(str1.begin(), str1.end(), str1.begin(), ::tolower); transform(str2.begin(), str2.end(), str2.begin(), ::tolower); // Comparing both using inbuilt function int x = str1.compare(str2); // if strings are equal, // return true otherwise false if (x != 0) return false; else return true;} // Function to print the same or not same// if strings are equal or not equalvoid equalIgnoreCaseUtil(string str1, string str2){ bool res = equalIgnoreCase(str1, str2); if (res == true) cout << \"Same\" << endl; else cout << \"Not Same\" << endl;} // Driver Codeint main(){ string str1, str2; str1 = \"Geeks\"; str2 = \"geeks\"; equalIgnoreCaseUtil(str1, str2); str1 = \"Geek\"; str2 = \"geeksforgeeks\"; equalIgnoreCaseUtil(str1, str2); return 0;}",
"e": 21766,
"s": 20701,
"text": null
},
{
"code": "// A Java Program to find the longest common prefixclass GFG{ // Function to compare two strings ignoring their casesstatic boolean equalIgnoreCase(String str1, String str2){ int i = 0; // Convert to lowercase // using toLowerCase function str1 = str1.toLowerCase(); str2 = str2.toLowerCase(); // Comparing both using inbuilt function int x = str1.compareTo(str2); // if strings are equal, // return true otherwise false return x == 0;} // Function to print the same or not same// if strings are equal or not equalstatic void equalIgnoreCaseUtil(String str1, String str2){ boolean res = equalIgnoreCase(str1, str2); if (res == true) System.out.println(\"Same\"); else System.out.println(\"Not Same\");} // Driver Codepublic static void main(String[] args){ String str1, str2; str1 = \"Geeks\"; str2 = \"geeks\"; equalIgnoreCaseUtil(str1, str2); str1 = \"Geek\"; str2 = \"geeksforgeeks\"; equalIgnoreCaseUtil(str1, str2);}} // This code contributed by Rajput-Ji",
"e": 22796,
"s": 21766,
"text": null
},
{
"code": "# Python 3 Code for above approach # Function to compare two strings# ignoring their casesdef equalIgnoreCase(str1, str2) : # Convert to lower case str1 = str1.lower(); str2 = str2.lower(); # if strings are equal, # return true otherwise false x = str1 == str2; return x; # Function to print the same or not same# if strings are equal or not equaldef equalIgnoreCaseUtil(str1, str2) : res = equalIgnoreCase(str1, str2); if (res == True) : print(\"Same\"); else : print(\"Not Same\"); # Driver Codeif __name__ == \"__main__\" : str1 = \"Geeks\"; str2 = \"geeks\"; equalIgnoreCaseUtil(str1, str2); str1 = \"Geek\"; str2 = \"geeksforgeeks\"; equalIgnoreCaseUtil(str1, str2); # This code is contributed by ihritik",
"e": 23565,
"s": 22796,
"text": null
},
{
"code": "using System; class GFG{ // Function to compare two Strings ignoring their cases static bool equalIgnoreCase(String str1, String str2) { // Convert to lowercase // using toUpperCase function str1 = str1.ToUpper(); str2 = str2.ToUpper(); // Comparing both using inbuilt function int x = str1.CompareTo(str2); // if Strings are equal, // return true otherwise false if (x != 0) { return false; } else { return true; } } // Function to print the same or not same // if Strings are equal or not equal static void equalIgnoreCaseUtil(String str1, String str2) { bool res = equalIgnoreCase(str1, str2); if (res == true) { Console.WriteLine(\"Same\"); } else { Console.WriteLine(\"Not Same\"); } } // Driver Code public static void Main() { String str1, str2; str1 = \"Geeks\"; str2 = \"geeks\"; equalIgnoreCaseUtil(str1, str2); str1 = \"Geek\"; str2 = \"geeksforgeeks\"; equalIgnoreCaseUtil(str1, str2); }} /* This code contributed by PrinciRaj1992 */",
"e": 24786,
"s": 23565,
"text": null
},
{
"code": "<script>// A Javascript Program to find the longest common prefix // Function to compare two strings ignoring their casesfunction equalIgnoreCase(str1,str2){ let i = 0; // Convert to lowercase // using toLowerCase function str1 = str1.toLowerCase(); str2 = str2.toLowerCase(); // Comparing both using inbuilt function let x = (str1 == (str2)); // if strings are equal, // return true otherwise false return x == true;} // Function to print the same or not same// if strings are equal or not equalfunction equalIgnoreCaseUtil(str1,str2){ let res = equalIgnoreCase(str1, str2); if (res == true) document.write(\"Same<br>\"); else document.write(\"Not Same<br>\");} // Driver Codelet str1, str2; str1 = \"Geeks\";str2 = \"geeks\";equalIgnoreCaseUtil(str1, str2); str1 = \"Geek\";str2 = \"geeksforgeeks\";equalIgnoreCaseUtil(str1, str2); // This code is contributed by rag2127</script>",
"e": 25720,
"s": 24786,
"text": null
},
{
"code": null,
"e": 25734,
"s": 25720,
"text": "Same\nNot Same"
},
{
"code": null,
"e": 25744,
"s": 25736,
"text": "ankthon"
},
{
"code": null,
"e": 25755,
"s": 25744,
"text": "andrew1234"
},
{
"code": null,
"e": 25772,
"s": 25755,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 25780,
"s": 25772,
"text": "ihritik"
},
{
"code": null,
"e": 25790,
"s": 25780,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 25804,
"s": 25790,
"text": "princiraj1992"
},
{
"code": null,
"e": 25816,
"s": 25804,
"text": "29AjayKumar"
},
{
"code": null,
"e": 25825,
"s": 25816,
"text": "Shivam_k"
},
{
"code": null,
"e": 25839,
"s": 25825,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 25857,
"s": 25839,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 25878,
"s": 25857,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 25886,
"s": 25878,
"text": "rag2127"
},
{
"code": null,
"e": 25901,
"s": 25886,
"text": "Java-Functions"
},
{
"code": null,
"e": 25922,
"s": 25901,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 25936,
"s": 25922,
"text": "Java Programs"
},
{
"code": null,
"e": 25944,
"s": 25936,
"text": "Strings"
},
{
"code": null,
"e": 25952,
"s": 25944,
"text": "Strings"
}
] |
Output of Java Programs | Set 34 (Collections)
|
09 Apr, 2021
1. What is the Output of the following Java Program?
Java
import java.util.LinkedList; class Demo {public void show() { LinkedList<Integer> list = new LinkedList<Integer>(); list.add(1); list.add(4); list.add(7); list.add(5); for (int i = 0; i < list.size(); i++) { System.out.print(list.get(i) + " "); } }} public class Main {public static void main(String[] args) { Demo demo = new Demo(); demo.show(); }}
A. Compilation Error B. 1 4 7 5 C. 1 4 5 7
Answer: B. 1 4 7 5
Explanation: List stores elements in sequential order and then we can access an element in List using an index. The List provides the ability to access its elements by using its index. But in the set, map elements are not accessed by using an index.
2. What is the output of the following Java Program?
Java
import java.util.Collections;import java.util.LinkedList;import java.util.List; class Demo {public void show() { List<Integer> list = new LinkedList<Integer>(); list.add(1); list.add(4); list.add(7); list.add(5); Collections.sort(list); // line 8 System.out.println(list); }} public class Main {public static void main(String[] args) { Demo demo = new Demo(); demo.show(); }}
A. Compilation Error at line 9 B. [1, 4, 5, 7] C. [1, 4, 7, 5]
Answer: B. [1, 4, 5, 7]
Explanation: Collections.sort() sort the list in ascending order. Collections class provides static methods for sorting the elements in collections. If Collection elements are of set type elements are inserted in sorted order no need to sort.
3. What is the output of the following Java Program?
Java
import java.util.ArrayList;import java.util.Collections;import java.util.Iterator; class Demo {public void show() { ArrayList<String> list = new ArrayList<String>(); list.add("banana"); list.add("apple"); Iterator itr = list.iterator(); Collections.sort(list); while (itr.hasNext()) { System.out.print(itr.next() + " "); } }} public class Main {public static void main(String[] args) { Demo demo = new Demo(); demo.show(); }}
A. Exception in thread “main” java.util.ConcurrentModificationExceptionB. apple banana C. banana apple
Answer: A. Exception in thread "main" java.util.ConcurrentModificationException
Explanation: Collections.sort() sort element and Iterator is an object used to traverse through a Collection. Iterator is an interface available in the Collection framework in java.util.package. It is used to traverse elements one by one.
4. What is the Output of the following Java Program?
Java
import java.util.ArrayList; class Demo {public void show() { ArrayList<String> list = new ArrayList<String>(); ArrayList<Integer> list1 = new ArrayList<Integer>(); boolean check = (list.getClass() == list1.getClass()); System.out.println(check); }} public class Main {public static void main(String[] args) { Demo demo = new Demo(); demo.show(); }}
A. true B. false
Answer: A. true
Explanation: getclass() method returns the runtime class of an object. That class object is the object that is locked by the static synchronized method of represented class. Here both are in ArrayList Class so the answer is true.
5. What is the Output of the following Java Program?
Java
import java.util.LinkedList; class Demo {public void show() { LinkedList<String> list = new LinkedList<String>(); System.out.println(list.getClass()); }} public class Main {public static void main(String[] args) { Demo demo = new Demo(); demo.show(); }}
A. class java.util.LinkedList B. String C. Compiler Error
Answer: A. class java.util.LinkedList
Explanation: getclass() method returns the runtime class of an object. That class object is the object that is locked by the static synchronized method of represented class. Here LinkedList is the runtime class so the answer is java.util.LinkedList.
This article is contributed by RanjaniRavi. 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.
aktmishra143
Java-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 108,
"s": 54,
"text": "1. What is the Output of the following Java Program? "
},
{
"code": null,
"e": 113,
"s": 108,
"text": "Java"
},
{
"code": "import java.util.LinkedList; class Demo {public void show() { LinkedList<Integer> list = new LinkedList<Integer>(); list.add(1); list.add(4); list.add(7); list.add(5); for (int i = 0; i < list.size(); i++) { System.out.print(list.get(i) + \" \"); } }} public class Main {public static void main(String[] args) { Demo demo = new Demo(); demo.show(); }}",
"e": 549,
"s": 113,
"text": null
},
{
"code": null,
"e": 594,
"s": 549,
"text": "A. Compilation Error B. 1 4 7 5 C. 1 4 5 7 "
},
{
"code": null,
"e": 613,
"s": 594,
"text": "Answer: B. 1 4 7 5"
},
{
"code": null,
"e": 863,
"s": 613,
"text": "Explanation: List stores elements in sequential order and then we can access an element in List using an index. The List provides the ability to access its elements by using its index. But in the set, map elements are not accessed by using an index."
},
{
"code": null,
"e": 918,
"s": 863,
"text": "2. What is the output of the following Java Program? "
},
{
"code": null,
"e": 923,
"s": 918,
"text": "Java"
},
{
"code": "import java.util.Collections;import java.util.LinkedList;import java.util.List; class Demo {public void show() { List<Integer> list = new LinkedList<Integer>(); list.add(1); list.add(4); list.add(7); list.add(5); Collections.sort(list); // line 8 System.out.println(list); }} public class Main {public static void main(String[] args) { Demo demo = new Demo(); demo.show(); }}",
"e": 1374,
"s": 923,
"text": null
},
{
"code": null,
"e": 1439,
"s": 1374,
"text": "A. Compilation Error at line 9 B. [1, 4, 5, 7] C. [1, 4, 7, 5] "
},
{
"code": null,
"e": 1463,
"s": 1439,
"text": "Answer: B. [1, 4, 5, 7]"
},
{
"code": null,
"e": 1706,
"s": 1463,
"text": "Explanation: Collections.sort() sort the list in ascending order. Collections class provides static methods for sorting the elements in collections. If Collection elements are of set type elements are inserted in sorted order no need to sort."
},
{
"code": null,
"e": 1761,
"s": 1706,
"text": "3. What is the output of the following Java Program? "
},
{
"code": null,
"e": 1766,
"s": 1761,
"text": "Java"
},
{
"code": "import java.util.ArrayList;import java.util.Collections;import java.util.Iterator; class Demo {public void show() { ArrayList<String> list = new ArrayList<String>(); list.add(\"banana\"); list.add(\"apple\"); Iterator itr = list.iterator(); Collections.sort(list); while (itr.hasNext()) { System.out.print(itr.next() + \" \"); } }} public class Main {public static void main(String[] args) { Demo demo = new Demo(); demo.show(); }}",
"e": 2279,
"s": 1766,
"text": null
},
{
"code": null,
"e": 2384,
"s": 2279,
"text": "A. Exception in thread “main” java.util.ConcurrentModificationExceptionB. apple banana C. banana apple "
},
{
"code": null,
"e": 2464,
"s": 2384,
"text": "Answer: A. Exception in thread \"main\" java.util.ConcurrentModificationException"
},
{
"code": null,
"e": 2703,
"s": 2464,
"text": "Explanation: Collections.sort() sort element and Iterator is an object used to traverse through a Collection. Iterator is an interface available in the Collection framework in java.util.package. It is used to traverse elements one by one."
},
{
"code": null,
"e": 2758,
"s": 2703,
"text": "4. What is the Output of the following Java Program? "
},
{
"code": null,
"e": 2763,
"s": 2758,
"text": "Java"
},
{
"code": "import java.util.ArrayList; class Demo {public void show() { ArrayList<String> list = new ArrayList<String>(); ArrayList<Integer> list1 = new ArrayList<Integer>(); boolean check = (list.getClass() == list1.getClass()); System.out.println(check); }} public class Main {public static void main(String[] args) { Demo demo = new Demo(); demo.show(); }}",
"e": 3166,
"s": 2763,
"text": null
},
{
"code": null,
"e": 3184,
"s": 3166,
"text": "A. true B. false "
},
{
"code": null,
"e": 3200,
"s": 3184,
"text": "Answer: A. true"
},
{
"code": null,
"e": 3430,
"s": 3200,
"text": "Explanation: getclass() method returns the runtime class of an object. That class object is the object that is locked by the static synchronized method of represented class. Here both are in ArrayList Class so the answer is true."
},
{
"code": null,
"e": 3485,
"s": 3430,
"text": "5. What is the Output of the following Java Program? "
},
{
"code": null,
"e": 3490,
"s": 3485,
"text": "Java"
},
{
"code": "import java.util.LinkedList; class Demo {public void show() { LinkedList<String> list = new LinkedList<String>(); System.out.println(list.getClass()); }} public class Main {public static void main(String[] args) { Demo demo = new Demo(); demo.show(); }}",
"e": 3785,
"s": 3490,
"text": null
},
{
"code": null,
"e": 3844,
"s": 3785,
"text": "A. class java.util.LinkedList B. String C. Compiler Error "
},
{
"code": null,
"e": 3882,
"s": 3844,
"text": "Answer: A. class java.util.LinkedList"
},
{
"code": null,
"e": 4132,
"s": 3882,
"text": "Explanation: getclass() method returns the runtime class of an object. That class object is the object that is locked by the static synchronized method of represented class. Here LinkedList is the runtime class so the answer is java.util.LinkedList."
},
{
"code": null,
"e": 4556,
"s": 4132,
"text": "This article is contributed by RanjaniRavi. 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": 4569,
"s": 4556,
"text": "aktmishra143"
},
{
"code": null,
"e": 4581,
"s": 4569,
"text": "Java-Output"
},
{
"code": null,
"e": 4596,
"s": 4581,
"text": "Program Output"
}
] |
PHP | ob_end_flush(), ob_end_clean() Functions
|
08 Mar, 2018
In the previous article on ob_start(), we learned how to start the output buffer; now we need to end the output buffering and send the whole HTML to the browser to render. We can do this by the help of functions ob_end_flush() and ob_end_clean().
ob_end_flush() Function
Syntax:
bool ob_end_flush ()
Parameters: The function doesn’t take any parameter.
Return Type: This function sends the HTML stored to browser and turns off output buffering. On success, TRUE is returned otherwise FALSE.
ob_end_clean() Function
Syntax:
bool ob_end_clean()
Parameters: The function doesn’t take any parameter.
Return Type: This function cleans the HTML stored and turns off output buffering. On success, TRUE is returned otherwise FALSE.
Below program illustrates the working of ob_end_flush() and ob_end_clean() in PHP:
<?php // PHP code to illustrate the working of // ob_end_flush() and ob_end_clean() // ob_end_flush()ob_start();echo "Hello Geek!"; //This will get printed.ob_end_flush(); // ob_end_clean() ob_start();echo "Hi Geek!"; //This will not get printed.ob_end_clean(); ?>
Output:
Hello Geek!
Important points to note:
ob_end_flush() or ob_end_clean() are not necessary functions i.e. if a developer ever uses ob_start() without using the mentioned functions the webpage will appear to be working correctly displaying every content, but what happens in the back is nowhere near optimized. When PHP encounters ob_start() it allocates a new output buffer and concatenates every HTML that appears after it, if there is no terminating function then upon reaching the end the stored data is sent to the browser as a default action. Developers can create optimized web pages by terminating the output buffering when not required thus keeping the global stack clear.
There raises a question, if we use ob_end_clean() to clean the whole output buffer then why even use output buffering. We use ob_end_clean() with ob_get_contents() which first gets the contents as a string and then the output buffer is cleaned and turned off, this clears the global stack and keeps the whole content in a variable to be processed further.
Reference:
http://php.net/manual/en/function.ob-end-flush.php
http://php.net/manual/en/function.ob-end-clean.php
PHP-function
PHP-output
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Mar, 2018"
},
{
"code": null,
"e": 275,
"s": 28,
"text": "In the previous article on ob_start(), we learned how to start the output buffer; now we need to end the output buffering and send the whole HTML to the browser to render. We can do this by the help of functions ob_end_flush() and ob_end_clean()."
},
{
"code": null,
"e": 299,
"s": 275,
"text": "ob_end_flush() Function"
},
{
"code": null,
"e": 307,
"s": 299,
"text": "Syntax:"
},
{
"code": null,
"e": 329,
"s": 307,
"text": "bool ob_end_flush ()\n"
},
{
"code": null,
"e": 382,
"s": 329,
"text": "Parameters: The function doesn’t take any parameter."
},
{
"code": null,
"e": 520,
"s": 382,
"text": "Return Type: This function sends the HTML stored to browser and turns off output buffering. On success, TRUE is returned otherwise FALSE."
},
{
"code": null,
"e": 544,
"s": 520,
"text": "ob_end_clean() Function"
},
{
"code": null,
"e": 552,
"s": 544,
"text": "Syntax:"
},
{
"code": null,
"e": 573,
"s": 552,
"text": "bool ob_end_clean()\n"
},
{
"code": null,
"e": 626,
"s": 573,
"text": "Parameters: The function doesn’t take any parameter."
},
{
"code": null,
"e": 754,
"s": 626,
"text": "Return Type: This function cleans the HTML stored and turns off output buffering. On success, TRUE is returned otherwise FALSE."
},
{
"code": null,
"e": 837,
"s": 754,
"text": "Below program illustrates the working of ob_end_flush() and ob_end_clean() in PHP:"
},
{
"code": "<?php // PHP code to illustrate the working of // ob_end_flush() and ob_end_clean() // ob_end_flush()ob_start();echo \"Hello Geek!\"; //This will get printed.ob_end_flush(); // ob_end_clean() ob_start();echo \"Hi Geek!\"; //This will not get printed.ob_end_clean(); ?>",
"e": 1107,
"s": 837,
"text": null
},
{
"code": null,
"e": 1115,
"s": 1107,
"text": "Output:"
},
{
"code": null,
"e": 1128,
"s": 1115,
"text": "Hello Geek!\n"
},
{
"code": null,
"e": 1154,
"s": 1128,
"text": "Important points to note:"
},
{
"code": null,
"e": 1795,
"s": 1154,
"text": "ob_end_flush() or ob_end_clean() are not necessary functions i.e. if a developer ever uses ob_start() without using the mentioned functions the webpage will appear to be working correctly displaying every content, but what happens in the back is nowhere near optimized. When PHP encounters ob_start() it allocates a new output buffer and concatenates every HTML that appears after it, if there is no terminating function then upon reaching the end the stored data is sent to the browser as a default action. Developers can create optimized web pages by terminating the output buffering when not required thus keeping the global stack clear."
},
{
"code": null,
"e": 2151,
"s": 1795,
"text": "There raises a question, if we use ob_end_clean() to clean the whole output buffer then why even use output buffering. We use ob_end_clean() with ob_get_contents() which first gets the contents as a string and then the output buffer is cleaned and turned off, this clears the global stack and keeps the whole content in a variable to be processed further."
},
{
"code": null,
"e": 2162,
"s": 2151,
"text": "Reference:"
},
{
"code": null,
"e": 2213,
"s": 2162,
"text": "http://php.net/manual/en/function.ob-end-flush.php"
},
{
"code": null,
"e": 2264,
"s": 2213,
"text": "http://php.net/manual/en/function.ob-end-clean.php"
},
{
"code": null,
"e": 2277,
"s": 2264,
"text": "PHP-function"
},
{
"code": null,
"e": 2288,
"s": 2277,
"text": "PHP-output"
},
{
"code": null,
"e": 2292,
"s": 2288,
"text": "PHP"
},
{
"code": null,
"e": 2309,
"s": 2292,
"text": "Web Technologies"
},
{
"code": null,
"e": 2313,
"s": 2309,
"text": "PHP"
}
] |
GATE | GATE-CS-2005 | Question 32
|
28 Jun, 2021
Consider the following C-program:
double foo (double); /* Line 1 */ int main(){ double da, db; // input da db = foo(da); } double foo(double a){ return a;}
The above code compiled without any error or warning. If Line 1 is deleted, the above code will show:(A) no compile warning or error(B) some compiler-warnings not leading to unintended results(C) some compiler-warnings due to type-mismatch eventually leading to unintended results(D) compiler errorsAnswer: (D)Explanation: Refer What happens when a function is called before its declaration in C?Quiz of this Question
GATE-CS-2005
GATE-GATE-CS-2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 62,
"s": 28,
"text": "Consider the following C-program:"
},
{
"code": "double foo (double); /* Line 1 */ int main(){ double da, db; // input da db = foo(da); } double foo(double a){ return a;}",
"e": 205,
"s": 62,
"text": null
},
{
"code": null,
"e": 623,
"s": 205,
"text": "The above code compiled without any error or warning. If Line 1 is deleted, the above code will show:(A) no compile warning or error(B) some compiler-warnings not leading to unintended results(C) some compiler-warnings due to type-mismatch eventually leading to unintended results(D) compiler errorsAnswer: (D)Explanation: Refer What happens when a function is called before its declaration in C?Quiz of this Question"
},
{
"code": null,
"e": 636,
"s": 623,
"text": "GATE-CS-2005"
},
{
"code": null,
"e": 654,
"s": 636,
"text": "GATE-GATE-CS-2005"
},
{
"code": null,
"e": 659,
"s": 654,
"text": "GATE"
}
] |
Image Translation using OpenCV | Python
|
20 May, 2019
Translation refers to the rectilinear shift of an object i.e. an image from one location to another. If we know the amount of shift in horizontal and the vertical direction, say (tx, ty) then we can make a transformation matrix e.g. where tx denotes the shift along the x-axis and ty denotes shift along the y-axis i.e. the number of pixels by which we need to shift about in that direction.Now, we can use the cv2.wrapAffine() function to implement these translations. This function requires a 2×3 array. The numpy array should be of float type.
Below is the Python code for Image Translation:
import cv2import numpy as np image = cv2.imread('C:\\gfg\\tomatoes.jpg') # Store height and width of the imageheight, width = image.shape[:2] quarter_height, quarter_width = height / 4, width / 4 T = np.float32([[1, 0, quarter_width], [0, 1, quarter_height]]) # We use warpAffine to transform# the image using the matrix, Timg_translation = cv2.warpAffine(image, T, (width, height)) cv2.imshow("Originalimage", image)cv2.imshow('Translation', img_translation)cv2.waitKey() cv2.destroyAllWindows()
Output:
Advantages/application of image translation are:
Hiding a part of the image
Cropping an image
Shifting an image
Animating an image using image translations in loop.
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 May, 2019"
},
{
"code": null,
"e": 575,
"s": 28,
"text": "Translation refers to the rectilinear shift of an object i.e. an image from one location to another. If we know the amount of shift in horizontal and the vertical direction, say (tx, ty) then we can make a transformation matrix e.g. where tx denotes the shift along the x-axis and ty denotes shift along the y-axis i.e. the number of pixels by which we need to shift about in that direction.Now, we can use the cv2.wrapAffine() function to implement these translations. This function requires a 2×3 array. The numpy array should be of float type."
},
{
"code": null,
"e": 623,
"s": 575,
"text": "Below is the Python code for Image Translation:"
},
{
"code": "import cv2import numpy as np image = cv2.imread('C:\\\\gfg\\\\tomatoes.jpg') # Store height and width of the imageheight, width = image.shape[:2] quarter_height, quarter_width = height / 4, width / 4 T = np.float32([[1, 0, quarter_width], [0, 1, quarter_height]]) # We use warpAffine to transform# the image using the matrix, Timg_translation = cv2.warpAffine(image, T, (width, height)) cv2.imshow(\"Originalimage\", image)cv2.imshow('Translation', img_translation)cv2.waitKey() cv2.destroyAllWindows()",
"e": 1127,
"s": 623,
"text": null
},
{
"code": null,
"e": 1135,
"s": 1127,
"text": "Output:"
},
{
"code": null,
"e": 1184,
"s": 1135,
"text": "Advantages/application of image translation are:"
},
{
"code": null,
"e": 1211,
"s": 1184,
"text": "Hiding a part of the image"
},
{
"code": null,
"e": 1229,
"s": 1211,
"text": "Cropping an image"
},
{
"code": null,
"e": 1247,
"s": 1229,
"text": "Shifting an image"
},
{
"code": null,
"e": 1300,
"s": 1247,
"text": "Animating an image using image translations in loop."
},
{
"code": null,
"e": 1317,
"s": 1300,
"text": "Image-Processing"
},
{
"code": null,
"e": 1324,
"s": 1317,
"text": "OpenCV"
},
{
"code": null,
"e": 1331,
"s": 1324,
"text": "Python"
},
{
"code": null,
"e": 1429,
"s": 1331,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1461,
"s": 1429,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1488,
"s": 1461,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1509,
"s": 1488,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1532,
"s": 1509,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1588,
"s": 1532,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1619,
"s": 1588,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1661,
"s": 1619,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1703,
"s": 1661,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1742,
"s": 1703,
"text": "Python | datetime.timedelta() function"
}
] |
Least frequent element in an array
|
24 May, 2021
Given an array, find the least frequent element in it. If there are multiple elements that appear least number of times, print any one of them.Examples :
Input : arr[] = {1, 3, 2, 1, 2, 2, 3, 1}
Output : 3
3 appears minimum number of times in given
array.
Input : arr[] = {10, 20, 30}
Output : 10 or 20 or 30
A simple solution is to run two loops. The outer loop picks all elements one by one. The inner loop finds frequency of the picked element and compares with the minimum so far. Time complexity of this solution is O(n2)A better solution is to do sorting. We first sort the array, then linearly traverse the array.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find the least frequent element// in an array.#include <bits/stdc++.h>using namespace std; int leastFrequent(int arr[], int n){ // Sort the array sort(arr, arr + n); // find the min frequency using linear traversal int min_count = n+1, res = -1, curr_count = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else { if (curr_count < min_count) { min_count = curr_count; res = arr[i - 1]; } curr_count = 1; } } // If last element is least frequent if (curr_count < min_count) { min_count = curr_count; res = arr[n - 1]; } return res;} // driver programint main(){ int arr[] = {1, 3, 2, 1, 2, 2, 3, 1}; int n = sizeof(arr) / sizeof(arr[0]); cout << leastFrequent(arr, n); return 0;}
// Java program to find the least frequent element// in an array.import java.io.*;import java.util.*; class GFG { static int leastFrequent(int arr[], int n) { // Sort the array Arrays.sort(arr); // find the min frequency using // linear traversal int min_count = n+1, res = -1; int curr_count = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else { if (curr_count < min_count) { min_count = curr_count; res = arr[i - 1]; } curr_count = 1; } } // If last element is least frequent if (curr_count < min_count) { min_count = curr_count; res = arr[n - 1]; } return res; } // driver program public static void main(String args[]) { int arr[] = {1, 3, 2, 1, 2, 2, 3, 1}; int n = arr.length; System.out.print(leastFrequent(arr, n)); }} /*This code is contributed by Nikita Tiwari.*/
# Python 3 program to find the least# frequent element in an array. def leastFrequent(arr, n) : # Sort the array arr.sort() # find the min frequency using # linear traversal min_count = n + 1 res = -1 curr_count = 1 for i in range(1, n) : if (arr[i] == arr[i - 1]) : curr_count = curr_count + 1 else : if (curr_count < min_count) : min_count = curr_count res = arr[i - 1] curr_count = 1 # If last element is least frequent if (curr_count < min_count) : min_count = curr_count res = arr[n - 1] return res # Driver programarr = [1, 3, 2, 1, 2, 2, 3, 1]n = len(arr)print(leastFrequent(arr, n)) # This code is contributed# by Nikita Tiwari.
// C# program to find the least// frequent element in an array.using System; class GFG { static int leastFrequent(int[] arr, int n) { // Sort the array Array.Sort(arr); // find the min frequency // using linear traversal int min_count = n + 1, res = -1; int curr_count = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else { if (curr_count < min_count) { min_count = curr_count; res = arr[i - 1]; } curr_count = 1; } } // If last element is least frequent if (curr_count < min_count) { min_count = curr_count; res = arr[n - 1]; } return res; } // Driver code static public void Main () { int[] arr = {1, 3, 2, 1, 2, 2, 3, 1}; int n = arr.Length; // Function calling Console.Write(leastFrequent(arr, n)); }} // This code is contributed by Shrikant13
<?php// PHP program to find the// least frequent element// in an array. function leastFrequent($arr, $n){ // Sort the array sort($arr); sort($arr , $n); // find the min frequency // using linear traversal $min_count = $n + 1; $res = -1; $curr_count = 1; for($i = 1; $i < $n; $i++) { if ($arr[$i] == $arr[$i - 1]) $curr_count++; else { if ($curr_count < $min_count) { $min_count = $curr_count; $res = $arr[$i - 1]; } $curr_count = 1; } } // If last element is // least frequent if ($curr_count < $min_count) { $min_count = $curr_count; $res = $arr[$n - 1]; } return $res;} // Driver Code{ $arr = array(1, 3, 2, 1, 2, 2, 3, 1); $n = sizeof($arr) / sizeof($arr[0]); echo leastFrequent($arr, $n); return 0;} // This code is contributed by nitin mittal?>
<script> // JavaScript program to find the least frequent element// in an array. function leastFrequent(arr, n) { // Sort the array arr.sort(); // find the min frequency using // linear traversal let min_count = n+1, res = -1; let curr_count = 1; for (let i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else { if (curr_count < min_count) { min_count = curr_count; res = arr[i - 1]; } curr_count = 1; } } // If last element is least frequent if (curr_count < min_count) { min_count = curr_count; res = arr[n - 1]; } return res; } // Driver code let arr = [1, 3, 2, 1, 2, 2, 3, 1]; let n = arr.length; document.write(leastFrequent(arr, n)); </script>
3
Time Complexity : O(n Log n) Auxiliary Space : O(1)An efficient solution is to use hashing. We create a hash table and store elements and their frequency counts as key value pairs. Finally we traverse the hash table and print the key with minimum value.
C++
Java
Python3
C#
Javascript
// CPP program to find the least frequent element// in an array.#include <bits/stdc++.h>using namespace std; int leastFrequent(int arr[], int n){ // Insert all elements in hash. unordered_map<int, int> hash; for (int i = 0; i < n; i++) hash[arr[i]]++; // find the min frequency int min_count = n+1, res = -1; for (auto i : hash) { if (min_count >= i.second) { res = i.first; min_count = i.second; } } return res;} // driver programint main(){ int arr[] = {1, 3, 2, 1, 2, 2, 3, 1}; int n = sizeof(arr) / sizeof(arr[0]); cout << leastFrequent(arr, n); return 0;}
//Java program to find the least frequent element//in an arrayimport java.util.HashMap;import java.util.Map;import java.util.Map.Entry; class GFG { static int leastFrequent(int arr[],int n) { // Insert all elements in hash. Map<Integer,Integer> count = new HashMap<Integer,Integer>(); for(int i = 0; i < n; i++) { int key = arr[i]; if(count.containsKey(key)) { int freq = count.get(key); freq++; count.put(key,freq); } else count.put(key,1); } // find min frequency. int min_count = n+1, res = -1; for(Entry<Integer,Integer> val : count.entrySet()) { if (min_count >= val.getValue()) { res = val.getKey(); min_count = val.getValue(); } } return res; } // driver program public static void main (String[] args) { int arr[] = {1, 3, 2, 1, 2, 2, 3, 1}; int n = arr.length; System.out.println(leastFrequent(arr,n)); }} // This code is contributed by Akash Singh.
# Python3 program to find the most# frequent element in an array.import math as mt def leastFrequent(arr, n): # Insert all elements in Hash. Hash = dict() for i in range(n): if arr[i] in Hash.keys(): Hash[arr[i]] += 1 else: Hash[arr[i]] = 1 # find the max frequency min_count = n + 1 res = -1 for i in Hash: if (min_count >= Hash[i]): res = i min_count = Hash[i] return res # Driver Codearr = [1, 3, 2, 1, 2, 2, 3, 1]n = len(arr)print(leastFrequent(arr, n)) # This code is contributed by# mohit kumar 29
// C# program to find the// least frequent element// in an array.using System;using System.Collections.Generic; class GFG{ static int leastFrequent(int []arr, int n) { // Insert all elements in hash. Dictionary<int, int> count = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { int key = arr[i]; if(count.ContainsKey(key)) { int freq = count[key]; freq++; count[key] = freq; } else count.Add(key, 1); } // find the min frequency int min_count = n + 1, res = -1; foreach (KeyValuePair<int, int> pair in count) { if (min_count >= pair.Value) { res = pair.Key; min_count = pair.Value; } } return res; } // Driver Code static void Main() { int []arr = new int[]{1, 3, 2, 1, 2, 2, 3, 1}; int n = arr.Length; Console.Write(leastFrequent(arr, n)); }} // This code is contributed by// Manish Shaw(manishshaw1)
<script> // JavaScript program to find the least frequent element// in an array. function leastFrequent(arr, n){ // Insert all elements in hash. var hash = new Map(); for (var i = 0; i < n; i++) { if(hash.has(arr[i])) hash.set(arr[i], hash.get(arr[i])+1) else hash.set(arr[i], 1); } // find the min frequency var min_count = n+1, res = -1; hash.forEach((value, key) => { if (min_count >= value) { res = key; min_count = value; } }); return res;} // driver programvar arr = [1, 3, 2, 1, 2, 2, 3, 1];var n = arr.length;document.write( leastFrequent(arr, n)); </script>
3
Time Complexity : O(n) Auxiliary Space : O(n)
shrikanth13
nitin mittal
manishshaw1
mohit kumar 29
sanjoy_62
rrrtnx
frequency-counting
Arrays
Searching
Sorting
Arrays
Searching
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
Binary Search
Linear Search
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array
Find the Missing Number
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 208,
"s": 52,
"text": "Given an array, find the least frequent element in it. If there are multiple elements that appear least number of times, print any one of them.Examples : "
},
{
"code": null,
"e": 364,
"s": 208,
"text": "Input : arr[] = {1, 3, 2, 1, 2, 2, 3, 1}\nOutput : 3\n3 appears minimum number of times in given\narray.\n\nInput : arr[] = {10, 20, 30}\nOutput : 10 or 20 or 30"
},
{
"code": null,
"e": 679,
"s": 366,
"text": "A simple solution is to run two loops. The outer loop picks all elements one by one. The inner loop finds frequency of the picked element and compares with the minimum so far. Time complexity of this solution is O(n2)A better solution is to do sorting. We first sort the array, then linearly traverse the array. "
},
{
"code": null,
"e": 683,
"s": 679,
"text": "C++"
},
{
"code": null,
"e": 688,
"s": 683,
"text": "Java"
},
{
"code": null,
"e": 696,
"s": 688,
"text": "Python3"
},
{
"code": null,
"e": 699,
"s": 696,
"text": "C#"
},
{
"code": null,
"e": 703,
"s": 699,
"text": "PHP"
},
{
"code": null,
"e": 714,
"s": 703,
"text": "Javascript"
},
{
"code": "// CPP program to find the least frequent element// in an array.#include <bits/stdc++.h>using namespace std; int leastFrequent(int arr[], int n){ // Sort the array sort(arr, arr + n); // find the min frequency using linear traversal int min_count = n+1, res = -1, curr_count = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else { if (curr_count < min_count) { min_count = curr_count; res = arr[i - 1]; } curr_count = 1; } } // If last element is least frequent if (curr_count < min_count) { min_count = curr_count; res = arr[n - 1]; } return res;} // driver programint main(){ int arr[] = {1, 3, 2, 1, 2, 2, 3, 1}; int n = sizeof(arr) / sizeof(arr[0]); cout << leastFrequent(arr, n); return 0;}",
"e": 1594,
"s": 714,
"text": null
},
{
"code": "// Java program to find the least frequent element// in an array.import java.io.*;import java.util.*; class GFG { static int leastFrequent(int arr[], int n) { // Sort the array Arrays.sort(arr); // find the min frequency using // linear traversal int min_count = n+1, res = -1; int curr_count = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else { if (curr_count < min_count) { min_count = curr_count; res = arr[i - 1]; } curr_count = 1; } } // If last element is least frequent if (curr_count < min_count) { min_count = curr_count; res = arr[n - 1]; } return res; } // driver program public static void main(String args[]) { int arr[] = {1, 3, 2, 1, 2, 2, 3, 1}; int n = arr.length; System.out.print(leastFrequent(arr, n)); }} /*This code is contributed by Nikita Tiwari.*/",
"e": 2751,
"s": 1594,
"text": null
},
{
"code": "# Python 3 program to find the least# frequent element in an array. def leastFrequent(arr, n) : # Sort the array arr.sort() # find the min frequency using # linear traversal min_count = n + 1 res = -1 curr_count = 1 for i in range(1, n) : if (arr[i] == arr[i - 1]) : curr_count = curr_count + 1 else : if (curr_count < min_count) : min_count = curr_count res = arr[i - 1] curr_count = 1 # If last element is least frequent if (curr_count < min_count) : min_count = curr_count res = arr[n - 1] return res # Driver programarr = [1, 3, 2, 1, 2, 2, 3, 1]n = len(arr)print(leastFrequent(arr, n)) # This code is contributed# by Nikita Tiwari.",
"e": 3557,
"s": 2751,
"text": null
},
{
"code": "// C# program to find the least// frequent element in an array.using System; class GFG { static int leastFrequent(int[] arr, int n) { // Sort the array Array.Sort(arr); // find the min frequency // using linear traversal int min_count = n + 1, res = -1; int curr_count = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else { if (curr_count < min_count) { min_count = curr_count; res = arr[i - 1]; } curr_count = 1; } } // If last element is least frequent if (curr_count < min_count) { min_count = curr_count; res = arr[n - 1]; } return res; } // Driver code static public void Main () { int[] arr = {1, 3, 2, 1, 2, 2, 3, 1}; int n = arr.Length; // Function calling Console.Write(leastFrequent(arr, n)); }} // This code is contributed by Shrikant13",
"e": 4718,
"s": 3557,
"text": null
},
{
"code": "<?php// PHP program to find the// least frequent element// in an array. function leastFrequent($arr, $n){ // Sort the array sort($arr); sort($arr , $n); // find the min frequency // using linear traversal $min_count = $n + 1; $res = -1; $curr_count = 1; for($i = 1; $i < $n; $i++) { if ($arr[$i] == $arr[$i - 1]) $curr_count++; else { if ($curr_count < $min_count) { $min_count = $curr_count; $res = $arr[$i - 1]; } $curr_count = 1; } } // If last element is // least frequent if ($curr_count < $min_count) { $min_count = $curr_count; $res = $arr[$n - 1]; } return $res;} // Driver Code{ $arr = array(1, 3, 2, 1, 2, 2, 3, 1); $n = sizeof($arr) / sizeof($arr[0]); echo leastFrequent($arr, $n); return 0;} // This code is contributed by nitin mittal?>",
"e": 5666,
"s": 4718,
"text": null
},
{
"code": "<script> // JavaScript program to find the least frequent element// in an array. function leastFrequent(arr, n) { // Sort the array arr.sort(); // find the min frequency using // linear traversal let min_count = n+1, res = -1; let curr_count = 1; for (let i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else { if (curr_count < min_count) { min_count = curr_count; res = arr[i - 1]; } curr_count = 1; } } // If last element is least frequent if (curr_count < min_count) { min_count = curr_count; res = arr[n - 1]; } return res; } // Driver code let arr = [1, 3, 2, 1, 2, 2, 3, 1]; let n = arr.length; document.write(leastFrequent(arr, n)); </script>",
"e": 6698,
"s": 5666,
"text": null
},
{
"code": null,
"e": 6700,
"s": 6698,
"text": "3"
},
{
"code": null,
"e": 6957,
"s": 6702,
"text": "Time Complexity : O(n Log n) Auxiliary Space : O(1)An efficient solution is to use hashing. We create a hash table and store elements and their frequency counts as key value pairs. Finally we traverse the hash table and print the key with minimum value. "
},
{
"code": null,
"e": 6961,
"s": 6957,
"text": "C++"
},
{
"code": null,
"e": 6966,
"s": 6961,
"text": "Java"
},
{
"code": null,
"e": 6974,
"s": 6966,
"text": "Python3"
},
{
"code": null,
"e": 6977,
"s": 6974,
"text": "C#"
},
{
"code": null,
"e": 6988,
"s": 6977,
"text": "Javascript"
},
{
"code": "// CPP program to find the least frequent element// in an array.#include <bits/stdc++.h>using namespace std; int leastFrequent(int arr[], int n){ // Insert all elements in hash. unordered_map<int, int> hash; for (int i = 0; i < n; i++) hash[arr[i]]++; // find the min frequency int min_count = n+1, res = -1; for (auto i : hash) { if (min_count >= i.second) { res = i.first; min_count = i.second; } } return res;} // driver programint main(){ int arr[] = {1, 3, 2, 1, 2, 2, 3, 1}; int n = sizeof(arr) / sizeof(arr[0]); cout << leastFrequent(arr, n); return 0;}",
"e": 7630,
"s": 6988,
"text": null
},
{
"code": "//Java program to find the least frequent element//in an arrayimport java.util.HashMap;import java.util.Map;import java.util.Map.Entry; class GFG { static int leastFrequent(int arr[],int n) { // Insert all elements in hash. Map<Integer,Integer> count = new HashMap<Integer,Integer>(); for(int i = 0; i < n; i++) { int key = arr[i]; if(count.containsKey(key)) { int freq = count.get(key); freq++; count.put(key,freq); } else count.put(key,1); } // find min frequency. int min_count = n+1, res = -1; for(Entry<Integer,Integer> val : count.entrySet()) { if (min_count >= val.getValue()) { res = val.getKey(); min_count = val.getValue(); } } return res; } // driver program public static void main (String[] args) { int arr[] = {1, 3, 2, 1, 2, 2, 3, 1}; int n = arr.length; System.out.println(leastFrequent(arr,n)); }} // This code is contributed by Akash Singh.",
"e": 8876,
"s": 7630,
"text": null
},
{
"code": "# Python3 program to find the most# frequent element in an array.import math as mt def leastFrequent(arr, n): # Insert all elements in Hash. Hash = dict() for i in range(n): if arr[i] in Hash.keys(): Hash[arr[i]] += 1 else: Hash[arr[i]] = 1 # find the max frequency min_count = n + 1 res = -1 for i in Hash: if (min_count >= Hash[i]): res = i min_count = Hash[i] return res # Driver Codearr = [1, 3, 2, 1, 2, 2, 3, 1]n = len(arr)print(leastFrequent(arr, n)) # This code is contributed by# mohit kumar 29",
"e": 9480,
"s": 8876,
"text": null
},
{
"code": "// C# program to find the// least frequent element// in an array.using System;using System.Collections.Generic; class GFG{ static int leastFrequent(int []arr, int n) { // Insert all elements in hash. Dictionary<int, int> count = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { int key = arr[i]; if(count.ContainsKey(key)) { int freq = count[key]; freq++; count[key] = freq; } else count.Add(key, 1); } // find the min frequency int min_count = n + 1, res = -1; foreach (KeyValuePair<int, int> pair in count) { if (min_count >= pair.Value) { res = pair.Key; min_count = pair.Value; } } return res; } // Driver Code static void Main() { int []arr = new int[]{1, 3, 2, 1, 2, 2, 3, 1}; int n = arr.Length; Console.Write(leastFrequent(arr, n)); }} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 10739,
"s": 9480,
"text": null
},
{
"code": "<script> // JavaScript program to find the least frequent element// in an array. function leastFrequent(arr, n){ // Insert all elements in hash. var hash = new Map(); for (var i = 0; i < n; i++) { if(hash.has(arr[i])) hash.set(arr[i], hash.get(arr[i])+1) else hash.set(arr[i], 1); } // find the min frequency var min_count = n+1, res = -1; hash.forEach((value, key) => { if (min_count >= value) { res = key; min_count = value; } }); return res;} // driver programvar arr = [1, 3, 2, 1, 2, 2, 3, 1];var n = arr.length;document.write( leastFrequent(arr, n)); </script>",
"e": 11420,
"s": 10739,
"text": null
},
{
"code": null,
"e": 11422,
"s": 11420,
"text": "3"
},
{
"code": null,
"e": 11471,
"s": 11424,
"text": "Time Complexity : O(n) Auxiliary Space : O(n) "
},
{
"code": null,
"e": 11483,
"s": 11471,
"text": "shrikanth13"
},
{
"code": null,
"e": 11496,
"s": 11483,
"text": "nitin mittal"
},
{
"code": null,
"e": 11508,
"s": 11496,
"text": "manishshaw1"
},
{
"code": null,
"e": 11523,
"s": 11508,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 11533,
"s": 11523,
"text": "sanjoy_62"
},
{
"code": null,
"e": 11540,
"s": 11533,
"text": "rrrtnx"
},
{
"code": null,
"e": 11559,
"s": 11540,
"text": "frequency-counting"
},
{
"code": null,
"e": 11566,
"s": 11559,
"text": "Arrays"
},
{
"code": null,
"e": 11576,
"s": 11566,
"text": "Searching"
},
{
"code": null,
"e": 11584,
"s": 11576,
"text": "Sorting"
},
{
"code": null,
"e": 11591,
"s": 11584,
"text": "Arrays"
},
{
"code": null,
"e": 11601,
"s": 11591,
"text": "Searching"
},
{
"code": null,
"e": 11609,
"s": 11601,
"text": "Sorting"
},
{
"code": null,
"e": 11707,
"s": 11609,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11751,
"s": 11707,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 11783,
"s": 11751,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 11797,
"s": 11783,
"text": "Linear Search"
},
{
"code": null,
"e": 11882,
"s": 11797,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 11905,
"s": 11882,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 11919,
"s": 11905,
"text": "Binary Search"
},
{
"code": null,
"e": 11933,
"s": 11919,
"text": "Linear Search"
},
{
"code": null,
"e": 11989,
"s": 11933,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 12037,
"s": 11989,
"text": "Search an element in a sorted and rotated array"
}
] |
How to create Dialog Box in ReactJS?
|
05 Mar, 2021
A Dialog is a type of modal window which appears in front of app content to provide critical information or ask for a decision. Material UI for React has this component available for us, and it is very easy to integrate. We can create Dialog Box 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
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 Dialog from "@material-ui/core/Dialog";import DialogContentText from "@material-ui/core/DialogContentText";import DialogTitle from "@material-ui/core/DialogTitle";import DialogActions from "@material-ui/core/DialogActions";import DialogContent from "@material-ui/core/DialogContent";import Button from "@material-ui/core/Button"; export default function App() { const [open, setOpen] = React.useState(false); const handleClickToOpen = () => { setOpen(true); }; const handleToClose = () => { setOpen(false); }; return ( <div stlye={{}}> <h4>How to create Dialog Box in ReactJS?</h4> <Button variant="outlined" color="primary" onClick={handleClickToOpen}> Open Demo Dialog </Button> <Dialog open={open} onClose={handleToClose}> <DialogTitle>{"How are you?"}</DialogTitle> <DialogContent> <DialogContentText> I am Good, Hope the same for you! </DialogContentText> </DialogContent> <DialogActions> <Button onClick={handleToClose} color="primary" autoFocus> Close </Button> </DialogActions> </Dialog> </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://material-ui.com/components/dialogs/
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
How to pass data from one component to other component in ReactJS ?
Re-rendering Components in ReactJS
ReactJS defaultProps
How to create a table in ReactJS ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Mar, 2021"
},
{
"code": null,
"e": 315,
"s": 28,
"text": "A Dialog is a type of modal window which appears in front of app content to provide critical information or ask for a decision. Material UI for React has this component available for us, and it is very easy to integrate. We can create Dialog Box in ReactJS using the following approach."
},
{
"code": null,
"e": 365,
"s": 315,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 429,
"s": 365,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 461,
"s": 429,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 561,
"s": 461,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command."
},
{
"code": null,
"e": 575,
"s": 561,
"text": "cd foldername"
},
{
"code": null,
"e": 684,
"s": 575,
"text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command."
},
{
"code": null,
"e": 714,
"s": 684,
"text": "npm install @material-ui/core"
},
{
"code": null,
"e": 766,
"s": 714,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 784,
"s": 766,
"text": "Project Structure"
},
{
"code": null,
"e": 914,
"s": 784,
"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": 921,
"s": 914,
"text": "App.js"
},
{
"code": "import React from \"react\";import Dialog from \"@material-ui/core/Dialog\";import DialogContentText from \"@material-ui/core/DialogContentText\";import DialogTitle from \"@material-ui/core/DialogTitle\";import DialogActions from \"@material-ui/core/DialogActions\";import DialogContent from \"@material-ui/core/DialogContent\";import Button from \"@material-ui/core/Button\"; export default function App() { const [open, setOpen] = React.useState(false); const handleClickToOpen = () => { setOpen(true); }; const handleToClose = () => { setOpen(false); }; return ( <div stlye={{}}> <h4>How to create Dialog Box in ReactJS?</h4> <Button variant=\"outlined\" color=\"primary\" onClick={handleClickToOpen}> Open Demo Dialog </Button> <Dialog open={open} onClose={handleToClose}> <DialogTitle>{\"How are you?\"}</DialogTitle> <DialogContent> <DialogContentText> I am Good, Hope the same for you! </DialogContentText> </DialogContent> <DialogActions> <Button onClick={handleToClose} color=\"primary\" autoFocus> Close </Button> </DialogActions> </Dialog> </div> );}",
"e": 2144,
"s": 921,
"text": null
},
{
"code": null,
"e": 2257,
"s": 2144,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project."
},
{
"code": null,
"e": 2267,
"s": 2257,
"text": "npm start"
},
{
"code": null,
"e": 2366,
"s": 2267,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output."
},
{
"code": null,
"e": 2421,
"s": 2366,
"text": "Reference: https://material-ui.com/components/dialogs/"
},
{
"code": null,
"e": 2433,
"s": 2421,
"text": "Material-UI"
},
{
"code": null,
"e": 2449,
"s": 2433,
"text": "React-Questions"
},
{
"code": null,
"e": 2457,
"s": 2449,
"text": "ReactJS"
},
{
"code": null,
"e": 2474,
"s": 2457,
"text": "Web Technologies"
},
{
"code": null,
"e": 2572,
"s": 2474,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2610,
"s": 2572,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 2678,
"s": 2610,
"text": "How to pass data from one component to other component in ReactJS ?"
},
{
"code": null,
"e": 2713,
"s": 2678,
"text": "Re-rendering Components in ReactJS"
},
{
"code": null,
"e": 2734,
"s": 2713,
"text": "ReactJS defaultProps"
},
{
"code": null,
"e": 2769,
"s": 2734,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 2802,
"s": 2769,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2864,
"s": 2802,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2925,
"s": 2864,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2975,
"s": 2925,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to Convert java.sql.Date to java.util.Date in Java?
|
04 Sep, 2021
If we have the Date object of the SQL package, then we can easily convert it into an util Date object. We need to pass the getTime() method while creating the util Date object.
java.util.Date utilDate = new java.util.Date(sqlDate.getTime());
It will give us util Date object.
Syntax:
public long getTime()
Parameters: The function does not accept any parameter.
Return Value: It returns the number of milliseconds since January 1, 1970, 00:00:00 GTM.
Exception: The function does not throw any exception.
Java
// Java program to Convert java.sql.Date to java.util.Date import java.sql.*;import java.text.*;import java.util.*;public class GFG { public static void main(String[] args) { // sql date object takes time in milliseconds long millis = System.currentTimeMillis(); // creating sql date object java.sql.Date sqlDate = new java.sql.Date(millis); // creating util date object by passing gettime() // method of sql date class java.util.Date utilDate = new java.util.Date(sqlDate.getTime()); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // converting the util date into string format final String stringDate = dateFormat.format(utilDate); // printing both dates System.out.println("utilDate:" + stringDate); System.out.println("sqlDate:" + sqlDate); }}
Output:
utilDate:2021-01-20
sqlDate:2021-01-20
sooda367
Java-Date-Time
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Sep, 2021"
},
{
"code": null,
"e": 205,
"s": 28,
"text": "If we have the Date object of the SQL package, then we can easily convert it into an util Date object. We need to pass the getTime() method while creating the util Date object."
},
{
"code": null,
"e": 271,
"s": 205,
"text": "java.util.Date utilDate = new java.util.Date(sqlDate.getTime());"
},
{
"code": null,
"e": 305,
"s": 271,
"text": "It will give us util Date object."
},
{
"code": null,
"e": 313,
"s": 305,
"text": "Syntax:"
},
{
"code": null,
"e": 335,
"s": 313,
"text": "public long getTime()"
},
{
"code": null,
"e": 391,
"s": 335,
"text": "Parameters: The function does not accept any parameter."
},
{
"code": null,
"e": 480,
"s": 391,
"text": "Return Value: It returns the number of milliseconds since January 1, 1970, 00:00:00 GTM."
},
{
"code": null,
"e": 534,
"s": 480,
"text": "Exception: The function does not throw any exception."
},
{
"code": null,
"e": 539,
"s": 534,
"text": "Java"
},
{
"code": "// Java program to Convert java.sql.Date to java.util.Date import java.sql.*;import java.text.*;import java.util.*;public class GFG { public static void main(String[] args) { // sql date object takes time in milliseconds long millis = System.currentTimeMillis(); // creating sql date object java.sql.Date sqlDate = new java.sql.Date(millis); // creating util date object by passing gettime() // method of sql date class java.util.Date utilDate = new java.util.Date(sqlDate.getTime()); DateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd\"); // converting the util date into string format final String stringDate = dateFormat.format(utilDate); // printing both dates System.out.println(\"utilDate:\" + stringDate); System.out.println(\"sqlDate:\" + sqlDate); }}",
"e": 1413,
"s": 539,
"text": null
},
{
"code": null,
"e": 1421,
"s": 1413,
"text": "Output:"
},
{
"code": null,
"e": 1460,
"s": 1421,
"text": "utilDate:2021-01-20\nsqlDate:2021-01-20"
},
{
"code": null,
"e": 1469,
"s": 1460,
"text": "sooda367"
},
{
"code": null,
"e": 1484,
"s": 1469,
"text": "Java-Date-Time"
},
{
"code": null,
"e": 1491,
"s": 1484,
"text": "Picked"
},
{
"code": null,
"e": 1496,
"s": 1491,
"text": "Java"
},
{
"code": null,
"e": 1510,
"s": 1496,
"text": "Java Programs"
},
{
"code": null,
"e": 1515,
"s": 1510,
"text": "Java"
},
{
"code": null,
"e": 1613,
"s": 1515,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1628,
"s": 1613,
"text": "Stream In Java"
},
{
"code": null,
"e": 1649,
"s": 1628,
"text": "Introduction to Java"
},
{
"code": null,
"e": 1670,
"s": 1649,
"text": "Constructors in Java"
},
{
"code": null,
"e": 1689,
"s": 1670,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 1706,
"s": 1689,
"text": "Generics in Java"
},
{
"code": null,
"e": 1732,
"s": 1706,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 1766,
"s": 1732,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 1813,
"s": 1766,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 1851,
"s": 1813,
"text": "Factory method design pattern in Java"
}
] |
CharField - Django Forms - GeeksforGeeks
|
13 Feb, 2020
CharField in Django Forms is a string field, for small- to large-sized strings. It is used for taking text inputs from the user. The default widget for this input is TextInput. It uses MaxLengthValidator and MinLengthValidator if max_length and min_length are provided. Otherwise, all inputs are valid.
CharField has following optional arguments:
max_length and min_length :- If provided, these arguments ensure that the string is at most or at least the given length.
strip :- If True (default), the value will be stripped of leading and trailing whitespace.
empty_value :- The value to use to represent “empty”. Defaults to an empty string.
Syntax
field_name = forms.CharField(**options)
Illustration of CharField using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into forms.py file of geeks app.
from django import forms # creating a form class GeeksForm(forms.Form): geeks_field = forms.CharField(max_length = 200)
Add the geeks app to INSTALLED_APPS
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]
Now to render this form into a view we need a view and a URL mapped to that URL. Let’s create a view first in views.py of geeks app,
from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} context['form'] = GeeksForm() return render( request, "home.html", context)
Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html.
<form method = "GET"> {{ form }} <input type = "submit" value = "Submit"></form>
Finally, a URL to map to this view in urls.py
from django.urls import path # importing views from views..pyfrom .views import home_view urlpatterns = [ path('', home_view ),]
Let’s run the server and check what has actually happened, Run
Python manage.py runserver
Thus, an geeks_field CharField is created by replacing “_” with ” “. It is a field to input small to large-sized strings.
CharField is used for input of small sized strings in the database. One can input First Name, Last Name, Address Details, etc. Till now we have discussed how to implement CharField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into field into a python string instance.In views.py,
from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context ={} form = GeeksForm() context['form']= form if request.GET: temp = request.GET['geeks_field'] print(temp) return render(request, "home.html", context)
Now let’s try entering data into the field.
Now this data can be fetched using corresponding request dictionary. If method is GET, data would be available in request.GET and if post, request.POST correspondingly. In above example we have the value in temp which we can use for any purpose.
Core Field arguments are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument required = False to CharField will enable it to be left blank by the user. Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:
NaveenArora
Django-forms
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24140,
"s": 24112,
"text": "\n13 Feb, 2020"
},
{
"code": null,
"e": 24443,
"s": 24140,
"text": "CharField in Django Forms is a string field, for small- to large-sized strings. It is used for taking text inputs from the user. The default widget for this input is TextInput. It uses MaxLengthValidator and MinLengthValidator if max_length and min_length are provided. Otherwise, all inputs are valid."
},
{
"code": null,
"e": 24487,
"s": 24443,
"text": "CharField has following optional arguments:"
},
{
"code": null,
"e": 24609,
"s": 24487,
"text": "max_length and min_length :- If provided, these arguments ensure that the string is at most or at least the given length."
},
{
"code": null,
"e": 24700,
"s": 24609,
"text": "strip :- If True (default), the value will be stripped of leading and trailing whitespace."
},
{
"code": null,
"e": 24783,
"s": 24700,
"text": "empty_value :- The value to use to represent “empty”. Defaults to an empty string."
},
{
"code": null,
"e": 24790,
"s": 24783,
"text": "Syntax"
},
{
"code": null,
"e": 24830,
"s": 24790,
"text": "field_name = forms.CharField(**options)"
},
{
"code": null,
"e": 24940,
"s": 24830,
"text": "Illustration of CharField using an Example. Consider a project named geeksforgeeks having an app named geeks."
},
{
"code": null,
"e": 25027,
"s": 24940,
"text": "Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 25078,
"s": 25027,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 25111,
"s": 25078,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 25169,
"s": 25111,
"text": "Enter the following code into forms.py file of geeks app."
},
{
"code": "from django import forms # creating a form class GeeksForm(forms.Form): geeks_field = forms.CharField(max_length = 200)",
"e": 25293,
"s": 25169,
"text": null
},
{
"code": null,
"e": 25329,
"s": 25293,
"text": "Add the geeks app to INSTALLED_APPS"
},
{
"code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]",
"e": 25567,
"s": 25329,
"text": null
},
{
"code": null,
"e": 25700,
"s": 25567,
"text": "Now to render this form into a view we need a view and a URL mapped to that URL. Let’s create a view first in views.py of geeks app,"
},
{
"code": "from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} context['form'] = GeeksForm() return render( request, \"home.html\", context)",
"e": 25912,
"s": 25700,
"text": null
},
{
"code": null,
"e": 26198,
"s": 25912,
"text": "Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html."
},
{
"code": "<form method = \"GET\"> {{ form }} <input type = \"submit\" value = \"Submit\"></form>",
"e": 26285,
"s": 26198,
"text": null
},
{
"code": null,
"e": 26331,
"s": 26285,
"text": "Finally, a URL to map to this view in urls.py"
},
{
"code": "from django.urls import path # importing views from views..pyfrom .views import home_view urlpatterns = [ path('', home_view ),]",
"e": 26465,
"s": 26331,
"text": null
},
{
"code": null,
"e": 26528,
"s": 26465,
"text": "Let’s run the server and check what has actually happened, Run"
},
{
"code": null,
"e": 26555,
"s": 26528,
"text": "Python manage.py runserver"
},
{
"code": null,
"e": 26677,
"s": 26555,
"text": "Thus, an geeks_field CharField is created by replacing “_” with ” “. It is a field to input small to large-sized strings."
},
{
"code": null,
"e": 27036,
"s": 26677,
"text": "CharField is used for input of small sized strings in the database. One can input First Name, Last Name, Address Details, etc. Till now we have discussed how to implement CharField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into field into a python string instance.In views.py,"
},
{
"code": "from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context ={} form = GeeksForm() context['form']= form if request.GET: temp = request.GET['geeks_field'] print(temp) return render(request, \"home.html\", context)",
"e": 27339,
"s": 27036,
"text": null
},
{
"code": null,
"e": 27383,
"s": 27339,
"text": "Now let’s try entering data into the field."
},
{
"code": null,
"e": 27629,
"s": 27383,
"text": "Now this data can be fetched using corresponding request dictionary. If method is GET, data would be available in request.GET and if post, request.POST correspondingly. In above example we have the value in temp which we can use for any purpose."
},
{
"code": null,
"e": 28056,
"s": 27629,
"text": "Core Field arguments are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument required = False to CharField will enable it to be left blank by the user. Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:"
},
{
"code": null,
"e": 28068,
"s": 28056,
"text": "NaveenArora"
},
{
"code": null,
"e": 28081,
"s": 28068,
"text": "Django-forms"
},
{
"code": null,
"e": 28095,
"s": 28081,
"text": "Python Django"
},
{
"code": null,
"e": 28102,
"s": 28095,
"text": "Python"
},
{
"code": null,
"e": 28200,
"s": 28102,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28218,
"s": 28200,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28253,
"s": 28218,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28275,
"s": 28253,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28307,
"s": 28275,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28337,
"s": 28307,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28379,
"s": 28337,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28405,
"s": 28379,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28442,
"s": 28405,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28485,
"s": 28442,
"text": "Python program to convert a list to string"
}
] |
Create simple Blockchain using Python - GeeksforGeeks
|
19 Feb, 2022
A blockchain is a time-stamped decentralized series of fixed records that contains data of any size is controlled by a large network of computers that are scattered around the globe and not owned by a single organization. Every block is secured and connected with each other using hashing technology which protects it from being tempered by an unauthorized person.
Creating Blockchain using Python, mining new blocks, and displaying the whole blockchain:
The data will be stored in JSON format which is very easy to implement and easy to read. The data is stored in a block and the block contains multiple data. Each and every minute multiple blocks are added and to differentiate one from the other we will use fingerprinting.
The fingerprinting is done by using hash and to be particular we will use the SHA256 hashing algorithm. Every block will contain its own hash and also the hash of the previous function so that it cannot get tampered with.
This fingerprinting will be used to chain the blocks together. Every block will be attached to the previous block having its hash and to the next block by giving its hash.
The mining of the new block is done by giving successfully finding the answer to the proof of work. To make mining hard the proof of work must be hard enough to get exploited.
After mining the block successfully the block will then be added to the chain.
After mining several blocks the validity of the chain must be checked in order to prevent any kind of tampering with the blockchain.
Then the web app will be made by using Flask and deployed locally or publicly as per the need of the user.
Python3
# Python program to create Blockchain # For timestampimport datetime # Calculating the hash# in order to add digital# fingerprints to the blocksimport hashlib # To store data# in our blockchainimport JSON # Flask is for creating the web# app and jsonify is for# displaying the blockchainfrom flask import Flask, jsonify class Blockchain: # This function is created # to create the very first # block and set its hash to "0" def __init__(self): self.chain = [] self.create_block(proof=1, previous_hash='0') # This function is created # to add further blocks # into the chain def create_block(self, proof, previous_hash): block = {'index': len(self.chain) + 1, 'timestamp': str(datetime.datetime.now()), 'proof': proof, 'previous_hash': previous_hash} self.chain.append(block) return block # This function is created # to display the previous block def print_previous_block(self): return self.chain[-1] # This is the function for proof of work # and used to successfully mine the block def proof_of_work(self, previous_proof): new_proof = 1 check_proof = False while check_proof is False: hash_operation = hashlib.sha256( str(new_proof**2 - previous_proof**2).encode()).hexdigest() if hash_operation[:5] == '00000': check_proof = True else: new_proof += 1 return new_proof def hash(self, block): encoded_block = json.dumps(block, sort_keys=True).encode() return hashlib.sha256(encoded_block).hexdigest() def chain_valid(self, chain): previous_block = chain[0] block_index = 1 while block_index < len(chain): block = chain[block_index] if block['previous_hash'] != self.hash(previous_block): return False previous_proof = previous_block['proof'] proof = block['proof'] hash_operation = hashlib.sha256( str(proof**2 - previous_proof**2).encode()).hexdigest() if hash_operation[:5] != '00000': return False previous_block = block block_index += 1 return True # Creating the Web# App using flaskapp = Flask(__name__) # Create the object# of the class blockchainblockchain = Blockchain() # Mining a new block@app.route('/mine_block', methods=['GET'])def mine_block(): previous_block = blockchain.print_previous_block() previous_proof = previous_block['proof'] proof = blockchain.proof_of_work(previous_proof) previous_hash = blockchain.hash(previous_block) block = blockchain.create_block(proof, previous_hash) response = {'message': 'A block is MINED', 'index': block['index'], 'timestamp': block['timestamp'], 'proof': block['proof'], 'previous_hash': block['previous_hash']} return jsonify(response), 200 # Display blockchain in json format@app.route('/get_chain', methods=['GET'])def display_chain(): response = {'chain': blockchain.chain, 'length': len(blockchain.chain)} return jsonify(response), 200 # Check validity of blockchain@app.route('/valid', methods=['GET'])def valid(): valid = blockchain.chain_valid(blockchain.chain) if valid: response = {'message': 'The Blockchain is valid.'} else: response = {'message': 'The Blockchain is not valid.'} return jsonify(response), 200 # Run the flask server locallyapp.run(host='127.0.0.1', port=5000)
Output (mine_block):
{
"index":2,
"message":"A block is MINED",
"previous_hash":"2d83a826f87415edb31b7e12b35949b9dbf702aee7e383cbab119456847b957c",
"proof":533,
"timestamp":"2020-06-01 22:47:59.309000"
}
Output (get_chain):
{
"chain":[{"index":1,
"previous_hash":"0",
"proof":1,
"timestamp":"2020-06-01 22:47:05.915000"},{"index":2,
"previous_hash":"2d83a826f87415edb31b7e12b35949b9dbf702aee7e383cbab119456847b957c",
"proof":533,
"timestamp":"2020-06-01 22:47:59.309000"}],
"length":2
}
Output(valid):
{"message":"The Blockchain is valid."}
simranarora5sos
nikunjbaid
punamsingh628700
BlockChain
python-utility
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 ?
Different ways to create Pandas Dataframe
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Graph Plotting in Python | Set 1
Print lists in Python (4 Different Ways)
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
|
[
{
"code": null,
"e": 24135,
"s": 24107,
"text": "\n19 Feb, 2022"
},
{
"code": null,
"e": 24501,
"s": 24135,
"text": "A blockchain is a time-stamped decentralized series of fixed records that contains data of any size is controlled by a large network of computers that are scattered around the globe and not owned by a single organization. Every block is secured and connected with each other using hashing technology which protects it from being tempered by an unauthorized person. "
},
{
"code": null,
"e": 24592,
"s": 24501,
"text": "Creating Blockchain using Python, mining new blocks, and displaying the whole blockchain: "
},
{
"code": null,
"e": 24865,
"s": 24592,
"text": "The data will be stored in JSON format which is very easy to implement and easy to read. The data is stored in a block and the block contains multiple data. Each and every minute multiple blocks are added and to differentiate one from the other we will use fingerprinting."
},
{
"code": null,
"e": 25087,
"s": 24865,
"text": "The fingerprinting is done by using hash and to be particular we will use the SHA256 hashing algorithm. Every block will contain its own hash and also the hash of the previous function so that it cannot get tampered with."
},
{
"code": null,
"e": 25259,
"s": 25087,
"text": "This fingerprinting will be used to chain the blocks together. Every block will be attached to the previous block having its hash and to the next block by giving its hash."
},
{
"code": null,
"e": 25435,
"s": 25259,
"text": "The mining of the new block is done by giving successfully finding the answer to the proof of work. To make mining hard the proof of work must be hard enough to get exploited."
},
{
"code": null,
"e": 25514,
"s": 25435,
"text": "After mining the block successfully the block will then be added to the chain."
},
{
"code": null,
"e": 25647,
"s": 25514,
"text": "After mining several blocks the validity of the chain must be checked in order to prevent any kind of tampering with the blockchain."
},
{
"code": null,
"e": 25754,
"s": 25647,
"text": "Then the web app will be made by using Flask and deployed locally or publicly as per the need of the user."
},
{
"code": null,
"e": 25762,
"s": 25754,
"text": "Python3"
},
{
"code": "# Python program to create Blockchain # For timestampimport datetime # Calculating the hash# in order to add digital# fingerprints to the blocksimport hashlib # To store data# in our blockchainimport JSON # Flask is for creating the web# app and jsonify is for# displaying the blockchainfrom flask import Flask, jsonify class Blockchain: # This function is created # to create the very first # block and set its hash to \"0\" def __init__(self): self.chain = [] self.create_block(proof=1, previous_hash='0') # This function is created # to add further blocks # into the chain def create_block(self, proof, previous_hash): block = {'index': len(self.chain) + 1, 'timestamp': str(datetime.datetime.now()), 'proof': proof, 'previous_hash': previous_hash} self.chain.append(block) return block # This function is created # to display the previous block def print_previous_block(self): return self.chain[-1] # This is the function for proof of work # and used to successfully mine the block def proof_of_work(self, previous_proof): new_proof = 1 check_proof = False while check_proof is False: hash_operation = hashlib.sha256( str(new_proof**2 - previous_proof**2).encode()).hexdigest() if hash_operation[:5] == '00000': check_proof = True else: new_proof += 1 return new_proof def hash(self, block): encoded_block = json.dumps(block, sort_keys=True).encode() return hashlib.sha256(encoded_block).hexdigest() def chain_valid(self, chain): previous_block = chain[0] block_index = 1 while block_index < len(chain): block = chain[block_index] if block['previous_hash'] != self.hash(previous_block): return False previous_proof = previous_block['proof'] proof = block['proof'] hash_operation = hashlib.sha256( str(proof**2 - previous_proof**2).encode()).hexdigest() if hash_operation[:5] != '00000': return False previous_block = block block_index += 1 return True # Creating the Web# App using flaskapp = Flask(__name__) # Create the object# of the class blockchainblockchain = Blockchain() # Mining a new block@app.route('/mine_block', methods=['GET'])def mine_block(): previous_block = blockchain.print_previous_block() previous_proof = previous_block['proof'] proof = blockchain.proof_of_work(previous_proof) previous_hash = blockchain.hash(previous_block) block = blockchain.create_block(proof, previous_hash) response = {'message': 'A block is MINED', 'index': block['index'], 'timestamp': block['timestamp'], 'proof': block['proof'], 'previous_hash': block['previous_hash']} return jsonify(response), 200 # Display blockchain in json format@app.route('/get_chain', methods=['GET'])def display_chain(): response = {'chain': blockchain.chain, 'length': len(blockchain.chain)} return jsonify(response), 200 # Check validity of blockchain@app.route('/valid', methods=['GET'])def valid(): valid = blockchain.chain_valid(blockchain.chain) if valid: response = {'message': 'The Blockchain is valid.'} else: response = {'message': 'The Blockchain is not valid.'} return jsonify(response), 200 # Run the flask server locallyapp.run(host='127.0.0.1', port=5000)",
"e": 29467,
"s": 25762,
"text": null
},
{
"code": null,
"e": 29488,
"s": 29467,
"text": "Output (mine_block):"
},
{
"code": null,
"e": 29671,
"s": 29488,
"text": "{\n\"index\":2,\n\"message\":\"A block is MINED\",\n\"previous_hash\":\"2d83a826f87415edb31b7e12b35949b9dbf702aee7e383cbab119456847b957c\",\n\"proof\":533,\n\"timestamp\":\"2020-06-01 22:47:59.309000\"\n}"
},
{
"code": null,
"e": 29691,
"s": 29671,
"text": "Output (get_chain):"
},
{
"code": null,
"e": 29954,
"s": 29691,
"text": "{\n\"chain\":[{\"index\":1,\n\"previous_hash\":\"0\",\n\"proof\":1,\n\"timestamp\":\"2020-06-01 22:47:05.915000\"},{\"index\":2,\n\"previous_hash\":\"2d83a826f87415edb31b7e12b35949b9dbf702aee7e383cbab119456847b957c\",\n\"proof\":533,\n\"timestamp\":\"2020-06-01 22:47:59.309000\"}],\n\"length\":2\n}"
},
{
"code": null,
"e": 29969,
"s": 29954,
"text": "Output(valid):"
},
{
"code": null,
"e": 30008,
"s": 29969,
"text": "{\"message\":\"The Blockchain is valid.\"}"
},
{
"code": null,
"e": 30024,
"s": 30008,
"text": "simranarora5sos"
},
{
"code": null,
"e": 30035,
"s": 30024,
"text": "nikunjbaid"
},
{
"code": null,
"e": 30052,
"s": 30035,
"text": "punamsingh628700"
},
{
"code": null,
"e": 30063,
"s": 30052,
"text": "BlockChain"
},
{
"code": null,
"e": 30078,
"s": 30063,
"text": "python-utility"
},
{
"code": null,
"e": 30085,
"s": 30078,
"text": "Python"
},
{
"code": null,
"e": 30183,
"s": 30085,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30192,
"s": 30183,
"text": "Comments"
},
{
"code": null,
"e": 30205,
"s": 30192,
"text": "Old Comments"
},
{
"code": null,
"e": 30237,
"s": 30205,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30279,
"s": 30237,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30304,
"s": 30279,
"text": "sum() function in Python"
},
{
"code": null,
"e": 30341,
"s": 30304,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 30397,
"s": 30341,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30426,
"s": 30397,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 30459,
"s": 30426,
"text": "Graph Plotting in Python | Set 1"
},
{
"code": null,
"e": 30500,
"s": 30459,
"text": "Print lists in Python (4 Different Ways)"
},
{
"code": null,
"e": 30542,
"s": 30500,
"text": "How To Convert Python Dictionary To JSON?"
}
] |
Java Connection getCatalog() method with example
|
In general, a catalog is a directory which holds information about data sets, file or, a database. Whereas in a database catalog holds the list of all the databases, base tables, views (virtual tables), synonyms, value ranges, indexes, users, and user groups.
The getCatalog() method of the Connection interface returns the name of the current catalog/database, of the current connection object.
This method returns a Sting value representing the name of the catalog. It returns null if there is no catalog.
To get the catalog name −
Register the driver using the registerDriver() method of the DriverManager class as −
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Get the connection using the getConnection() method of the DriverManager class as −
//Getting the connection
String url = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(url, "root", "password");
Retrieve the connection objects catalog name using the getCatalog() method as −
//Retrieving the current catalog name
String catalogName = con.getCatalog();
Let us create a database with name mydatabase in MySQL using CREATE statement as shown below.
create database mydatabase;
Following JDBC program establishes connection with MySQL database, retrieves and, displays the name of the underlying catalog.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connection_getCatalog {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String url = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(url, "root", "password");
System.out.println("Connection established......");
//Setting the auto commit false
con.setAutoCommit(false);
//Retrieving the current catalog name
String catalogName = con.getCatalog();
System.out.println("Current catalog name is: "+catalogName);
}
}
Connection established......
Current catalog name is: mydatabase
|
[
{
"code": null,
"e": 1322,
"s": 1062,
"text": "In general, a catalog is a directory which holds information about data sets, file or, a database. Whereas in a database catalog holds the list of all the databases, base tables, views (virtual tables), synonyms, value ranges, indexes, users, and user groups."
},
{
"code": null,
"e": 1458,
"s": 1322,
"text": "The getCatalog() method of the Connection interface returns the name of the current catalog/database, of the current connection object."
},
{
"code": null,
"e": 1570,
"s": 1458,
"text": "This method returns a Sting value representing the name of the catalog. It returns null if there is no catalog."
},
{
"code": null,
"e": 1596,
"s": 1570,
"text": "To get the catalog name −"
},
{
"code": null,
"e": 1682,
"s": 1596,
"text": "Register the driver using the registerDriver() method of the DriverManager class as −"
},
{
"code": null,
"e": 1766,
"s": 1682,
"text": "//Registering the Driver\nDriverManager.registerDriver(new com.mysql.jdbc.Driver());"
},
{
"code": null,
"e": 1850,
"s": 1766,
"text": "Get the connection using the getConnection() method of the DriverManager class as −"
},
{
"code": null,
"e": 1996,
"s": 1850,
"text": "//Getting the connection\nString url = \"jdbc:mysql://localhost/mydatabase\";\nConnection con = DriverManager.getConnection(url, \"root\", \"password\");"
},
{
"code": null,
"e": 2076,
"s": 1996,
"text": "Retrieve the connection objects catalog name using the getCatalog() method as −"
},
{
"code": null,
"e": 2153,
"s": 2076,
"text": "//Retrieving the current catalog name\nString catalogName = con.getCatalog();"
},
{
"code": null,
"e": 2247,
"s": 2153,
"text": "Let us create a database with name mydatabase in MySQL using CREATE statement as shown below."
},
{
"code": null,
"e": 2275,
"s": 2247,
"text": "create database mydatabase;"
},
{
"code": null,
"e": 2402,
"s": 2275,
"text": "Following JDBC program establishes connection with MySQL database, retrieves and, displays the name of the underlying catalog."
},
{
"code": null,
"e": 3143,
"s": 2402,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\npublic class Connection_getCatalog {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String url = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(url, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Setting the auto commit false\n con.setAutoCommit(false);\n //Retrieving the current catalog name\n String catalogName = con.getCatalog();\n System.out.println(\"Current catalog name is: \"+catalogName);\n }\n}"
},
{
"code": null,
"e": 3208,
"s": 3143,
"text": "Connection established......\nCurrent catalog name is: mydatabase"
}
] |
C program to add all perfect square elements in an array.
|
Write a program to find the sum of perfect square elements in an array.
Given a number of elements in array as input and the sum of all the perfect square of those elements present in the array is output.
For example,
Input= 1, 2, 3, 4, 5, 9,10,11,16
The perfect squares are 1, 4, 9, 16.
Sum = 1 + 4 + 9 +16 = 30
Output: 30
Refer an algorithm given below to add the perfect square elements in an array.
Step 1 − Read number of elements in array at runtime.
Step 2 − Input the elements.
Step 3 − Declare and initialize the sum=0
Step 4 − Check, whether the array element is a perfect square or not.
Step 5 − If it is a perfect square, then, compute sum=sum+number.
Step 6 − Return sum.
Following is the C program to find the sum of perfect square elements in an array −
#include<stdio.h>
#include<math.h>
int isPerfectSquare(int number){
int iVar;
float fVar;
fVar=sqrt((double)number);
iVar=fVar;
if(iVar==fVar)
return number;
else
return 0;
}
int main(){
int n;
printf("enter no: of elements:");
scanf("%d",&n);
int arr[n];
int i;
printf("enter the elements in an array:\n");
for(i = 0; i < n; i++){
scanf("%d",&arr[i]);
}
int sum = 0;
for(i = 0; i < n; i++){
sum = sum + isPerfectSquare(arr[i]);
}
printf("sum=%d",sum);
return 0;
}
When the above program is executed, it produces the following output −
Run 1:
enter no: of elements:5
enter the elements in an array:
1
3
5
9
10
sum=10
Run 2:
enter no: of elements:5
enter the elements in an array:
1
4
9
16
25
sum=55
|
[
{
"code": null,
"e": 1134,
"s": 1062,
"text": "Write a program to find the sum of perfect square elements in an array."
},
{
"code": null,
"e": 1267,
"s": 1134,
"text": "Given a number of elements in array as input and the sum of all the perfect square of those elements present in the array is output."
},
{
"code": null,
"e": 1280,
"s": 1267,
"text": "For example,"
},
{
"code": null,
"e": 1386,
"s": 1280,
"text": "Input= 1, 2, 3, 4, 5, 9,10,11,16\nThe perfect squares are 1, 4, 9, 16.\nSum = 1 + 4 + 9 +16 = 30\nOutput: 30"
},
{
"code": null,
"e": 1465,
"s": 1386,
"text": "Refer an algorithm given below to add the perfect square elements in an array."
},
{
"code": null,
"e": 1519,
"s": 1465,
"text": "Step 1 − Read number of elements in array at runtime."
},
{
"code": null,
"e": 1548,
"s": 1519,
"text": "Step 2 − Input the elements."
},
{
"code": null,
"e": 1590,
"s": 1548,
"text": "Step 3 − Declare and initialize the sum=0"
},
{
"code": null,
"e": 1660,
"s": 1590,
"text": "Step 4 − Check, whether the array element is a perfect square or not."
},
{
"code": null,
"e": 1726,
"s": 1660,
"text": "Step 5 − If it is a perfect square, then, compute sum=sum+number."
},
{
"code": null,
"e": 1747,
"s": 1726,
"text": "Step 6 − Return sum."
},
{
"code": null,
"e": 1831,
"s": 1747,
"text": "Following is the C program to find the sum of perfect square elements in an array −"
},
{
"code": null,
"e": 2374,
"s": 1831,
"text": "#include<stdio.h>\n#include<math.h>\nint isPerfectSquare(int number){\n int iVar;\n float fVar;\n fVar=sqrt((double)number);\n iVar=fVar;\n if(iVar==fVar)\n return number;\n else\n return 0;\n}\nint main(){\n int n;\n printf(\"enter no: of elements:\");\n scanf(\"%d\",&n);\n int arr[n];\n int i;\n printf(\"enter the elements in an array:\\n\");\n for(i = 0; i < n; i++){\n scanf(\"%d\",&arr[i]);\n }\n int sum = 0;\n for(i = 0; i < n; i++){\n sum = sum + isPerfectSquare(arr[i]);\n }\n printf(\"sum=%d\",sum);\n return 0;\n}"
},
{
"code": null,
"e": 2445,
"s": 2374,
"text": "When the above program is executed, it produces the following output −"
},
{
"code": null,
"e": 2608,
"s": 2445,
"text": "Run 1:\nenter no: of elements:5\nenter the elements in an array:\n1\n3\n5\n9\n10\nsum=10\nRun 2:\nenter no: of elements:5\nenter the elements in an array:\n1\n4\n9\n16\n25\nsum=55"
}
] |
How can I avoid too many OR statements in a MySQL query?
|
Use MySQL IN() to avoid too many OR statements. Let us first create a table −
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name varchar(40)
);
Query OK, 0 rows affected (0.89 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Name) values('Robert');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable(Name) values('Mike');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Name) values('Sam');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+
| Id | Name |
+----+--------+
| 1 | Chris |
| 2 | Robert |
| 3 | Mike |
| 4 | Sam |
| 5 | David |
+----+--------+
5 rows in set (0.00 sec)
Following is the query to avoid too many OR statements in a MySQL query i.e. using IN() −
mysql> select *from DemoTable where Id IN(1,3,5);
This will produce the following output −
+----+-------+
| Id | Name |
+----+-------+
| 1 | Chris |
| 3 | Mike |
| 5 | David |
+----+-------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1140,
"s": 1062,
"text": "Use MySQL IN() to avoid too many OR statements. Let us first create a table −"
},
{
"code": null,
"e": 1279,
"s": 1140,
"text": "mysql> create table DemoTable\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n Name varchar(40)\n);\nQuery OK, 0 rows affected (0.89 sec)"
},
{
"code": null,
"e": 1335,
"s": 1279,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1773,
"s": 1335,
"text": "mysql> insert into DemoTable(Name) values('Chris');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable(Name) values('Robert');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into DemoTable(Name) values('Mike');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable(Name) values('Sam');\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable(Name) values('David');\nQuery OK, 1 row affected (0.14 sec)"
},
{
"code": null,
"e": 1833,
"s": 1773,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1864,
"s": 1833,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1905,
"s": 1864,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2074,
"s": 1905,
"text": "+----+--------+\n| Id | Name |\n+----+--------+\n| 1 | Chris |\n| 2 | Robert |\n| 3 | Mike |\n| 4 | Sam |\n| 5 | David |\n+----+--------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2164,
"s": 2074,
"text": "Following is the query to avoid too many OR statements in a MySQL query i.e. using IN() −"
},
{
"code": null,
"e": 2214,
"s": 2164,
"text": "mysql> select *from DemoTable where Id IN(1,3,5);"
},
{
"code": null,
"e": 2255,
"s": 2214,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2385,
"s": 2255,
"text": "+----+-------+\n| Id | Name |\n+----+-------+\n| 1 | Chris |\n| 3 | Mike |\n| 5 | David |\n+----+-------+\n3 rows in set (0.00 sec)"
}
] |
Maximize Toys | Practice | GeeksforGeeks
|
Given an array arr[ ] of length N consisting cost of N toys and an integer K depicting the amount with you. Your task is to find maximum number of toys you can buy with K amount.
Example 1:
Input:
N = 7
K = 50
arr[] = {1, 12, 5, 111, 200, 1000, 10}
Output: 4
Explaination: The costs of the toys
you can buy are 1, 12, 5 and 10.
Example 2:
Input:
N = 3
K = 100
arr[] = {20, 30, 50}
Output: 3
Explaination: You can buy all toys.
Your Task:
You do not need to read input or print anything. Your task is to complete the function toyCount() which takes the integer N, integer K and the array arr[ ] as input parameters and returns the maximum count of toys you can have.
Expected Time Complexity: O(N * Log(N))
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 105
1 ≤ K, arr[i] ≤ 109
0
akashkhurana283 days ago
JAVA PRIORITY QUEUE
PriorityQueue<Integer> pq=new PriorityQueue<Integer>(); int res=0; for(int i=0;i<N;i++) pq.add(arr[i]); for(int i=0;i<N;i++){ if(pq.peek()<=K){ K-=pq.poll(); res++; }else{ break; } } return res; } }
0
19bcs13142 weeks ago
// Greedy Approach
class Solution{
static int toyCount(int n, int k, int arr[])
{
// code here
Arrays.sort(arr);
int count=0;
for(int i=0;i<n;i++){
if(arr[i]<=k){
k=k-arr[i];
count++;
}else{
break;
}
}
return count;
}
}
0
abytespaceneeded3 weeks ago
class Solution{
public:
int toyCount(int N, int K, vector<int> arr)
{
// code here
priority_queue<int, vector<int>, greater<int>> pq(arr.begin(),arr.end());
int item = 0;
while(pq.empty() == false)
{
if(pq.top() <= K)
{
++item;
K = K-pq.top();
pq.pop();
}
else
break;
}
return item;
}
};
0
abytespaceneeded
This comment was deleted.
0
mitradiptamoy3 weeks ago
//C++ soln
int toyCount(int N, int K, vector<int> arr) { // code here sort(arr.begin(),arr.end()); int i=0; int x=0; int s=0; while(i<N){ s+=arr[i]; if(s<=K) { x++; } else { break; } i++; } return x; }
0
madhukartemba3 weeks ago
JAVA SOLUTION:
class Solution
{
static int toyCount(int N, int K, int arr[])
{
Arrays.sort(arr);
int count = 0;
for(int i=0; i<N; i++)
{
if(K>=arr[i])
{
K-=arr[i];
count++;
}
else return count;
}
return count;
}
}
0
hpankur023 weeks ago
//Python Easy solution
arr.sort() count=0 for i in range(0,N): if(arr[i]<=K ): count+=1 K=K-arr[i] return count
0
gauralkshirsagar54 weeks ago
int sum=0; int count =0; sort(arr.begin(),arr.end()); for(int i=0;i<=N-1;++i){ sum=arr[i]+sum; if(sum>K) break; count++; } return count; }
0
gupta2411sumit1 month ago
//Easy C++ Solution
int toyCount(int N, int k, vector<int> arr) { // code here sort( arr.begin() , arr.end()) ; int count = 0 ; long long int cost = 0 ; int i = 0 ; while(cost<k && i<N) { cost += arr[i] ; if(cost<=k) { count++ ; } i++ ; } return count ; }
0
mummadiug1 month ago
def toyCount(self, N, K, arr): # code here arr=sorted(arr) c=0 for i in range(N): if arr[i]<=K: c+=1 K=K-arr[i] return c
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 418,
"s": 238,
"text": "Given an array arr[ ] of length N consisting cost of N toys and an integer K depicting the amount with you. Your task is to find maximum number of toys you can buy with K amount. "
},
{
"code": null,
"e": 429,
"s": 418,
"text": "Example 1:"
},
{
"code": null,
"e": 570,
"s": 429,
"text": "Input: \nN = 7 \nK = 50\narr[] = {1, 12, 5, 111, 200, 1000, 10}\nOutput: 4\nExplaination: The costs of the toys \nyou can buy are 1, 12, 5 and 10."
},
{
"code": null,
"e": 581,
"s": 570,
"text": "Example 2:"
},
{
"code": null,
"e": 671,
"s": 581,
"text": "Input: \nN = 3 \nK = 100\narr[] = {20, 30, 50}\nOutput: 3\nExplaination: You can buy all toys."
},
{
"code": null,
"e": 910,
"s": 671,
"text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function toyCount() which takes the integer N, integer K and the array arr[ ] as input parameters and returns the maximum count of toys you can have."
},
{
"code": null,
"e": 981,
"s": 910,
"text": "Expected Time Complexity: O(N * Log(N))\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1026,
"s": 981,
"text": "Constraints:\n1 ≤ N ≤ 105\n1 ≤ K, arr[i] ≤ 109"
},
{
"code": null,
"e": 1028,
"s": 1026,
"text": "0"
},
{
"code": null,
"e": 1053,
"s": 1028,
"text": "akashkhurana283 days ago"
},
{
"code": null,
"e": 1073,
"s": 1053,
"text": "JAVA PRIORITY QUEUE"
},
{
"code": null,
"e": 1406,
"s": 1073,
"text": " PriorityQueue<Integer> pq=new PriorityQueue<Integer>(); int res=0; for(int i=0;i<N;i++) pq.add(arr[i]); for(int i=0;i<N;i++){ if(pq.peek()<=K){ K-=pq.poll(); res++; }else{ break; } } return res; } }"
},
{
"code": null,
"e": 1410,
"s": 1408,
"text": "0"
},
{
"code": null,
"e": 1431,
"s": 1410,
"text": "19bcs13142 weeks ago"
},
{
"code": null,
"e": 1806,
"s": 1431,
"text": "// Greedy Approach\n\n\nclass Solution{\n static int toyCount(int n, int k, int arr[])\n {\n // code here\n Arrays.sort(arr);\n \n int count=0;\n for(int i=0;i<n;i++){\n if(arr[i]<=k){\n k=k-arr[i];\n count++;\n }else{\n break;\n }\n }\n return count;\n }\n}"
},
{
"code": null,
"e": 1808,
"s": 1806,
"text": "0"
},
{
"code": null,
"e": 1836,
"s": 1808,
"text": "abytespaceneeded3 weeks ago"
},
{
"code": null,
"e": 2331,
"s": 1836,
"text": "class Solution{\npublic:\n int toyCount(int N, int K, vector<int> arr)\n {\n // code here\n priority_queue<int, vector<int>, greater<int>> pq(arr.begin(),arr.end());\n \n int item = 0;\n \n while(pq.empty() == false)\n {\n if(pq.top() <= K)\n {\n ++item;\n K = K-pq.top();\n pq.pop();\n }\n else\n break;\n }\n \n return item;\n }\n};"
},
{
"code": null,
"e": 2333,
"s": 2331,
"text": "0"
},
{
"code": null,
"e": 2350,
"s": 2333,
"text": "abytespaceneeded"
},
{
"code": null,
"e": 2376,
"s": 2350,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2378,
"s": 2376,
"text": "0"
},
{
"code": null,
"e": 2403,
"s": 2378,
"text": "mitradiptamoy3 weeks ago"
},
{
"code": null,
"e": 2414,
"s": 2403,
"text": "//C++ soln"
},
{
"code": null,
"e": 2767,
"s": 2416,
"text": "int toyCount(int N, int K, vector<int> arr) { // code here sort(arr.begin(),arr.end()); int i=0; int x=0; int s=0; while(i<N){ s+=arr[i]; if(s<=K) { x++; } else { break; } i++; } return x; }"
},
{
"code": null,
"e": 2769,
"s": 2767,
"text": "0"
},
{
"code": null,
"e": 2794,
"s": 2769,
"text": "madhukartemba3 weeks ago"
},
{
"code": null,
"e": 2809,
"s": 2794,
"text": "JAVA SOLUTION:"
},
{
"code": null,
"e": 3176,
"s": 2809,
"text": "class Solution\n{\n static int toyCount(int N, int K, int arr[])\n {\n Arrays.sort(arr);\n \n int count = 0;\n \n for(int i=0; i<N; i++)\n {\n if(K>=arr[i]) \n {\n K-=arr[i];\n count++;\n }\n else return count;\n }\n \n return count;\n }\n}"
},
{
"code": null,
"e": 3178,
"s": 3176,
"text": "0"
},
{
"code": null,
"e": 3199,
"s": 3178,
"text": "hpankur023 weeks ago"
},
{
"code": null,
"e": 3222,
"s": 3199,
"text": "//Python Easy solution"
},
{
"code": null,
"e": 3388,
"s": 3222,
"text": " arr.sort() count=0 for i in range(0,N): if(arr[i]<=K ): count+=1 K=K-arr[i] return count"
},
{
"code": null,
"e": 3390,
"s": 3388,
"text": "0"
},
{
"code": null,
"e": 3419,
"s": 3390,
"text": "gauralkshirsagar54 weeks ago"
},
{
"code": null,
"e": 3630,
"s": 3419,
"text": "int sum=0; int count =0; sort(arr.begin(),arr.end()); for(int i=0;i<=N-1;++i){ sum=arr[i]+sum; if(sum>K) break; count++; } return count; }"
},
{
"code": null,
"e": 3632,
"s": 3630,
"text": "0"
},
{
"code": null,
"e": 3658,
"s": 3632,
"text": "gupta2411sumit1 month ago"
},
{
"code": null,
"e": 3678,
"s": 3658,
"text": "//Easy C++ Solution"
},
{
"code": null,
"e": 4068,
"s": 3678,
"text": "int toyCount(int N, int k, vector<int> arr) { // code here sort( arr.begin() , arr.end()) ; int count = 0 ; long long int cost = 0 ; int i = 0 ; while(cost<k && i<N) { cost += arr[i] ; if(cost<=k) { count++ ; } i++ ; } return count ; }"
},
{
"code": null,
"e": 4070,
"s": 4068,
"text": "0"
},
{
"code": null,
"e": 4091,
"s": 4070,
"text": "mummadiug1 month ago"
},
{
"code": null,
"e": 4280,
"s": 4091,
"text": "def toyCount(self, N, K, arr): # code here arr=sorted(arr) c=0 for i in range(N): if arr[i]<=K: c+=1 K=K-arr[i] return c"
},
{
"code": null,
"e": 4426,
"s": 4280,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 4462,
"s": 4426,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4472,
"s": 4462,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4482,
"s": 4472,
"text": "\nContest\n"
},
{
"code": null,
"e": 4545,
"s": 4482,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4693,
"s": 4545,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 4901,
"s": 4693,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 5007,
"s": 4901,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Introduction to Regression Analysis [using Excel] | by Pranav Kaushik | Towards Data Science
|
Not familiar with tools like Python or R?
It’s perfectly fine! You can still perform a regression analysis using Excel. And you don’t need to have any programming knowledge to do that.
Excel is undoubtedly a very powerful tool when it comes to data analysis. You can do data cleaning, perform analysis using pivot tables, design visuals and much more.
If you’re looking to explore more on data analysis using Excel, here are a few excellent resources you can check out.
Data cleaning: 10 Super Neat Ways to Clean Data in Excel Spreadsheets
Data analysis: Introduction to Data Analysis using Excel
Pretty amazing right!
But wait. There’s more!
Excel has an add-in called “Data Analysis ToolPak” that allows you to perform various statistical operations, including Regression just with the click of a button.
Now that we’ve talked enough about Excel, let’s move on to Regression.
I’m simple terms; Regression is the process of determining the relationship between the dependent variable and a set of independent variables.
Consider the following example:
This table shows the relationship between the advertising cost spent on TV with the respective sales revenue.
Now if you need to find the relationship between the two variables, the most straightforward way is to plot a scatter plot which looks like this.
Observing the plot, we can say that there is a positive relationship between the ad spent on TV and sales revenue.
That’s a sign of positive correlation.
Now, let’s say that we need to quantify the relationship. How will you do that?
Again, it’s pretty simple. Just draw a line that best fits all the points shown in the scatter plot, and the line equation will give you the relationship between variables.
Sales = 0.0555*(TV) + 6.9748
That’s the basic idea of Regression. It is quantifying the relationship between variables by fitting all points using a function.
The method used to determine the best fitting line is out of the scope of this article. But if you’re interested, it’s done by a technique called ordinary least squares.
The example that we just saw is called simple linear Regression which involves only one independent variable or feature (advertising cost on TV).
But the same concept of Regression can be expanded to multiple independent variables or features, which is called multiple linear Regression.
For example, check out this table.
Here, we have advertising costs spent on TV, radio and newspaper along with the respective sales revenue.
We won’t be able to visualise the relationship on a 2D plane, but the concept of linear Regression can still be applied to determine the best fitting function for all these points.
And the function will be of the form:
Sales = 0.0544*(TV) + 0.1070*(Radio) + 0.0003*(Newspaper) + 4.6251
So this is the basic idea behind Regression.
Now let’s look at how to implement Regression using Excel.
The first step is the add data analysis toolpak
Data Analysis ToolPak is not available by default, and you need to activate the add-in separately.
To activate, go to File -> Options -> Add-ins and then activate the Analysis ToolPak. Once you’ve activated the add-in, it should appear under the Data tab of your toolbar.
Once you’ve added data analysis toolpak and download the data in an Excel file, move to the next step.
To perform the Regression, go to Data Analysis Tools and select Regression from the available options. Once you choose Regression, the following window should appear.
Enter the range of the dependent variable in the Input Y Range and range of independent variables in the Input X Range. And then press, OK.
You’ve successfully completed performing Regression using Excel!
Now let’s look at how to interpret the results.
Once you’ve performed Regression, your result page should look something like this.
If you take a look at the third table, there is the first column named coefficients. This column gives the values of the coefficient of each variable in the multiple linear regression equation.
Sales = 0.0544*(TV) + 0.1070*(Radio) + 0.0003*(Newspaper) + 4.6251
The other measures that have been calculated on the tables are used to compare the performance, statistical significance and other factors. These measures require a good understanding of statistics, and hence I haven’t discussed all that in this introductory article.
Once you’ve performed Regression, there are two things that you can do.
Analyse the relationship between variablesBuild a predictive model
Analyse the relationship between variables
Build a predictive model
Since we already talked about analysing the relationship between variables, let’s look at how to build a predictive model.
A predictive model is nothing but a process of predicting the value of the dependent variable by providing values for the independent variables.
So again, our multiple linear regression equation is the predictive model function where if we enter the values of the independent variables, we can get the predicted value of Sales.
For example, if you want to predict the sales revenue for the following combination of advertising spends,
TV = 100
Radio = 200
Newspaper = 500
Enter the values into the multiple linear regression equation. This will give you a sales revenue of 31.6377 which is the predicted revenue.
I hope that you would have got a good understanding of what Regression is, implementation using Excel, analysing the relationship and building predictive a model.
And of course, this is just an introduction of Regression, and there are a lot of other concepts that you can explore once you’re familiar with the basics covered in this article.
You can download the excel file containing the data and steps covered in this article here.
|
[
{
"code": null,
"e": 214,
"s": 172,
"text": "Not familiar with tools like Python or R?"
},
{
"code": null,
"e": 357,
"s": 214,
"text": "It’s perfectly fine! You can still perform a regression analysis using Excel. And you don’t need to have any programming knowledge to do that."
},
{
"code": null,
"e": 524,
"s": 357,
"text": "Excel is undoubtedly a very powerful tool when it comes to data analysis. You can do data cleaning, perform analysis using pivot tables, design visuals and much more."
},
{
"code": null,
"e": 642,
"s": 524,
"text": "If you’re looking to explore more on data analysis using Excel, here are a few excellent resources you can check out."
},
{
"code": null,
"e": 712,
"s": 642,
"text": "Data cleaning: 10 Super Neat Ways to Clean Data in Excel Spreadsheets"
},
{
"code": null,
"e": 769,
"s": 712,
"text": "Data analysis: Introduction to Data Analysis using Excel"
},
{
"code": null,
"e": 791,
"s": 769,
"text": "Pretty amazing right!"
},
{
"code": null,
"e": 815,
"s": 791,
"text": "But wait. There’s more!"
},
{
"code": null,
"e": 979,
"s": 815,
"text": "Excel has an add-in called “Data Analysis ToolPak” that allows you to perform various statistical operations, including Regression just with the click of a button."
},
{
"code": null,
"e": 1050,
"s": 979,
"text": "Now that we’ve talked enough about Excel, let’s move on to Regression."
},
{
"code": null,
"e": 1193,
"s": 1050,
"text": "I’m simple terms; Regression is the process of determining the relationship between the dependent variable and a set of independent variables."
},
{
"code": null,
"e": 1225,
"s": 1193,
"text": "Consider the following example:"
},
{
"code": null,
"e": 1335,
"s": 1225,
"text": "This table shows the relationship between the advertising cost spent on TV with the respective sales revenue."
},
{
"code": null,
"e": 1481,
"s": 1335,
"text": "Now if you need to find the relationship between the two variables, the most straightforward way is to plot a scatter plot which looks like this."
},
{
"code": null,
"e": 1596,
"s": 1481,
"text": "Observing the plot, we can say that there is a positive relationship between the ad spent on TV and sales revenue."
},
{
"code": null,
"e": 1635,
"s": 1596,
"text": "That’s a sign of positive correlation."
},
{
"code": null,
"e": 1715,
"s": 1635,
"text": "Now, let’s say that we need to quantify the relationship. How will you do that?"
},
{
"code": null,
"e": 1888,
"s": 1715,
"text": "Again, it’s pretty simple. Just draw a line that best fits all the points shown in the scatter plot, and the line equation will give you the relationship between variables."
},
{
"code": null,
"e": 1917,
"s": 1888,
"text": "Sales = 0.0555*(TV) + 6.9748"
},
{
"code": null,
"e": 2047,
"s": 1917,
"text": "That’s the basic idea of Regression. It is quantifying the relationship between variables by fitting all points using a function."
},
{
"code": null,
"e": 2217,
"s": 2047,
"text": "The method used to determine the best fitting line is out of the scope of this article. But if you’re interested, it’s done by a technique called ordinary least squares."
},
{
"code": null,
"e": 2363,
"s": 2217,
"text": "The example that we just saw is called simple linear Regression which involves only one independent variable or feature (advertising cost on TV)."
},
{
"code": null,
"e": 2505,
"s": 2363,
"text": "But the same concept of Regression can be expanded to multiple independent variables or features, which is called multiple linear Regression."
},
{
"code": null,
"e": 2540,
"s": 2505,
"text": "For example, check out this table."
},
{
"code": null,
"e": 2646,
"s": 2540,
"text": "Here, we have advertising costs spent on TV, radio and newspaper along with the respective sales revenue."
},
{
"code": null,
"e": 2827,
"s": 2646,
"text": "We won’t be able to visualise the relationship on a 2D plane, but the concept of linear Regression can still be applied to determine the best fitting function for all these points."
},
{
"code": null,
"e": 2865,
"s": 2827,
"text": "And the function will be of the form:"
},
{
"code": null,
"e": 2932,
"s": 2865,
"text": "Sales = 0.0544*(TV) + 0.1070*(Radio) + 0.0003*(Newspaper) + 4.6251"
},
{
"code": null,
"e": 2977,
"s": 2932,
"text": "So this is the basic idea behind Regression."
},
{
"code": null,
"e": 3036,
"s": 2977,
"text": "Now let’s look at how to implement Regression using Excel."
},
{
"code": null,
"e": 3084,
"s": 3036,
"text": "The first step is the add data analysis toolpak"
},
{
"code": null,
"e": 3183,
"s": 3084,
"text": "Data Analysis ToolPak is not available by default, and you need to activate the add-in separately."
},
{
"code": null,
"e": 3356,
"s": 3183,
"text": "To activate, go to File -> Options -> Add-ins and then activate the Analysis ToolPak. Once you’ve activated the add-in, it should appear under the Data tab of your toolbar."
},
{
"code": null,
"e": 3459,
"s": 3356,
"text": "Once you’ve added data analysis toolpak and download the data in an Excel file, move to the next step."
},
{
"code": null,
"e": 3626,
"s": 3459,
"text": "To perform the Regression, go to Data Analysis Tools and select Regression from the available options. Once you choose Regression, the following window should appear."
},
{
"code": null,
"e": 3766,
"s": 3626,
"text": "Enter the range of the dependent variable in the Input Y Range and range of independent variables in the Input X Range. And then press, OK."
},
{
"code": null,
"e": 3831,
"s": 3766,
"text": "You’ve successfully completed performing Regression using Excel!"
},
{
"code": null,
"e": 3879,
"s": 3831,
"text": "Now let’s look at how to interpret the results."
},
{
"code": null,
"e": 3963,
"s": 3879,
"text": "Once you’ve performed Regression, your result page should look something like this."
},
{
"code": null,
"e": 4157,
"s": 3963,
"text": "If you take a look at the third table, there is the first column named coefficients. This column gives the values of the coefficient of each variable in the multiple linear regression equation."
},
{
"code": null,
"e": 4224,
"s": 4157,
"text": "Sales = 0.0544*(TV) + 0.1070*(Radio) + 0.0003*(Newspaper) + 4.6251"
},
{
"code": null,
"e": 4492,
"s": 4224,
"text": "The other measures that have been calculated on the tables are used to compare the performance, statistical significance and other factors. These measures require a good understanding of statistics, and hence I haven’t discussed all that in this introductory article."
},
{
"code": null,
"e": 4564,
"s": 4492,
"text": "Once you’ve performed Regression, there are two things that you can do."
},
{
"code": null,
"e": 4631,
"s": 4564,
"text": "Analyse the relationship between variablesBuild a predictive model"
},
{
"code": null,
"e": 4674,
"s": 4631,
"text": "Analyse the relationship between variables"
},
{
"code": null,
"e": 4699,
"s": 4674,
"text": "Build a predictive model"
},
{
"code": null,
"e": 4822,
"s": 4699,
"text": "Since we already talked about analysing the relationship between variables, let’s look at how to build a predictive model."
},
{
"code": null,
"e": 4967,
"s": 4822,
"text": "A predictive model is nothing but a process of predicting the value of the dependent variable by providing values for the independent variables."
},
{
"code": null,
"e": 5150,
"s": 4967,
"text": "So again, our multiple linear regression equation is the predictive model function where if we enter the values of the independent variables, we can get the predicted value of Sales."
},
{
"code": null,
"e": 5257,
"s": 5150,
"text": "For example, if you want to predict the sales revenue for the following combination of advertising spends,"
},
{
"code": null,
"e": 5266,
"s": 5257,
"text": "TV = 100"
},
{
"code": null,
"e": 5278,
"s": 5266,
"text": "Radio = 200"
},
{
"code": null,
"e": 5294,
"s": 5278,
"text": "Newspaper = 500"
},
{
"code": null,
"e": 5435,
"s": 5294,
"text": "Enter the values into the multiple linear regression equation. This will give you a sales revenue of 31.6377 which is the predicted revenue."
},
{
"code": null,
"e": 5598,
"s": 5435,
"text": "I hope that you would have got a good understanding of what Regression is, implementation using Excel, analysing the relationship and building predictive a model."
},
{
"code": null,
"e": 5778,
"s": 5598,
"text": "And of course, this is just an introduction of Regression, and there are a lot of other concepts that you can explore once you’re familiar with the basics covered in this article."
}
] |
How to handle the warning of file_get_contents() function in PHP ? - GeeksforGeeks
|
07 May, 2021
The file_get_contents() function in PHP is an inbuilt function which is used to read a file into a string. The function uses memory mapping techniques which are supported by the server and thus enhances the performances making it a preferred way of reading contents of a file. The path of the file to be read is sent as a parameter to the function and it returns the data read on success and FALSE on failure.
Return Value: It returns the read data on success and FALSE on failure.
Errors And Exception:
If you want to open a file with special characters, such as spaces, it needs to be encoded first using urlencode().
The file_get_contents() function returns Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.
An E_WARNING level error is generated if filename cannot be found, max length is less than zero, or if seeking to the specified offset in the stream fails.
Examples:
Input: file_get_contents('https://www.geeksforgeeks.org/');
Output: A computer science portal for geeks
Input: file_get_contents('gfg.txt', FALSE, NULL, 0, 14);
Output: A computer science portal for geeks
Program 1:
PHP
<?php // Reading contents from the// GeeksforGeeks homepage$homepage = file_get_contents( "https://www.geeksforgeeks.org/");echo $homepage; ?>
Runtime Errors:
PHP Warning: file_get_contents(): php_network_getaddresses: getaddrinfo failed: System error in /home/3d11f9784b99e2c83058d5842d5533ce.php on line 5 PHP Warning: file_get_contents(https://www.geeksforgeeks.org/): failed to open stream: php_network_getaddresses: getaddrinfo failed: System error in /home/3d11f9784b99e2c83058d5842d5533ce.php on line 5
Output:
It will redirect to GeeksforGeeks Home Page
Program 2:
PHP
<?php // Reading 36 bytes starting from// the 0th character of gfg.txt$text = file_get_contents('gfg.txt', FALSE, NULL, 0, 36);echo $text; ?>
Runtime Errors:
PHP Warning: file_get_contents(): php_network_getaddresses: getaddrinfo failed: System error in /home/4659aeca06fdba457da0c5d78befb39a.php on line 6 PHP Warning: file_get_contents(gfg.txt): failed to open stream: No such file or directory in /home/4659aeca06fdba457da0c5d78befb39a.php on line 6
Output:
It will display the content of gfg.txt file.
For Example: A computer science portal for geeks
As clearly we can see above runtime errors in the form PHP Warning have occurred which were really unexpected. Here the questions arise of removing these errors, is there a way to handle these errors? Yes, PHP provides us with a simple solution.
PHP supports one error control operator: the sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored. So, above PHP Warning can be suppressed by simply inserting error control operator(@) before the function call file_get_contents() in the following way:
Updated Program 1:
PHP
<?php // Reading contents from the// GeeksforGeeks homepage$homepage = @file_get_contents( "https://www.geeksforgeeks.org/");echo $homepage; ?>
Output:
It will redirect to GeeksforGeeks Home Page
Updated Program 2:
PHP
<?php // Reading 36 bytes starting from// the 0th character from gfg.txt$text = @file_get_contents('gfg.txt', FALSE, NULL, 0, 36);echo $text; ?>
Output:
It will display the content of gfg.txt file.
For Example: A computer science portal for geeks
So, after adding the ‘@’ symbol we can see that all those PHP warnings are suppressed and only output is displayed as above.Reference: https://www.php.net/manual/en/language.operators.errorcontrol.php
arorakashish0911
PHP-Misc
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24373,
"s": 24345,
"text": "\n07 May, 2021"
},
{
"code": null,
"e": 24783,
"s": 24373,
"text": "The file_get_contents() function in PHP is an inbuilt function which is used to read a file into a string. The function uses memory mapping techniques which are supported by the server and thus enhances the performances making it a preferred way of reading contents of a file. The path of the file to be read is sent as a parameter to the function and it returns the data read on success and FALSE on failure."
},
{
"code": null,
"e": 24855,
"s": 24783,
"text": "Return Value: It returns the read data on success and FALSE on failure."
},
{
"code": null,
"e": 24878,
"s": 24855,
"text": "Errors And Exception: "
},
{
"code": null,
"e": 24994,
"s": 24878,
"text": "If you want to open a file with special characters, such as spaces, it needs to be encoded first using urlencode()."
},
{
"code": null,
"e": 25116,
"s": 24994,
"text": "The file_get_contents() function returns Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE."
},
{
"code": null,
"e": 25272,
"s": 25116,
"text": "An E_WARNING level error is generated if filename cannot be found, max length is less than zero, or if seeking to the specified offset in the stream fails."
},
{
"code": null,
"e": 25284,
"s": 25272,
"text": "Examples: "
},
{
"code": null,
"e": 25492,
"s": 25284,
"text": "Input: file_get_contents('https://www.geeksforgeeks.org/');\nOutput: A computer science portal for geeks\n\nInput: file_get_contents('gfg.txt', FALSE, NULL, 0, 14);\nOutput: A computer science portal for geeks"
},
{
"code": null,
"e": 25504,
"s": 25492,
"text": "Program 1: "
},
{
"code": null,
"e": 25508,
"s": 25504,
"text": "PHP"
},
{
"code": "<?php // Reading contents from the// GeeksforGeeks homepage$homepage = file_get_contents( \"https://www.geeksforgeeks.org/\");echo $homepage; ?>",
"e": 25656,
"s": 25508,
"text": null
},
{
"code": null,
"e": 25673,
"s": 25656,
"text": "Runtime Errors: "
},
{
"code": null,
"e": 26024,
"s": 25673,
"text": "PHP Warning: file_get_contents(): php_network_getaddresses: getaddrinfo failed: System error in /home/3d11f9784b99e2c83058d5842d5533ce.php on line 5 PHP Warning: file_get_contents(https://www.geeksforgeeks.org/): failed to open stream: php_network_getaddresses: getaddrinfo failed: System error in /home/3d11f9784b99e2c83058d5842d5533ce.php on line 5"
},
{
"code": null,
"e": 26034,
"s": 26024,
"text": " Output: "
},
{
"code": null,
"e": 26078,
"s": 26034,
"text": "It will redirect to GeeksforGeeks Home Page"
},
{
"code": null,
"e": 26090,
"s": 26078,
"text": "Program 2: "
},
{
"code": null,
"e": 26094,
"s": 26090,
"text": "PHP"
},
{
"code": "<?php // Reading 36 bytes starting from// the 0th character of gfg.txt$text = file_get_contents('gfg.txt', FALSE, NULL, 0, 36);echo $text; ?>",
"e": 26253,
"s": 26094,
"text": null
},
{
"code": null,
"e": 26270,
"s": 26253,
"text": "Runtime Errors: "
},
{
"code": null,
"e": 26565,
"s": 26270,
"text": "PHP Warning: file_get_contents(): php_network_getaddresses: getaddrinfo failed: System error in /home/4659aeca06fdba457da0c5d78befb39a.php on line 6 PHP Warning: file_get_contents(gfg.txt): failed to open stream: No such file or directory in /home/4659aeca06fdba457da0c5d78befb39a.php on line 6"
},
{
"code": null,
"e": 26575,
"s": 26565,
"text": " Output: "
},
{
"code": null,
"e": 26669,
"s": 26575,
"text": "It will display the content of gfg.txt file.\nFor Example: A computer science portal for geeks"
},
{
"code": null,
"e": 26915,
"s": 26669,
"text": "As clearly we can see above runtime errors in the form PHP Warning have occurred which were really unexpected. Here the questions arise of removing these errors, is there a way to handle these errors? Yes, PHP provides us with a simple solution."
},
{
"code": null,
"e": 27242,
"s": 26915,
"text": "PHP supports one error control operator: the sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored. So, above PHP Warning can be suppressed by simply inserting error control operator(@) before the function call file_get_contents() in the following way:"
},
{
"code": null,
"e": 27263,
"s": 27242,
"text": "Updated Program 1: "
},
{
"code": null,
"e": 27267,
"s": 27263,
"text": "PHP"
},
{
"code": "<?php // Reading contents from the// GeeksforGeeks homepage$homepage = @file_get_contents( \"https://www.geeksforgeeks.org/\");echo $homepage; ?>",
"e": 27416,
"s": 27267,
"text": null
},
{
"code": null,
"e": 27425,
"s": 27416,
"text": "Output: "
},
{
"code": null,
"e": 27469,
"s": 27425,
"text": "It will redirect to GeeksforGeeks Home Page"
},
{
"code": null,
"e": 27489,
"s": 27469,
"text": "Updated Program 2: "
},
{
"code": null,
"e": 27493,
"s": 27489,
"text": "PHP"
},
{
"code": "<?php // Reading 36 bytes starting from// the 0th character from gfg.txt$text = @file_get_contents('gfg.txt', FALSE, NULL, 0, 36);echo $text; ?>",
"e": 27655,
"s": 27493,
"text": null
},
{
"code": null,
"e": 27664,
"s": 27655,
"text": "Output: "
},
{
"code": null,
"e": 27758,
"s": 27664,
"text": "It will display the content of gfg.txt file.\nFor Example: A computer science portal for geeks"
},
{
"code": null,
"e": 27960,
"s": 27758,
"text": "So, after adding the ‘@’ symbol we can see that all those PHP warnings are suppressed and only output is displayed as above.Reference: https://www.php.net/manual/en/language.operators.errorcontrol.php "
},
{
"code": null,
"e": 27977,
"s": 27960,
"text": "arorakashish0911"
},
{
"code": null,
"e": 27986,
"s": 27977,
"text": "PHP-Misc"
},
{
"code": null,
"e": 27993,
"s": 27986,
"text": "Picked"
},
{
"code": null,
"e": 27997,
"s": 27993,
"text": "PHP"
},
{
"code": null,
"e": 28014,
"s": 27997,
"text": "Web Technologies"
},
{
"code": null,
"e": 28018,
"s": 28014,
"text": "PHP"
},
{
"code": null,
"e": 28116,
"s": 28018,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28125,
"s": 28116,
"text": "Comments"
},
{
"code": null,
"e": 28138,
"s": 28125,
"text": "Old Comments"
},
{
"code": null,
"e": 28188,
"s": 28138,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28228,
"s": 28188,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 28289,
"s": 28228,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 28339,
"s": 28289,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 28366,
"s": 28339,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 28422,
"s": 28366,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28455,
"s": 28422,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28517,
"s": 28455,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28560,
"s": 28517,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python | Word location in String
|
22 Apr, 2020
Sometimes, while working with Python strings, we can have problem in which we need to find location of a particular word. This can have application in domains such as day-day programming. Lets discuss certain ways in which this task can be done.
Method #1 : Using re.findall() + index()This is one of the way in which we can find the location where word exists. In this we look for substring pattern using findall() and its position using index().
# Python3 code to demonstrate working of # Word location in String# Using findall() + index()import re # initializing stringtest_str = 'geeksforgeeks is best for geeks' # printing original stringprint("The original string is : " + test_str) # initializing word wrd = 'best' # Word location in String# Using findall() + index()test_str = test_str.split()res = -1for idx in test_str: if len(re.findall(wrd, idx)) > 0: res = test_str.index(idx) + 1 # printing result print("The location of word is : " + str(res))
The original string is : geeksforgeeks is best for geeks
The location of word is : 3
Method #2 : Using re.sub() + index()This performs this task in similar way as above method. In this also regex is employed. We use different regex function in this method.
# Python3 code to demonstrate working of # Word location in String# Using re.sub() + index()import re # initializing stringtest_str = 'geeksforgeeks is best for geeks' # printing original stringprint("The original string is : " + test_str) # initializing word wrd = 'best' # Word location in String# Using re.sub() + index()res = re.sub("[^\w]", " ", test_str).split()res = res.index(wrd) + 1 # printing result print("The location of word is : " + str(res))
The original string is : geeksforgeeks is best for geeks
The location of word is : 3
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 299,
"s": 53,
"text": "Sometimes, while working with Python strings, we can have problem in which we need to find location of a particular word. This can have application in domains such as day-day programming. Lets discuss certain ways in which this task can be done."
},
{
"code": null,
"e": 501,
"s": 299,
"text": "Method #1 : Using re.findall() + index()This is one of the way in which we can find the location where word exists. In this we look for substring pattern using findall() and its position using index()."
},
{
"code": "# Python3 code to demonstrate working of # Word location in String# Using findall() + index()import re # initializing stringtest_str = 'geeksforgeeks is best for geeks' # printing original stringprint(\"The original string is : \" + test_str) # initializing word wrd = 'best' # Word location in String# Using findall() + index()test_str = test_str.split()res = -1for idx in test_str: if len(re.findall(wrd, idx)) > 0: res = test_str.index(idx) + 1 # printing result print(\"The location of word is : \" + str(res)) ",
"e": 1028,
"s": 501,
"text": null
},
{
"code": null,
"e": 1114,
"s": 1028,
"text": "The original string is : geeksforgeeks is best for geeks\nThe location of word is : 3\n"
},
{
"code": null,
"e": 1288,
"s": 1116,
"text": "Method #2 : Using re.sub() + index()This performs this task in similar way as above method. In this also regex is employed. We use different regex function in this method."
},
{
"code": "# Python3 code to demonstrate working of # Word location in String# Using re.sub() + index()import re # initializing stringtest_str = 'geeksforgeeks is best for geeks' # printing original stringprint(\"The original string is : \" + test_str) # initializing word wrd = 'best' # Word location in String# Using re.sub() + index()res = re.sub(\"[^\\w]\", \" \", test_str).split()res = res.index(wrd) + 1 # printing result print(\"The location of word is : \" + str(res)) ",
"e": 1753,
"s": 1288,
"text": null
},
{
"code": null,
"e": 1839,
"s": 1753,
"text": "The original string is : geeksforgeeks is best for geeks\nThe location of word is : 3\n"
},
{
"code": null,
"e": 1862,
"s": 1839,
"text": "Python string-programs"
},
{
"code": null,
"e": 1869,
"s": 1862,
"text": "Python"
},
{
"code": null,
"e": 1885,
"s": 1869,
"text": "Python Programs"
}
] |
route command in Linux with Examples
|
17 May, 2020
route command in Linux is used when you want to work with the IP/kernel routing table. It is mainly used to set up static routes to specific hosts or networks via an interface. It is used for showing or update the IP/kernel routing table.
Many Linux distributions do not have route command pre-installed. To install it use the following commands as per your Linux distribution.
In case of Debian/Ubuntu
$sudo apt-get install net-tools
In case of CentOS/RedHat
$sudo yum install net-tools
In case of Fedora OS
$sudo dnf install net-tools
1. To display the IP/kernel routing table.
$route
It displays the routing table entries.
2. To display routing table in full numeric form.
$route -n
It is even useful when you have to determine why the route to nameserver has even vanished.
3. To add a default gateway.
$sudo route add default gw 169.254.0.0
This assigns a gateway address on which all the packets that do not belong to the network are forwarded.
Note: In this case the, We wish to choose 169.254.0.0 as the default gateway. You may choose as per your need.
4. To list kernel’s routing cache information.
$route -Cn
To route the packets faster, Kernel maintains this routing cache information. The above command will print the cache information. In this case, the cache information is maintained.
5. To reject routing to a particular host or network.
$sudo route add -host 192.168.1.51 reject
Now if you will ping to the above-mentioned IP it will display “Network is unreachable”.
6. To get details of the kernel/IP routing table using ip command.
$ip route
This will give the details of the kernel/IP routing table and in this case, we have used IP command.
7. To delete the default gateway.
$route del default
Caution: This may lead to some malfunctioning of internet. Keep a note of your default gateway before proceeding with the command.
This will remove the default gateway.
8. To get the details of the local table with destination addresses assigned to the localhost.
$ip route show table local
This will print the details of the local table.
9. To get output related to IPv4.
$ip -4 route
This will only display the entries with ipv4.
10. To get output related to IPv6.
$ip -6 route
This will only display the entries with ipv6.
linux-command
Linux-networking-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
Introduction to Linux Operating System
SED command in Linux | Set 2
nohup Command in Linux with Examples
mv command in Linux with examples
Array Basics in Shell Scripting | Set 1
chmod command in Linux with examples
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 May, 2020"
},
{
"code": null,
"e": 291,
"s": 52,
"text": "route command in Linux is used when you want to work with the IP/kernel routing table. It is mainly used to set up static routes to specific hosts or networks via an interface. It is used for showing or update the IP/kernel routing table."
},
{
"code": null,
"e": 430,
"s": 291,
"text": "Many Linux distributions do not have route command pre-installed. To install it use the following commands as per your Linux distribution."
},
{
"code": null,
"e": 455,
"s": 430,
"text": "In case of Debian/Ubuntu"
},
{
"code": null,
"e": 487,
"s": 455,
"text": "$sudo apt-get install net-tools"
},
{
"code": null,
"e": 512,
"s": 487,
"text": "In case of CentOS/RedHat"
},
{
"code": null,
"e": 540,
"s": 512,
"text": "$sudo yum install net-tools"
},
{
"code": null,
"e": 561,
"s": 540,
"text": "In case of Fedora OS"
},
{
"code": null,
"e": 589,
"s": 561,
"text": "$sudo dnf install net-tools"
},
{
"code": null,
"e": 632,
"s": 589,
"text": "1. To display the IP/kernel routing table."
},
{
"code": null,
"e": 639,
"s": 632,
"text": "$route"
},
{
"code": null,
"e": 678,
"s": 639,
"text": "It displays the routing table entries."
},
{
"code": null,
"e": 728,
"s": 678,
"text": "2. To display routing table in full numeric form."
},
{
"code": null,
"e": 738,
"s": 728,
"text": "$route -n"
},
{
"code": null,
"e": 830,
"s": 738,
"text": "It is even useful when you have to determine why the route to nameserver has even vanished."
},
{
"code": null,
"e": 859,
"s": 830,
"text": "3. To add a default gateway."
},
{
"code": null,
"e": 898,
"s": 859,
"text": "$sudo route add default gw 169.254.0.0"
},
{
"code": null,
"e": 1003,
"s": 898,
"text": "This assigns a gateway address on which all the packets that do not belong to the network are forwarded."
},
{
"code": null,
"e": 1114,
"s": 1003,
"text": "Note: In this case the, We wish to choose 169.254.0.0 as the default gateway. You may choose as per your need."
},
{
"code": null,
"e": 1161,
"s": 1114,
"text": "4. To list kernel’s routing cache information."
},
{
"code": null,
"e": 1173,
"s": 1161,
"text": "$route -Cn\n"
},
{
"code": null,
"e": 1354,
"s": 1173,
"text": "To route the packets faster, Kernel maintains this routing cache information. The above command will print the cache information. In this case, the cache information is maintained."
},
{
"code": null,
"e": 1408,
"s": 1354,
"text": "5. To reject routing to a particular host or network."
},
{
"code": null,
"e": 1451,
"s": 1408,
"text": "$sudo route add -host 192.168.1.51 reject\n"
},
{
"code": null,
"e": 1540,
"s": 1451,
"text": "Now if you will ping to the above-mentioned IP it will display “Network is unreachable”."
},
{
"code": null,
"e": 1607,
"s": 1540,
"text": "6. To get details of the kernel/IP routing table using ip command."
},
{
"code": null,
"e": 1618,
"s": 1607,
"text": "$ip route\n"
},
{
"code": null,
"e": 1719,
"s": 1618,
"text": "This will give the details of the kernel/IP routing table and in this case, we have used IP command."
},
{
"code": null,
"e": 1753,
"s": 1719,
"text": "7. To delete the default gateway."
},
{
"code": null,
"e": 1773,
"s": 1753,
"text": "$route del default\n"
},
{
"code": null,
"e": 1904,
"s": 1773,
"text": "Caution: This may lead to some malfunctioning of internet. Keep a note of your default gateway before proceeding with the command."
},
{
"code": null,
"e": 1942,
"s": 1904,
"text": "This will remove the default gateway."
},
{
"code": null,
"e": 2037,
"s": 1942,
"text": "8. To get the details of the local table with destination addresses assigned to the localhost."
},
{
"code": null,
"e": 2065,
"s": 2037,
"text": "$ip route show table local\n"
},
{
"code": null,
"e": 2113,
"s": 2065,
"text": "This will print the details of the local table."
},
{
"code": null,
"e": 2147,
"s": 2113,
"text": "9. To get output related to IPv4."
},
{
"code": null,
"e": 2161,
"s": 2147,
"text": "$ip -4 route\n"
},
{
"code": null,
"e": 2207,
"s": 2161,
"text": "This will only display the entries with ipv4."
},
{
"code": null,
"e": 2242,
"s": 2207,
"text": "10. To get output related to IPv6."
},
{
"code": null,
"e": 2256,
"s": 2242,
"text": "$ip -6 route\n"
},
{
"code": null,
"e": 2302,
"s": 2256,
"text": "This will only display the entries with ipv6."
},
{
"code": null,
"e": 2316,
"s": 2302,
"text": "linux-command"
},
{
"code": null,
"e": 2342,
"s": 2316,
"text": "Linux-networking-commands"
},
{
"code": null,
"e": 2353,
"s": 2342,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2451,
"s": 2353,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2477,
"s": 2451,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2512,
"s": 2477,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 2549,
"s": 2512,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 2588,
"s": 2549,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 2617,
"s": 2588,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 2654,
"s": 2617,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 2688,
"s": 2654,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 2728,
"s": 2688,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 2765,
"s": 2728,
"text": "chmod command in Linux with examples"
}
] |
How to set the Length of the Characters in TextBox in C#?
|
29 Nov, 2019
In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set the maximum number of characters which the user can type or paste or entered into the TextBox with the help of MaxLength property. The default value of this property is 32767. You can use this property in the form where you are restricted to enter some certain amount of characters like phone number, postal code, etc. In Windows form, you can set this property in two different ways:
1. Design-Time: It is the simplest way to set the MaxLength property of the TextBox as shown in the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the TextBox control from the ToolBox and Drop it on the windows form. You can place TextBox anywhere on the windows form according to your need. As shown in the below image:
Step 3: After drag and drop you will go to the properties of the TextBox control to set the MaxLength property of the TextBox. As shown in the below image:Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the MaxLength property of the TextBox programmatically with the help of given syntax:
public virtual int MaxLength { get; set; }
Here, the value of this property is of System.Int32 type. And it will throw an ArgumentOutOfRangeException if the value assigned to the property is less than 0. Following steps are used to set the MaxLength property of the TextBox:
Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox
TextBox Mytextbox = new TextBox();
// Creating textbox
TextBox Mytextbox = new TextBox();
Step 2 : After creating TextBox, set the MaxLength property of the TextBox provided by the TextBox class.// Set MaxLength property
Mytextbox2.MaxLength = 6;
// Set MaxLength property
Mytextbox2.MaxLength = 6;
Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form
this.Controls.Add(Mytextbox1);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel1 = new Label(); Mylablel1.Location = new Point(96, 54); Mylablel1.Text = "Enter Name"; Mylablel1.AutoSize = true; Mylablel1.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel1); // Creating and setting the properties of TextBox1 TextBox Mytextbox1 = new TextBox(); Mytextbox1.Location = new Point(187, 51); Mytextbox1.BackColor = Color.LightGray; Mytextbox1.AutoSize = true; Mytextbox1.Name = "text_box1"; // Add this textbox to form this.Controls.Add(Mytextbox1); // Creating and setting the properties of Lable1 Label Mylablel2 = new Label(); Mylablel2.Location = new Point(96, 102); Mylablel2.Text = "Enter Pincode"; Mylablel2.AutoSize = true; Mylablel2.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel2); // Creating and setting the properties of TextBox2 TextBox Mytextbox2 = new TextBox(); Mytextbox2.Location = new Point(187, 99); Mytextbox2.BackColor = Color.LightGray; Mytextbox2.AutoSize = true; Mytextbox2.MaxLength = 6; Mytextbox2.Name = "text_box2"; // Add this textbox to form this.Controls.Add(Mytextbox2); }}}Output:
// Add this textbox to form
this.Controls.Add(Mytextbox1);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel1 = new Label(); Mylablel1.Location = new Point(96, 54); Mylablel1.Text = "Enter Name"; Mylablel1.AutoSize = true; Mylablel1.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel1); // Creating and setting the properties of TextBox1 TextBox Mytextbox1 = new TextBox(); Mytextbox1.Location = new Point(187, 51); Mytextbox1.BackColor = Color.LightGray; Mytextbox1.AutoSize = true; Mytextbox1.Name = "text_box1"; // Add this textbox to form this.Controls.Add(Mytextbox1); // Creating and setting the properties of Lable1 Label Mylablel2 = new Label(); Mylablel2.Location = new Point(96, 102); Mylablel2.Text = "Enter Pincode"; Mylablel2.AutoSize = true; Mylablel2.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel2); // Creating and setting the properties of TextBox2 TextBox Mytextbox2 = new TextBox(); Mytextbox2.Location = new Point(187, 99); Mytextbox2.BackColor = Color.LightGray; Mytextbox2.AutoSize = true; Mytextbox2.MaxLength = 6; Mytextbox2.Name = "text_box2"; // Add this textbox to form this.Controls.Add(Mytextbox2); }}}
Output:
CSharp-Windows-Forms-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Nov, 2019"
},
{
"code": null,
"e": 618,
"s": 28,
"text": "In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set the maximum number of characters which the user can type or paste or entered into the TextBox with the help of MaxLength property. The default value of this property is 32767. You can use this property in the form where you are restricted to enter some certain amount of characters like phone number, postal code, etc. In Windows form, you can set this property in two different ways:"
},
{
"code": null,
"e": 735,
"s": 618,
"text": "1. Design-Time: It is the simplest way to set the MaxLength property of the TextBox as shown in the following steps:"
},
{
"code": null,
"e": 851,
"s": 735,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 1038,
"s": 851,
"text": "Step 2: Drag the TextBox control from the ToolBox and Drop it on the windows form. You can place TextBox anywhere on the windows form according to your need. As shown in the below image:"
},
{
"code": null,
"e": 1201,
"s": 1038,
"text": "Step 3: After drag and drop you will go to the properties of the TextBox control to set the MaxLength property of the TextBox. As shown in the below image:Output:"
},
{
"code": null,
"e": 1209,
"s": 1201,
"text": "Output:"
},
{
"code": null,
"e": 1387,
"s": 1209,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the MaxLength property of the TextBox programmatically with the help of given syntax:"
},
{
"code": null,
"e": 1430,
"s": 1387,
"text": "public virtual int MaxLength { get; set; }"
},
{
"code": null,
"e": 1662,
"s": 1430,
"text": "Here, the value of this property is of System.Int32 type. And it will throw an ArgumentOutOfRangeException if the value assigned to the property is less than 0. Following steps are used to set the MaxLength property of the TextBox:"
},
{
"code": null,
"e": 1806,
"s": 1662,
"text": "Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox\nTextBox Mytextbox = new TextBox();\n"
},
{
"code": null,
"e": 1862,
"s": 1806,
"text": "// Creating textbox\nTextBox Mytextbox = new TextBox();\n"
},
{
"code": null,
"e": 2020,
"s": 1862,
"text": "Step 2 : After creating TextBox, set the MaxLength property of the TextBox provided by the TextBox class.// Set MaxLength property\nMytextbox2.MaxLength = 6;\n"
},
{
"code": null,
"e": 2073,
"s": 2020,
"text": "// Set MaxLength property\nMytextbox2.MaxLength = 6;\n"
},
{
"code": null,
"e": 4000,
"s": 2073,
"text": "Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form\nthis.Controls.Add(Mytextbox1);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel1 = new Label(); Mylablel1.Location = new Point(96, 54); Mylablel1.Text = \"Enter Name\"; Mylablel1.AutoSize = true; Mylablel1.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel1); // Creating and setting the properties of TextBox1 TextBox Mytextbox1 = new TextBox(); Mytextbox1.Location = new Point(187, 51); Mytextbox1.BackColor = Color.LightGray; Mytextbox1.AutoSize = true; Mytextbox1.Name = \"text_box1\"; // Add this textbox to form this.Controls.Add(Mytextbox1); // Creating and setting the properties of Lable1 Label Mylablel2 = new Label(); Mylablel2.Location = new Point(96, 102); Mylablel2.Text = \"Enter Pincode\"; Mylablel2.AutoSize = true; Mylablel2.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel2); // Creating and setting the properties of TextBox2 TextBox Mytextbox2 = new TextBox(); Mytextbox2.Location = new Point(187, 99); Mytextbox2.BackColor = Color.LightGray; Mytextbox2.AutoSize = true; Mytextbox2.MaxLength = 6; Mytextbox2.Name = \"text_box2\"; // Add this textbox to form this.Controls.Add(Mytextbox2); }}}Output:"
},
{
"code": null,
"e": 4060,
"s": 4000,
"text": "// Add this textbox to form\nthis.Controls.Add(Mytextbox1);\n"
},
{
"code": null,
"e": 4069,
"s": 4060,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel1 = new Label(); Mylablel1.Location = new Point(96, 54); Mylablel1.Text = \"Enter Name\"; Mylablel1.AutoSize = true; Mylablel1.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel1); // Creating and setting the properties of TextBox1 TextBox Mytextbox1 = new TextBox(); Mytextbox1.Location = new Point(187, 51); Mytextbox1.BackColor = Color.LightGray; Mytextbox1.AutoSize = true; Mytextbox1.Name = \"text_box1\"; // Add this textbox to form this.Controls.Add(Mytextbox1); // Creating and setting the properties of Lable1 Label Mylablel2 = new Label(); Mylablel2.Location = new Point(96, 102); Mylablel2.Text = \"Enter Pincode\"; Mylablel2.AutoSize = true; Mylablel2.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel2); // Creating and setting the properties of TextBox2 TextBox Mytextbox2 = new TextBox(); Mytextbox2.Location = new Point(187, 99); Mytextbox2.BackColor = Color.LightGray; Mytextbox2.AutoSize = true; Mytextbox2.MaxLength = 6; Mytextbox2.Name = \"text_box2\"; // Add this textbox to form this.Controls.Add(Mytextbox2); }}}",
"e": 5852,
"s": 4069,
"text": null
},
{
"code": null,
"e": 5860,
"s": 5852,
"text": "Output:"
},
{
"code": null,
"e": 5891,
"s": 5860,
"text": "CSharp-Windows-Forms-Namespace"
},
{
"code": null,
"e": 5894,
"s": 5891,
"text": "C#"
}
] |
How to check/find an item in Dequeue using find() method
|
10 Dec, 2021
find() function finds the element in the given range of numbers. Returns an iterator to the first element in the range [first, last) that compares equal to the value to be searched. If no such element is found, the function returns last.
Syntax:
InputIterator find (InputIterator first, InputIterator last, const T& val)
Parameters:
first, last : Input iterators to the initial and final positions in a sequence.The range searched is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
val: Value to be search in the range.
Return Value:
An iterator to the first element in the range that compares equal to val.If no elements match, the function returns last.
Example:
Input: 10 20 30 40Output: Element 30 found at position : 2 (counting from zero)
Input: 8 5 9 2 7 1 3 10Output: Element 4 not found.
Example 1: Below is the C++ program to implement find() function in deque.
C++
// C++ program to implement// the above approach#include <iostream>#include<bits/stdc++.h>using namespace std; // Function to find element// in a dequevoid find(deque<int> q){ deque<int>::iterator itr; itr = find(q.begin(), q.end(), 2); if(itr != q.end()) { cout << "Found"; } else { cout << "Not Found"; }}// Driver codeint main() { // Declaring a deque deque<int> q; // Initializing deque q.push_back(1); q.push_back(2); q.push_back(3); q.push_back(4); q.push_back(5); // Calling function find() find(q); return 0;}
Output:
Found
Example 2: Below is a C++ program to demonstrate how to find elements in dequeue.
C++
// C++ program to implement// the above approach#include <iostream>#include<bits/stdc++.h>using namespace std; // Function to find an element // in a dequevoid find(deque<string> q){ deque<string>::iterator itr; itr = find(q.begin(), q.end(), "Raj"); if(itr != q.end()) { cout << "Found"; } else { cout << "Not Found"; }} // Driver codeint main() { // Declaring a deque deque<string> q; // Initializing a deque q.push_back("Akshit"); q.push_back("Nikita"); q.push_back("Deeksha"); q.push_back("Nandish"); q.push_back("Rajat"); // Calling find() function find(q); return 0;}
Output:
Not Found
std::find() in C++ vs find in Deque
In std::find() in C++, the range searched is [first, last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.In the case of finding an item in deque using find() function, the range searched is [first, last] i.e both first and last inclusive.
Below is the C++ program to demonstrate finding an item in dequeue.
C++
// C++ program to implement// the above approach#include <iostream>#include<bits/stdc++.h>using namespace std; void find(deque<int> q){ deque<int>::iterator itr; itr = find(q.begin(), q.end(), 5); if(itr != q.end()) { cout << "Found"; } else { cout << "Not Found"; }} // Driver codeint main() { // Declaring a deque deque<int> q; // Initializing deque q.push_back(1); q.push_back(2); q.push_back(3); q.push_back(4); q.push_back(5); // Calling find() function find(q); return 0;}
Output:
Found
deque
C++
Searching
Searching
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Dec, 2021"
},
{
"code": null,
"e": 266,
"s": 28,
"text": "find() function finds the element in the given range of numbers. Returns an iterator to the first element in the range [first, last) that compares equal to the value to be searched. If no such element is found, the function returns last."
},
{
"code": null,
"e": 274,
"s": 266,
"text": "Syntax:"
},
{
"code": null,
"e": 349,
"s": 274,
"text": "InputIterator find (InputIterator first, InputIterator last, const T& val)"
},
{
"code": null,
"e": 361,
"s": 349,
"text": "Parameters:"
},
{
"code": null,
"e": 608,
"s": 361,
"text": "first, last : Input iterators to the initial and final positions in a sequence.The range searched is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last."
},
{
"code": null,
"e": 646,
"s": 608,
"text": "val: Value to be search in the range."
},
{
"code": null,
"e": 660,
"s": 646,
"text": "Return Value:"
},
{
"code": null,
"e": 782,
"s": 660,
"text": "An iterator to the first element in the range that compares equal to val.If no elements match, the function returns last."
},
{
"code": null,
"e": 791,
"s": 782,
"text": "Example:"
},
{
"code": null,
"e": 873,
"s": 791,
"text": "Input: 10 20 30 40Output: Element 30 found at position : 2 (counting from zero) "
},
{
"code": null,
"e": 928,
"s": 873,
"text": "Input: 8 5 9 2 7 1 3 10Output: Element 4 not found. "
},
{
"code": null,
"e": 1003,
"s": 928,
"text": "Example 1: Below is the C++ program to implement find() function in deque."
},
{
"code": null,
"e": 1007,
"s": 1003,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <iostream>#include<bits/stdc++.h>using namespace std; // Function to find element// in a dequevoid find(deque<int> q){ deque<int>::iterator itr; itr = find(q.begin(), q.end(), 2); if(itr != q.end()) { cout << \"Found\"; } else { cout << \"Not Found\"; }}// Driver codeint main() { // Declaring a deque deque<int> q; // Initializing deque q.push_back(1); q.push_back(2); q.push_back(3); q.push_back(4); q.push_back(5); // Calling function find() find(q); return 0;}",
"e": 1559,
"s": 1007,
"text": null
},
{
"code": null,
"e": 1567,
"s": 1559,
"text": "Output:"
},
{
"code": null,
"e": 1573,
"s": 1567,
"text": "Found"
},
{
"code": null,
"e": 1655,
"s": 1573,
"text": "Example 2: Below is a C++ program to demonstrate how to find elements in dequeue."
},
{
"code": null,
"e": 1659,
"s": 1655,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <iostream>#include<bits/stdc++.h>using namespace std; // Function to find an element // in a dequevoid find(deque<string> q){ deque<string>::iterator itr; itr = find(q.begin(), q.end(), \"Raj\"); if(itr != q.end()) { cout << \"Found\"; } else { cout << \"Not Found\"; }} // Driver codeint main() { // Declaring a deque deque<string> q; // Initializing a deque q.push_back(\"Akshit\"); q.push_back(\"Nikita\"); q.push_back(\"Deeksha\"); q.push_back(\"Nandish\"); q.push_back(\"Rajat\"); // Calling find() function find(q); return 0;}",
"e": 2291,
"s": 1659,
"text": null
},
{
"code": null,
"e": 2299,
"s": 2291,
"text": "Output:"
},
{
"code": null,
"e": 2309,
"s": 2299,
"text": "Not Found"
},
{
"code": null,
"e": 2345,
"s": 2309,
"text": "std::find() in C++ vs find in Deque"
},
{
"code": null,
"e": 2671,
"s": 2345,
"text": "In std::find() in C++, the range searched is [first, last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.In the case of finding an item in deque using find() function, the range searched is [first, last] i.e both first and last inclusive. "
},
{
"code": null,
"e": 2739,
"s": 2671,
"text": "Below is the C++ program to demonstrate finding an item in dequeue."
},
{
"code": null,
"e": 2743,
"s": 2739,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <iostream>#include<bits/stdc++.h>using namespace std; void find(deque<int> q){ deque<int>::iterator itr; itr = find(q.begin(), q.end(), 5); if(itr != q.end()) { cout << \"Found\"; } else { cout << \"Not Found\"; }} // Driver codeint main() { // Declaring a deque deque<int> q; // Initializing deque q.push_back(1); q.push_back(2); q.push_back(3); q.push_back(4); q.push_back(5); // Calling find() function find(q); return 0;}",
"e": 3276,
"s": 2743,
"text": null
},
{
"code": null,
"e": 3284,
"s": 3276,
"text": "Output:"
},
{
"code": null,
"e": 3290,
"s": 3284,
"text": "Found"
},
{
"code": null,
"e": 3296,
"s": 3290,
"text": "deque"
},
{
"code": null,
"e": 3300,
"s": 3296,
"text": "C++"
},
{
"code": null,
"e": 3310,
"s": 3300,
"text": "Searching"
},
{
"code": null,
"e": 3320,
"s": 3310,
"text": "Searching"
},
{
"code": null,
"e": 3324,
"s": 3320,
"text": "CPP"
}
] |
Lower bound for comparison based sorting algorithms
|
06 Jul, 2021
The problem of sorting can be viewed as following.
Input: A sequence of n numbers <a1, a2, . . . , an>. Output: A permutation (reordering) <a‘1, a‘2, . . . , a‘n> of the input sequence such that a‘1 <= a‘2 ..... <= a’n.
A sorting algorithm is comparison based if it uses comparison operators to find the order between two numbers. Comparison sorts can be viewed abstractly in terms of decision trees. A decision tree is a full binary tree that represents the comparisons between elements that are performed by a particular sorting algorithm operating on an input of a given size. The execution of the sorting algorithm corresponds to tracing a path from the root of the decision tree to a leaf. At each internal node, a comparison ai <= aj is made. The left subtree then dictates subsequent comparisons for ai <= aj, and the right subtree dictates subsequent comparisons for ai > aj. When we come to a leaf, the sorting algorithm has established the ordering. So we can say following about the decision tree.
1) Each of the n! permutations on n elements must appear as one of the leaves of the decision tree for the sorting algorithm to sort properly.
2) Let x be the maximum number of comparisons in a sorting algorithm. The maximum height of the decision tree would be x. A tree with maximum height x has at most 2^x leaves.
After combining the above two facts, we get following relation.
n! <= 2^x
Taking Log on both sides.
log2(n!) <= x
Since log2(n!) = Θ(nLogn), we can say
x = Ω(nLog2n)
Therefore, any comparison based sorting algorithm must make at least nLog2n comparisons to sort the input array, and Heapsort and merge sort are asymptotically optimal comparison sorts.
References: Introduction to Algorithms, by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein
sooda367
Merge Sort
Sorting
Sorting
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 104,
"s": 52,
"text": "The problem of sorting can be viewed as following. "
},
{
"code": null,
"e": 274,
"s": 104,
"text": "Input: A sequence of n numbers <a1, a2, . . . , an>. Output: A permutation (reordering) <a‘1, a‘2, . . . , a‘n> of the input sequence such that a‘1 <= a‘2 ..... <= a’n. "
},
{
"code": null,
"e": 1065,
"s": 274,
"text": "A sorting algorithm is comparison based if it uses comparison operators to find the order between two numbers. Comparison sorts can be viewed abstractly in terms of decision trees. A decision tree is a full binary tree that represents the comparisons between elements that are performed by a particular sorting algorithm operating on an input of a given size. The execution of the sorting algorithm corresponds to tracing a path from the root of the decision tree to a leaf. At each internal node, a comparison ai <= aj is made. The left subtree then dictates subsequent comparisons for ai <= aj, and the right subtree dictates subsequent comparisons for ai > aj. When we come to a leaf, the sorting algorithm has established the ordering. So we can say following about the decision tree. "
},
{
"code": null,
"e": 1209,
"s": 1065,
"text": "1) Each of the n! permutations on n elements must appear as one of the leaves of the decision tree for the sorting algorithm to sort properly. "
},
{
"code": null,
"e": 1385,
"s": 1209,
"text": "2) Let x be the maximum number of comparisons in a sorting algorithm. The maximum height of the decision tree would be x. A tree with maximum height x has at most 2^x leaves. "
},
{
"code": null,
"e": 1451,
"s": 1385,
"text": "After combining the above two facts, we get following relation. "
},
{
"code": null,
"e": 1582,
"s": 1451,
"text": " \n n! <= 2^x\n\n Taking Log on both sides.\n log2(n!) <= x\n\n Since log2(n!) = Θ(nLogn), we can say\n x = Ω(nLog2n)"
},
{
"code": null,
"e": 1769,
"s": 1582,
"text": "Therefore, any comparison based sorting algorithm must make at least nLog2n comparisons to sort the input array, and Heapsort and merge sort are asymptotically optimal comparison sorts. "
},
{
"code": null,
"e": 1889,
"s": 1769,
"text": "References: Introduction to Algorithms, by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein "
},
{
"code": null,
"e": 1898,
"s": 1889,
"text": "sooda367"
},
{
"code": null,
"e": 1909,
"s": 1898,
"text": "Merge Sort"
},
{
"code": null,
"e": 1917,
"s": 1909,
"text": "Sorting"
},
{
"code": null,
"e": 1925,
"s": 1917,
"text": "Sorting"
},
{
"code": null,
"e": 1936,
"s": 1925,
"text": "Merge Sort"
}
] |
ReactJS Reactstrap Navbar Component
|
24 Nov, 2021
Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Navbar component provides a way for users to provide them navigation controls at the top of an application. We can use the following approach in ReactJS to use the ReactJS Reactstrap Navbar Component.
Navbar Props:
light: It is used to indicate whether to apply the light color class to it or not.
dark: It is used to indicate whether to apply the dark color class to it or not.
fixed: It is used to indicate whether to apply position fixed property or not.
color: It is used to denote the color for this component.
role: It is used to denote the value for role property for this component.
expand: It is used to indicate whether to expand Navbar on click or not.
tag: It is used to pass in custom elements to use.
NavbarBrand Props:
tag: It is used to pass in custom elements to use.
NavbarText Props:
tag: It is used to pass in custom elements to use.
NavbarTogglerProps:
type: It is used to denote the type for this component.
tag: It is used to pass in custom elements to use.
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 required module using the following command:
npm install reactstrap bootstrap
Project Structure: It will look like the following.
Project Structure
Example 1: Now write down the following code in the App.js file. Here, we have shown the Navbar component with the expand property.
Javascript
import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Navbar, NavItem, NavbarToggler, Collapse, NavLink, Nav, NavbarBrand} from 'reactstrap'; function App() { // Collapse isOpen State const [isOpen, setIsOpen] = React.useState(false); return ( <div style={{ display: 'block', width: 550, padding: 30 }}> <h5>ReactJS Reactstrap Navbar Component</h5> <Navbar color="light" light expand="md"> <NavbarBrand href="/">Brand</NavbarBrand> <NavbarToggler onClick={() => { setIsOpen(!isOpen) }} /> <Collapse isOpen={isOpen} navbar> <Nav className="mr-auto" navbar> <NavItem> <NavLink href="#">Home</NavLink> </NavItem> <NavItem> <NavLink href="#">Login</NavLink> </NavItem> <NavItem> <NavLink href="#">Signup</NavLink> </NavItem> </Nav> </Collapse> </Navbar> </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:
Example 2: Now write down the following code in the App.js file. Here, we have shown the Navbar component without the expand property.
Javascript
import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Navbar, NavItem, NavbarToggler, Collapse, NavLink, Nav, NavbarBrand} from 'reactstrap'; function App() { // Collapse isOpen State const [isOpen, setIsOpen] = React.useState(false); return ( <div style={{ display: 'block', width: 550, padding: 30 }}> <h5>ReactJS Reactstrap Navbar Component</h5> <Navbar color="light" light > <NavbarBrand href="/">Brand</NavbarBrand> <NavbarToggler onClick={() => { setIsOpen(!isOpen) }} /> <Collapse isOpen={isOpen} navbar> <Nav className="mr-auto" navbar> <NavItem> <NavLink href="#">Home</NavLink> </NavItem> <NavItem> <NavLink href="#">Login</NavLink> </NavItem> </Nav> </Collapse> </Navbar> </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:
Reference: https://reactstrap.github.io/components/navbar/
sumitgumber28
Reactstrap
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 395,
"s": 28,
"text": "Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Navbar component provides a way for users to provide them navigation controls at the top of an application. We can use the following approach in ReactJS to use the ReactJS Reactstrap Navbar Component."
},
{
"code": null,
"e": 409,
"s": 395,
"text": "Navbar Props:"
},
{
"code": null,
"e": 492,
"s": 409,
"text": "light: It is used to indicate whether to apply the light color class to it or not."
},
{
"code": null,
"e": 573,
"s": 492,
"text": "dark: It is used to indicate whether to apply the dark color class to it or not."
},
{
"code": null,
"e": 652,
"s": 573,
"text": "fixed: It is used to indicate whether to apply position fixed property or not."
},
{
"code": null,
"e": 710,
"s": 652,
"text": "color: It is used to denote the color for this component."
},
{
"code": null,
"e": 785,
"s": 710,
"text": "role: It is used to denote the value for role property for this component."
},
{
"code": null,
"e": 858,
"s": 785,
"text": "expand: It is used to indicate whether to expand Navbar on click or not."
},
{
"code": null,
"e": 909,
"s": 858,
"text": "tag: It is used to pass in custom elements to use."
},
{
"code": null,
"e": 928,
"s": 909,
"text": "NavbarBrand Props:"
},
{
"code": null,
"e": 979,
"s": 928,
"text": "tag: It is used to pass in custom elements to use."
},
{
"code": null,
"e": 997,
"s": 979,
"text": "NavbarText Props:"
},
{
"code": null,
"e": 1048,
"s": 997,
"text": "tag: It is used to pass in custom elements to use."
},
{
"code": null,
"e": 1070,
"s": 1050,
"text": "NavbarTogglerProps:"
},
{
"code": null,
"e": 1126,
"s": 1070,
"text": "type: It is used to denote the type for this component."
},
{
"code": null,
"e": 1177,
"s": 1126,
"text": "tag: It is used to pass in custom elements to use."
},
{
"code": null,
"e": 1227,
"s": 1177,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 1291,
"s": 1227,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 1323,
"s": 1291,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 1423,
"s": 1323,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 1437,
"s": 1423,
"text": "cd foldername"
},
{
"code": null,
"e": 1542,
"s": 1437,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 1575,
"s": 1542,
"text": "npm install reactstrap bootstrap"
},
{
"code": null,
"e": 1627,
"s": 1575,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 1645,
"s": 1627,
"text": "Project Structure"
},
{
"code": null,
"e": 1779,
"s": 1647,
"text": "Example 1: Now write down the following code in the App.js file. Here, we have shown the Navbar component with the expand property."
},
{
"code": null,
"e": 1790,
"s": 1779,
"text": "Javascript"
},
{
"code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Navbar, NavItem, NavbarToggler, Collapse, NavLink, Nav, NavbarBrand} from 'reactstrap'; function App() { // Collapse isOpen State const [isOpen, setIsOpen] = React.useState(false); return ( <div style={{ display: 'block', width: 550, padding: 30 }}> <h5>ReactJS Reactstrap Navbar Component</h5> <Navbar color=\"light\" light expand=\"md\"> <NavbarBrand href=\"/\">Brand</NavbarBrand> <NavbarToggler onClick={() => { setIsOpen(!isOpen) }} /> <Collapse isOpen={isOpen} navbar> <Nav className=\"mr-auto\" navbar> <NavItem> <NavLink href=\"#\">Home</NavLink> </NavItem> <NavItem> <NavLink href=\"#\">Login</NavLink> </NavItem> <NavItem> <NavLink href=\"#\">Signup</NavLink> </NavItem> </Nav> </Collapse> </Navbar> </div > );} export default App;",
"e": 3019,
"s": 1790,
"text": null
},
{
"code": null,
"e": 3132,
"s": 3019,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 3142,
"s": 3132,
"text": "npm start"
},
{
"code": null,
"e": 3241,
"s": 3142,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 3376,
"s": 3241,
"text": "Example 2: Now write down the following code in the App.js file. Here, we have shown the Navbar component without the expand property."
},
{
"code": null,
"e": 3387,
"s": 3376,
"text": "Javascript"
},
{
"code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Navbar, NavItem, NavbarToggler, Collapse, NavLink, Nav, NavbarBrand} from 'reactstrap'; function App() { // Collapse isOpen State const [isOpen, setIsOpen] = React.useState(false); return ( <div style={{ display: 'block', width: 550, padding: 30 }}> <h5>ReactJS Reactstrap Navbar Component</h5> <Navbar color=\"light\" light > <NavbarBrand href=\"/\">Brand</NavbarBrand> <NavbarToggler onClick={() => { setIsOpen(!isOpen) }} /> <Collapse isOpen={isOpen} navbar> <Nav className=\"mr-auto\" navbar> <NavItem> <NavLink href=\"#\">Home</NavLink> </NavItem> <NavItem> <NavLink href=\"#\">Login</NavLink> </NavItem> </Nav> </Collapse> </Navbar> </div > );} export default App;",
"e": 4476,
"s": 3387,
"text": null
},
{
"code": null,
"e": 4589,
"s": 4476,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 4599,
"s": 4589,
"text": "npm start"
},
{
"code": null,
"e": 4698,
"s": 4599,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 4757,
"s": 4698,
"text": "Reference: https://reactstrap.github.io/components/navbar/"
},
{
"code": null,
"e": 4771,
"s": 4757,
"text": "sumitgumber28"
},
{
"code": null,
"e": 4782,
"s": 4771,
"text": "Reactstrap"
},
{
"code": null,
"e": 4793,
"s": 4782,
"text": "JavaScript"
},
{
"code": null,
"e": 4801,
"s": 4793,
"text": "ReactJS"
},
{
"code": null,
"e": 4818,
"s": 4801,
"text": "Web Technologies"
}
] |
Maximum Rectangular Area in a Histogram | Practice | GeeksforGeeks
|
Find the largest rectangular area possible in a given histogram where the largest rectangle can be made of a number of contiguous bars. For simplicity, assume that all bars have the same width and the width is 1 unit, there will be N bars height of each bar will be given by the array arr.
Example 1:
Input:
N = 7
arr[] = {6,2,5,4,5,1,6}
Output: 12
Explanation:
Example 2:
Input:
N = 8
arr[] = {7 2 8 9 1 3 6 5}
Output: 16
Explanation: Maximum size of the histogram
will be 8 and there will be 2 consecutive
histogram. And hence the area of the
histogram will be 8x2 = 16.
Your Task:
The task is to complete the function getMaxArea() which takes the array arr[] and its size N as inputs and finds the largest rectangular area possible and returns the answer.
Expected Time Complxity : O(N)
Expected Auxilliary Space : O(N)
Constraints:
1 ≤ N ≤ 106
1 ≤ arr[i] ≤ 1012
0
coder_dhanush51 minutes ago
easy cpp solution u tube anuj bhaiya
vector<long long> lst(long long arr[],int n) { stack<int>s; vector<long long>v; for(int i=0;i<n;i++) { while(!s.empty() && arr[s.top()] >= arr[i]) { s.pop(); } if(s.empty()) { v.push_back(-1); } else{ v.push_back(s.top()); } s.push(i); } return v; } vector<long long> rst(long long arr[],int n) { stack<int>s; vector<long long>v; for(int i=n-1;i>=0;i--) { while(!s.empty() && arr[s.top()] >= arr[i]) { s.pop(); } if(s.empty()) { v.push_back(n); } else{ v.push_back(s.top()); } s.push(i); } reverse(v.begin(),v.end()); return v; } long long getMaxArea(long long arr[], int n) { long long mxsum=0; vector<long long> ls= lst(arr,n); vector<long long> rs=rst(arr,n); for(int i=0;i<n;i++) { long long curr=(rs[i]-ls[i]-1)*arr[i]; mxsum=max(curr,mxsum); } return mxsum; }};
video se smjh jaoge simply
0
abhishekvicky123452 days ago
/*Java Solution*/
class Solution{ public static long getMaxArea(long nums[], long n) { Stack<Integer> hs=new Stack<>(); long[] left=new long[nums.length]; for(int i=0;i<nums.length;i++) { while(!hs.empty() && nums[hs.peek()]>=nums[i]) hs.pop(); if(hs.empty())left[i]=0; else left[i]=hs.peek()+1; hs.push(i); } while(!hs.empty())hs.pop(); long[] right=new long[nums.length]; for(int i=nums.length-1;i>=0;i--) { while(!hs.empty() && nums[hs.peek()]>=nums[i]) hs.pop(); if(hs.empty())right[i]=nums.length-1; else right[i]=hs.peek()-1; hs.push(i); } long max=-10000000000L; for(int i=0;i<nums.length;i++) { max=Math.max(max,(right[i]-left[i]+1)*nums[i]); } return max; } }
0
debayanbiswas313 days ago
long long getMaxArea(long long arr[], int n)
{
// Your code here
stack<int>st;
vector<int>left(n);
vector<int>right(n);
for(int i=0;i<n;i++)
{
while(st.size()!=0 && arr[i]<=arr[st.top()])
{
st.pop();
}
left[i]= st.size()!=0?st.top()+1:0;
st.push(i);
}
while(st.size()!=0) st.pop();
for(int i=n-1;i>=0;i--)
{
while(st.size()!=0 && arr[i]<=arr[st.top()])
{
st.pop();
}
right[i]=st.size()!=0?st.top()-1:n-1;
st.push(i);
}
long long mx=0;
for(int i=0;i<n;i++)
{
long long curr_area=(right[i]-left[i]+1)*arr[i];
mx=max(mx,curr_area);
}
return mx;
}
0
akkeshri140420011 week ago
long long getMaxArea(long long arr[], int n)
{
// Your code here
vector<long long>left(n),right(n);
stack<long long>stk;
for(int i=0;i<n;i++)
{
while(!stk.empty() and arr[i]<=arr[stk.top()]){
stk.pop();
}
if(stk.empty()){
left[i]=0;
}
else{
left[i]=stk.top()+1;
}
stk.push(i);
}
while(!stk.empty()){
stk.pop();
}
for(int i=n-1;i>=0;i--){
while(!stk.empty() and arr[i]<=arr[stk.top()]){
stk.pop();
}
if(stk.empty()){
right[i]=n-1;
}
else{
right[i]=stk.top()-1;
}
stk.push(i);
}
long long maxi=0;
for(int i=0;i<n;i++){
maxi=max(maxi,(right[i]-left[i]+1)*arr[i]);
}
return maxi;
}
0
ujjwalraj8220011 week ago
JAVA Solution using Stack
class Solution{ //Function to find largest rectangular area possible in a given histogram. public static long getMaxArea(long hist[], long n) { // your code here int size = hist.length; long[] left = nsl(hist, size); long[] right = nsr(hist, size); long[] width = new long[size]; long[] area = new long[size]; for(int i = 0; i<size; i++) { width[i] = right[i] - left[i] -1; area[i] = (width[i] * hist[i]); } long max = area[0]; for(int i = 1; i<size; i++) { if(area[i] > max) { max = area[i]; } } return max; } //Function to find nearest smaller element to left public static long[] nsl(long[] hist, int n) { long[] index = new long[n]; Stack<long[]> s = new Stack<>(); for(int i = 0; i<n; i++) { if(s.isEmpty()) { index[i] = -1; } else if(!s.isEmpty() && s.peek()[0] >= hist[i]) { while(!s.isEmpty() && s.peek()[0] >= hist[i]) { s.pop(); } if(s.isEmpty()) { index[i] = -1; } else{ index[i] = s.peek()[1]; } } else{ index[i] = s.peek()[1]; } s.push(new long[] {hist[i], i}); } return index; } //Function to find nearest smaller element to right public static long[] nsr(long[] hist, int n) { long[] index = new long[n]; Stack<long[]> s = new Stack<>(); for(int i = n-1; i>=0; i--) { if(s.isEmpty()) { index[i] = n; } else if(s.peek()[0] >= hist[i]) { while(!s.isEmpty() && s.peek()[0]>= hist[i]) { s.pop(); } if(s.isEmpty()) { index[i] = n; } else { index[i] = s.peek()[1]; } } else { index[i] = s.peek()[1]; } s.push(new long[] {hist[i], i}); } return index; }}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints.
|
[
{
"code": null,
"e": 528,
"s": 238,
"text": "Find the largest rectangular area possible in a given histogram where the largest rectangle can be made of a number of contiguous bars. For simplicity, assume that all bars have the same width and the width is 1 unit, there will be N bars height of each bar will be given by the array arr."
},
{
"code": null,
"e": 539,
"s": 528,
"text": "Example 1:"
},
{
"code": null,
"e": 604,
"s": 539,
"text": "Input:\nN = 7\narr[] = {6,2,5,4,5,1,6}\nOutput: 12\nExplanation: \n\n\n"
},
{
"code": null,
"e": 615,
"s": 604,
"text": "Example 2:"
},
{
"code": null,
"e": 819,
"s": 615,
"text": "Input:\nN = 8\narr[] = {7 2 8 9 1 3 6 5}\nOutput: 16\nExplanation: Maximum size of the histogram \nwill be 8 and there will be 2 consecutive \nhistogram. And hence the area of the \nhistogram will be 8x2 = 16."
},
{
"code": null,
"e": 1005,
"s": 819,
"text": "Your Task:\nThe task is to complete the function getMaxArea() which takes the array arr[] and its size N as inputs and finds the largest rectangular area possible and returns the answer."
},
{
"code": null,
"e": 1069,
"s": 1005,
"text": "Expected Time Complxity : O(N)\nExpected Auxilliary Space : O(N)"
},
{
"code": null,
"e": 1112,
"s": 1069,
"text": "Constraints:\n1 ≤ N ≤ 106\n1 ≤ arr[i] ≤ 1012"
},
{
"code": null,
"e": 1114,
"s": 1112,
"text": "0"
},
{
"code": null,
"e": 1142,
"s": 1114,
"text": "coder_dhanush51 minutes ago"
},
{
"code": null,
"e": 1180,
"s": 1142,
"text": "easy cpp solution u tube anuj bhaiya "
},
{
"code": null,
"e": 2384,
"s": 1180,
"text": " vector<long long> lst(long long arr[],int n) { stack<int>s; vector<long long>v; for(int i=0;i<n;i++) { while(!s.empty() && arr[s.top()] >= arr[i]) { s.pop(); } if(s.empty()) { v.push_back(-1); } else{ v.push_back(s.top()); } s.push(i); } return v; } vector<long long> rst(long long arr[],int n) { stack<int>s; vector<long long>v; for(int i=n-1;i>=0;i--) { while(!s.empty() && arr[s.top()] >= arr[i]) { s.pop(); } if(s.empty()) { v.push_back(n); } else{ v.push_back(s.top()); } s.push(i); } reverse(v.begin(),v.end()); return v; } long long getMaxArea(long long arr[], int n) { long long mxsum=0; vector<long long> ls= lst(arr,n); vector<long long> rs=rst(arr,n); for(int i=0;i<n;i++) { long long curr=(rs[i]-ls[i]-1)*arr[i]; mxsum=max(curr,mxsum); } return mxsum; }}; "
},
{
"code": null,
"e": 2411,
"s": 2384,
"text": "video se smjh jaoge simply"
},
{
"code": null,
"e": 2413,
"s": 2411,
"text": "0"
},
{
"code": null,
"e": 2442,
"s": 2413,
"text": "abhishekvicky123452 days ago"
},
{
"code": null,
"e": 2460,
"s": 2442,
"text": "/*Java Solution*/"
},
{
"code": null,
"e": 3311,
"s": 2460,
"text": "class Solution{ public static long getMaxArea(long nums[], long n) { Stack<Integer> hs=new Stack<>(); long[] left=new long[nums.length]; for(int i=0;i<nums.length;i++) { while(!hs.empty() && nums[hs.peek()]>=nums[i]) hs.pop(); if(hs.empty())left[i]=0; else left[i]=hs.peek()+1; hs.push(i); } while(!hs.empty())hs.pop(); long[] right=new long[nums.length]; for(int i=nums.length-1;i>=0;i--) { while(!hs.empty() && nums[hs.peek()]>=nums[i]) hs.pop(); if(hs.empty())right[i]=nums.length-1; else right[i]=hs.peek()-1; hs.push(i); } long max=-10000000000L; for(int i=0;i<nums.length;i++) { max=Math.max(max,(right[i]-left[i]+1)*nums[i]); } return max; } }"
},
{
"code": null,
"e": 3321,
"s": 3319,
"text": "0"
},
{
"code": null,
"e": 3347,
"s": 3321,
"text": "debayanbiswas313 days ago"
},
{
"code": null,
"e": 4300,
"s": 3347,
"text": "long long getMaxArea(long long arr[], int n)\n {\n // Your code here\n stack<int>st;\n vector<int>left(n);\n vector<int>right(n);\n \n \n for(int i=0;i<n;i++)\n {\n while(st.size()!=0 && arr[i]<=arr[st.top()])\n {\n st.pop();\n }\n left[i]= st.size()!=0?st.top()+1:0;\n st.push(i);\n \n }\n \n while(st.size()!=0) st.pop();\n \n for(int i=n-1;i>=0;i--)\n {\n while(st.size()!=0 && arr[i]<=arr[st.top()])\n {\n st.pop();\n }\n \n right[i]=st.size()!=0?st.top()-1:n-1;\n st.push(i);\n }\n long long mx=0;\n for(int i=0;i<n;i++)\n {\n \n long long curr_area=(right[i]-left[i]+1)*arr[i];\n \n mx=max(mx,curr_area);\n }\n return mx;\n \n }"
},
{
"code": null,
"e": 4302,
"s": 4300,
"text": "0"
},
{
"code": null,
"e": 4329,
"s": 4302,
"text": "akkeshri140420011 week ago"
},
{
"code": null,
"e": 5285,
"s": 4329,
"text": "long long getMaxArea(long long arr[], int n)\n {\n // Your code here\n vector<long long>left(n),right(n);\n stack<long long>stk;\n for(int i=0;i<n;i++)\n {\n while(!stk.empty() and arr[i]<=arr[stk.top()]){\n stk.pop();\n }\n if(stk.empty()){\n left[i]=0;\n }\n else{\n left[i]=stk.top()+1;\n }\n stk.push(i);\n }\n while(!stk.empty()){\n stk.pop();\n }\n for(int i=n-1;i>=0;i--){\n while(!stk.empty() and arr[i]<=arr[stk.top()]){\n stk.pop();\n }\n if(stk.empty()){\n right[i]=n-1;\n }\n else{\n right[i]=stk.top()-1;\n }\n stk.push(i);\n }\n long long maxi=0;\n for(int i=0;i<n;i++){\n maxi=max(maxi,(right[i]-left[i]+1)*arr[i]);\n }\n return maxi;\n \n }"
},
{
"code": null,
"e": 5287,
"s": 5285,
"text": "0"
},
{
"code": null,
"e": 5313,
"s": 5287,
"text": "ujjwalraj8220011 week ago"
},
{
"code": null,
"e": 5340,
"s": 5313,
"text": "JAVA Solution using Stack "
},
{
"code": null,
"e": 7498,
"s": 5342,
"text": "class Solution{ //Function to find largest rectangular area possible in a given histogram. public static long getMaxArea(long hist[], long n) { // your code here int size = hist.length; long[] left = nsl(hist, size); long[] right = nsr(hist, size); long[] width = new long[size]; long[] area = new long[size]; for(int i = 0; i<size; i++) { width[i] = right[i] - left[i] -1; area[i] = (width[i] * hist[i]); } long max = area[0]; for(int i = 1; i<size; i++) { if(area[i] > max) { max = area[i]; } } return max; } //Function to find nearest smaller element to left public static long[] nsl(long[] hist, int n) { long[] index = new long[n]; Stack<long[]> s = new Stack<>(); for(int i = 0; i<n; i++) { if(s.isEmpty()) { index[i] = -1; } else if(!s.isEmpty() && s.peek()[0] >= hist[i]) { while(!s.isEmpty() && s.peek()[0] >= hist[i]) { s.pop(); } if(s.isEmpty()) { index[i] = -1; } else{ index[i] = s.peek()[1]; } } else{ index[i] = s.peek()[1]; } s.push(new long[] {hist[i], i}); } return index; } //Function to find nearest smaller element to right public static long[] nsr(long[] hist, int n) { long[] index = new long[n]; Stack<long[]> s = new Stack<>(); for(int i = n-1; i>=0; i--) { if(s.isEmpty()) { index[i] = n; } else if(s.peek()[0] >= hist[i]) { while(!s.isEmpty() && s.peek()[0]>= hist[i]) { s.pop(); } if(s.isEmpty()) { index[i] = n; } else { index[i] = s.peek()[1]; } } else { index[i] = s.peek()[1]; } s.push(new long[] {hist[i], i}); } return index; }}"
},
{
"code": null,
"e": 7646,
"s": 7500,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 7682,
"s": 7646,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7692,
"s": 7682,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7702,
"s": 7692,
"text": "\nContest\n"
},
{
"code": null,
"e": 7765,
"s": 7702,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7950,
"s": 7765,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 8234,
"s": 7950,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 8380,
"s": 8234,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 8457,
"s": 8380,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 8498,
"s": 8457,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 8526,
"s": 8498,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 8597,
"s": 8526,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 8784,
"s": 8597,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Program for Tower of Hanoi
|
13 Jul, 2022
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
Only one disk can be moved at a time.Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.No disk may be placed on top of a smaller disk.
Only one disk can be moved at a time.
Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
No disk may be placed on top of a smaller disk.
Approach :
Let rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'.
An example with 2 disks :
Step 1 : Shift first disk from 'A' to 'B'.
Step 2 : Shift second disk from 'A' to 'C'.
Step 3 : Shift first disk from 'B' to 'C'.
An example with 3 disks :
Step 1 : Shift first disk from 'A' to 'C'.
Step 2 : Shift second disk from 'A' to 'B'.
Step 3 : Shift first disk from 'C' to 'B'.
Step 4 : Shift third disk from 'A' to 'C'.
Step 5 : Shift first disk from 'B' to 'A'.
Step 6 : Shift second disk from 'B' to 'C'.
Step 7 : Shift first disk from 'A' to 'C'.
(Notice the gaps)
The pattern here is :
- Shift 'n-1' disks from 'A' to 'B', using C.
- Shift last disk from 'A' to 'C'.
- Shift 'n-1' disks from 'B' to 'C', using A.
Image illustration for 3 disks
Examples:
Input : 2
Output : Disk 1 moved from A to B
Disk 2 moved from A to C
Disk 1 moved from B to C
Input : 3
Output : Disk 1 moved from A to C
Disk 2 moved from A to B
Disk 1 moved from C to B
Disk 3 moved from A to C
Disk 1 moved from B to A
Disk 2 moved from B to C
Disk 1 moved from A to C
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// C++ recursive function to // solve tower of hanoi puzzle #include <bits/stdc++.h>using namespace std; void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) { if (n == 0) { return; } towerOfHanoi(n - 1, from_rod, aux_rod, to_rod); cout << "Move disk " << n << " from rod " << from_rod << " to rod " << to_rod << endl; towerOfHanoi(n - 1, aux_rod, to_rod, from_rod); } // Driver codeint main() { int n = 4; // Number of disks towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods return 0; } // This is code is contributed by rathbhupendra
// JAVA recursive function to // solve tower of hanoi puzzle import java.util.*;import java.io.*;import java.math.*;class GFG{static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) { if (n == 0) { return; } towerOfHanoi(n - 1, from_rod, aux_rod, to_rod); System.out.println("Move disk "+ n + " from rod " + from_rod +" to rod " + to_rod ); towerOfHanoi(n - 1, aux_rod, to_rod, from_rod); } // Driver codepublic static void main(String args[]) { int n = 4; // Number of disks towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods } } // This code is contributed by jyoti369
# Recursive Python function to solve tower of hanoi def TowerOfHanoi(n , from_rod, to_rod, aux_rod): if n == 0: return TowerOfHanoi(n-1, from_rod, aux_rod, to_rod) print("Move disk",n,"from rod",from_rod,"to rod",to_rod) TowerOfHanoi(n-1, aux_rod, to_rod, from_rod) # Driver coden = 4TowerOfHanoi(n, 'A', 'C', 'B') # A, C, B are the name of rods # Contributed By Harshit Agrawal
// C# recursive program to solve tower of hanoi puzzleusing System;class GFG{ static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) { if (n == 0) { return; } towerOfHanoi(n-1, from_rod, aux_rod, to_rod); Console.WriteLine("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod); towerOfHanoi(n-1, aux_rod, to_rod, from_rod); } // Driver method public static void Main(String []args) { int n = 4; // Number of disks towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods }} //This code is contributed by shivanisinghss2110
<?php // Tower of Hanoi (n-disk) algorithm in PHP with Display of Pole/rod // Contents the 3 poles representation$poles = array(array(), array(), array()); function TOH($n, $A="A", $B="B", $C="C"){ if ($n > 0){ TOH($n-1, $A, $C, $B); echo "Move disk from rod $A to rod $C \n"; move($A, $C); dispPoles(); TOH($n-1, $B, $A, $C); } else { return; }} function initPoles($n){ global $poles; for ($i=$n; $i>=1; --$i){ $poles[0][] = $i; }} function move($source, $destination){ global $poles; // get source and destination pointers if ($source=="A") $ptr1=0; elseif ($source=="B") $ptr1 = 1; else $ptr1 = 2; if ($destination=="A") $ptr2 = 0; elseif ($destination=="B") $ptr2 = 1; else $ptr2 = 2; $top = array_pop($poles[$ptr1]); array_push($poles[$ptr2], $top);} function dispPoles(){ global $poles; echo "A: [".implode(", ", $poles[0])."] "; echo "B: [".implode(", ", $poles[1])."] "; echo "C: [".implode(", ", $poles[2])."] "; echo "\n\n";} $numdisks = 4;initPoles($numdisks);echo "Tower of Hanoi Solution for $numdisks disks: \n\n";dispPoles();TOH($numdisks); // This code is contributed by ShreyakChakraborty?>
<script>// javascript recursive function to // solve tower of hanoi puzzle function towerOfHanoi(n, from_rod, to_rod, aux_rod){ if (n == 0) { return; } towerOfHanoi(n - 1, from_rod, aux_rod, to_rod); document.write("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod+"<br/>"); towerOfHanoi(n - 1, aux_rod, to_rod, from_rod); } // Driver code var n = 4; // Number of disks towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods // This code is contributed by gauravrajput1</script>
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A
Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Move disk 4 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 2 from rod B to rod A
Move disk 1 from rod C to rod A
Move disk 3 from rod B to rod C
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Time complexity: O(2^n)Space complexity: O(n)
Related Articles
Recursive Functions
Iterative solution to TOH puzzle
Quiz on Recursion
vaibhav29498
Rustam Ali
NipunPruthi
rathbhupendra
ShreyakChakraborty
himanshukanojiya
shivanisinghss2110
jyoti369
GauravRajput1
atulpandey10
kushsharma1001
anonrobinhood007
technophpfij
hardikkoriintern
Divide and Conquer
Recursion
School Programming
Stack
Recursion
Divide and Conquer
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jul, 2022"
},
{
"code": null,
"e": 241,
"s": 54,
"text": "Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: "
},
{
"code": null,
"e": 501,
"s": 241,
"text": "Only one disk can be moved at a time.Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.No disk may be placed on top of a smaller disk."
},
{
"code": null,
"e": 539,
"s": 501,
"text": "Only one disk can be moved at a time."
},
{
"code": null,
"e": 715,
"s": 539,
"text": "Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack."
},
{
"code": null,
"e": 763,
"s": 715,
"text": "No disk may be placed on top of a smaller disk."
},
{
"code": null,
"e": 775,
"s": 763,
"text": "Approach : "
},
{
"code": null,
"e": 976,
"s": 775,
"text": "Let rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'.\nAn example with 2 disks :\nStep 1 : Shift first disk from 'A' to 'B'.\n\nStep 2 : Shift second disk from 'A' to 'C'.\n\nStep 3 : Shift first disk from 'B' to 'C'."
},
{
"code": null,
"e": 1325,
"s": 976,
"text": "An example with 3 disks :\nStep 1 : Shift first disk from 'A' to 'C'.\nStep 2 : Shift second disk from 'A' to 'B'.\nStep 3 : Shift first disk from 'C' to 'B'.\n\nStep 4 : Shift third disk from 'A' to 'C'.\n\nStep 5 : Shift first disk from 'B' to 'A'.\nStep 6 : Shift second disk from 'B' to 'C'.\nStep 7 : Shift first disk from 'A' to 'C'.\n(Notice the gaps)"
},
{
"code": null,
"e": 1477,
"s": 1325,
"text": "The pattern here is :\n - Shift 'n-1' disks from 'A' to 'B', using C.\n - Shift last disk from 'A' to 'C'.\n - Shift 'n-1' disks from 'B' to 'C', using A."
},
{
"code": null,
"e": 1508,
"s": 1477,
"text": "Image illustration for 3 disks"
},
{
"code": null,
"e": 1519,
"s": 1508,
"text": "Examples: "
},
{
"code": null,
"e": 1880,
"s": 1519,
"text": "Input : 2\nOutput : Disk 1 moved from A to B\n Disk 2 moved from A to C\n Disk 1 moved from B to C\n\nInput : 3\nOutput : Disk 1 moved from A to C\n Disk 2 moved from A to B\n Disk 1 moved from C to B\n Disk 3 moved from A to C\n Disk 1 moved from B to A\n Disk 2 moved from B to C\n Disk 1 moved from A to C"
},
{
"code": null,
"e": 1896,
"s": 1880,
"text": "Implementation:"
},
{
"code": null,
"e": 1900,
"s": 1896,
"text": "C++"
},
{
"code": null,
"e": 1905,
"s": 1900,
"text": "Java"
},
{
"code": null,
"e": 1913,
"s": 1905,
"text": "Python3"
},
{
"code": null,
"e": 1916,
"s": 1913,
"text": "C#"
},
{
"code": null,
"e": 1920,
"s": 1916,
"text": "PHP"
},
{
"code": null,
"e": 1931,
"s": 1920,
"text": "Javascript"
},
{
"code": "// C++ recursive function to // solve tower of hanoi puzzle #include <bits/stdc++.h>using namespace std; void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) { if (n == 0) { return; } towerOfHanoi(n - 1, from_rod, aux_rod, to_rod); cout << \"Move disk \" << n << \" from rod \" << from_rod << \" to rod \" << to_rod << endl; towerOfHanoi(n - 1, aux_rod, to_rod, from_rod); } // Driver codeint main() { int n = 4; // Number of disks towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods return 0; } // This is code is contributed by rathbhupendra",
"e": 2593,
"s": 1931,
"text": null
},
{
"code": "// JAVA recursive function to // solve tower of hanoi puzzle import java.util.*;import java.io.*;import java.math.*;class GFG{static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) { if (n == 0) { return; } towerOfHanoi(n - 1, from_rod, aux_rod, to_rod); System.out.println(\"Move disk \"+ n + \" from rod \" + from_rod +\" to rod \" + to_rod ); towerOfHanoi(n - 1, aux_rod, to_rod, from_rod); } // Driver codepublic static void main(String args[]) { int n = 4; // Number of disks towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods } } // This code is contributed by jyoti369",
"e": 3280,
"s": 2593,
"text": null
},
{
"code": "# Recursive Python function to solve tower of hanoi def TowerOfHanoi(n , from_rod, to_rod, aux_rod): if n == 0: return TowerOfHanoi(n-1, from_rod, aux_rod, to_rod) print(\"Move disk\",n,\"from rod\",from_rod,\"to rod\",to_rod) TowerOfHanoi(n-1, aux_rod, to_rod, from_rod) # Driver coden = 4TowerOfHanoi(n, 'A', 'C', 'B') # A, C, B are the name of rods # Contributed By Harshit Agrawal",
"e": 3689,
"s": 3280,
"text": null
},
{
"code": "// C# recursive program to solve tower of hanoi puzzleusing System;class GFG{ static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) { if (n == 0) { return; } towerOfHanoi(n-1, from_rod, aux_rod, to_rod); Console.WriteLine(\"Move disk \" + n + \" from rod \" + from_rod + \" to rod \" + to_rod); towerOfHanoi(n-1, aux_rod, to_rod, from_rod); } // Driver method public static void Main(String []args) { int n = 4; // Number of disks towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods }} //This code is contributed by shivanisinghss2110",
"e": 4374,
"s": 3689,
"text": null
},
{
"code": "<?php // Tower of Hanoi (n-disk) algorithm in PHP with Display of Pole/rod // Contents the 3 poles representation$poles = array(array(), array(), array()); function TOH($n, $A=\"A\", $B=\"B\", $C=\"C\"){ if ($n > 0){ TOH($n-1, $A, $C, $B); echo \"Move disk from rod $A to rod $C \\n\"; move($A, $C); dispPoles(); TOH($n-1, $B, $A, $C); } else { return; }} function initPoles($n){ global $poles; for ($i=$n; $i>=1; --$i){ $poles[0][] = $i; }} function move($source, $destination){ global $poles; // get source and destination pointers if ($source==\"A\") $ptr1=0; elseif ($source==\"B\") $ptr1 = 1; else $ptr1 = 2; if ($destination==\"A\") $ptr2 = 0; elseif ($destination==\"B\") $ptr2 = 1; else $ptr2 = 2; $top = array_pop($poles[$ptr1]); array_push($poles[$ptr2], $top);} function dispPoles(){ global $poles; echo \"A: [\".implode(\", \", $poles[0]).\"] \"; echo \"B: [\".implode(\", \", $poles[1]).\"] \"; echo \"C: [\".implode(\", \", $poles[2]).\"] \"; echo \"\\n\\n\";} $numdisks = 4;initPoles($numdisks);echo \"Tower of Hanoi Solution for $numdisks disks: \\n\\n\";dispPoles();TOH($numdisks); // This code is contributed by ShreyakChakraborty?>",
"e": 5634,
"s": 4374,
"text": null
},
{
"code": "<script>// javascript recursive function to // solve tower of hanoi puzzle function towerOfHanoi(n, from_rod, to_rod, aux_rod){ if (n == 0) { return; } towerOfHanoi(n - 1, from_rod, aux_rod, to_rod); document.write(\"Move disk \" + n + \" from rod \" + from_rod + \" to rod \" + to_rod+\"<br/>\"); towerOfHanoi(n - 1, aux_rod, to_rod, from_rod); } // Driver code var n = 4; // Number of disks towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods // This code is contributed by gauravrajput1</script>",
"e": 6214,
"s": 5634,
"text": null
},
{
"code": null,
"e": 6694,
"s": 6214,
"text": "Move disk 1 from rod A to rod B\nMove disk 2 from rod A to rod C\nMove disk 1 from rod B to rod C\nMove disk 3 from rod A to rod B\nMove disk 1 from rod C to rod A\nMove disk 2 from rod C to rod B\nMove disk 1 from rod A to rod B\nMove disk 4 from rod A to rod C\nMove disk 1 from rod B to rod C\nMove disk 2 from rod B to rod A\nMove disk 1 from rod C to rod A\nMove disk 3 from rod B to rod C\nMove disk 1 from rod A to rod B\nMove disk 2 from rod A to rod C\nMove disk 1 from rod B to rod C"
},
{
"code": null,
"e": 6740,
"s": 6694,
"text": "Time complexity: O(2^n)Space complexity: O(n)"
},
{
"code": null,
"e": 6758,
"s": 6740,
"text": "Related Articles "
},
{
"code": null,
"e": 6778,
"s": 6758,
"text": "Recursive Functions"
},
{
"code": null,
"e": 6811,
"s": 6778,
"text": "Iterative solution to TOH puzzle"
},
{
"code": null,
"e": 6829,
"s": 6811,
"text": "Quiz on Recursion"
},
{
"code": null,
"e": 6842,
"s": 6829,
"text": "vaibhav29498"
},
{
"code": null,
"e": 6853,
"s": 6842,
"text": "Rustam Ali"
},
{
"code": null,
"e": 6865,
"s": 6853,
"text": "NipunPruthi"
},
{
"code": null,
"e": 6879,
"s": 6865,
"text": "rathbhupendra"
},
{
"code": null,
"e": 6898,
"s": 6879,
"text": "ShreyakChakraborty"
},
{
"code": null,
"e": 6915,
"s": 6898,
"text": "himanshukanojiya"
},
{
"code": null,
"e": 6934,
"s": 6915,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 6943,
"s": 6934,
"text": "jyoti369"
},
{
"code": null,
"e": 6957,
"s": 6943,
"text": "GauravRajput1"
},
{
"code": null,
"e": 6970,
"s": 6957,
"text": "atulpandey10"
},
{
"code": null,
"e": 6985,
"s": 6970,
"text": "kushsharma1001"
},
{
"code": null,
"e": 7002,
"s": 6985,
"text": "anonrobinhood007"
},
{
"code": null,
"e": 7015,
"s": 7002,
"text": "technophpfij"
},
{
"code": null,
"e": 7032,
"s": 7015,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 7051,
"s": 7032,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 7061,
"s": 7051,
"text": "Recursion"
},
{
"code": null,
"e": 7080,
"s": 7061,
"text": "School Programming"
},
{
"code": null,
"e": 7086,
"s": 7080,
"text": "Stack"
},
{
"code": null,
"e": 7096,
"s": 7086,
"text": "Recursion"
},
{
"code": null,
"e": 7115,
"s": 7096,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 7121,
"s": 7115,
"text": "Stack"
}
] |
Number of subarrays having product less than K
|
22 Jul, 2021
Given an array of positive numbers, calculate the number of possible contiguous subarrays having product lesser than a given number K.
Examples :
Input : arr[] = [1, 2, 3, 4]
K = 10
Output : 7
The subarrays are {1}, {2}, {3}, {4}
{1, 2}, {1, 2, 3} and {2, 3}
Input : arr[] = [1, 9, 2, 8, 6, 4, 3]
K = 100
Output : 16
Input : arr[] = [10, 5, 2, 6]
K = 100
Output : 8
One naive approach to this problem is to generate all subarrays of the array and then count the number of arrays having product less than K. Below is the implementation of the above approach :
C++
Java
Python3
C#
PHP
Javascript
// CPP program to count subarrays having// product less than k.#include <iostream>using namespace std; int countsubarray(int array[], int n, int k){ int count = 0; int i, j, mul; for (i = 0; i < n; i++) { // Counter for single element if (array[i] < k) count++; mul = array[i]; for (j = i + 1; j < n; j++) { // Multiple subarray mul = mul * array[j]; // If this multiple is less // than k, then increment if (mul < k) count++; else break; } } return count;} // Driver Codeint main(){ int array[] = { 1, 2, 3, 4 }; int k = 10; int size = sizeof(array) / sizeof(array[0]); int count = countsubarray(array, size, k); cout << count << "\n";} // This code is contributed by 'Dev Agarwal'.
// Java program to count subarrays// having product less than k.class GFG { static int countsubarray(int array[], int n, int k) { int count = 0; int i, j, mul; for (i = 0; i < n; i++) { // Counter for single element if (array[i] < k) count++; mul = array[i]; for (j = i + 1; j < n; j++) { // Multiple subarray mul = mul * array[j]; // If this multiple is less // than k, then increment if (mul < k) count++; else break; } } return count; } // Driver Code public static void main(String args[]) { int array[] = { 1, 2, 3, 4 }; int k = 10; int size = array.length; int count = countsubarray(array, size, k); System.out.print(count); }} // This code is contributed by Sam007
# Python3 program to count subarrays# having product less than k. def countsubarray(array, n, k): count = 0 for i in range(0, n): # Counter for single element if array[i] < k: count += 1 mul = array[i] for j in range(i + 1, n): # Multiple subarray mul = mul * array[j] # If this multiple is less # than k, then increment if mul < k: count += 1 else: break return count # Driver Codearray = [1, 2, 3, 4]k = 10size = len(array)count = countsubarray(array, size, k)print(count, end=" ") # This code is contributed by Shreyanshi Arun.
// C# program to count subarrays having// product less than k.using System; public class GFG { static int countsubarray(int[] array, int n, int k) { int count = 0; int i, j, mul; for (i = 0; i < n; i++) { // Counter for single element if (array[i] < k) count++; mul = array[i]; for (j = i + 1; j < n; j++) { // Multiple subarray mul = mul * array[j]; // If this multiple is less // than k, then increment if (mul < k) count++; else break; } } return count; } // Driver Code static public void Main() { int[] array = { 1, 2, 3, 4 }; int k = 10; int size = array.Length; int count = countsubarray(array, size, k); Console.WriteLine(count); }} // This code is contributed by vt_m.
<?php// PHP program to count subarrays// having product less than k. // function that returns countfunction countsubarray($array, $n, $k){ $count = 0; for ($i = 0; $i < $n; $i++) { // Counter for single element if ($array[$i] < $k) $count++; $mul = $array[$i]; for ($j = $i + 1; $j < $n; $j++) { // Multiple subarray $mul = $mul * $array[$j]; // If this multiple is less // than k, then increment if ($mul < $k) $count++; else break; } } return $count;} // Driver Code$array = array(1, 2, 3, 4);$k = 10;$size = sizeof($array);$count = countsubarray($array, $size, $k);echo($count . "\n"); // This code is contributed by Ajit.?>
<script>// javascript program to count subarrays// having product less than k. function countsubarray(array , n , k) { var count = 0; var i, j, mul; for (i = 0; i < n; i++) { // Counter for single element if (array[i] < k) count++; mul = array[i]; for (j = i + 1; j < n; j++) { // Multiple subarray mul = mul * array[j]; // If this multiple is less // than k, then increment if (mul < k) count++; else break; } } return count; } // Driver Code var array = [ 1, 2, 3, 4 ]; var k = 10; var size = array.length; var count = countsubarray(array, size, k); document.write(count); // This code is contributed by todaysgaurav</script>
7
Time complexity : O(n^2).
We can optimized approach is based on sliding window technique (Note that we need to find contiguous parts)Firstly, according to the description, all elements in the array are strictly positive. Also let’s assume that the product of all array elements always fits in 64-bit integer type. Taking these two points into consideration, we are able to multiply and divide array’s elements safety (no division by zero, no overflows).
Let’s see how to count the desired amount. Assume, we have a window between start and end, and the product of all elements of it is p < k. Now, let’s try to add a new element x. There are two possible cases.
Case 1. p*x < k This means we can move the window’s right bound one step further. How many contiguous arrays does this step produce? It is: 1 + (end-start).Indeed, the element itself comprises an array, and also we can add x to all contiguous arrays which have right border at end. There are as many such arrays as the length of the window.
Case 2. p*x >= kThis means we must first adjust the window’s left border so that the product is again less than k. After that, we can apply the formula from Case 1.
Example :
a = [5, 3, 2]
k = 16
counter = 0
Window: [5]
Product: 5
5 counter += 1+ (0-0)
counter = 1
Window: [5,3]
Product: 15
15 counter += 1 + (1-0)
counter = 3
Window: [5,3,2]
Product: 30
30 > 16 --> Adjust the left border
New Window: [3,2]
New Product: 6
6 counter += 1 + (2-1)
counter = 5
Answer: 5
C++
Java
Python3
C#
PHP
Javascript
// CPP program to count subarrays having product// less than k.#include <iostream>#include <vector>using namespace std; int countSubArrayProductLessThanK(const vector<int>& a, long long k){ const int n = a.size(); long long p = 1; int res = 0; for (int start = 0, end = 0; end < n; end++) { // Move right bound by 1 step. Update the product. p *= a[end]; // Move left bound so guarantee that p is again // less than k. while (start < end && p >= k) p /= a[start++]; // If p is less than k, update the counter. // Note that this is working even for (start == // end): it means that the previous window cannot // grow anymore and a single array element is the // only addendum. if (p < k) { int len = end - start + 1; res += len; } } return res;} // Driver Codeint main(){ // Function Calls cout << countSubArrayProductLessThanK({ 1, 2, 3, 4 }, 10) << endl; cout << countSubArrayProductLessThanK( { 1, 9, 2, 8, 6, 4, 3 }, 100) << endl; cout << countSubArrayProductLessThanK({ 5, 3, 2 }, 16) << endl; cout << countSubArrayProductLessThanK({ 100, 200 }, 100) << endl; cout << countSubArrayProductLessThanK({ 100, 200 }, 101) << endl;}
// Java program to count subarrays having// product less than k.import java.util.*; class GFG { static int countSubArrayProductLessThanK(ArrayList<Integer> a, long k) { int n = a.size(); long p = 1; int res = 0; for (int start = 0, end = 0; end < n; end++) { // Move right bound by 1 step. // Update the product. p *= a.get(end); // Move left bound so guarantee that // p is again less than k. while (start < end && p >= k) p /= a.get(start++); // If p is less than k, update the counter. // Note that this is working even for // (start == end): it means that the // previous window cannot grow anymore // and a single array element is the only // addendum. if (p < k) { int len = end - start + 1; res += len; } } return res; } // Drive Code public static void main(String[] args) { // Function Calls ArrayList<Integer> al = new ArrayList<Integer>(); al.add(1); al.add(2); al.add(3); al.add(4); System.out.println( countSubArrayProductLessThanK(al, 10)); ArrayList<Integer> al1 = new ArrayList<Integer>(); al1.add(1); al1.add(9); al1.add(2); al1.add(8); al1.add(6); al1.add(4); al1.add(3); System.out.println( countSubArrayProductLessThanK(al1, 100)); ArrayList<Integer> al2 = new ArrayList<Integer>(); al2.add(5); al2.add(3); al2.add(2); System.out.println( countSubArrayProductLessThanK(al2, 16)); ArrayList<Integer> al3 = new ArrayList<Integer>(); al3.add(100); al3.add(200); System.out.println( countSubArrayProductLessThanK(al3, 100)); ArrayList<Integer> al4 = new ArrayList<Integer>(); al4.add(100); al4.add(200); System.out.println( countSubArrayProductLessThanK(al3, 101)); }}// This code is contributed by Prerna Saini
# Python3 program to count# subarrays having product# less than k. def countSubArrayProductLessThanK(a, k): n = len(a) p = 1 res = 0 start = 0 end = 0 while(end < n): # Move right bound by 1 # step. Update the product. p *= a[end] # Move left bound so guarantee # that p is again less than k. while (start < end and p >= k): p = int(p//a[start]) start += 1 # If p is less than k, update # the counter. Note that this # is working even for (start == end): # it means that the previous # window cannot grow anymore # and a single array element # is the only addendum. if (p < k): l = end - start + 1 res += l end += 1 return res # Driver Codeif __name__ == '__main__': print(countSubArrayProductLessThanK([1, 2, 3, 4], 10)) print(countSubArrayProductLessThanK([1, 9, 2, 8, 6, 4, 3], 100)) print(countSubArrayProductLessThanK([5, 3, 2], 16)) print(countSubArrayProductLessThanK([100, 200], 100)) print(countSubArrayProductLessThanK([100, 200], 101)) # This code is contributed by mits
// C# program to count subarrays// having product less than k.using System;using System.Collections; class GFG { static int countSubArrayProductLessThanK(ArrayList a, int k) { int n = a.Count; int p = 1; int res = 0; for (int start = 0, end = 0; end < n; end++) { // Move right bound by 1 step. // Update the product. p *= (int)a[end]; // Move left bound so guarantee // that p is again less than k. while (start < end && p >= k) p /= (int)a[start++]; // If p is less than k, update the // counter. Note that this is working // even for (start == end): it means // that the previous window cannot // grow anymore and a single array // element is the only Addendum. if (p < k) { int len = end - start + 1; res += len; } } return res; } // Driver Code static void Main() { ArrayList al = new ArrayList(); al.Add(1); al.Add(2); al.Add(3); al.Add(4); Console.WriteLine( countSubArrayProductLessThanK(al, 10)); ArrayList al1 = new ArrayList(); al1.Add(1); al1.Add(9); al1.Add(2); al1.Add(8); al1.Add(6); al1.Add(4); al1.Add(3); Console.WriteLine( countSubArrayProductLessThanK(al1, 100)); ArrayList al2 = new ArrayList(); al2.Add(5); al2.Add(3); al2.Add(2); Console.WriteLine( countSubArrayProductLessThanK(al2, 16)); ArrayList al3 = new ArrayList(); al3.Add(100); al3.Add(200); Console.WriteLine( countSubArrayProductLessThanK(al3, 100)); ArrayList al4 = new ArrayList(); al4.Add(100); al4.Add(200); Console.WriteLine( countSubArrayProductLessThanK(al3, 101)); }} // This code is contributed by mits
<?php// PHP program to count// subarrays having product// less than k. function countSubArrayProductLessThanK($a,$k){ $n = count($a); $p = 1; $res = 0; for ($start = 0, $end = 0; $end < $n; $end++) { // Move right bound by 1 // step. Update the product. $p *= $a[$end]; // Move left bound so guarantee // that p is again less than k. while ($start < $end && $p >= $k) $p /= $a[$start++]; // If p is less than k, update // the counter. Note that this // is working even for (start == end): // it means that the previous // window cannot grow anymore // and a single array element // is the only addendum. if ($p < $k) { $len = $end - $start + 1; $res += $len; } } return $res;} // Driver Codeecho countSubArrayProductLessThanK( array(1, 2, 3, 4), 10) . "\n";echo countSubArrayProductLessThanK( array(1, 9, 2, 8, 6, 4, 3), 100) . "\n";echo countSubArrayProductLessThanK( array(5, 3, 2), 16) . "\n";echo countSubArrayProductLessThanK( array(100, 200), 100) . "\n";echo countSubArrayProductLessThanK( array(100, 200), 101) . "\n"; // This code is contributed by mits?>
<script>// js program to count subarrays having product// less than k. function countSubArrayProductLessThanK(a, k){ let n = a.length; let p = 1; let res = 0; for (let start = 0, end = 0; end < n; end++) { // Move right bound by 1 step. Update the product. p *= a[end]; // Move left bound so guarantee that p is again // less than k. while (start < end && p >= k) p =Math.floor(p/ a[start++]); // If p is less than k, update the counter. // Note that this is working even for (start == // end): it means that the previous window cannot // grow anymore and a single array element is the // only addendum. if (p < k) { let len = end - start + 1; res += len; } } return res;} // Driver Code document.write(countSubArrayProductLessThanK([1, 2, 3, 4], 10),'<br>') document.write(countSubArrayProductLessThanK([1, 9, 2, 8, 6, 4, 3], 100),'<br>') document.write(countSubArrayProductLessThanK([5, 3, 2], 16),'<br>') document.write(countSubArrayProductLessThanK([100, 200], 100),'<br>') document.write(countSubArrayProductLessThanK([100, 200], 101),'<br>')</script>
Output :
7
16
5
0
1
Complexities: Every element in the array is accessed at most two times, therefore, it is O(n) time complexity. A few scalar variables are used, therefore, it is O(1) extra space.
Exercise 1: Update the solution so that it could handle nils in the input array. Exercise 2: Update the solution so that it could handle multiplication overflow when computing products.
This article is contributed by Raghav Sharma and improved by Andrey Khayrutdinov. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
jit_t
Sam007
Mithun Kumar
Saurav Sinha 1
Saurabh Vemuri
ManasChhabra2
ojasvishaklya
todaysgaurav
rohitsingh07052
swarnalii
Goldman Sachs
sliding-window
subarray
Arrays
Mathematical
Goldman Sachs
sliding-window
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Linear Search
Introduction to Arrays
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jul, 2021"
},
{
"code": null,
"e": 187,
"s": 52,
"text": "Given an array of positive numbers, calculate the number of possible contiguous subarrays having product lesser than a given number K."
},
{
"code": null,
"e": 199,
"s": 187,
"text": "Examples : "
},
{
"code": null,
"e": 452,
"s": 199,
"text": "Input : arr[] = [1, 2, 3, 4] \n K = 10\nOutput : 7\nThe subarrays are {1}, {2}, {3}, {4}\n{1, 2}, {1, 2, 3} and {2, 3}\n\nInput : arr[] = [1, 9, 2, 8, 6, 4, 3] \n K = 100\nOutput : 16\n\nInput : arr[] = [10, 5, 2, 6] \n K = 100\nOutput : 8"
},
{
"code": null,
"e": 647,
"s": 452,
"text": "One naive approach to this problem is to generate all subarrays of the array and then count the number of arrays having product less than K. Below is the implementation of the above approach : "
},
{
"code": null,
"e": 651,
"s": 647,
"text": "C++"
},
{
"code": null,
"e": 656,
"s": 651,
"text": "Java"
},
{
"code": null,
"e": 664,
"s": 656,
"text": "Python3"
},
{
"code": null,
"e": 667,
"s": 664,
"text": "C#"
},
{
"code": null,
"e": 671,
"s": 667,
"text": "PHP"
},
{
"code": null,
"e": 682,
"s": 671,
"text": "Javascript"
},
{
"code": "// CPP program to count subarrays having// product less than k.#include <iostream>using namespace std; int countsubarray(int array[], int n, int k){ int count = 0; int i, j, mul; for (i = 0; i < n; i++) { // Counter for single element if (array[i] < k) count++; mul = array[i]; for (j = i + 1; j < n; j++) { // Multiple subarray mul = mul * array[j]; // If this multiple is less // than k, then increment if (mul < k) count++; else break; } } return count;} // Driver Codeint main(){ int array[] = { 1, 2, 3, 4 }; int k = 10; int size = sizeof(array) / sizeof(array[0]); int count = countsubarray(array, size, k); cout << count << \"\\n\";} // This code is contributed by 'Dev Agarwal'.",
"e": 1543,
"s": 682,
"text": null
},
{
"code": "// Java program to count subarrays// having product less than k.class GFG { static int countsubarray(int array[], int n, int k) { int count = 0; int i, j, mul; for (i = 0; i < n; i++) { // Counter for single element if (array[i] < k) count++; mul = array[i]; for (j = i + 1; j < n; j++) { // Multiple subarray mul = mul * array[j]; // If this multiple is less // than k, then increment if (mul < k) count++; else break; } } return count; } // Driver Code public static void main(String args[]) { int array[] = { 1, 2, 3, 4 }; int k = 10; int size = array.length; int count = countsubarray(array, size, k); System.out.print(count); }} // This code is contributed by Sam007",
"e": 2513,
"s": 1543,
"text": null
},
{
"code": "# Python3 program to count subarrays# having product less than k. def countsubarray(array, n, k): count = 0 for i in range(0, n): # Counter for single element if array[i] < k: count += 1 mul = array[i] for j in range(i + 1, n): # Multiple subarray mul = mul * array[j] # If this multiple is less # than k, then increment if mul < k: count += 1 else: break return count # Driver Codearray = [1, 2, 3, 4]k = 10size = len(array)count = countsubarray(array, size, k)print(count, end=\" \") # This code is contributed by Shreyanshi Arun.",
"e": 3195,
"s": 2513,
"text": null
},
{
"code": "// C# program to count subarrays having// product less than k.using System; public class GFG { static int countsubarray(int[] array, int n, int k) { int count = 0; int i, j, mul; for (i = 0; i < n; i++) { // Counter for single element if (array[i] < k) count++; mul = array[i]; for (j = i + 1; j < n; j++) { // Multiple subarray mul = mul * array[j]; // If this multiple is less // than k, then increment if (mul < k) count++; else break; } } return count; } // Driver Code static public void Main() { int[] array = { 1, 2, 3, 4 }; int k = 10; int size = array.Length; int count = countsubarray(array, size, k); Console.WriteLine(count); }} // This code is contributed by vt_m.",
"e": 4173,
"s": 3195,
"text": null
},
{
"code": "<?php// PHP program to count subarrays// having product less than k. // function that returns countfunction countsubarray($array, $n, $k){ $count = 0; for ($i = 0; $i < $n; $i++) { // Counter for single element if ($array[$i] < $k) $count++; $mul = $array[$i]; for ($j = $i + 1; $j < $n; $j++) { // Multiple subarray $mul = $mul * $array[$j]; // If this multiple is less // than k, then increment if ($mul < $k) $count++; else break; } } return $count;} // Driver Code$array = array(1, 2, 3, 4);$k = 10;$size = sizeof($array);$count = countsubarray($array, $size, $k);echo($count . \"\\n\"); // This code is contributed by Ajit.?>",
"e": 5005,
"s": 4173,
"text": null
},
{
"code": "<script>// javascript program to count subarrays// having product less than k. function countsubarray(array , n , k) { var count = 0; var i, j, mul; for (i = 0; i < n; i++) { // Counter for single element if (array[i] < k) count++; mul = array[i]; for (j = i + 1; j < n; j++) { // Multiple subarray mul = mul * array[j]; // If this multiple is less // than k, then increment if (mul < k) count++; else break; } } return count; } // Driver Code var array = [ 1, 2, 3, 4 ]; var k = 10; var size = array.length; var count = countsubarray(array, size, k); document.write(count); // This code is contributed by todaysgaurav</script>",
"e": 5944,
"s": 5005,
"text": null
},
{
"code": null,
"e": 5946,
"s": 5944,
"text": "7"
},
{
"code": null,
"e": 5972,
"s": 5946,
"text": "Time complexity : O(n^2)."
},
{
"code": null,
"e": 6400,
"s": 5972,
"text": "We can optimized approach is based on sliding window technique (Note that we need to find contiguous parts)Firstly, according to the description, all elements in the array are strictly positive. Also let’s assume that the product of all array elements always fits in 64-bit integer type. Taking these two points into consideration, we are able to multiply and divide array’s elements safety (no division by zero, no overflows)."
},
{
"code": null,
"e": 6608,
"s": 6400,
"text": "Let’s see how to count the desired amount. Assume, we have a window between start and end, and the product of all elements of it is p < k. Now, let’s try to add a new element x. There are two possible cases."
},
{
"code": null,
"e": 6949,
"s": 6608,
"text": "Case 1. p*x < k This means we can move the window’s right bound one step further. How many contiguous arrays does this step produce? It is: 1 + (end-start).Indeed, the element itself comprises an array, and also we can add x to all contiguous arrays which have right border at end. There are as many such arrays as the length of the window."
},
{
"code": null,
"e": 7114,
"s": 6949,
"text": "Case 2. p*x >= kThis means we must first adjust the window’s left border so that the product is again less than k. After that, we can apply the formula from Case 1."
},
{
"code": null,
"e": 7126,
"s": 7114,
"text": "Example : "
},
{
"code": null,
"e": 7467,
"s": 7126,
"text": " a = [5, 3, 2]\n k = 16\n \n counter = 0\n Window: [5]\n Product: 5\n\n 5 counter += 1+ (0-0)\n counter = 1\n Window: [5,3]\n Product: 15\n\n 15 counter += 1 + (1-0)\n counter = 3\n Window: [5,3,2]\n Product: 30\n\n 30 > 16 --> Adjust the left border\n New Window: [3,2]\n New Product: 6\n\n 6 counter += 1 + (2-1)\n counter = 5\n Answer: 5 "
},
{
"code": null,
"e": 7471,
"s": 7467,
"text": "C++"
},
{
"code": null,
"e": 7476,
"s": 7471,
"text": "Java"
},
{
"code": null,
"e": 7484,
"s": 7476,
"text": "Python3"
},
{
"code": null,
"e": 7487,
"s": 7484,
"text": "C#"
},
{
"code": null,
"e": 7491,
"s": 7487,
"text": "PHP"
},
{
"code": null,
"e": 7502,
"s": 7491,
"text": "Javascript"
},
{
"code": "// CPP program to count subarrays having product// less than k.#include <iostream>#include <vector>using namespace std; int countSubArrayProductLessThanK(const vector<int>& a, long long k){ const int n = a.size(); long long p = 1; int res = 0; for (int start = 0, end = 0; end < n; end++) { // Move right bound by 1 step. Update the product. p *= a[end]; // Move left bound so guarantee that p is again // less than k. while (start < end && p >= k) p /= a[start++]; // If p is less than k, update the counter. // Note that this is working even for (start == // end): it means that the previous window cannot // grow anymore and a single array element is the // only addendum. if (p < k) { int len = end - start + 1; res += len; } } return res;} // Driver Codeint main(){ // Function Calls cout << countSubArrayProductLessThanK({ 1, 2, 3, 4 }, 10) << endl; cout << countSubArrayProductLessThanK( { 1, 9, 2, 8, 6, 4, 3 }, 100) << endl; cout << countSubArrayProductLessThanK({ 5, 3, 2 }, 16) << endl; cout << countSubArrayProductLessThanK({ 100, 200 }, 100) << endl; cout << countSubArrayProductLessThanK({ 100, 200 }, 101) << endl;}",
"e": 8919,
"s": 7502,
"text": null
},
{
"code": "// Java program to count subarrays having// product less than k.import java.util.*; class GFG { static int countSubArrayProductLessThanK(ArrayList<Integer> a, long k) { int n = a.size(); long p = 1; int res = 0; for (int start = 0, end = 0; end < n; end++) { // Move right bound by 1 step. // Update the product. p *= a.get(end); // Move left bound so guarantee that // p is again less than k. while (start < end && p >= k) p /= a.get(start++); // If p is less than k, update the counter. // Note that this is working even for // (start == end): it means that the // previous window cannot grow anymore // and a single array element is the only // addendum. if (p < k) { int len = end - start + 1; res += len; } } return res; } // Drive Code public static void main(String[] args) { // Function Calls ArrayList<Integer> al = new ArrayList<Integer>(); al.add(1); al.add(2); al.add(3); al.add(4); System.out.println( countSubArrayProductLessThanK(al, 10)); ArrayList<Integer> al1 = new ArrayList<Integer>(); al1.add(1); al1.add(9); al1.add(2); al1.add(8); al1.add(6); al1.add(4); al1.add(3); System.out.println( countSubArrayProductLessThanK(al1, 100)); ArrayList<Integer> al2 = new ArrayList<Integer>(); al2.add(5); al2.add(3); al2.add(2); System.out.println( countSubArrayProductLessThanK(al2, 16)); ArrayList<Integer> al3 = new ArrayList<Integer>(); al3.add(100); al3.add(200); System.out.println( countSubArrayProductLessThanK(al3, 100)); ArrayList<Integer> al4 = new ArrayList<Integer>(); al4.add(100); al4.add(200); System.out.println( countSubArrayProductLessThanK(al3, 101)); }}// This code is contributed by Prerna Saini",
"e": 11112,
"s": 8919,
"text": null
},
{
"code": "# Python3 program to count# subarrays having product# less than k. def countSubArrayProductLessThanK(a, k): n = len(a) p = 1 res = 0 start = 0 end = 0 while(end < n): # Move right bound by 1 # step. Update the product. p *= a[end] # Move left bound so guarantee # that p is again less than k. while (start < end and p >= k): p = int(p//a[start]) start += 1 # If p is less than k, update # the counter. Note that this # is working even for (start == end): # it means that the previous # window cannot grow anymore # and a single array element # is the only addendum. if (p < k): l = end - start + 1 res += l end += 1 return res # Driver Codeif __name__ == '__main__': print(countSubArrayProductLessThanK([1, 2, 3, 4], 10)) print(countSubArrayProductLessThanK([1, 9, 2, 8, 6, 4, 3], 100)) print(countSubArrayProductLessThanK([5, 3, 2], 16)) print(countSubArrayProductLessThanK([100, 200], 100)) print(countSubArrayProductLessThanK([100, 200], 101)) # This code is contributed by mits",
"e": 12286,
"s": 11112,
"text": null
},
{
"code": "// C# program to count subarrays// having product less than k.using System;using System.Collections; class GFG { static int countSubArrayProductLessThanK(ArrayList a, int k) { int n = a.Count; int p = 1; int res = 0; for (int start = 0, end = 0; end < n; end++) { // Move right bound by 1 step. // Update the product. p *= (int)a[end]; // Move left bound so guarantee // that p is again less than k. while (start < end && p >= k) p /= (int)a[start++]; // If p is less than k, update the // counter. Note that this is working // even for (start == end): it means // that the previous window cannot // grow anymore and a single array // element is the only Addendum. if (p < k) { int len = end - start + 1; res += len; } } return res; } // Driver Code static void Main() { ArrayList al = new ArrayList(); al.Add(1); al.Add(2); al.Add(3); al.Add(4); Console.WriteLine( countSubArrayProductLessThanK(al, 10)); ArrayList al1 = new ArrayList(); al1.Add(1); al1.Add(9); al1.Add(2); al1.Add(8); al1.Add(6); al1.Add(4); al1.Add(3); Console.WriteLine( countSubArrayProductLessThanK(al1, 100)); ArrayList al2 = new ArrayList(); al2.Add(5); al2.Add(3); al2.Add(2); Console.WriteLine( countSubArrayProductLessThanK(al2, 16)); ArrayList al3 = new ArrayList(); al3.Add(100); al3.Add(200); Console.WriteLine( countSubArrayProductLessThanK(al3, 100)); ArrayList al4 = new ArrayList(); al4.Add(100); al4.Add(200); Console.WriteLine( countSubArrayProductLessThanK(al3, 101)); }} // This code is contributed by mits",
"e": 14348,
"s": 12286,
"text": null
},
{
"code": "<?php// PHP program to count// subarrays having product// less than k. function countSubArrayProductLessThanK($a,$k){ $n = count($a); $p = 1; $res = 0; for ($start = 0, $end = 0; $end < $n; $end++) { // Move right bound by 1 // step. Update the product. $p *= $a[$end]; // Move left bound so guarantee // that p is again less than k. while ($start < $end && $p >= $k) $p /= $a[$start++]; // If p is less than k, update // the counter. Note that this // is working even for (start == end): // it means that the previous // window cannot grow anymore // and a single array element // is the only addendum. if ($p < $k) { $len = $end - $start + 1; $res += $len; } } return $res;} // Driver Codeecho countSubArrayProductLessThanK( array(1, 2, 3, 4), 10) . \"\\n\";echo countSubArrayProductLessThanK( array(1, 9, 2, 8, 6, 4, 3), 100) . \"\\n\";echo countSubArrayProductLessThanK( array(5, 3, 2), 16) . \"\\n\";echo countSubArrayProductLessThanK( array(100, 200), 100) . \"\\n\";echo countSubArrayProductLessThanK( array(100, 200), 101) . \"\\n\"; // This code is contributed by mits?>",
"e": 15685,
"s": 14348,
"text": null
},
{
"code": "<script>// js program to count subarrays having product// less than k. function countSubArrayProductLessThanK(a, k){ let n = a.length; let p = 1; let res = 0; for (let start = 0, end = 0; end < n; end++) { // Move right bound by 1 step. Update the product. p *= a[end]; // Move left bound so guarantee that p is again // less than k. while (start < end && p >= k) p =Math.floor(p/ a[start++]); // If p is less than k, update the counter. // Note that this is working even for (start == // end): it means that the previous window cannot // grow anymore and a single array element is the // only addendum. if (p < k) { let len = end - start + 1; res += len; } } return res;} // Driver Code document.write(countSubArrayProductLessThanK([1, 2, 3, 4], 10),'<br>') document.write(countSubArrayProductLessThanK([1, 9, 2, 8, 6, 4, 3], 100),'<br>') document.write(countSubArrayProductLessThanK([5, 3, 2], 16),'<br>') document.write(countSubArrayProductLessThanK([100, 200], 100),'<br>') document.write(countSubArrayProductLessThanK([100, 200], 101),'<br>')</script>",
"e": 16896,
"s": 15685,
"text": null
},
{
"code": null,
"e": 16906,
"s": 16896,
"text": "Output : "
},
{
"code": null,
"e": 16917,
"s": 16906,
"text": "7\n16\n5\n0\n1"
},
{
"code": null,
"e": 17096,
"s": 16917,
"text": "Complexities: Every element in the array is accessed at most two times, therefore, it is O(n) time complexity. A few scalar variables are used, therefore, it is O(1) extra space."
},
{
"code": null,
"e": 17282,
"s": 17096,
"text": "Exercise 1: Update the solution so that it could handle nils in the input array. Exercise 2: Update the solution so that it could handle multiplication overflow when computing products."
},
{
"code": null,
"e": 17740,
"s": 17282,
"text": "This article is contributed by Raghav Sharma and improved by Andrey Khayrutdinov. 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": 17745,
"s": 17740,
"text": "vt_m"
},
{
"code": null,
"e": 17751,
"s": 17745,
"text": "jit_t"
},
{
"code": null,
"e": 17758,
"s": 17751,
"text": "Sam007"
},
{
"code": null,
"e": 17771,
"s": 17758,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 17786,
"s": 17771,
"text": "Saurav Sinha 1"
},
{
"code": null,
"e": 17801,
"s": 17786,
"text": "Saurabh Vemuri"
},
{
"code": null,
"e": 17815,
"s": 17801,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 17829,
"s": 17815,
"text": "ojasvishaklya"
},
{
"code": null,
"e": 17842,
"s": 17829,
"text": "todaysgaurav"
},
{
"code": null,
"e": 17858,
"s": 17842,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 17868,
"s": 17858,
"text": "swarnalii"
},
{
"code": null,
"e": 17882,
"s": 17868,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 17897,
"s": 17882,
"text": "sliding-window"
},
{
"code": null,
"e": 17906,
"s": 17897,
"text": "subarray"
},
{
"code": null,
"e": 17913,
"s": 17906,
"text": "Arrays"
},
{
"code": null,
"e": 17926,
"s": 17913,
"text": "Mathematical"
},
{
"code": null,
"e": 17940,
"s": 17926,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 17955,
"s": 17940,
"text": "sliding-window"
},
{
"code": null,
"e": 17962,
"s": 17955,
"text": "Arrays"
},
{
"code": null,
"e": 17975,
"s": 17962,
"text": "Mathematical"
},
{
"code": null,
"e": 18073,
"s": 17975,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 18141,
"s": 18073,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 18185,
"s": 18141,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 18217,
"s": 18185,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 18231,
"s": 18217,
"text": "Linear Search"
},
{
"code": null,
"e": 18254,
"s": 18231,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 18284,
"s": 18254,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 18327,
"s": 18284,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 18387,
"s": 18327,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 18402,
"s": 18387,
"text": "C++ Data Types"
}
] |
StringBuilder.ToString Method in C#
|
29 Jan, 2019
This method is used to converts the value of this instance to a String. A new String object is created and initialized to get the character sequence from this StringBuilder object and then String is returned by ToString(). Subsequent changes to this sequence contained by Object do not affect the contents of the String.
Syntax: public override string ToString ();
Return Value: This method returns the String representing the data contained by StringBuilder Object.
Below programs illustrate the StringBuilder.ToString() method:
Example 1:
// C# program to demonstrate// the ToString() Methodusing System;using System.Text; class GFG { // Main Method public static void Main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("GeeksForGeeks"); // print string Console.WriteLine("String contains = " + str.ToString()); }}
String contains = GeeksForGeeks
Example 2:
// C# program to demonstrate// the ToString() Methodusing System;using System.Text; class GFG { // Main Method public static void Main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("GeeksforGeeks Contribute"); // print string Console.WriteLine("String contains = " + str.ToString()); }}
String contains = GeeksforGeeks Contribute
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.tostring?view=netframework-4.7.2
CSharp-method
CSharp-StringBuilder-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jan, 2019"
},
{
"code": null,
"e": 349,
"s": 28,
"text": "This method is used to converts the value of this instance to a String. A new String object is created and initialized to get the character sequence from this StringBuilder object and then String is returned by ToString(). Subsequent changes to this sequence contained by Object do not affect the contents of the String."
},
{
"code": null,
"e": 393,
"s": 349,
"text": "Syntax: public override string ToString ();"
},
{
"code": null,
"e": 495,
"s": 393,
"text": "Return Value: This method returns the String representing the data contained by StringBuilder Object."
},
{
"code": null,
"e": 558,
"s": 495,
"text": "Below programs illustrate the StringBuilder.ToString() method:"
},
{
"code": null,
"e": 569,
"s": 558,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate// the ToString() Methodusing System;using System.Text; class GFG { // Main Method public static void Main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"GeeksForGeeks\"); // print string Console.WriteLine(\"String contains = \" + str.ToString()); }}",
"e": 1012,
"s": 569,
"text": null
},
{
"code": null,
"e": 1045,
"s": 1012,
"text": "String contains = GeeksForGeeks\n"
},
{
"code": null,
"e": 1056,
"s": 1045,
"text": "Example 2:"
},
{
"code": "// C# program to demonstrate// the ToString() Methodusing System;using System.Text; class GFG { // Main Method public static void Main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"GeeksforGeeks Contribute\"); // print string Console.WriteLine(\"String contains = \" + str.ToString()); }}",
"e": 1544,
"s": 1056,
"text": null
},
{
"code": null,
"e": 1588,
"s": 1544,
"text": "String contains = GeeksforGeeks Contribute\n"
},
{
"code": null,
"e": 1599,
"s": 1588,
"text": "Reference:"
},
{
"code": null,
"e": 1702,
"s": 1599,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.tostring?view=netframework-4.7.2"
},
{
"code": null,
"e": 1716,
"s": 1702,
"text": "CSharp-method"
},
{
"code": null,
"e": 1743,
"s": 1716,
"text": "CSharp-StringBuilder-Class"
},
{
"code": null,
"e": 1746,
"s": 1743,
"text": "C#"
}
] |
Multiple Color Detection in Real-Time using Python-OpenCV
|
10 May, 2020
For a robot to visualize the environment, along with the object detection, detection of its color in real-time is also very important.
In self-driving car, to detect the traffic signals.
Multiple color detection is used in some industrial robots, to performing pick-and-place task in separating different colored objects.
This is an implementation of detecting multiple colors (here, only red, green and blue colors have been considered) in real-time using Python programming language.Python Libraries Used:
NumPy
OpenCV-Python
Below is the implementation.
# Python code for Multiple Color Detection import numpy as npimport cv2 # Capturing video through webcamwebcam = cv2.VideoCapture(0) # Start a while loopwhile(1): # Reading the video from the # webcam in image frames _, imageFrame = webcam.read() # Convert the imageFrame in # BGR(RGB color space) to # HSV(hue-saturation-value) # color space hsvFrame = cv2.cvtColor(imageFrame, cv2.COLOR_BGR2HSV) # Set range for red color and # define mask red_lower = np.array([136, 87, 111], np.uint8) red_upper = np.array([180, 255, 255], np.uint8) red_mask = cv2.inRange(hsvFrame, red_lower, red_upper) # Set range for green color and # define mask green_lower = np.array([25, 52, 72], np.uint8) green_upper = np.array([102, 255, 255], np.uint8) green_mask = cv2.inRange(hsvFrame, green_lower, green_upper) # Set range for blue color and # define mask blue_lower = np.array([94, 80, 2], np.uint8) blue_upper = np.array([120, 255, 255], np.uint8) blue_mask = cv2.inRange(hsvFrame, blue_lower, blue_upper) # Morphological Transform, Dilation # for each color and bitwise_and operator # between imageFrame and mask determines # to detect only that particular color kernal = np.ones((5, 5), "uint8") # For red color red_mask = cv2.dilate(red_mask, kernal) res_red = cv2.bitwise_and(imageFrame, imageFrame, mask = red_mask) # For green color green_mask = cv2.dilate(green_mask, kernal) res_green = cv2.bitwise_and(imageFrame, imageFrame, mask = green_mask) # For blue color blue_mask = cv2.dilate(blue_mask, kernal) res_blue = cv2.bitwise_and(imageFrame, imageFrame, mask = blue_mask) # Creating contour to track red color contours, hierarchy = cv2.findContours(red_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for pic, contour in enumerate(contours): area = cv2.contourArea(contour) if(area > 300): x, y, w, h = cv2.boundingRect(contour) imageFrame = cv2.rectangle(imageFrame, (x, y), (x + w, y + h), (0, 0, 255), 2) cv2.putText(imageFrame, "Red Colour", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255)) # Creating contour to track green color contours, hierarchy = cv2.findContours(green_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for pic, contour in enumerate(contours): area = cv2.contourArea(contour) if(area > 300): x, y, w, h = cv2.boundingRect(contour) imageFrame = cv2.rectangle(imageFrame, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(imageFrame, "Green Colour", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0)) # Creating contour to track blue color contours, hierarchy = cv2.findContours(blue_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for pic, contour in enumerate(contours): area = cv2.contourArea(contour) if(area > 300): x, y, w, h = cv2.boundingRect(contour) imageFrame = cv2.rectangle(imageFrame, (x, y), (x + w, y + h), (255, 0, 0), 2) cv2.putText(imageFrame, "Blue Colour", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 0, 0)) # Program Termination cv2.imshow("Multiple Color Detection in Real-TIme", imageFrame) if cv2.waitKey(10) & 0xFF == ord('q'): cap.release() cv2.destroyAllWindows() break
Output:
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
Python OOPs Concepts
Python Classes and Objects
*args and **kwargs in Python
Introduction To PYTHON
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 189,
"s": 54,
"text": "For a robot to visualize the environment, along with the object detection, detection of its color in real-time is also very important."
},
{
"code": null,
"e": 241,
"s": 189,
"text": "In self-driving car, to detect the traffic signals."
},
{
"code": null,
"e": 376,
"s": 241,
"text": "Multiple color detection is used in some industrial robots, to performing pick-and-place task in separating different colored objects."
},
{
"code": null,
"e": 562,
"s": 376,
"text": "This is an implementation of detecting multiple colors (here, only red, green and blue colors have been considered) in real-time using Python programming language.Python Libraries Used:"
},
{
"code": null,
"e": 568,
"s": 562,
"text": "NumPy"
},
{
"code": null,
"e": 582,
"s": 568,
"text": "OpenCV-Python"
},
{
"code": null,
"e": 611,
"s": 582,
"text": "Below is the implementation."
},
{
"code": "# Python code for Multiple Color Detection import numpy as npimport cv2 # Capturing video through webcamwebcam = cv2.VideoCapture(0) # Start a while loopwhile(1): # Reading the video from the # webcam in image frames _, imageFrame = webcam.read() # Convert the imageFrame in # BGR(RGB color space) to # HSV(hue-saturation-value) # color space hsvFrame = cv2.cvtColor(imageFrame, cv2.COLOR_BGR2HSV) # Set range for red color and # define mask red_lower = np.array([136, 87, 111], np.uint8) red_upper = np.array([180, 255, 255], np.uint8) red_mask = cv2.inRange(hsvFrame, red_lower, red_upper) # Set range for green color and # define mask green_lower = np.array([25, 52, 72], np.uint8) green_upper = np.array([102, 255, 255], np.uint8) green_mask = cv2.inRange(hsvFrame, green_lower, green_upper) # Set range for blue color and # define mask blue_lower = np.array([94, 80, 2], np.uint8) blue_upper = np.array([120, 255, 255], np.uint8) blue_mask = cv2.inRange(hsvFrame, blue_lower, blue_upper) # Morphological Transform, Dilation # for each color and bitwise_and operator # between imageFrame and mask determines # to detect only that particular color kernal = np.ones((5, 5), \"uint8\") # For red color red_mask = cv2.dilate(red_mask, kernal) res_red = cv2.bitwise_and(imageFrame, imageFrame, mask = red_mask) # For green color green_mask = cv2.dilate(green_mask, kernal) res_green = cv2.bitwise_and(imageFrame, imageFrame, mask = green_mask) # For blue color blue_mask = cv2.dilate(blue_mask, kernal) res_blue = cv2.bitwise_and(imageFrame, imageFrame, mask = blue_mask) # Creating contour to track red color contours, hierarchy = cv2.findContours(red_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for pic, contour in enumerate(contours): area = cv2.contourArea(contour) if(area > 300): x, y, w, h = cv2.boundingRect(contour) imageFrame = cv2.rectangle(imageFrame, (x, y), (x + w, y + h), (0, 0, 255), 2) cv2.putText(imageFrame, \"Red Colour\", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255)) # Creating contour to track green color contours, hierarchy = cv2.findContours(green_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for pic, contour in enumerate(contours): area = cv2.contourArea(contour) if(area > 300): x, y, w, h = cv2.boundingRect(contour) imageFrame = cv2.rectangle(imageFrame, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(imageFrame, \"Green Colour\", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0)) # Creating contour to track blue color contours, hierarchy = cv2.findContours(blue_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for pic, contour in enumerate(contours): area = cv2.contourArea(contour) if(area > 300): x, y, w, h = cv2.boundingRect(contour) imageFrame = cv2.rectangle(imageFrame, (x, y), (x + w, y + h), (255, 0, 0), 2) cv2.putText(imageFrame, \"Blue Colour\", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 0, 0)) # Program Termination cv2.imshow(\"Multiple Color Detection in Real-TIme\", imageFrame) if cv2.waitKey(10) & 0xFF == ord('q'): cap.release() cv2.destroyAllWindows() break",
"e": 4780,
"s": 611,
"text": null
},
{
"code": null,
"e": 4788,
"s": 4780,
"text": "Output:"
},
{
"code": null,
"e": 4802,
"s": 4788,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 4809,
"s": 4802,
"text": "Python"
},
{
"code": null,
"e": 4907,
"s": 4809,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4925,
"s": 4907,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4947,
"s": 4925,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4989,
"s": 4947,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 5024,
"s": 4989,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 5056,
"s": 5024,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5082,
"s": 5056,
"text": "Python String | replace()"
},
{
"code": null,
"e": 5103,
"s": 5082,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 5130,
"s": 5103,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5159,
"s": 5130,
"text": "*args and **kwargs in Python"
}
] |
Python - Iterate over Tuples in Dictionary - GeeksforGeeks
|
24 Jan, 2022
In this article, we will discuss how to Iterate over Tuples in Dictionary in Python.
We can get the particular tuples by using an index:
Syntax:
dictionary_name[index]
To iterate the entire tuple values in a particular index
for i in range(0, len(dictionary_name[index])):
print(dictionary_name[index][i]
Example:
Python
# Initializing a dictionarymyDict = {1: ("Apple", "Boy", "Cat"), 2: ("Geeks", "For", "Geeks"), 3: ("I", "Am", "Learning", "Python")} print("Tuple mapped with the key 1 =>"), # Directly printing entire tuple mapped# with the key 1print(myDict[1]) print("Tuple mapped with the key 2 =>"), # Printing tuple elements mapped with# the key 2 one by onefor each in myDict[2]: print(each), print("")print("Tuple mapped with the key 3 =>"), # Accessing tuple elements mapped with# the key 3 using indexfor i in range(0, len(myDict[3])): print(myDict[3][i]),
Output:
Tuple mapped with the key 1 =>
('Apple', 'Boy', 'Cat')
Tuple mapped with the key 2 =>
Geeks
For
Geeks
Tuple mapped with the key 3 =>
I
Am
Learning
Python
we can use dictionary.values() to iterate over the tuples in a dictionary with for loop
Syntax:
for i in dictionary_name.values():
for j in i:
print(j)
print(" ")
Example:
Python3
# Initializing a dictionarymyDict = {1: ("Apple", "Boy", "Cat"), 2: ("Geeks", "For", "Geeks"), 3: ("I", "Am", "Learning", "Python")} # iterate over all tuples using# values() methodfor i in myDict.values(): for j in i: print(j) print(" ")
Output:
Apple
Boy
Cat
Geeks
For
Geeks
I
Am
Learning
Python
surinderdawra388
Picked
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
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": "\n24 Jan, 2022"
},
{
"code": null,
"e": 25623,
"s": 25537,
"text": "In this article, we will discuss how to Iterate over Tuples in Dictionary in Python. "
},
{
"code": null,
"e": 25675,
"s": 25623,
"text": "We can get the particular tuples by using an index:"
},
{
"code": null,
"e": 25683,
"s": 25675,
"text": "Syntax:"
},
{
"code": null,
"e": 25706,
"s": 25683,
"text": "dictionary_name[index]"
},
{
"code": null,
"e": 25763,
"s": 25706,
"text": "To iterate the entire tuple values in a particular index"
},
{
"code": null,
"e": 25847,
"s": 25763,
"text": "for i in range(0, len(dictionary_name[index])):\n print(dictionary_name[index][i]"
},
{
"code": null,
"e": 25857,
"s": 25847,
"text": " Example:"
},
{
"code": null,
"e": 25864,
"s": 25857,
"text": "Python"
},
{
"code": "# Initializing a dictionarymyDict = {1: (\"Apple\", \"Boy\", \"Cat\"), 2: (\"Geeks\", \"For\", \"Geeks\"), 3: (\"I\", \"Am\", \"Learning\", \"Python\")} print(\"Tuple mapped with the key 1 =>\"), # Directly printing entire tuple mapped# with the key 1print(myDict[1]) print(\"Tuple mapped with the key 2 =>\"), # Printing tuple elements mapped with# the key 2 one by onefor each in myDict[2]: print(each), print(\"\")print(\"Tuple mapped with the key 3 =>\"), # Accessing tuple elements mapped with# the key 3 using indexfor i in range(0, len(myDict[3])): print(myDict[3][i]),",
"e": 26437,
"s": 25864,
"text": null
},
{
"code": null,
"e": 26445,
"s": 26437,
"text": "Output:"
},
{
"code": null,
"e": 26600,
"s": 26445,
"text": "Tuple mapped with the key 1 =>\n('Apple', 'Boy', 'Cat')\nTuple mapped with the key 2 =>\nGeeks\nFor\nGeeks\n\nTuple mapped with the key 3 =>\nI\nAm\nLearning\nPython"
},
{
"code": null,
"e": 26688,
"s": 26600,
"text": "we can use dictionary.values() to iterate over the tuples in a dictionary with for loop"
},
{
"code": null,
"e": 26696,
"s": 26688,
"text": "Syntax:"
},
{
"code": null,
"e": 26773,
"s": 26696,
"text": "for i in dictionary_name.values():\n for j in i:\n print(j)\n print(\" \")"
},
{
"code": null,
"e": 26782,
"s": 26773,
"text": "Example:"
},
{
"code": null,
"e": 26790,
"s": 26782,
"text": "Python3"
},
{
"code": "# Initializing a dictionarymyDict = {1: (\"Apple\", \"Boy\", \"Cat\"), 2: (\"Geeks\", \"For\", \"Geeks\"), 3: (\"I\", \"Am\", \"Learning\", \"Python\")} # iterate over all tuples using# values() methodfor i in myDict.values(): for j in i: print(j) print(\" \")",
"e": 27060,
"s": 26790,
"text": null
},
{
"code": null,
"e": 27068,
"s": 27060,
"text": "Output:"
},
{
"code": null,
"e": 27123,
"s": 27068,
"text": "Apple\nBoy\nCat\n \nGeeks\nFor\nGeeks\n \nI\nAm\nLearning\nPython"
},
{
"code": null,
"e": 27140,
"s": 27123,
"text": "surinderdawra388"
},
{
"code": null,
"e": 27147,
"s": 27140,
"text": "Picked"
},
{
"code": null,
"e": 27174,
"s": 27147,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 27186,
"s": 27174,
"text": "python-dict"
},
{
"code": null,
"e": 27193,
"s": 27186,
"text": "Python"
},
{
"code": null,
"e": 27209,
"s": 27193,
"text": "Python Programs"
},
{
"code": null,
"e": 27221,
"s": 27209,
"text": "python-dict"
},
{
"code": null,
"e": 27319,
"s": 27221,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27351,
"s": 27319,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27393,
"s": 27351,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27435,
"s": 27393,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27491,
"s": 27435,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27518,
"s": 27491,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27540,
"s": 27518,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27579,
"s": 27540,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27625,
"s": 27579,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27663,
"s": 27625,
"text": "Python | Convert a list to dictionary"
}
] |
C# | BitArray Class - GeeksforGeeks
|
03 Apr, 2019
The BitArray class manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on i.e, 1 and false indicates the bit is off i.e, 0. This class is contained in System.Collections namespace.
Properties of BitArray Class:
The BitArray class is a collection class in which the capacity is always the same as the count.
Elements are added to a BitArray by increasing the Length property.
Elements are deleted by decreasing the Length property.
Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.
Example:
// C# code to create a BitArrayusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a BitArray BitArray myBitArr = new BitArray(5); myBitArr[0] = true; myBitArr[1] = true; myBitArr[2] = false; myBitArr[3] = true; myBitArr[4] = false; // To get the value of index at index 2 Console.WriteLine(myBitArr.Get(2)); // To get the value of index at index 3 Console.WriteLine(myBitArr.Get(3)); }}
Output:
False
True
Example:
// C# program to illustrate the // BitArray Class Propertiesusing System; using System.Collections; class GFG { // Driver code public static void Main() { // Creating a BitArray BitArray myBitArr = new BitArray(new byte[] { 0, 0, 0, 1 }); // -------- IsReadOnly Property -------- // Checking if the BitArray is read-only Console.WriteLine(myBitArr.IsReadOnly); // -------- Count Property -------- // To get the number of elements // contained in the BitArray Console.WriteLine(myBitArr.Count); } }
Output:
False
32
Example 1:
// C# code to do bitwise// OR between BitArrayusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a BitArray BitArray myBitArr1 = new BitArray(4); // Creating a BitArray BitArray myBitArr2 = new BitArray(4); // Initializing values in myBitArr1 myBitArr1[0] = false; myBitArr1[1] = false; myBitArr1[2] = true; myBitArr1[3] = true; // Initializing values in myBitArr2 myBitArr2[0] = false; myBitArr2[2] = false; myBitArr2[1] = true; myBitArr2[3] = true; // function calling PrintValues(myBitArr1.Or(myBitArr2)); } // Displaying the result public static void PrintValues(IEnumerable myList) { foreach(Object obj in myList) { Console.WriteLine(obj); } }}
Output:
False
True
True
True
Example 2:
// C# code to set all bits in the// BitArray to the specified valueusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a BitArray myBitArr BitArray myBitArr = new BitArray(5); // Initializing all the bits in myBitArr myBitArr[0] = false; myBitArr[1] = true; myBitArr[2] = true; myBitArr[3] = false; myBitArr[4] = true; // Printing the values in myBitArr Console.WriteLine("Initially the bits are as : "); PrintIndexAndValues(myBitArr); // Setting all bits to false myBitArr.SetAll(false); // Printing the values in myBitArr // It should display all the bits as false Console.WriteLine("Finally the bits are as : "); PrintIndexAndValues(myBitArr); } // Function to display bits public static void PrintIndexAndValues(IEnumerable myArr) { foreach(Object obj in myArr) { Console.WriteLine(obj); } }}
Output:
Initially the bits are as :
False
True
True
False
True
Finally the bits are as :
False
False
False
False
False
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.bitarray?view=netframework-4.7.2
CSharp-Collections-BitArray
CSharp-Collections-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
C# | Class and Object
C# | Constructors
Extension Method in C#
Introduction to .NET Framework
C# | String.IndexOf( ) Method | Set - 1
|
[
{
"code": null,
"e": 25639,
"s": 25611,
"text": "\n03 Apr, 2019"
},
{
"code": null,
"e": 25879,
"s": 25639,
"text": "The BitArray class manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on i.e, 1 and false indicates the bit is off i.e, 0. This class is contained in System.Collections namespace."
},
{
"code": null,
"e": 25909,
"s": 25879,
"text": "Properties of BitArray Class:"
},
{
"code": null,
"e": 26005,
"s": 25909,
"text": "The BitArray class is a collection class in which the capacity is always the same as the count."
},
{
"code": null,
"e": 26073,
"s": 26005,
"text": "Elements are added to a BitArray by increasing the Length property."
},
{
"code": null,
"e": 26129,
"s": 26073,
"text": "Elements are deleted by decreasing the Length property."
},
{
"code": null,
"e": 26240,
"s": 26129,
"text": "Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based."
},
{
"code": null,
"e": 26249,
"s": 26240,
"text": "Example:"
},
{
"code": "// C# code to create a BitArrayusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a BitArray BitArray myBitArr = new BitArray(5); myBitArr[0] = true; myBitArr[1] = true; myBitArr[2] = false; myBitArr[3] = true; myBitArr[4] = false; // To get the value of index at index 2 Console.WriteLine(myBitArr.Get(2)); // To get the value of index at index 3 Console.WriteLine(myBitArr.Get(3)); }}",
"e": 26791,
"s": 26249,
"text": null
},
{
"code": null,
"e": 26799,
"s": 26791,
"text": "Output:"
},
{
"code": null,
"e": 26811,
"s": 26799,
"text": "False\nTrue\n"
},
{
"code": null,
"e": 26820,
"s": 26811,
"text": "Example:"
},
{
"code": "// C# program to illustrate the // BitArray Class Propertiesusing System; using System.Collections; class GFG { // Driver code public static void Main() { // Creating a BitArray BitArray myBitArr = new BitArray(new byte[] { 0, 0, 0, 1 }); // -------- IsReadOnly Property -------- // Checking if the BitArray is read-only Console.WriteLine(myBitArr.IsReadOnly); // -------- Count Property -------- // To get the number of elements // contained in the BitArray Console.WriteLine(myBitArr.Count); } } ",
"e": 27459,
"s": 26820,
"text": null
},
{
"code": null,
"e": 27467,
"s": 27459,
"text": "Output:"
},
{
"code": null,
"e": 27477,
"s": 27467,
"text": "False\n32\n"
},
{
"code": null,
"e": 27488,
"s": 27477,
"text": "Example 1:"
},
{
"code": "// C# code to do bitwise// OR between BitArrayusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a BitArray BitArray myBitArr1 = new BitArray(4); // Creating a BitArray BitArray myBitArr2 = new BitArray(4); // Initializing values in myBitArr1 myBitArr1[0] = false; myBitArr1[1] = false; myBitArr1[2] = true; myBitArr1[3] = true; // Initializing values in myBitArr2 myBitArr2[0] = false; myBitArr2[2] = false; myBitArr2[1] = true; myBitArr2[3] = true; // function calling PrintValues(myBitArr1.Or(myBitArr2)); } // Displaying the result public static void PrintValues(IEnumerable myList) { foreach(Object obj in myList) { Console.WriteLine(obj); } }}",
"e": 28376,
"s": 27488,
"text": null
},
{
"code": null,
"e": 28384,
"s": 28376,
"text": "Output:"
},
{
"code": null,
"e": 28406,
"s": 28384,
"text": "False\nTrue\nTrue\nTrue\n"
},
{
"code": null,
"e": 28417,
"s": 28406,
"text": "Example 2:"
},
{
"code": "// C# code to set all bits in the// BitArray to the specified valueusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a BitArray myBitArr BitArray myBitArr = new BitArray(5); // Initializing all the bits in myBitArr myBitArr[0] = false; myBitArr[1] = true; myBitArr[2] = true; myBitArr[3] = false; myBitArr[4] = true; // Printing the values in myBitArr Console.WriteLine(\"Initially the bits are as : \"); PrintIndexAndValues(myBitArr); // Setting all bits to false myBitArr.SetAll(false); // Printing the values in myBitArr // It should display all the bits as false Console.WriteLine(\"Finally the bits are as : \"); PrintIndexAndValues(myBitArr); } // Function to display bits public static void PrintIndexAndValues(IEnumerable myArr) { foreach(Object obj in myArr) { Console.WriteLine(obj); } }}",
"e": 29462,
"s": 28417,
"text": null
},
{
"code": null,
"e": 29470,
"s": 29462,
"text": "Output:"
},
{
"code": null,
"e": 29584,
"s": 29470,
"text": "Initially the bits are as : \nFalse\nTrue\nTrue\nFalse\nTrue\nFinally the bits are as : \nFalse\nFalse\nFalse\nFalse\nFalse\n"
},
{
"code": null,
"e": 29595,
"s": 29584,
"text": "Reference:"
},
{
"code": null,
"e": 29691,
"s": 29595,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.bitarray?view=netframework-4.7.2"
},
{
"code": null,
"e": 29719,
"s": 29691,
"text": "CSharp-Collections-BitArray"
},
{
"code": null,
"e": 29748,
"s": 29719,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 29751,
"s": 29748,
"text": "C#"
},
{
"code": null,
"e": 29849,
"s": 29751,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29877,
"s": 29849,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 29892,
"s": 29877,
"text": "C# | Delegates"
},
{
"code": null,
"e": 29915,
"s": 29892,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 29937,
"s": 29915,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 29983,
"s": 29937,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 30005,
"s": 29983,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 30023,
"s": 30005,
"text": "C# | Constructors"
},
{
"code": null,
"e": 30046,
"s": 30023,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 30077,
"s": 30046,
"text": "Introduction to .NET Framework"
}
] |
How to Install Tkinter on MacOS? - GeeksforGeeks
|
22 Sep, 2021
In this article, we will learn how to install Tkinter in Python on MacOS. Tkinter is a Python binding to the Tk GUI toolkit. It is the standard Python interface to the Tk GUI toolkit, and is Python’s de-facto standard GUI.
Follow the below steps to install the Tkinter package on macOS using pip:
Step 1: Install the latest Python3 in MacOS
Step 2: Check if pip3 and python3 are correctly installed.
python3 --version
pip3 --version
Step 3: Upgrade your pip to avoid errors during installation.
pip3 install --upgrade pip
Step 4: Enter the following command to install Tkinter using pip3.
pip3 install tk
Follow the below steps to install the yesTkinter package on macOS using the setup.py file:
Step 1: Download the latest source package of Tkinter for python3 from here.
curl https://files.pythonhosted.org/packages/a0/81/742b342fd642e672fbedecde725ba44db44e800dc4c936216c3c6729885a/tk-0.1.0.tar.gz > tk.tar.gz
Step 2: Extract the downloaded package using the following command.
tar -xzvf tk.tar.gz
Step 3: Go inside the folder and Enter the following command to install the package.
Note: You must have developer tools for XCode MacOS installed in your system
cd tk-0.1.0
python3 setup.py install
Make the following import in your python terminal to verify if the installation has been done properly:
import tk
If there is any error while importing the module then is not installed properly.
Blogathon-2021
how-to-install
Picked
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
Python program to convert XML to Dictionary
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
|
[
{
"code": null,
"e": 26031,
"s": 26003,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 26254,
"s": 26031,
"text": "In this article, we will learn how to install Tkinter in Python on MacOS. Tkinter is a Python binding to the Tk GUI toolkit. It is the standard Python interface to the Tk GUI toolkit, and is Python’s de-facto standard GUI."
},
{
"code": null,
"e": 26328,
"s": 26254,
"text": "Follow the below steps to install the Tkinter package on macOS using pip:"
},
{
"code": null,
"e": 26372,
"s": 26328,
"text": "Step 1: Install the latest Python3 in MacOS"
},
{
"code": null,
"e": 26431,
"s": 26372,
"text": "Step 2: Check if pip3 and python3 are correctly installed."
},
{
"code": null,
"e": 26464,
"s": 26431,
"text": "python3 --version\npip3 --version"
},
{
"code": null,
"e": 26526,
"s": 26464,
"text": "Step 3: Upgrade your pip to avoid errors during installation."
},
{
"code": null,
"e": 26553,
"s": 26526,
"text": "pip3 install --upgrade pip"
},
{
"code": null,
"e": 26620,
"s": 26553,
"text": "Step 4: Enter the following command to install Tkinter using pip3."
},
{
"code": null,
"e": 26636,
"s": 26620,
"text": "pip3 install tk"
},
{
"code": null,
"e": 26727,
"s": 26636,
"text": "Follow the below steps to install the yesTkinter package on macOS using the setup.py file:"
},
{
"code": null,
"e": 26804,
"s": 26727,
"text": "Step 1: Download the latest source package of Tkinter for python3 from here."
},
{
"code": null,
"e": 26944,
"s": 26804,
"text": "curl https://files.pythonhosted.org/packages/a0/81/742b342fd642e672fbedecde725ba44db44e800dc4c936216c3c6729885a/tk-0.1.0.tar.gz > tk.tar.gz"
},
{
"code": null,
"e": 27012,
"s": 26944,
"text": "Step 2: Extract the downloaded package using the following command."
},
{
"code": null,
"e": 27032,
"s": 27012,
"text": "tar -xzvf tk.tar.gz"
},
{
"code": null,
"e": 27117,
"s": 27032,
"text": "Step 3: Go inside the folder and Enter the following command to install the package."
},
{
"code": null,
"e": 27194,
"s": 27117,
"text": "Note: You must have developer tools for XCode MacOS installed in your system"
},
{
"code": null,
"e": 27231,
"s": 27194,
"text": "cd tk-0.1.0\npython3 setup.py install"
},
{
"code": null,
"e": 27335,
"s": 27231,
"text": "Make the following import in your python terminal to verify if the installation has been done properly:"
},
{
"code": null,
"e": 27345,
"s": 27335,
"text": "import tk"
},
{
"code": null,
"e": 27426,
"s": 27345,
"text": "If there is any error while importing the module then is not installed properly."
},
{
"code": null,
"e": 27441,
"s": 27426,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 27456,
"s": 27441,
"text": "how-to-install"
},
{
"code": null,
"e": 27463,
"s": 27456,
"text": "Picked"
},
{
"code": null,
"e": 27473,
"s": 27463,
"text": "Blogathon"
},
{
"code": null,
"e": 27480,
"s": 27473,
"text": "How To"
},
{
"code": null,
"e": 27499,
"s": 27480,
"text": "Installation Guide"
},
{
"code": null,
"e": 27597,
"s": 27499,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27654,
"s": 27597,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 27695,
"s": 27654,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 27725,
"s": 27695,
"text": "Stratified Sampling in Pandas"
},
{
"code": null,
"e": 27760,
"s": 27725,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 27804,
"s": 27760,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 27836,
"s": 27804,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27889,
"s": 27836,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 27933,
"s": 27889,
"text": "How to install Jupyter Notebook on Windows?"
},
{
"code": null,
"e": 27960,
"s": 27933,
"text": "How to Align Text in HTML?"
}
] |
PHP | strtolower() Function - GeeksforGeeks
|
01 Aug, 2021
The strtolower() function is used to convert a string into lowercase. This function takes a string as parameter and converts all the uppercase english alphabets present in the string to lowercase. All other numeric characters or special characters in the string remains unchanged.
Syntax:
string strtolower( $string )
Parameter: The only parameter to this function is a string that is to be converted to lower case.
Return value: This function returns a string in which all the alphabets are lower case.
Examples:
Input : $str = "GeeksForGeeks"
strtolower($str)
Output: geeksforgeeks
Input : $str = "going BACK he SAW THIS 123$#%"
strtolower($str)
Output: going back he saw this 123$#%
Below programs illustrate the strtolower() function in PHP:
Program 1:
<?php // original string$str = "GeeksForGeeks"; // string converted to lower case$resStr = strtolower($str); print_r($resStr); ?>
Output:
geeksforgeeks
Program 2:
<?php // original string$str = "going BACK he SAW THIS 123$#%"; // string converted to lower case$resStr = strtolower($str); print_r($resStr); ?>
Output:
going back he saw this 123$#%
Reference:http://php.net/manual/en/function.strtolower.php
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
Vaibhav Bajpai
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
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": 26191,
"s": 26163,
"text": "\n01 Aug, 2021"
},
{
"code": null,
"e": 26472,
"s": 26191,
"text": "The strtolower() function is used to convert a string into lowercase. This function takes a string as parameter and converts all the uppercase english alphabets present in the string to lowercase. All other numeric characters or special characters in the string remains unchanged."
},
{
"code": null,
"e": 26480,
"s": 26472,
"text": "Syntax:"
},
{
"code": null,
"e": 26510,
"s": 26480,
"text": "string strtolower( $string )\n"
},
{
"code": null,
"e": 26608,
"s": 26510,
"text": "Parameter: The only parameter to this function is a string that is to be converted to lower case."
},
{
"code": null,
"e": 26696,
"s": 26608,
"text": "Return value: This function returns a string in which all the alphabets are lower case."
},
{
"code": null,
"e": 26706,
"s": 26696,
"text": "Examples:"
},
{
"code": null,
"e": 26898,
"s": 26706,
"text": "Input : $str = \"GeeksForGeeks\"\n strtolower($str)\nOutput: geeksforgeeks\n\nInput : $str = \"going BACK he SAW THIS 123$#%\"\n strtolower($str)\nOutput: going back he saw this 123$#%\n"
},
{
"code": null,
"e": 26958,
"s": 26898,
"text": "Below programs illustrate the strtolower() function in PHP:"
},
{
"code": null,
"e": 26969,
"s": 26958,
"text": "Program 1:"
},
{
"code": "<?php // original string$str = \"GeeksForGeeks\"; // string converted to lower case$resStr = strtolower($str); print_r($resStr); ?>",
"e": 27103,
"s": 26969,
"text": null
},
{
"code": null,
"e": 27111,
"s": 27103,
"text": "Output:"
},
{
"code": null,
"e": 27126,
"s": 27111,
"text": "geeksforgeeks\n"
},
{
"code": null,
"e": 27137,
"s": 27126,
"text": "Program 2:"
},
{
"code": "<?php // original string$str = \"going BACK he SAW THIS 123$#%\"; // string converted to lower case$resStr = strtolower($str); print_r($resStr); ?>",
"e": 27287,
"s": 27137,
"text": null
},
{
"code": null,
"e": 27295,
"s": 27287,
"text": "Output:"
},
{
"code": null,
"e": 27326,
"s": 27295,
"text": "going back he saw this 123$#%\n"
},
{
"code": null,
"e": 27385,
"s": 27326,
"text": "Reference:http://php.net/manual/en/function.strtolower.php"
},
{
"code": null,
"e": 27554,
"s": 27385,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 27569,
"s": 27554,
"text": "Vaibhav Bajpai"
},
{
"code": null,
"e": 27580,
"s": 27569,
"text": "PHP-string"
},
{
"code": null,
"e": 27584,
"s": 27580,
"text": "PHP"
},
{
"code": null,
"e": 27601,
"s": 27584,
"text": "Web Technologies"
},
{
"code": null,
"e": 27605,
"s": 27601,
"text": "PHP"
},
{
"code": null,
"e": 27703,
"s": 27605,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27753,
"s": 27703,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27793,
"s": 27753,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 27854,
"s": 27793,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 27904,
"s": 27854,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 27949,
"s": 27904,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 27989,
"s": 27949,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28022,
"s": 27989,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28067,
"s": 28022,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28110,
"s": 28067,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
D3.js hierarchy() Function - GeeksforGeeks
|
23 Sep, 2020
The d3.hierarchy() function in D3.js library is used to construct a root node data from a given hierarchical data. The data that is given must be of an object and must represent a root node.
Syntax:
d3.hierarchy(data[, children]);
Parameters: This function takes a single parameter as given above and described below.
data: This parameter is an object of representing hierarchical data.
Return Value: This function return an object.
Below given are a few examples of the function given above.
Example 1:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent= "width=device-width, initial-scale = 1.0"/> <script src="https://d3js.org/d3.v4.min.js"> </script></head> <body> <script> var obj = d3.hierarchy({ name: "rootNode", children: [ { name: "child1" }, { name: "child2", children: [ { name: "grandChild1" }, { name: "grandChild2" }, { name: "grandChild3" }, { name: "grandChild4" } ] }, { name: "child3", children: [ { name: "grandChild5" }, { name: "grandChild6" }, ] } ] }); console.log(obj); </script></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent= "width=device-width, initial-scale = 1.0"/> <script src="https://d3js.org/d3.v4.min.js"> </script></head> <body> <script> var obj = d3.hierarchy({ name: "rootNode", children: [ { name: "child1" }, { name: "child2", children: [ { name: "grandChild1" }, ] } ] }); console.log(obj); console.log(obj.data); console.log(obj.data.children[0]); </script></body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
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
Difference Between PUT and PATCH Request
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": 25809,
"s": 25781,
"text": "\n23 Sep, 2020"
},
{
"code": null,
"e": 26000,
"s": 25809,
"text": "The d3.hierarchy() function in D3.js library is used to construct a root node data from a given hierarchical data. The data that is given must be of an object and must represent a root node."
},
{
"code": null,
"e": 26008,
"s": 26000,
"text": "Syntax:"
},
{
"code": null,
"e": 26040,
"s": 26008,
"text": "d3.hierarchy(data[, children]);"
},
{
"code": null,
"e": 26127,
"s": 26040,
"text": "Parameters: This function takes a single parameter as given above and described below."
},
{
"code": null,
"e": 26196,
"s": 26127,
"text": "data: This parameter is an object of representing hierarchical data."
},
{
"code": null,
"e": 26242,
"s": 26196,
"text": "Return Value: This function return an object."
},
{
"code": null,
"e": 26302,
"s": 26242,
"text": "Below given are a few examples of the function given above."
},
{
"code": null,
"e": 26313,
"s": 26302,
"text": "Example 1:"
},
{
"code": null,
"e": 26318,
"s": 26313,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" path1tent= \"width=device-width, initial-scale = 1.0\"/> <script src=\"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <script> var obj = d3.hierarchy({ name: \"rootNode\", children: [ { name: \"child1\" }, { name: \"child2\", children: [ { name: \"grandChild1\" }, { name: \"grandChild2\" }, { name: \"grandChild3\" }, { name: \"grandChild4\" } ] }, { name: \"child3\", children: [ { name: \"grandChild5\" }, { name: \"grandChild6\" }, ] } ] }); console.log(obj); </script></body> </html>",
"e": 27330,
"s": 26318,
"text": null
},
{
"code": null,
"e": 27338,
"s": 27330,
"text": "Output:"
},
{
"code": null,
"e": 27349,
"s": 27338,
"text": "Example 2:"
},
{
"code": null,
"e": 27354,
"s": 27349,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" path1tent= \"width=device-width, initial-scale = 1.0\"/> <script src=\"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <script> var obj = d3.hierarchy({ name: \"rootNode\", children: [ { name: \"child1\" }, { name: \"child2\", children: [ { name: \"grandChild1\" }, ] } ] }); console.log(obj); console.log(obj.data); console.log(obj.data.children[0]); </script></body> </html>",
"e": 28077,
"s": 27354,
"text": null
},
{
"code": null,
"e": 28085,
"s": 28077,
"text": "Output:"
},
{
"code": null,
"e": 28091,
"s": 28085,
"text": "D3.js"
},
{
"code": null,
"e": 28102,
"s": 28091,
"text": "JavaScript"
},
{
"code": null,
"e": 28119,
"s": 28102,
"text": "Web Technologies"
},
{
"code": null,
"e": 28217,
"s": 28119,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28257,
"s": 28217,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28302,
"s": 28257,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28363,
"s": 28302,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28435,
"s": 28363,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28476,
"s": 28435,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28516,
"s": 28476,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28549,
"s": 28516,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28594,
"s": 28549,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28637,
"s": 28594,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Javascript String @@iterator Method - GeeksforGeeks
|
28 Apr, 2021
String [@@iterator]( ) Method is used to make String iterable. [@@iterator]() returns iterator object which iterate over all code point of String. String[@@iterator] is Built – in Property of String.
We can use this method by making a string iterator. We can make an iterator by calling the @@iterator property of String. In place of @@iterator, we use Symbol.iterator constant.
Syntax:
// Test String
var str ="String";
// iterator to String
var iter = str[Symbol.iterator]();
We can get iterator object with next(). It returns the object with keys value and done. The value key holds a real iterating value string and the done key holds true or false if iteration finishes it keeps true if not then false. We can get the value of the object by str.value and done by str.done.
Example 1: Below is the code that illustrates the use of above approach.
Javascript
<script> const str = 'GFG'; const iterator = str[Symbol.iterator](); let theChar = iterator.next(); for(let i = 0; i < str.length ;i++) { console.log(theChar.value , theChar.done); theChar = iterator.next(); }</script>
Output :
"G" false
"F" false
"G" false
We can use @@iterator method without assigning iterator by using for — of loop to iterate over-collection of data by using @@iterator method. On each iteration for — of loop call _next().value to iterate in the collection.
Example 2: Below is the code that illustrates the use of above approach.
Javascript
<script> const str = 'GFG'; const iterator = str[Symbol.iterator](); let theChar = iterator; for(let i = 0; i < str.length ;i++) { console.log(theChar.next().value ); } // Using for - of loop console.log("Iterating by for-of loop :") for(let i of str) { console.log(i) }</script>
Output:
"G"
"F"
"G"
Iterating by for-of loop :
"G"
"F"
"G"
JavaScript-Methods
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 26746,
"s": 26545,
"text": "String [@@iterator]( ) Method is used to make String iterable. [@@iterator]() returns iterator object which iterate over all code point of String. String[@@iterator] is Built – in Property of String. "
},
{
"code": null,
"e": 26925,
"s": 26746,
"text": "We can use this method by making a string iterator. We can make an iterator by calling the @@iterator property of String. In place of @@iterator, we use Symbol.iterator constant."
},
{
"code": null,
"e": 26933,
"s": 26925,
"text": "Syntax:"
},
{
"code": null,
"e": 27026,
"s": 26933,
"text": "// Test String\nvar str =\"String\"; \n\n// iterator to String\nvar iter = str[Symbol.iterator]();"
},
{
"code": null,
"e": 27326,
"s": 27026,
"text": "We can get iterator object with next(). It returns the object with keys value and done. The value key holds a real iterating value string and the done key holds true or false if iteration finishes it keeps true if not then false. We can get the value of the object by str.value and done by str.done."
},
{
"code": null,
"e": 27399,
"s": 27326,
"text": "Example 1: Below is the code that illustrates the use of above approach."
},
{
"code": null,
"e": 27410,
"s": 27399,
"text": "Javascript"
},
{
"code": "<script> const str = 'GFG'; const iterator = str[Symbol.iterator](); let theChar = iterator.next(); for(let i = 0; i < str.length ;i++) { console.log(theChar.value , theChar.done); theChar = iterator.next(); }</script>",
"e": 27642,
"s": 27410,
"text": null
},
{
"code": null,
"e": 27652,
"s": 27642,
"text": "Output : "
},
{
"code": null,
"e": 27682,
"s": 27652,
"text": "\"G\" false\n\"F\" false\n\"G\" false"
},
{
"code": null,
"e": 27905,
"s": 27682,
"text": "We can use @@iterator method without assigning iterator by using for — of loop to iterate over-collection of data by using @@iterator method. On each iteration for — of loop call _next().value to iterate in the collection."
},
{
"code": null,
"e": 27978,
"s": 27905,
"text": "Example 2: Below is the code that illustrates the use of above approach."
},
{
"code": null,
"e": 27989,
"s": 27978,
"text": "Javascript"
},
{
"code": "<script> const str = 'GFG'; const iterator = str[Symbol.iterator](); let theChar = iterator; for(let i = 0; i < str.length ;i++) { console.log(theChar.next().value ); } // Using for - of loop console.log(\"Iterating by for-of loop :\") for(let i of str) { console.log(i) }</script>",
"e": 28294,
"s": 27989,
"text": null
},
{
"code": null,
"e": 28302,
"s": 28294,
"text": "Output:"
},
{
"code": null,
"e": 28354,
"s": 28302,
"text": "\"G\"\n\"F\"\n\"G\"\nIterating by for-of loop :\n\"G\"\n\"F\"\n\"G\""
},
{
"code": null,
"e": 28373,
"s": 28354,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 28380,
"s": 28373,
"text": "Picked"
},
{
"code": null,
"e": 28391,
"s": 28380,
"text": "JavaScript"
},
{
"code": null,
"e": 28408,
"s": 28391,
"text": "Web Technologies"
},
{
"code": null,
"e": 28506,
"s": 28408,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28546,
"s": 28506,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28607,
"s": 28546,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28648,
"s": 28607,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28670,
"s": 28648,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28724,
"s": 28670,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28764,
"s": 28724,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28797,
"s": 28764,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28840,
"s": 28797,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28902,
"s": 28840,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
C# | How to get the Standard Output Stream through Console - GeeksforGeeks
|
28 Jan, 2019
Given a normal console, the task is to get the Standard Output Stream through this Console in C#.
Approach: This can be done using the Out property in the Console class of the System package in C#.
Program: Getting the Standard Output Stream
// C# program to illustrate the// Console.Out Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the Standard Output Stream Console.WriteLine("Standard Output Stream: {0}", Console.Out); }}}
Output:
Note: The TextWriter represents the standard output stream.
CSharp-Console-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Class and Object
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
Introduction to .NET Framework
C# | Arrays
|
[
{
"code": null,
"e": 25355,
"s": 25327,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 25453,
"s": 25355,
"text": "Given a normal console, the task is to get the Standard Output Stream through this Console in C#."
},
{
"code": null,
"e": 25553,
"s": 25453,
"text": "Approach: This can be done using the Out property in the Console class of the System package in C#."
},
{
"code": null,
"e": 25597,
"s": 25553,
"text": "Program: Getting the Standard Output Stream"
},
{
"code": "// C# program to illustrate the// Console.Out Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the Standard Output Stream Console.WriteLine(\"Standard Output Stream: {0}\", Console.Out); }}}",
"e": 26000,
"s": 25597,
"text": null
},
{
"code": null,
"e": 26008,
"s": 26000,
"text": "Output:"
},
{
"code": null,
"e": 26068,
"s": 26008,
"text": "Note: The TextWriter represents the standard output stream."
},
{
"code": null,
"e": 26089,
"s": 26068,
"text": "CSharp-Console-Class"
},
{
"code": null,
"e": 26092,
"s": 26089,
"text": "C#"
},
{
"code": null,
"e": 26190,
"s": 26092,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26205,
"s": 26190,
"text": "C# | Delegates"
},
{
"code": null,
"e": 26227,
"s": 26205,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 26273,
"s": 26227,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 26296,
"s": 26273,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26318,
"s": 26296,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 26336,
"s": 26318,
"text": "C# | Constructors"
},
{
"code": null,
"e": 26376,
"s": 26336,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 26398,
"s": 26376,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 26429,
"s": 26398,
"text": "Introduction to .NET Framework"
}
] |
Python | Numpy matrix.trace() - GeeksforGeeks
|
29 May, 2019
With the help of Numpy matrix.trace() method, we can find the sum of all the elements of diagonal of a matrix by using the matrix.trace() method.
Syntax : matrix.trace()Return : Return sum of a diagonal elements of a matrix
Example #1 :In this example we can see that by using matrix.trace() method can help us to find the sum of all the elements of a diagonal of given matrix.
# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[4, 1; 12, 3]') # applying matrix.trace() methodgeek = gfg.trace() print(geek)
[[7]]
Example #2 :
# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[4, 1, 9; 12, 3, 1; 4, 5, 6]') # applying matrix.trace() methodgeek = gfg.trace() print(geek)
[[13]]
Python numpy-Matrix 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": 26436,
"s": 26408,
"text": "\n29 May, 2019"
},
{
"code": null,
"e": 26582,
"s": 26436,
"text": "With the help of Numpy matrix.trace() method, we can find the sum of all the elements of diagonal of a matrix by using the matrix.trace() method."
},
{
"code": null,
"e": 26660,
"s": 26582,
"text": "Syntax : matrix.trace()Return : Return sum of a diagonal elements of a matrix"
},
{
"code": null,
"e": 26814,
"s": 26660,
"text": "Example #1 :In this example we can see that by using matrix.trace() method can help us to find the sum of all the elements of a diagonal of given matrix."
},
{
"code": "# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[4, 1; 12, 3]') # applying matrix.trace() methodgeek = gfg.trace() print(geek)",
"e": 27021,
"s": 26814,
"text": null
},
{
"code": null,
"e": 27028,
"s": 27021,
"text": "[[7]]\n"
},
{
"code": null,
"e": 27041,
"s": 27028,
"text": "Example #2 :"
},
{
"code": "# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[4, 1, 9; 12, 3, 1; 4, 5, 6]') # applying matrix.trace() methodgeek = gfg.trace() print(geek)",
"e": 27263,
"s": 27041,
"text": null
},
{
"code": null,
"e": 27271,
"s": 27263,
"text": "[[13]]\n"
},
{
"code": null,
"e": 27300,
"s": 27271,
"text": "Python numpy-Matrix Function"
},
{
"code": null,
"e": 27313,
"s": 27300,
"text": "Python-numpy"
},
{
"code": null,
"e": 27320,
"s": 27313,
"text": "Python"
},
{
"code": null,
"e": 27418,
"s": 27320,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27436,
"s": 27418,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27471,
"s": 27436,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27503,
"s": 27471,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27525,
"s": 27503,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27567,
"s": 27525,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27597,
"s": 27567,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27623,
"s": 27597,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27652,
"s": 27623,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27696,
"s": 27652,
"text": "Reading and Writing to text files in Python"
}
] |
Sound generation on clicking the button using JavaScript - GeeksforGeeks
|
16 Apr, 2019
The sound generation after clicking the button, receiving notifications or at the time of page load can be done by using JavaScript.
Note:
URL provided in the playSound function can be changed to give the custom sound url.
Style property is not the part of implementation. It is used to provide a nice interface for viewers.
Example: This example generating the sound after clicking the button.
<!DOCTYPE html><html> <head> <title> Sound generation after clicking the button </title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src='https://code.jquery.com/jquery-2.2.0.min.js'> </script> <script src='https://cdn.rawgit.com/admsev/jquery-play-sound/master/jquery.playSound.js'> </script></head> <body style="text-align:center;"> <div class="container-fluid" style="margin:35px;"> <p style="font-size:30px;"> <strong> Click on the button to generate sound </strong> </p> <br><br> <button class="btn btn-primary" onclick='$.playSound("http://tusharbaheti28.000webhostapp.com/notification.mp3")'> Click Me! </button> </div></body> </html>
Output:
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26021,
"s": 25993,
"text": "\n16 Apr, 2019"
},
{
"code": null,
"e": 26154,
"s": 26021,
"text": "The sound generation after clicking the button, receiving notifications or at the time of page load can be done by using JavaScript."
},
{
"code": null,
"e": 26160,
"s": 26154,
"text": "Note:"
},
{
"code": null,
"e": 26244,
"s": 26160,
"text": "URL provided in the playSound function can be changed to give the custom sound url."
},
{
"code": null,
"e": 26346,
"s": 26244,
"text": "Style property is not the part of implementation. It is used to provide a nice interface for viewers."
},
{
"code": null,
"e": 26416,
"s": 26346,
"text": "Example: This example generating the sound after clicking the button."
},
{
"code": "<!DOCTYPE html><html> <head> <title> Sound generation after clicking the button </title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src='https://code.jquery.com/jquery-2.2.0.min.js'> </script> <script src='https://cdn.rawgit.com/admsev/jquery-play-sound/master/jquery.playSound.js'> </script></head> <body style=\"text-align:center;\"> <div class=\"container-fluid\" style=\"margin:35px;\"> <p style=\"font-size:30px;\"> <strong> Click on the button to generate sound </strong> </p> <br><br> <button class=\"btn btn-primary\" onclick='$.playSound(\"http://tusharbaheti28.000webhostapp.com/notification.mp3\")'> Click Me! </button> </div></body> </html> ",
"e": 27291,
"s": 26416,
"text": null
},
{
"code": null,
"e": 27299,
"s": 27291,
"text": "Output:"
},
{
"code": null,
"e": 27310,
"s": 27299,
"text": "JavaScript"
},
{
"code": null,
"e": 27327,
"s": 27310,
"text": "Web Technologies"
},
{
"code": null,
"e": 27354,
"s": 27327,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 27452,
"s": 27354,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27492,
"s": 27452,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27537,
"s": 27492,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27598,
"s": 27537,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27670,
"s": 27598,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27722,
"s": 27670,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 27762,
"s": 27722,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27795,
"s": 27762,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27840,
"s": 27795,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27883,
"s": 27840,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
GATE | GATE CS 2020 | Question 12 - GeeksforGeeks
|
26 May, 2021
For parameters a and b, both of which are ω(1), T(n)=T(n1/a)+1, and T(b)=1. Then T(n) is(A) Θ(logalogbn)(B) Θ(logabn)(C) Θ(logblogan)(D) Θ(log2log2n)Answer: (A)Explanation: Given,
T(n) = T(n1/a)+1,
T(b) = 1
Now, using iterative method,
= T(n)
= [T(n1/a2)+1] + 1
= [T(n1/a3)+1] + 2
= [T(n1/a4)+1] + 3
.
.
.
= [T(n1/ak)+1] + (k-1)
= T(n1/ak) + k
Let,
→ n1/ak = b
→ log(n1/ak) = log(b)
→ ak = log(n) / log (b) = logb(n)
→ k = logalogb(n)
Therefore,
= T(n1/ak) + k
= T(b) + logalogb(n)
= 1 + logalogb(n)
= Θ(logalogb(n))
Option (A) is correct.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
|
[
{
"code": null,
"e": 25713,
"s": 25685,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 25893,
"s": 25713,
"text": "For parameters a and b, both of which are ω(1), T(n)=T(n1/a)+1, and T(b)=1. Then T(n) is(A) Θ(logalogbn)(B) Θ(logabn)(C) Θ(logblogan)(D) Θ(log2log2n)Answer: (A)Explanation: Given,"
},
{
"code": null,
"e": 25922,
"s": 25893,
"text": "T(n) = T(n1/a)+1, \nT(b) = 1 "
},
{
"code": null,
"e": 25951,
"s": 25922,
"text": "Now, using iterative method,"
},
{
"code": null,
"e": 26061,
"s": 25951,
"text": "= T(n) \n= [T(n1/a2)+1] + 1\n= [T(n1/a3)+1] + 2\n= [T(n1/a4)+1] + 3\n.\n.\n.\n= [T(n1/ak)+1] + (k-1)\n= T(n1/ak) + k "
},
{
"code": null,
"e": 26066,
"s": 26061,
"text": "Let,"
},
{
"code": null,
"e": 26152,
"s": 26066,
"text": "→ n1/ak = b\n→ log(n1/ak) = log(b)\n→ ak = log(n) / log (b) = logb(n)\n→ k = logalogb(n)"
},
{
"code": null,
"e": 26163,
"s": 26152,
"text": "Therefore,"
},
{
"code": null,
"e": 26235,
"s": 26163,
"text": "= T(n1/ak) + k\n= T(b) + logalogb(n)\n= 1 + logalogb(n)\n= Θ(logalogb(n)) "
},
{
"code": null,
"e": 26279,
"s": 26235,
"text": "Option (A) is correct.Quiz of this Question"
},
{
"code": null,
"e": 26284,
"s": 26279,
"text": "GATE"
},
{
"code": null,
"e": 26382,
"s": 26284,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26416,
"s": 26382,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26450,
"s": 26416,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26484,
"s": 26450,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 26517,
"s": 26484,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26553,
"s": 26517,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26587,
"s": 26553,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 26623,
"s": 26587,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 26657,
"s": 26623,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 26691,
"s": 26657,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
turtle.heading() function in Python
|
14 Mar, 2022
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to return the turtle’s current heading. It doesn’t require any argument.
Syntax :
turtle.heading()
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle # default heading valueprint(turtle.heading())
Output :
0.0
Example 2 :
Python3
# import packageimport turtle # set turtle speed# for better understandingsturtle.speed(1) # loop for patternfor i in range(4): turtle.forward(100) # get heading value val = turtle.heading() # write it turtle.write(str(val)) turtle.backward(100) turtle.left(90)
Output :
sumitgumber28
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Mar, 2022"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 340,
"s": 245,
"text": "This function is used to return the turtle’s current heading. It doesn’t require any argument."
},
{
"code": null,
"e": 349,
"s": 340,
"text": "Syntax :"
},
{
"code": null,
"e": 366,
"s": 349,
"text": "turtle.heading()"
},
{
"code": null,
"e": 435,
"s": 366,
"text": "Below is the implementation of the above method with some examples :"
},
{
"code": null,
"e": 447,
"s": 435,
"text": "Example 1 :"
},
{
"code": null,
"e": 455,
"s": 447,
"text": "Python3"
},
{
"code": "# import packageimport turtle # default heading valueprint(turtle.heading())",
"e": 532,
"s": 455,
"text": null
},
{
"code": null,
"e": 545,
"s": 536,
"text": "Output :"
},
{
"code": null,
"e": 551,
"s": 547,
"text": "0.0"
},
{
"code": null,
"e": 565,
"s": 553,
"text": "Example 2 :"
},
{
"code": null,
"e": 575,
"s": 567,
"text": "Python3"
},
{
"code": "# import packageimport turtle # set turtle speed# for better understandingsturtle.speed(1) # loop for patternfor i in range(4): turtle.forward(100) # get heading value val = turtle.heading() # write it turtle.write(str(val)) turtle.backward(100) turtle.left(90)",
"e": 868,
"s": 575,
"text": null
},
{
"code": null,
"e": 881,
"s": 872,
"text": "Output :"
},
{
"code": null,
"e": 899,
"s": 885,
"text": "sumitgumber28"
},
{
"code": null,
"e": 913,
"s": 899,
"text": "Python-turtle"
},
{
"code": null,
"e": 920,
"s": 913,
"text": "Python"
}
] |
How to plot overlapping lines in Matplotlib?
|
To plot overlapping lines in matplotlib, we can use variable overlapping that basically sets the opacity or alpha value in the plot.
Set the figure size and adjust the padding between and around the subplots.
Initialize a variable overlapping to set the alpha value of the line.
Plot line1 and line2 with red and green colors, respectively, with the same alpha value.
To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
overlapping = 0.150
line1 = plt.plot([1, 3, 5, 2, 5, 3, 1], c='red', alpha=overlapping, lw=5)
line2 = plt.plot([7, 2, 5, 7, 5, 2, 7], c='green', alpha=overlapping,
lw=5)
plt.show()
|
[
{
"code": null,
"e": 1320,
"s": 1187,
"text": "To plot overlapping lines in matplotlib, we can use variable overlapping that basically sets the opacity or alpha value in the plot."
},
{
"code": null,
"e": 1396,
"s": 1320,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1466,
"s": 1396,
"text": "Initialize a variable overlapping to set the alpha value of the line."
},
{
"code": null,
"e": 1555,
"s": 1466,
"text": "Plot line1 and line2 with red and green colors, respectively, with the same alpha value."
},
{
"code": null,
"e": 1597,
"s": 1555,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1902,
"s": 1597,
"text": "from matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\noverlapping = 0.150\nline1 = plt.plot([1, 3, 5, 2, 5, 3, 1], c='red', alpha=overlapping, lw=5)\nline2 = plt.plot([7, 2, 5, 7, 5, 2, 7], c='green', alpha=overlapping,\nlw=5)\nplt.show()"
}
] |
URL getPort() method in Java with Examples
|
27 Dec, 2018
The getPort() function is a part of URL class. The function getPort() returns the port of a specified URL. The function returns the port number or -1 if the port is not set
Function Signature
public int getPort()
Syntax
url.getPort()
Return Type: The function returns Integer Type
Parameter: This function does not require any parameter
Below programs illustrates the use of getPort() function:
Example 1display port of specified URL
// Java program to show the use of the function getPort()import java.net.*;class Solution { public static void main(String args[]) { // url object URL url = null; try { // create a URL url = new URL("https:// www.geeksforgeeks.org:80"); // get the port int _port = url.getPort(); // display the URL System.out.println("URL = " + url); // display the port System.out.println(" Port=" + _port); } // if any error occurs catch (Exception e) { // display the error System.out.println(e); } }}
URL = https:// www.geeksforgeeks.org:80
Port=80
Example 2: Create a URL with no defined port and then try to get the port using the getPort() function.
// Java program to show the// use of the function getPort() import java.net.*; class Solution { public static void main(String args[]) { // url object URL url = null; try { // create a URL url = new URL("https:// www.geeksforgeeks.org"); // get the port int _port = url.getPort(); // display the URL System.out.println("URL = " + url); // display the port System.out.println(" Port=" + _port); } // if any error occurs catch (Exception e) { // display the error System.out.println(e); } }}
URL = https:// www.geeksforgeeks.org
Port=-1
Java-Functions
Java-net-package
Java-URL
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Singleton Class in Java
Set in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Dec, 2018"
},
{
"code": null,
"e": 201,
"s": 28,
"text": "The getPort() function is a part of URL class. The function getPort() returns the port of a specified URL. The function returns the port number or -1 if the port is not set"
},
{
"code": null,
"e": 220,
"s": 201,
"text": "Function Signature"
},
{
"code": null,
"e": 242,
"s": 220,
"text": "public int getPort()\n"
},
{
"code": null,
"e": 249,
"s": 242,
"text": "Syntax"
},
{
"code": null,
"e": 264,
"s": 249,
"text": "url.getPort()\n"
},
{
"code": null,
"e": 311,
"s": 264,
"text": "Return Type: The function returns Integer Type"
},
{
"code": null,
"e": 367,
"s": 311,
"text": "Parameter: This function does not require any parameter"
},
{
"code": null,
"e": 425,
"s": 367,
"text": "Below programs illustrates the use of getPort() function:"
},
{
"code": null,
"e": 464,
"s": 425,
"text": "Example 1display port of specified URL"
},
{
"code": "// Java program to show the use of the function getPort()import java.net.*;class Solution { public static void main(String args[]) { // url object URL url = null; try { // create a URL url = new URL(\"https:// www.geeksforgeeks.org:80\"); // get the port int _port = url.getPort(); // display the URL System.out.println(\"URL = \" + url); // display the port System.out.println(\" Port=\" + _port); } // if any error occurs catch (Exception e) { // display the error System.out.println(e); } }}",
"e": 1136,
"s": 464,
"text": null
},
{
"code": null,
"e": 1186,
"s": 1136,
"text": "URL = https:// www.geeksforgeeks.org:80\n Port=80\n"
},
{
"code": null,
"e": 1290,
"s": 1186,
"text": "Example 2: Create a URL with no defined port and then try to get the port using the getPort() function."
},
{
"code": "// Java program to show the// use of the function getPort() import java.net.*; class Solution { public static void main(String args[]) { // url object URL url = null; try { // create a URL url = new URL(\"https:// www.geeksforgeeks.org\"); // get the port int _port = url.getPort(); // display the URL System.out.println(\"URL = \" + url); // display the port System.out.println(\" Port=\" + _port); } // if any error occurs catch (Exception e) { // display the error System.out.println(e); } }}",
"e": 1962,
"s": 1290,
"text": null
},
{
"code": null,
"e": 2009,
"s": 1962,
"text": "URL = https:// www.geeksforgeeks.org\n Port=-1\n"
},
{
"code": null,
"e": 2024,
"s": 2009,
"text": "Java-Functions"
},
{
"code": null,
"e": 2041,
"s": 2024,
"text": "Java-net-package"
},
{
"code": null,
"e": 2050,
"s": 2041,
"text": "Java-URL"
},
{
"code": null,
"e": 2055,
"s": 2050,
"text": "Java"
},
{
"code": null,
"e": 2060,
"s": 2055,
"text": "Java"
},
{
"code": null,
"e": 2158,
"s": 2060,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2209,
"s": 2158,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2240,
"s": 2209,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2259,
"s": 2240,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2289,
"s": 2259,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 2307,
"s": 2289,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2327,
"s": 2307,
"text": "Collections in Java"
},
{
"code": null,
"e": 2359,
"s": 2327,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 2374,
"s": 2359,
"text": "Stream In Java"
},
{
"code": null,
"e": 2398,
"s": 2374,
"text": "Singleton Class in Java"
}
] |
Python – Alternate List elements
|
30 Aug, 2020
Given 2 lists, print element in zig-zag manner, i.e print similar indices of lists and then proceed to next.
Input : test_list1 = [5, 3, 1], test_list2 = [6, 4, 2]Output : [5, 6, 3, 4, 1, 2, 4]Explanation : 5 and 6, as in 0th index are printed first, then 3 and 4 on 1st index, and so on.
Input : test_list1 = [5, 3, 1, 9], test_list2 = [6, 4, 2, 10]Output : [5, 6, 3, 4, 1, 2, 4, 9, 10]Explanation : 5 and 6, as in 0th index are printed first, then 3 and 4 on 1st index, and so on.
Method #1 : Using loop
This is one of the ways in which this task can be performed. In this we plainly perform iteration and append the similar index elements one after another in result list.
Python3
# Python3 code to demonstrate working of# Alternate List elements# Using loop # initializing liststest_list1 = [5, 3, 1, 4, 7]test_list2 = [6, 4, 2, 5, 1] # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2)) # Using loop to print elements in criss cross mannerres = []for idx in range(0, len(test_list1)): res.append(test_list1[idx]) res.append(test_list2[idx]) # printing resultprint("The zig-zag printing of elements : " + str(res))
The original list 1 : [5, 3, 1, 4, 7]
The original list 2 : [6, 4, 2, 5, 1]
The zig-zag printing of elements : [5, 6, 3, 4, 1, 2, 4, 5, 7, 1]
Method #2 : Using zip() + loop
The combination of above functions can be used to solve this problem. In this, we pair each element with similar index using zip() and then each element is fed into result list using loop.
Python3
# Python3 code to demonstrate working of # Alternate List elements# Using zip() + loop # initializing liststest_list1 = [5, 3, 1, 4, 7]test_list2 = [6, 4, 2, 5, 1] # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2)) # Using zip() to perform pairing and loop to # get elements into result listres = []for ele1, ele2 in zip(test_list1, test_list2): res.append(ele1) res.append(ele2) # printing result print("The zig-zag printing of elements : " + str(res))
The original list 1 : [5, 3, 1, 4, 7]
The original list 2 : [6, 4, 2, 5, 1]
The zig-zag printing of elements : [5, 6, 3, 4, 1, 2, 4, 5, 7, 1]
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 ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Aug, 2020"
},
{
"code": null,
"e": 137,
"s": 28,
"text": "Given 2 lists, print element in zig-zag manner, i.e print similar indices of lists and then proceed to next."
},
{
"code": null,
"e": 317,
"s": 137,
"text": "Input : test_list1 = [5, 3, 1], test_list2 = [6, 4, 2]Output : [5, 6, 3, 4, 1, 2, 4]Explanation : 5 and 6, as in 0th index are printed first, then 3 and 4 on 1st index, and so on."
},
{
"code": null,
"e": 511,
"s": 317,
"text": "Input : test_list1 = [5, 3, 1, 9], test_list2 = [6, 4, 2, 10]Output : [5, 6, 3, 4, 1, 2, 4, 9, 10]Explanation : 5 and 6, as in 0th index are printed first, then 3 and 4 on 1st index, and so on."
},
{
"code": null,
"e": 536,
"s": 511,
"text": "Method #1 : Using loop "
},
{
"code": null,
"e": 706,
"s": 536,
"text": "This is one of the ways in which this task can be performed. In this we plainly perform iteration and append the similar index elements one after another in result list."
},
{
"code": null,
"e": 714,
"s": 706,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Alternate List elements# Using loop # initializing liststest_list1 = [5, 3, 1, 4, 7]test_list2 = [6, 4, 2, 5, 1] # printing original listsprint(\"The original list 1 : \" + str(test_list1))print(\"The original list 2 : \" + str(test_list2)) # Using loop to print elements in criss cross mannerres = []for idx in range(0, len(test_list1)): res.append(test_list1[idx]) res.append(test_list2[idx]) # printing resultprint(\"The zig-zag printing of elements : \" + str(res))",
"e": 1230,
"s": 714,
"text": null
},
{
"code": null,
"e": 1373,
"s": 1230,
"text": "The original list 1 : [5, 3, 1, 4, 7]\nThe original list 2 : [6, 4, 2, 5, 1]\nThe zig-zag printing of elements : [5, 6, 3, 4, 1, 2, 4, 5, 7, 1]\n"
},
{
"code": null,
"e": 1404,
"s": 1373,
"text": "Method #2 : Using zip() + loop"
},
{
"code": null,
"e": 1593,
"s": 1404,
"text": "The combination of above functions can be used to solve this problem. In this, we pair each element with similar index using zip() and then each element is fed into result list using loop."
},
{
"code": null,
"e": 1601,
"s": 1593,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Alternate List elements# Using zip() + loop # initializing liststest_list1 = [5, 3, 1, 4, 7]test_list2 = [6, 4, 2, 5, 1] # printing original listsprint(\"The original list 1 : \" + str(test_list1))print(\"The original list 2 : \" + str(test_list2)) # Using zip() to perform pairing and loop to # get elements into result listres = []for ele1, ele2 in zip(test_list1, test_list2): res.append(ele1) res.append(ele2) # printing result print(\"The zig-zag printing of elements : \" + str(res))",
"e": 2143,
"s": 1601,
"text": null
},
{
"code": null,
"e": 2286,
"s": 2143,
"text": "The original list 1 : [5, 3, 1, 4, 7]\nThe original list 2 : [6, 4, 2, 5, 1]\nThe zig-zag printing of elements : [5, 6, 3, 4, 1, 2, 4, 5, 7, 1]\n"
},
{
"code": null,
"e": 2307,
"s": 2286,
"text": "Python list-programs"
},
{
"code": null,
"e": 2314,
"s": 2307,
"text": "Python"
},
{
"code": null,
"e": 2330,
"s": 2314,
"text": "Python Programs"
},
{
"code": null,
"e": 2428,
"s": 2330,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2460,
"s": 2428,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2487,
"s": 2460,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2518,
"s": 2487,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2541,
"s": 2518,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2562,
"s": 2541,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2584,
"s": 2562,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2623,
"s": 2584,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2661,
"s": 2623,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2710,
"s": 2661,
"text": "Python | Convert string dictionary to dictionary"
}
] |
OS Process Management - GeeksforGeeks
|
28 Jul, 2021
void P (binary_semaphore *s) {
unsigned y;
unsigned *x = &(s->value);
do {
fetch-and-set x, y;
} while (y);
}
void V (binary_semaphore *s) {
S->value = 0;
}
Semaphore S is initialized to 2
Process W executes S=1, x=1 but it doesn't update the x variable.
Then process Y executes S=0, it decrements x, now x= -2 and
signal semaphore S=1
Now process Z executes s=0, x=-4, signal semaphore S=1
Now process W updates x=1, S=2
Then process X executes X=2
Process X: Process Y:
private i; private i;
for (i=0; i < n; i++) { for (i=0; i < n; i++) {
a[i] = f(i); EntryY(R, S);
ExitX(R, S); b[i]=g(a[i]);
} }
ExitX(R, S) {
P(R);
V(S);
}
EntryY (R, S) {
P(S);
V(R);
}
ExitX(R, S) {
V(R);
V(S);
}
EntryY(R, S) {
P(R);
P(S);
}
ExitX(R, S) {
P(S);
V(R);
}
EntryY(R, S) {
V(S);
P(R);
}
ExitX(R, S) {
V(R);
P(S);
}
EntryY(R, S) {
V(S);
P(R);
}
The purpose here is neither the deadlock should occur
nor the binary semaphores be assigned value greater
than one.
A leads to deadlock
B can increase value of semaphores b/w 1 to n
D may increase the value of semaphore R and S to
2 in some cases
Process X: Process Y:
private i; private i;
for (i=0; i < n; i++) { for (i=0; i < n; i++) {
a[i] = f(i); EntryY(R, S);
ExitX(R, S); b[i]=g(a[i]);
} }
ExitX(R, S) {
P(R);
V(S);
}
EntryY (R, S) {
P(S);
V(R);
}
ExitX(R, S) {
V(R);
V(S);
}
EntryY(R, S) {
P(R);
P(S);
}
ExitX(R, S) {
P(S);
V(R);
}
EntryY(R, S) {
V(S);
P(R);
}
ExitX(R, S) {
V(R);
P(S);
}
EntryY(R, S) {
V(S);
P(R);
}
The purpose here is neither the deadlock should occur
nor the binary semaphores be assigned value greater
than one.
A leads to deadlock
B can increase value of semaphores b/w 1 to n
D may increase the value of semaphore R and S to
2 in some cases
fork();
fork();
fork();
fork (); // Line 1
fork (); // Line 2
fork (); // Line 3
L1 // There will be 1 child process created by line 1
/ \
L2 L2 // There will be 2 child processes created by line 2
/ \ / \
L3 L3 L3 L3 // There will be 4 child processes created by line 3
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Learn C++ Programming Step by Step - A 20 Day Curriculum!
Must Do Coding Questions for Product Based Companies
Samsung R&D Internship Interview Experience (On-Campus)
Software Testing - Web Based Testing
What are the different ways of Data Representation?
Bash Script - Command Substitution
Naming Convention in C++
Floyd’s Cycle Finding Algorithm
Samsung R&D Interview Experience
|
[
{
"code": null,
"e": 34185,
"s": 34157,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 34359,
"s": 34185,
"text": "void P (binary_semaphore *s) {\n unsigned y;\n unsigned *x = &(s->value);\n do {\n fetch-and-set x, y;\n } while (y);\n}\n\nvoid V (binary_semaphore *s) {\n S->value = 0;\n}\n"
},
{
"code": null,
"e": 34658,
"s": 34359,
"text": "Semaphore S is initialized to 2\n\nProcess W executes S=1, x=1 but it doesn't update the x variable.\n\nThen process Y executes S=0, it decrements x, now x= -2 and \nsignal semaphore S=1\n\nNow process Z executes s=0, x=-4, signal semaphore S=1\nNow process W updates x=1, S=2\n\nThen process X executes X=2 "
},
{
"code": null,
"e": 34949,
"s": 34658,
"text": "Process X: Process Y:\nprivate i; private i;\nfor (i=0; i < n; i++) { for (i=0; i < n; i++) {\n a[i] = f(i); EntryY(R, S);\n ExitX(R, S); b[i]=g(a[i]);\n} }"
},
{
"code": null,
"e": 35016,
"s": 34949,
"text": "ExitX(R, S) {\n P(R);\n V(S);\n}\n\nEntryY (R, S) {\n P(S);\n V(R);\n}"
},
{
"code": null,
"e": 35082,
"s": 35016,
"text": "ExitX(R, S) {\n V(R);\n V(S);\n}\n\nEntryY(R, S) {\n P(R);\n P(S);\n}"
},
{
"code": null,
"e": 35147,
"s": 35082,
"text": "ExitX(R, S) {\n P(S);\n V(R);\n}\nEntryY(R, S) {\n V(S);\n P(R);\n}"
},
{
"code": null,
"e": 35212,
"s": 35147,
"text": "ExitX(R, S) {\n V(R);\n P(S);\n}\nEntryY(R, S) {\n V(S);\n P(R);\n}"
},
{
"code": null,
"e": 35461,
"s": 35212,
"text": "The purpose here is neither the deadlock should occur\nnor the binary semaphores be assigned value greater \nthan one.\nA leads to deadlock\nB can increase value of semaphores b/w 1 to n\nD may increase the value of semaphore R and S to\n 2 in some cases"
},
{
"code": null,
"e": 35752,
"s": 35461,
"text": "Process X: Process Y:\nprivate i; private i;\nfor (i=0; i < n; i++) { for (i=0; i < n; i++) {\n a[i] = f(i); EntryY(R, S);\n ExitX(R, S); b[i]=g(a[i]);\n} }"
},
{
"code": null,
"e": 35819,
"s": 35752,
"text": "ExitX(R, S) {\n P(R);\n V(S);\n}\n\nEntryY (R, S) {\n P(S);\n V(R);\n}"
},
{
"code": null,
"e": 35885,
"s": 35819,
"text": "ExitX(R, S) {\n V(R);\n V(S);\n}\n\nEntryY(R, S) {\n P(R);\n P(S);\n}"
},
{
"code": null,
"e": 35950,
"s": 35885,
"text": "ExitX(R, S) {\n P(S);\n V(R);\n}\nEntryY(R, S) {\n V(S);\n P(R);\n}"
},
{
"code": null,
"e": 36015,
"s": 35950,
"text": "ExitX(R, S) {\n V(R);\n P(S);\n}\nEntryY(R, S) {\n V(S);\n P(R);\n}"
},
{
"code": null,
"e": 36265,
"s": 36015,
"text": "The purpose here is neither the deadlock should occur\nnor the binary semaphores be assigned value greater \nthan one.\nA leads to deadlock\nB can increase value of semaphores b/w 1 to n\nD may increase the value of semaphore R and S to\n 2 in some cases"
},
{
"code": null,
"e": 36290,
"s": 36265,
"text": "fork();\nfork();\nfork(); "
},
{
"code": null,
"e": 36592,
"s": 36290,
"text": " fork (); // Line 1\n fork (); // Line 2\n fork (); // Line 3\n\n L1 // There will be 1 child process created by line 1\n / \\\n L2 L2 // There will be 2 child processes created by line 2\n / \\ / \\\nL3 L3 L3 L3 // There will be 4 child processes created by line 3"
},
{
"code": null,
"e": 36690,
"s": 36592,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 36764,
"s": 36690,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 36822,
"s": 36764,
"text": "Learn C++ Programming Step by Step - A 20 Day Curriculum!"
},
{
"code": null,
"e": 36875,
"s": 36822,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 36931,
"s": 36875,
"text": "Samsung R&D Internship Interview Experience (On-Campus)"
},
{
"code": null,
"e": 36968,
"s": 36931,
"text": "Software Testing - Web Based Testing"
},
{
"code": null,
"e": 37020,
"s": 36968,
"text": "What are the different ways of Data Representation?"
},
{
"code": null,
"e": 37055,
"s": 37020,
"text": "Bash Script - Command Substitution"
},
{
"code": null,
"e": 37080,
"s": 37055,
"text": "Naming Convention in C++"
},
{
"code": null,
"e": 37112,
"s": 37080,
"text": "Floyd’s Cycle Finding Algorithm"
}
] |
Convex Hull using Divide and Conquer Algorithm
|
22 Jun, 2022
A convex hull is the smallest convex polygon containing all the given points.
Input is an array of points specified by their x and y coordinates. The output is the convex hull of this set of points. Examples:
Input : points[] = {(0, 0), (0, 4), (-4, 0), (5, 0),
(0, -6), (1, 0)};
Output : (-4, 0), (5, 0), (0, -6), (0, 4)
Pre-requisite: Tangents between two convex polygons Algorithm: Given the set of points for which we have to find the convex hull. Suppose we know the convex hull of the left half points and the right half points, then the problem now is to merge these two convex hulls and determine the convex hull for the complete set. This can be done by finding the upper and lower tangent to the right and left convex hulls. This is illustrated here Tangents between two convex polygons Let the left convex hull be a and the right convex hull be b. Then the lower and upper tangents are named as 1 and 2 respectively, as shown in the figure. Then the red outline shows the final convex hull. Now the problem remains, how to find the convex hull for the left and right half. Now recursion comes into the picture, we divide the set of points until the number of points in the set is very small, say 5, and we can find the convex hull for these points by the brute algorithm. The merging of these halves would result in the convex hull for the complete set of points. Note: We have used the brute algorithm to find the convex hull for a small number of points and it has a time complexity of . But some people suggest the following, the convex hull for 3 or fewer points is the complete set of points. This is correct but the problem comes when we try to merge a left convex hull of 2 points and right convex hull of 3 points, then the program gets trapped in an infinite loop in some special cases. So, to get rid of this problem I directly found the convex hull for 5 or fewer points by algorithm, which is somewhat greater but does not affect the overall complexity of the algorithm.
CPP
// A divide and conquer program to find convex// hull of a given set of points.#include<bits/stdc++.h>using namespace std; // stores the centre of polygon (It is made// global because it is used in compare function)pair<int, int> mid; // determines the quadrant of a point// (used in compare())int quad(pair<int, int> p){ if (p.first >= 0 && p.second >= 0) return 1; if (p.first <= 0 && p.second >= 0) return 2; if (p.first <= 0 && p.second <= 0) return 3; return 4;} // Checks whether the line is crossing the polygonint orientation(pair<int, int> a, pair<int, int> b, pair<int, int> c){ int res = (b.second-a.second)*(c.first-b.first) - (c.second-b.second)*(b.first-a.first); if (res == 0) return 0; if (res > 0) return 1; return -1;} // compare function for sortingbool compare(pair<int, int> p1, pair<int, int> q1){ pair<int, int> p = make_pair(p1.first - mid.first, p1.second - mid.second); pair<int, int> q = make_pair(q1.first - mid.first, q1.second - mid.second); int one = quad(p); int two = quad(q); if (one != two) return (one < two); return (p.second*q.first < q.second*p.first);} // Finds upper tangent of two polygons 'a' and 'b'// represented as two vectors.vector<pair<int, int>> merger(vector<pair<int, int> > a, vector<pair<int, int> > b){ // n1 -> number of points in polygon a // n2 -> number of points in polygon b int n1 = a.size(), n2 = b.size(); int ia = 0, ib = 0; for (int i=1; i<n1; i++) if (a[i].first > a[ia].first) ia = i; // ib -> leftmost point of b for (int i=1; i<n2; i++) if (b[i].first < b[ib].first) ib=i; // finding the upper tangent int inda = ia, indb = ib; bool done = 0; while (!done) { done = 1; while (orientation(b[indb], a[inda], a[(inda+1)%n1]) >=0) inda = (inda + 1) % n1; while (orientation(a[inda], b[indb], b[(n2+indb-1)%n2]) <=0) { indb = (n2+indb-1)%n2; done = 0; } } int uppera = inda, upperb = indb; inda = ia, indb=ib; done = 0; int g = 0; while (!done)//finding the lower tangent { done = 1; while (orientation(a[inda], b[indb], b[(indb+1)%n2])>=0) indb=(indb+1)%n2; while (orientation(b[indb], a[inda], a[(n1+inda-1)%n1])<=0) { inda=(n1+inda-1)%n1; done=0; } } int lowera = inda, lowerb = indb; vector<pair<int, int>> ret; //ret contains the convex hull after merging the two convex hulls //with the points sorted in anti-clockwise order int ind = uppera; ret.push_back(a[uppera]); while (ind != lowera) { ind = (ind+1)%n1; ret.push_back(a[ind]); } ind = lowerb; ret.push_back(b[lowerb]); while (ind != upperb) { ind = (ind+1)%n2; ret.push_back(b[ind]); } return ret; } // Brute force algorithm to find convex hull for a set// of less than 6 pointsvector<pair<int, int>> bruteHull(vector<pair<int, int>> a){ // Take any pair of points from the set and check // whether it is the edge of the convex hull or not. // if all the remaining points are on the same side // of the line then the line is the edge of convex // hull otherwise not set<pair<int, int> >s; for (int i=0; i<a.size(); i++) { for (int j=i+1; j<a.size(); j++) { int x1 = a[i].first, x2 = a[j].first; int y1 = a[i].second, y2 = a[j].second; int a1 = y1-y2; int b1 = x2-x1; int c1 = x1*y2-y1*x2; int pos = 0, neg = 0; for (int k=0; k<a.size(); k++) { if (a1*a[k].first+b1*a[k].second+c1 <= 0) neg++; if (a1*a[k].first+b1*a[k].second+c1 >= 0) pos++; } if (pos == a.size() || neg == a.size()) { s.insert(a[i]); s.insert(a[j]); } } } vector<pair<int, int>>ret; for (auto e:s) ret.push_back(e); // Sorting the points in the anti-clockwise order mid = {0, 0}; int n = ret.size(); for (int i=0; i<n; i++) { mid.first += ret[i].first; mid.second += ret[i].second; ret[i].first *= n; ret[i].second *= n; } sort(ret.begin(), ret.end(), compare); for (int i=0; i<n; i++) ret[i] = make_pair(ret[i].first/n, ret[i].second/n); return ret;} // Returns the convex hull for the given set of pointsvector<pair<int, int>> divide(vector<pair<int, int>> a){ // If the number of points is less than 6 then the // function uses the brute algorithm to find the // convex hull if (a.size() <= 5) return bruteHull(a); // left contains the left half points // right contains the right half points vector<pair<int, int>>left, right; for (int i=0; i<a.size()/2; i++) left.push_back(a[i]); for (int i=a.size()/2; i<a.size(); i++) right.push_back(a[i]); // convex hull for the left and right sets vector<pair<int, int>>left_hull = divide(left); vector<pair<int, int>>right_hull = divide(right); // merging the convex hulls return merger(left_hull, right_hull);} // Driver codeint main(){ vector<pair<int, int> > a; a.push_back(make_pair(0, 0)); a.push_back(make_pair(1, -4)); a.push_back(make_pair(-1, -5)); a.push_back(make_pair(-5, -3)); a.push_back(make_pair(-3, -1)); a.push_back(make_pair(-1, -3)); a.push_back(make_pair(-2, -2)); a.push_back(make_pair(-1, -1)); a.push_back(make_pair(-2, -1)); a.push_back(make_pair(-1, 1)); int n = a.size(); // sorting the set of points according // to the x-coordinate sort(a.begin(), a.end()); vector<pair<int, int> >ans = divide(a); cout << "convex hull:\n"; for (auto e:ans) cout << e.first << " " << e.second << endl; return 0;}
Output:
Convex Hull:
-5 -3
-1 -5
1 -4
0 0
-1 1
Time Complexity: The merging of the left and the right convex hulls take O(n) time and as we are dividing the points into two equal parts, so the time complexity of the above algorithm is O(n * log n).
Auxiliary Space: O(n)
Related Articles :
Convex Hull | Set 1 (Jarvis’s Algorithm or Wrapping)
Convex Hull | Set 2 (Graham Scan)
Quickhull Algorithm for Convex Hull
This article is contributed by Aarti_Rathi and Amritya Vagmi 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.
_shinchancode
Divide and Conquer
Geometric
Divide and Conquer
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge Sort
QuickSort
Binary Search
Count Inversions in an array | Set 1 (Using Merge Sort)
Median of two sorted arrays of different sizes
Program for distance between two points on earth
Closest Pair of Points using Divide and Conquer algorithm
How to check if a given point lies inside or outside a polygon?
How to check if two given line segments intersect?
Find if two rectangles overlap
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 132,
"s": 54,
"text": "A convex hull is the smallest convex polygon containing all the given points."
},
{
"code": null,
"e": 263,
"s": 132,
"text": "Input is an array of points specified by their x and y coordinates. The output is the convex hull of this set of points. Examples:"
},
{
"code": null,
"e": 396,
"s": 263,
"text": "Input : points[] = {(0, 0), (0, 4), (-4, 0), (5, 0), \n (0, -6), (1, 0)};\nOutput : (-4, 0), (5, 0), (0, -6), (0, 4)"
},
{
"code": null,
"e": 2070,
"s": 396,
"text": "Pre-requisite: Tangents between two convex polygons Algorithm: Given the set of points for which we have to find the convex hull. Suppose we know the convex hull of the left half points and the right half points, then the problem now is to merge these two convex hulls and determine the convex hull for the complete set. This can be done by finding the upper and lower tangent to the right and left convex hulls. This is illustrated here Tangents between two convex polygons Let the left convex hull be a and the right convex hull be b. Then the lower and upper tangents are named as 1 and 2 respectively, as shown in the figure. Then the red outline shows the final convex hull. Now the problem remains, how to find the convex hull for the left and right half. Now recursion comes into the picture, we divide the set of points until the number of points in the set is very small, say 5, and we can find the convex hull for these points by the brute algorithm. The merging of these halves would result in the convex hull for the complete set of points. Note: We have used the brute algorithm to find the convex hull for a small number of points and it has a time complexity of . But some people suggest the following, the convex hull for 3 or fewer points is the complete set of points. This is correct but the problem comes when we try to merge a left convex hull of 2 points and right convex hull of 3 points, then the program gets trapped in an infinite loop in some special cases. So, to get rid of this problem I directly found the convex hull for 5 or fewer points by algorithm, which is somewhat greater but does not affect the overall complexity of the algorithm. "
},
{
"code": null,
"e": 2074,
"s": 2070,
"text": "CPP"
},
{
"code": "// A divide and conquer program to find convex// hull of a given set of points.#include<bits/stdc++.h>using namespace std; // stores the centre of polygon (It is made// global because it is used in compare function)pair<int, int> mid; // determines the quadrant of a point// (used in compare())int quad(pair<int, int> p){ if (p.first >= 0 && p.second >= 0) return 1; if (p.first <= 0 && p.second >= 0) return 2; if (p.first <= 0 && p.second <= 0) return 3; return 4;} // Checks whether the line is crossing the polygonint orientation(pair<int, int> a, pair<int, int> b, pair<int, int> c){ int res = (b.second-a.second)*(c.first-b.first) - (c.second-b.second)*(b.first-a.first); if (res == 0) return 0; if (res > 0) return 1; return -1;} // compare function for sortingbool compare(pair<int, int> p1, pair<int, int> q1){ pair<int, int> p = make_pair(p1.first - mid.first, p1.second - mid.second); pair<int, int> q = make_pair(q1.first - mid.first, q1.second - mid.second); int one = quad(p); int two = quad(q); if (one != two) return (one < two); return (p.second*q.first < q.second*p.first);} // Finds upper tangent of two polygons 'a' and 'b'// represented as two vectors.vector<pair<int, int>> merger(vector<pair<int, int> > a, vector<pair<int, int> > b){ // n1 -> number of points in polygon a // n2 -> number of points in polygon b int n1 = a.size(), n2 = b.size(); int ia = 0, ib = 0; for (int i=1; i<n1; i++) if (a[i].first > a[ia].first) ia = i; // ib -> leftmost point of b for (int i=1; i<n2; i++) if (b[i].first < b[ib].first) ib=i; // finding the upper tangent int inda = ia, indb = ib; bool done = 0; while (!done) { done = 1; while (orientation(b[indb], a[inda], a[(inda+1)%n1]) >=0) inda = (inda + 1) % n1; while (orientation(a[inda], b[indb], b[(n2+indb-1)%n2]) <=0) { indb = (n2+indb-1)%n2; done = 0; } } int uppera = inda, upperb = indb; inda = ia, indb=ib; done = 0; int g = 0; while (!done)//finding the lower tangent { done = 1; while (orientation(a[inda], b[indb], b[(indb+1)%n2])>=0) indb=(indb+1)%n2; while (orientation(b[indb], a[inda], a[(n1+inda-1)%n1])<=0) { inda=(n1+inda-1)%n1; done=0; } } int lowera = inda, lowerb = indb; vector<pair<int, int>> ret; //ret contains the convex hull after merging the two convex hulls //with the points sorted in anti-clockwise order int ind = uppera; ret.push_back(a[uppera]); while (ind != lowera) { ind = (ind+1)%n1; ret.push_back(a[ind]); } ind = lowerb; ret.push_back(b[lowerb]); while (ind != upperb) { ind = (ind+1)%n2; ret.push_back(b[ind]); } return ret; } // Brute force algorithm to find convex hull for a set// of less than 6 pointsvector<pair<int, int>> bruteHull(vector<pair<int, int>> a){ // Take any pair of points from the set and check // whether it is the edge of the convex hull or not. // if all the remaining points are on the same side // of the line then the line is the edge of convex // hull otherwise not set<pair<int, int> >s; for (int i=0; i<a.size(); i++) { for (int j=i+1; j<a.size(); j++) { int x1 = a[i].first, x2 = a[j].first; int y1 = a[i].second, y2 = a[j].second; int a1 = y1-y2; int b1 = x2-x1; int c1 = x1*y2-y1*x2; int pos = 0, neg = 0; for (int k=0; k<a.size(); k++) { if (a1*a[k].first+b1*a[k].second+c1 <= 0) neg++; if (a1*a[k].first+b1*a[k].second+c1 >= 0) pos++; } if (pos == a.size() || neg == a.size()) { s.insert(a[i]); s.insert(a[j]); } } } vector<pair<int, int>>ret; for (auto e:s) ret.push_back(e); // Sorting the points in the anti-clockwise order mid = {0, 0}; int n = ret.size(); for (int i=0; i<n; i++) { mid.first += ret[i].first; mid.second += ret[i].second; ret[i].first *= n; ret[i].second *= n; } sort(ret.begin(), ret.end(), compare); for (int i=0; i<n; i++) ret[i] = make_pair(ret[i].first/n, ret[i].second/n); return ret;} // Returns the convex hull for the given set of pointsvector<pair<int, int>> divide(vector<pair<int, int>> a){ // If the number of points is less than 6 then the // function uses the brute algorithm to find the // convex hull if (a.size() <= 5) return bruteHull(a); // left contains the left half points // right contains the right half points vector<pair<int, int>>left, right; for (int i=0; i<a.size()/2; i++) left.push_back(a[i]); for (int i=a.size()/2; i<a.size(); i++) right.push_back(a[i]); // convex hull for the left and right sets vector<pair<int, int>>left_hull = divide(left); vector<pair<int, int>>right_hull = divide(right); // merging the convex hulls return merger(left_hull, right_hull);} // Driver codeint main(){ vector<pair<int, int> > a; a.push_back(make_pair(0, 0)); a.push_back(make_pair(1, -4)); a.push_back(make_pair(-1, -5)); a.push_back(make_pair(-5, -3)); a.push_back(make_pair(-3, -1)); a.push_back(make_pair(-1, -3)); a.push_back(make_pair(-2, -2)); a.push_back(make_pair(-1, -1)); a.push_back(make_pair(-2, -1)); a.push_back(make_pair(-1, 1)); int n = a.size(); // sorting the set of points according // to the x-coordinate sort(a.begin(), a.end()); vector<pair<int, int> >ans = divide(a); cout << \"convex hull:\\n\"; for (auto e:ans) cout << e.first << \" \" << e.second << endl; return 0;}",
"e": 8164,
"s": 2074,
"text": null
},
{
"code": null,
"e": 8172,
"s": 8164,
"text": "Output:"
},
{
"code": null,
"e": 8211,
"s": 8172,
"text": "Convex Hull:\n-5 -3\n-1 -5\n1 -4\n0 0\n-1 1"
},
{
"code": null,
"e": 8415,
"s": 8211,
"text": " Time Complexity: The merging of the left and the right convex hulls take O(n) time and as we are dividing the points into two equal parts, so the time complexity of the above algorithm is O(n * log n). "
},
{
"code": null,
"e": 8437,
"s": 8415,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 8457,
"s": 8437,
"text": "Related Articles : "
},
{
"code": null,
"e": 8511,
"s": 8457,
"text": "Convex Hull | Set 1 (Jarvis’s Algorithm or Wrapping) "
},
{
"code": null,
"e": 8545,
"s": 8511,
"text": "Convex Hull | Set 2 (Graham Scan)"
},
{
"code": null,
"e": 8581,
"s": 8545,
"text": "Quickhull Algorithm for Convex Hull"
},
{
"code": null,
"e": 8992,
"s": 8581,
"text": "This article is contributed by Aarti_Rathi and Amritya Vagmi 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": 9006,
"s": 8992,
"text": "_shinchancode"
},
{
"code": null,
"e": 9025,
"s": 9006,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 9035,
"s": 9025,
"text": "Geometric"
},
{
"code": null,
"e": 9054,
"s": 9035,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 9064,
"s": 9054,
"text": "Geometric"
},
{
"code": null,
"e": 9162,
"s": 9064,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9173,
"s": 9162,
"text": "Merge Sort"
},
{
"code": null,
"e": 9183,
"s": 9173,
"text": "QuickSort"
},
{
"code": null,
"e": 9197,
"s": 9183,
"text": "Binary Search"
},
{
"code": null,
"e": 9253,
"s": 9197,
"text": "Count Inversions in an array | Set 1 (Using Merge Sort)"
},
{
"code": null,
"e": 9300,
"s": 9253,
"text": "Median of two sorted arrays of different sizes"
},
{
"code": null,
"e": 9349,
"s": 9300,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 9407,
"s": 9349,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 9471,
"s": 9407,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 9522,
"s": 9471,
"text": "How to check if two given line segments intersect?"
}
] |
Count all possible paths from top left to bottom right of a mXn matrix
|
23 Jun, 2022
The problem is to count all the possible paths from top left to bottom right of a mXn matrix with the constraints that from each cell you can either move only to right or downExamples :
Input : m = 2, n = 2;
Output : 2
There are two paths
(0, 0) -> (0, 1) -> (1, 1)
(0, 0) -> (1, 0) -> (1, 1)
Input : m = 2, n = 3;
Output : 3
There are three paths
(0, 0) -> (0, 1) -> (0, 2) -> (1, 2)
(0, 0) -> (0, 1) -> (1, 1) -> (1, 2)
(0, 0) -> (1, 0) -> (1, 1) -> (1, 2)
We have discussed a solution to print all possible paths, counting all paths is easier. Let NumberOfPaths(m, n) be the count of paths to reach row number m and column number n in the matrix, NumberOfPaths(m, n) can be recursively written as following.
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// A C++ program to count all possible paths// from top left to bottom right #include <iostream>using namespace std; // Returns count of possible paths to reach cell at row// number m and column number n from the topmost leftmost// cell (cell at 1, 1)int numberOfPaths(int m, int n){ // If either given row number is first or given column // number is first if (m == 1 || n == 1) return 1; // If diagonal movements are allowed then the last // addition is required. return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1); // + numberOfPaths(m-1, n-1);} int main(){ cout << numberOfPaths(3, 3); return 0;}
// A Java program to count all possible paths// from top left to bottom right class GFG { // Returns count of possible paths to reach // cell at row number m and column number n // from the topmost leftmost cell (cell at 1, 1) static int numberOfPaths(int m, int n) { // If either given row number is first or // given column number is first if (m == 1 || n == 1) return 1; // If diagonal movements are allowed then // the last addition is required. return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1); // + numberOfPaths(m-1, n-1); } public static void main(String args[]) { System.out.println(numberOfPaths(3, 3)); }} // This code is contributed by Sumit Ghosh
# Python program to count all possible paths# from top left to bottom right # function to return count of possible paths# to reach cell at row number m and column# number n from the topmost leftmost# cell (cell at 1, 1)def numberOfPaths(m, n):# If either given row number is first# or given column number is first if(m == 1 or n == 1): return 1 # If diagonal movements are allowed# then the last addition# is required. return numberOfPaths(m-1, n) + numberOfPaths(m, n-1) # Driver program to test above functionm = 3n = 3print(numberOfPaths(m, n)) # This code is contributed by Aditi Sharma
// A C# program to count all possible paths// from top left to bottom right using System; public class GFG { // Returns count of possible paths to reach // cell at row number m and column number n // from the topmost leftmost cell (cell at 1, 1) static int numberOfPaths(int m, int n) { // If either given row number is first or // given column number is first if (m == 1 || n == 1) return 1; // If diagonal movements are allowed then // the last addition is required. return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1); // + numberOfPaths(m-1, n-1); } static public void Main() { Console.WriteLine(numberOfPaths(3, 3)); }} // This code is contributed by ajit
<?php // Returns count of possible paths// to reach cell at row number m// and column number n from the// topmost leftmost cell (cell at 1, 1)function numberOfPaths($m, $n){ // If either given row number // is first or given column // number is first if ($m == 1 || $n == 1) return 1; // If diagonal movements // are allowed then the last // addition is required. return numberOfPaths($m - 1, $n) + numberOfPaths($m, $n - 1);} // Driver Codeecho numberOfPaths(3, 3); // This code is contributed by akt_mit?>
<script>// A Javascript program to count all possible paths// from top left to bottom right // Returns count of possible paths to reach // cell at row number m and column number n // from the topmost leftmost cell (cell at 1, 1) function numberOfPaths(m, n) { // If either given row number is first or // given column number is first if (m == 1 || n == 1) return 1; // If diagonal movements are allowed then // the last addition is required. return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1); // + numberOfPaths(m - 1, n - 1); } document.write(numberOfPaths(3, 3)+"<br>"); // This code is contributed by rag2127</script>
6
The time complexity of above recursive solution is exponential – O(2^n). There are many overlapping subproblems. We can draw a recursion tree for numberOfPaths(3, 3) and see many overlapping subproblems. The recursion tree would be similar to Recursion tree for Longest Common Subsequence problem.
So this problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array count[][] in bottom up manner using the above recursive formula.
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// A C++ program to count all possible paths// from top left to bottom right#include <iostream>using namespace std; // Returns count of possible paths to reach cell at// row number m and column number n from the topmost// leftmost cell (cell at 1, 1)int numberOfPaths(int m, int n){ // Create a 2D table to store results of subproblems int count[m][n]; // Count of paths to reach any cell in first column is 1 for (int i = 0; i < m; i++) count[i][0] = 1; // Count of paths to reach any cell in first row is 1 for (int j = 0; j < n; j++) count[0][j] = 1; // Calculate count of paths for other cells in // bottom-up manner using the recursive solution for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) // By uncommenting the last part the code calculates the total // possible paths if the diagonal Movements are allowed count[i][j] = count[i - 1][j] + count[i][j - 1]; //+ count[i-1][j-1]; } return count[m - 1][n - 1];} // Driver program to test above functionsint main(){ cout << numberOfPaths(3, 3); return 0;}
// A Java program to count all possible paths// from top left to bottom rightclass GFG { // Returns count of possible paths to reach // cell at row number m and column number n from // the topmost leftmost cell (cell at 1, 1) static int numberOfPaths(int m, int n) { // Create a 2D table to store results // of subproblems int count[][] = new int[m][n]; // Count of paths to reach any cell in // first column is 1 for (int i = 0; i < m; i++) count[i][0] = 1; // Count of paths to reach any cell in // first column is 1 for (int j = 0; j < n; j++) count[0][j] = 1; // Calculate count of paths for other // cells in bottom-up manner using // the recursive solution for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) // By uncommenting the last part the // code calculates the total possible paths // if the diagonal Movements are allowed count[i][j] = count[i - 1][j] + count[i][j - 1]; //+ count[i-1][j-1]; } return count[m - 1][n - 1]; } // Driver program to test above function public static void main(String args[]) { System.out.println(numberOfPaths(3, 3)); }} // This code is contributed by Sumit Ghosh
# Python program to count all possible paths# from top left to bottom right # Returns count of possible paths to reach cell# at row number m and column number n from the# topmost leftmost cell (cell at 1, 1)def numberOfPaths(m, n): # Create a 2D table to store # results of subproblems # one-liner logic to take input for rows and columns # mat = [[int(input()) for x in range (C)] for y in range(R)] count = [[0 for x in range(n)] for y in range(m)] # Count of paths to reach any # cell in first column is 1 for i in range(m): count[i][0] = 1; # Count of paths to reach any # cell in first column is 1 for j in range(n): count[0][j] = 1; # Calculate count of paths for other # cells in bottom-up # manner using the recursive solution for i in range(1, m): for j in range(1, n): count[i][j] = count[i-1][j] + count[i][j-1] return count[m-1][n-1] # Driver program to test above functionm = 3n = 3print( numberOfPaths(m, n)) # This code is contributed by Aditi Sharma
// A C# program to count all possible paths// from top left to bottom rightusing System; public class GFG { // Returns count of possible paths to reach // cell at row number m and column number n from // the topmost leftmost cell (cell at 1, 1) static int numberOfPaths(int m, int n) { // Create a 2D table to store results // of subproblems int[, ] count = new int[m, n]; // Count of paths to reach any cell in // first column is 1 for (int i = 0; i < m; i++) count[i, 0] = 1; // Count of paths to reach any cell in // first column is 1 for (int j = 0; j < n; j++) count[0, j] = 1; // Calculate count of paths for other // cells in bottom-up manner using // the recursive solution for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) // By uncommenting the last part the // code calculates the total possible paths // if the diagonal Movements are allowed count[i, j] = count[i - 1, j] + count[i, j - 1]; //+ count[i-1][j-1]; } return count[m - 1, n - 1]; } // Driver program to test above function static public void Main() { Console.WriteLine(numberOfPaths(3, 3)); }} // This code is contributed by akt_mit
<?php// A PHP program to count all possible// paths from top left to bottom right // Returns count of possible paths to// reach cell at row number m and column// number n from the topmost leftmost// cell (cell at 1, 1)function numberOfPaths($m, $n){ // Create a 2D table to store // results of subproblems $count = array(); // Count of paths to reach any cell // in first column is 1 for ($i = 0; $i < $m; $i++) $count[$i][0] = 1; // Count of paths to reach any cell // in first column is 1 for ($j = 0; $j < $n; $j++) $count[0][$j] = 1; // Calculate count of paths for other // cells in bottom-up manner using the // recursive solution for ($i = 1; $i < $m; $i++) { for ($j = 1; $j < $n; $j++) // By uncommenting the last part the // code calculated the total possible // paths if the diagonal Movements are allowed $count[$i][$j] = $count[$i - 1][$j] + $count[$i][$j - 1]; //+ count[i-1][j-1]; } return $count[$m - 1][$n - 1];} // Driver Codeecho numberOfPaths(3, 3); // This code is contributed// by Mukul Singh?>
<script> // A javascript program to count all possible paths// from top left to bottom right // Returns count of possible paths to reach// cell at row number m and column number n from// the topmost leftmost cell (cell at 1, 1)function numberOfPaths(m , n){ // Create a 2D table to store results // of subproblems var count = Array(m).fill(0).map(x => Array(n).fill(0)); // Count of paths to reach any cell in // first column is 1 for (i = 0; i < m; i++) count[i][0] = 1; // Count of paths to reach any cell in // first column is 1 for (j = 0; j < n; j++) count[0][j] = 1; // Calculate count of paths for other // cells in bottom-up manner using // the recursive solution for (i = 1; i < m; i++) { for (j = 1; j < n; j++) // By uncommenting the last part the // code calculates the total possible paths // if the diagonal Movements are allowed //+ count[i-1][j-1]; count[i][j] = count[i - 1][j] + count[i][j - 1]; } return count[m - 1][n - 1];} // Driver program to test above functiondocument.write(numberOfPaths(3, 3)); // This code is contributed by 29AjayKumar </script>
6
Time Complexity: O(M*N) – Due to nested for loops. Auxiliary Space : O(M*N) – We have used a 2D array of size MxN.
Recursive Dynamic Programming solution. The following implementation is based on the Top-Down approach.
C++
Java
Python3
C#
Javascript
// A C++ program to count all possible paths from// top left to top bottom right using// Recursive Dynamic Programming#include <iostream>#include <cstring>using namespace std; // Returns count of possible paths to reach// cell at row number m and column number n from// the topmost leftmost cell (cell at 1, 1)int numberOfPaths(int n,int m,int DP[4][4]){ if(n == 1 || m == 1) return DP[n][m] = 1; // Add the element in the DP table // If it is was not computed before if(DP[n][m] == 0) DP[n][m] = numberOfPaths(n - 1, m,DP) + numberOfPaths(n, m - 1,DP); return DP[n][m];} // Driver codeint main(){ // Create an empty 2D table int DP[4][4] = {0}; memset(DP, 0, sizeof(DP)); cout << numberOfPaths(3, 3,DP); return 0;} // This code is contributed // by Gatea David
// Java program to count all possible paths from// top left to top bottom right using// Recursive Dynamic Programmingimport java.util.*;public class GFG{ // Returns count of possible paths to reach // cell at row number m and column number n from // the topmost leftmost cell (cell at 1, 1) static int numberOfPaths(int n, int m, int DP[][]) { if (n == 1 || m == 1) return DP[n][m] = 1; // Add the element in the DP table // If it is was not computed before if (DP[n][m] == 0) DP[n][m] = numberOfPaths(n - 1, m, DP) + numberOfPaths(n, m - 1, DP); return DP[n][m]; } // Driver code public static void main(String args[]) { // Create an empty 2D table int DP[][] = new int[4][4]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { DP[i][j] = 0; } } System.out.println(numberOfPaths(3, 3, DP)); }} // This code is contributed// by Samim Hossain Mondal.
# Python program to count all possible paths from# top left to top bottom right using# Recursive Dynamic Programming # Returns count of possible paths to reach# cell at row number m and column number n from# the topmost leftmost cell (cell at 1, 1)def numberOfPaths(n, m, DP): if (n == 1 or m == 1): DP[n][m] = 1; return 1; # Add the element in the DP table # If it is was not computed before if (DP[n][m] == 0): DP[n][m] = numberOfPaths(n - 1, m, DP) + numberOfPaths(n, m - 1, DP); return DP[n][m]; # Driver codeif __name__ == '__main__': # Create an empty 2D table DP = [[0 for i in range(4)] for j in range(4)] ; print(numberOfPaths(3, 3, DP)); # This code is contributed by gauravrajput1
// C# program to count all possible paths from// top left to top bottom right using// Recursive Dynamic Programmingusing System;class GFG { // Returns count of possible paths to reach // cell at row number m and column number n from // the topmost leftmost cell (cell at 1, 1) static int numberOfPaths(int n, int m, int[, ] DP) { if (n == 1 || m == 1) return DP[n, m] = 1; // Add the element in the DP table // If it is was not computed before if (DP[n, m] == 0) DP[n, m] = numberOfPaths(n - 1, m, DP) + numberOfPaths(n, m - 1, DP); return DP[n, m]; } // Driver code public static void Main() { // Create an empty 2D table int[, ] DP = new int[4, 4]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { DP[i, j] = 0; } } Console.WriteLine(numberOfPaths(3, 3, DP)); }} // This code is contributed// by Samim Hossain Mondal.
<script>// Javascript program to count all possible paths from// top left to top bottom right using// Recursive Dynamic Programming // Create an empty 2D tablelet DP = new Array(4);for(let i = 0; i < 4; i++) { DP[i] = new Array(4); for(let j = 0; j < 4; j++) { DP[i][j] = 0; }} // Returns count of possible paths to reach// cell at row number m and column number n from// the topmost leftmost cell (cell at 1, 1)function numberOfPaths(n, m, DP){ if(n == 1 || m == 1) return DP[n][m] = 1; // Add the element in the DP table // If it is was not computed before if(DP[n][m] == 0) DP[n][m] = numberOfPaths(n - 1, m,DP) + numberOfPaths(n, m - 1,DP); return DP[n][m];} // Driver code document.write(numberOfPaths(3, 3,DP)); // This code is contributed// by Samim Hossain Mondal. </script>
6
Time complexity of the above 2 dynamic programming solutions is O(mn). The space complexity of the above 2 solutions is O(mn) which is a stack space.Space Optimization of DP solution.
Above solution is more intuitive but we can also reduce the space by O(n); where n is column size. Implementation:
C++
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h> using namespace std; // Returns count of possible paths to reach// cell at row number m and column number n from// the topmost leftmost cell (cell at 1, 1)int numberOfPaths(int m, int n){ // Create a 1D array to store results of subproblems int dp[n] = { 1 }; dp[0] = 1; for (int i = 0; i < m; i++) { for (int j = 1; j < n; j++) { dp[j] += dp[j - 1]; } } return dp[n - 1];} // Driver codeint main(){ cout << numberOfPaths(3, 3);} // This code is contributed by mohit kumar 29
class GFG { // Returns count of possible paths to reach // cell at row number m and column number n from // the topmost leftmost cell (cell at 1, 1) static int numberOfPaths(int m, int n) { // Create a 1D array to store results of subproblems int[] dp = new int[n]; dp[0] = 1; for (int i = 0; i < m; i++) { for (int j = 1; j < n; j++) { dp[j] += dp[j - 1]; } } return dp[n - 1]; } // Driver program to test above function public static void main(String args[]) { System.out.println(numberOfPaths(3, 3)); }}
# Returns count of possible paths# to reach cell at row number m and# column number n from the topmost# leftmost cell (cell at 1, 1)def numberOfPaths(p, q): # Create a 1D array to store # results of subproblems dp = [1 for i in range(q)] for i in range(p - 1): for j in range(1, q): dp[j] += dp[j - 1] return dp[q - 1] # Driver Codeprint(numberOfPaths(3, 3)) # This code is contributed# by Ankit Yadav
using System; class GFG { // Returns count of possible paths // to reach cell at row number m // and column number n from the // topmost leftmost cell (cell at 1, 1) static int numberOfPaths(int m, int n) { // Create a 1D array to store // results of subproblems int[] dp = new int[n]; dp[0] = 1; for (int i = 0; i < m; i++) { for (int j = 1; j < n; j++) { dp[j] += dp[j - 1]; } } return dp[n - 1]; } // Driver Code public static void Main() { Console.Write(numberOfPaths(3, 3)); }} // This code is contributed// by ChitraNayal
<?php// Returns count of possible paths to// reach cell at row number m and// column number n from the topmost// leftmost cell (cell at 1, 1)function numberOfPaths($m, $n){ // Create a 1D array to store // results of subproblems $dp = array(); $dp[0] = 1; for ($i = 0; $i < $m; $i++) { for ($j = 1; $j < $n; $j++) { $dp[$j] += $dp[$j - 1]; } } return $dp[$n - 1];} // Driver Codeecho numberOfPaths(3, 3); // This code is contributed// by Akanksha Rai?>
<script> // Returns count of possible paths to reach// cell at row number m and column number n from// the topmost leftmost cell (cell at 1, 1)function numberOfPaths(m , n){ // Create a 1D array to store results of subproblems dp = Array.from({length: n}, (_, i) => 0); dp[0] = 1; for (i = 0; i < m; i++) { for (j = 1; j < n; j++) { dp[j] += dp[j - 1]; } } return dp[n - 1];} // Driver program to test above functiondocument.write(numberOfPaths(3, 3)); // This code contributed by Princi Singh </script>
6
Time Complexity: O(m*n)Auxiliary Space: O(n)
This code is contributed by Vivek Singh
Note the count can also be calculated using the formula (m-1 + n-1)!/(m-1)!(n-1)!.
Another Approach: (Using combinatorics) In this approach We have to calculate m+n-2Cn-1 here which will be (m+n-2)! / (n-1)! (m-1)!
Now, let us see how this formula is giving the correct answer (Reference 1) (Reference 2) read reference 1 and reference 2 for a better understanding
m = number of rows, n = number of columns
Total number of moves in which we have to move down to reach the last row = m – 1 (m rows, since we are starting from (1, 1) that is not included)
Total number of moves in which we have to move right to reach the last column = n – 1 (n column, since we are starting from (1, 1) that is not included)
Down moves = (m – 1)Right moves = (n – 1)
Total moves = Down moves + Right moves = (m – 1) + (n – 1)
Now think moves as a string of ‘R’ and ‘D’ character where ‘R’ at any ith index will tell us to move ‘Right’ and ‘D’ will tell us to move ‘Down’
Now think of how many unique strings (moves) we can make where in total there should be (n – 1 + m – 1) characters and there should be (m – 1) ‘D’ character and (n – 1) ‘R’ character?
Choosing positions of (n – 1) ‘R’ characters, results in automatic choosing of (m – 1) ‘D’ character positions
Calculate nCr Number of ways to choose positions for (n – 1) ‘R’ character = Total positions C n – 1 = Total positions C m – 1 = (n – 1 + m – 1) !=
Another way to think about this problem: Count the Number of ways to make an N digit Binary String (String with 0s and 1s only) with ‘X’ zeros and ‘Y’ ones (here we have replaced ‘R’ with ‘0’ or ‘1’ and ‘D’ with ‘1’ or ‘0’ respectively whichever suits you better)
C++
Java
Python3
C#
PHP
Javascript
// A C++ program to count all possible paths from// top left to top bottom using combinatorics #include <iostream>using namespace std; int numberOfPaths(int m, int n){ // We have to calculate m+n-2 C n-1 here // which will be (m+n-2)! / (n-1)! (m-1)! int path = 1; for (int i = n; i < (m + n - 1); i++) { path *= i; path /= (i - n + 1); } return path;} // Driver codeint main(){ cout << numberOfPaths(3, 3); return 0;} // This code is suggested by Kartik Sapra
// Java program to count all possible paths from// top left to top bottom using combinatoricsclass GFG { static int numberOfPaths(int m, int n) { // We have to calculate m+n-2 C n-1 here // which will be (m+n-2)! / (n-1)! (m-1)! int path = 1; for (int i = n; i < (m + n - 1); i++) { path *= i; path /= (i - n + 1); } return path; } // Driver code public static void main(String[] args) { System.out.println(numberOfPaths(3, 3)); }} // This code is contributed by Code_Mech.
# Python3 program to count all possible# paths from top left to top bottom# using combinatoricsdef numberOfPaths(m, n) : path = 1 # We have to calculate m + n-2 C n-1 here # which will be (m + n-2)! / (n-1)! (m-1)! path = 1; for i in range(n, (m + n - 1)): path *= i; path //= (i - n + 1); return path; # Driver codeprint(numberOfPaths(3, 3)); # This code is contributed# by Akanksha Rai
// C# program to count all possible paths from// top left to top bottom using combinatoricsusing System; class GFG { static int numberOfPaths(int m, int n) { // We have to calculate m+n-2 C n-1 here // which will be (m+n-2)! / (n-1)! (m-1)! int path = 1; for (int i = n; i < (m + n - 1); i++) { path *= i; path /= (i - n + 1); } return path; } // Driver code public static void Main() { Console.WriteLine(numberOfPaths(3, 3)); }} // This code is contributed by Code_Mech.
<?php // PHP program to count all possible paths from// top left to top bottom using combinatoricsfunction numberOfPaths($m, $n){ // We have to calculate m+n-2 C n-1 here // which will be (m+n-2)! / (n-1)! (m-1)! $path = 1; for ($i = $n; $i < ($m + $n - 1); $i++) { $path *= $i; $path /= ($i - $n + 1); } return $path;} // Driver code{ echo(numberOfPaths(3, 3));} // This code is contributed by Code_Mech.
<script> // javascript program to count all possible paths from// top left to top bottom using combinatorics function numberOfPaths(m , n) { // We have to calculate m+n-2 C n-1 here // which will be (m+n-2)! / (n-1)! (m-1)! var path = 1; for (i = n; i < (m + n - 1); i++) { path *= i; path = parseInt(path/(i - n + 1)); } return path; } // Driver codedocument.write(numberOfPaths(3, 3)); // This code contributed by Princi Singh</script>
6
Time Complexity: O(m+n)
Auxiliary Space: O(1)
Count of Sum of Consecutives | Recently asked questions in DE Shaw & Co. Interviews - YouTubeGeeksforGeeks Practice29K subscribersCount of Sum of Consecutives | Recently asked questions in DE Shaw & Co. InterviewsWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 53:14•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=uKcvoXmfXZc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Hariprasad NG. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
viveksingh14
jit_t
ukasp
Code_Mech
Akanksha_Rai
TheAlchemist0
clumsyowl
mohit kumar 29
xRahul
Majorssn
parthbanathia
rag2127
princi singh
29AjayKumar
nareshsaharan1
swapnilkr099
anshkush92
davidgatea21
amartyaghoshgfg
ShaktiVishwakarma
samim2000
GauravRajput1
r_c
ayush0212
hardikkoriintern
Amazon
Linkedin
Microsoft
Paytm
Walmart
Dynamic Programming
Mathematical
Matrix
Recursion
Paytm
Amazon
Microsoft
Walmart
Linkedin
Dynamic Programming
Mathematical
Recursion
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Floyd Warshall Algorithm | DP-16
Matrix Chain Multiplication | DP-8
Find if there is a path between two vertices in an undirected graph
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Find minimum number of coins that make a given value
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
Operators in C / C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 239,
"s": 52,
"text": "The problem is to count all the possible paths from top left to bottom right of a mXn matrix with the constraints that from each cell you can either move only to right or downExamples : "
},
{
"code": null,
"e": 515,
"s": 239,
"text": "Input : m = 2, n = 2;\nOutput : 2\nThere are two paths\n(0, 0) -> (0, 1) -> (1, 1)\n(0, 0) -> (1, 0) -> (1, 1)\n\nInput : m = 2, n = 3;\nOutput : 3\nThere are three paths\n(0, 0) -> (0, 1) -> (0, 2) -> (1, 2)\n(0, 0) -> (0, 1) -> (1, 1) -> (1, 2)\n(0, 0) -> (1, 0) -> (1, 1) -> (1, 2)"
},
{
"code": null,
"e": 767,
"s": 515,
"text": "We have discussed a solution to print all possible paths, counting all paths is easier. Let NumberOfPaths(m, n) be the count of paths to reach row number m and column number n in the matrix, NumberOfPaths(m, n) can be recursively written as following."
},
{
"code": null,
"e": 783,
"s": 767,
"text": "Implementation:"
},
{
"code": null,
"e": 787,
"s": 783,
"text": "C++"
},
{
"code": null,
"e": 792,
"s": 787,
"text": "Java"
},
{
"code": null,
"e": 800,
"s": 792,
"text": "Python3"
},
{
"code": null,
"e": 803,
"s": 800,
"text": "C#"
},
{
"code": null,
"e": 807,
"s": 803,
"text": "PHP"
},
{
"code": null,
"e": 818,
"s": 807,
"text": "Javascript"
},
{
"code": "// A C++ program to count all possible paths// from top left to bottom right #include <iostream>using namespace std; // Returns count of possible paths to reach cell at row// number m and column number n from the topmost leftmost// cell (cell at 1, 1)int numberOfPaths(int m, int n){ // If either given row number is first or given column // number is first if (m == 1 || n == 1) return 1; // If diagonal movements are allowed then the last // addition is required. return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1); // + numberOfPaths(m-1, n-1);} int main(){ cout << numberOfPaths(3, 3); return 0;}",
"e": 1461,
"s": 818,
"text": null
},
{
"code": "// A Java program to count all possible paths// from top left to bottom right class GFG { // Returns count of possible paths to reach // cell at row number m and column number n // from the topmost leftmost cell (cell at 1, 1) static int numberOfPaths(int m, int n) { // If either given row number is first or // given column number is first if (m == 1 || n == 1) return 1; // If diagonal movements are allowed then // the last addition is required. return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1); // + numberOfPaths(m-1, n-1); } public static void main(String args[]) { System.out.println(numberOfPaths(3, 3)); }} // This code is contributed by Sumit Ghosh",
"e": 2226,
"s": 1461,
"text": null
},
{
"code": "# Python program to count all possible paths# from top left to bottom right # function to return count of possible paths# to reach cell at row number m and column# number n from the topmost leftmost# cell (cell at 1, 1)def numberOfPaths(m, n):# If either given row number is first# or given column number is first if(m == 1 or n == 1): return 1 # If diagonal movements are allowed# then the last addition# is required. return numberOfPaths(m-1, n) + numberOfPaths(m, n-1) # Driver program to test above functionm = 3n = 3print(numberOfPaths(m, n)) # This code is contributed by Aditi Sharma",
"e": 2830,
"s": 2226,
"text": null
},
{
"code": "// A C# program to count all possible paths// from top left to bottom right using System; public class GFG { // Returns count of possible paths to reach // cell at row number m and column number n // from the topmost leftmost cell (cell at 1, 1) static int numberOfPaths(int m, int n) { // If either given row number is first or // given column number is first if (m == 1 || n == 1) return 1; // If diagonal movements are allowed then // the last addition is required. return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1); // + numberOfPaths(m-1, n-1); } static public void Main() { Console.WriteLine(numberOfPaths(3, 3)); }} // This code is contributed by ajit",
"e": 3592,
"s": 2830,
"text": null
},
{
"code": "<?php // Returns count of possible paths// to reach cell at row number m// and column number n from the// topmost leftmost cell (cell at 1, 1)function numberOfPaths($m, $n){ // If either given row number // is first or given column // number is first if ($m == 1 || $n == 1) return 1; // If diagonal movements // are allowed then the last // addition is required. return numberOfPaths($m - 1, $n) + numberOfPaths($m, $n - 1);} // Driver Codeecho numberOfPaths(3, 3); // This code is contributed by akt_mit?>",
"e": 4159,
"s": 3592,
"text": null
},
{
"code": "<script>// A Javascript program to count all possible paths// from top left to bottom right // Returns count of possible paths to reach // cell at row number m and column number n // from the topmost leftmost cell (cell at 1, 1) function numberOfPaths(m, n) { // If either given row number is first or // given column number is first if (m == 1 || n == 1) return 1; // If diagonal movements are allowed then // the last addition is required. return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1); // + numberOfPaths(m - 1, n - 1); } document.write(numberOfPaths(3, 3)+\"<br>\"); // This code is contributed by rag2127</script>",
"e": 4907,
"s": 4159,
"text": null
},
{
"code": null,
"e": 4909,
"s": 4907,
"text": "6"
},
{
"code": null,
"e": 5208,
"s": 4909,
"text": "The time complexity of above recursive solution is exponential – O(2^n). There are many overlapping subproblems. We can draw a recursion tree for numberOfPaths(3, 3) and see many overlapping subproblems. The recursion tree would be similar to Recursion tree for Longest Common Subsequence problem. "
},
{
"code": null,
"e": 5500,
"s": 5208,
"text": "So this problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array count[][] in bottom up manner using the above recursive formula."
},
{
"code": null,
"e": 5516,
"s": 5500,
"text": "Implementation:"
},
{
"code": null,
"e": 5520,
"s": 5516,
"text": "C++"
},
{
"code": null,
"e": 5525,
"s": 5520,
"text": "Java"
},
{
"code": null,
"e": 5533,
"s": 5525,
"text": "Python3"
},
{
"code": null,
"e": 5536,
"s": 5533,
"text": "C#"
},
{
"code": null,
"e": 5540,
"s": 5536,
"text": "PHP"
},
{
"code": null,
"e": 5551,
"s": 5540,
"text": "Javascript"
},
{
"code": "// A C++ program to count all possible paths// from top left to bottom right#include <iostream>using namespace std; // Returns count of possible paths to reach cell at// row number m and column number n from the topmost// leftmost cell (cell at 1, 1)int numberOfPaths(int m, int n){ // Create a 2D table to store results of subproblems int count[m][n]; // Count of paths to reach any cell in first column is 1 for (int i = 0; i < m; i++) count[i][0] = 1; // Count of paths to reach any cell in first row is 1 for (int j = 0; j < n; j++) count[0][j] = 1; // Calculate count of paths for other cells in // bottom-up manner using the recursive solution for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) // By uncommenting the last part the code calculates the total // possible paths if the diagonal Movements are allowed count[i][j] = count[i - 1][j] + count[i][j - 1]; //+ count[i-1][j-1]; } return count[m - 1][n - 1];} // Driver program to test above functionsint main(){ cout << numberOfPaths(3, 3); return 0;}",
"e": 6670,
"s": 5551,
"text": null
},
{
"code": "// A Java program to count all possible paths// from top left to bottom rightclass GFG { // Returns count of possible paths to reach // cell at row number m and column number n from // the topmost leftmost cell (cell at 1, 1) static int numberOfPaths(int m, int n) { // Create a 2D table to store results // of subproblems int count[][] = new int[m][n]; // Count of paths to reach any cell in // first column is 1 for (int i = 0; i < m; i++) count[i][0] = 1; // Count of paths to reach any cell in // first column is 1 for (int j = 0; j < n; j++) count[0][j] = 1; // Calculate count of paths for other // cells in bottom-up manner using // the recursive solution for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) // By uncommenting the last part the // code calculates the total possible paths // if the diagonal Movements are allowed count[i][j] = count[i - 1][j] + count[i][j - 1]; //+ count[i-1][j-1]; } return count[m - 1][n - 1]; } // Driver program to test above function public static void main(String args[]) { System.out.println(numberOfPaths(3, 3)); }} // This code is contributed by Sumit Ghosh",
"e": 8024,
"s": 6670,
"text": null
},
{
"code": "# Python program to count all possible paths# from top left to bottom right # Returns count of possible paths to reach cell# at row number m and column number n from the# topmost leftmost cell (cell at 1, 1)def numberOfPaths(m, n): # Create a 2D table to store # results of subproblems # one-liner logic to take input for rows and columns # mat = [[int(input()) for x in range (C)] for y in range(R)] count = [[0 for x in range(n)] for y in range(m)] # Count of paths to reach any # cell in first column is 1 for i in range(m): count[i][0] = 1; # Count of paths to reach any # cell in first column is 1 for j in range(n): count[0][j] = 1; # Calculate count of paths for other # cells in bottom-up # manner using the recursive solution for i in range(1, m): for j in range(1, n): count[i][j] = count[i-1][j] + count[i][j-1] return count[m-1][n-1] # Driver program to test above functionm = 3n = 3print( numberOfPaths(m, n)) # This code is contributed by Aditi Sharma",
"e": 9096,
"s": 8024,
"text": null
},
{
"code": "// A C# program to count all possible paths// from top left to bottom rightusing System; public class GFG { // Returns count of possible paths to reach // cell at row number m and column number n from // the topmost leftmost cell (cell at 1, 1) static int numberOfPaths(int m, int n) { // Create a 2D table to store results // of subproblems int[, ] count = new int[m, n]; // Count of paths to reach any cell in // first column is 1 for (int i = 0; i < m; i++) count[i, 0] = 1; // Count of paths to reach any cell in // first column is 1 for (int j = 0; j < n; j++) count[0, j] = 1; // Calculate count of paths for other // cells in bottom-up manner using // the recursive solution for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) // By uncommenting the last part the // code calculates the total possible paths // if the diagonal Movements are allowed count[i, j] = count[i - 1, j] + count[i, j - 1]; //+ count[i-1][j-1]; } return count[m - 1, n - 1]; } // Driver program to test above function static public void Main() { Console.WriteLine(numberOfPaths(3, 3)); }} // This code is contributed by akt_mit",
"e": 10453,
"s": 9096,
"text": null
},
{
"code": "<?php// A PHP program to count all possible// paths from top left to bottom right // Returns count of possible paths to// reach cell at row number m and column// number n from the topmost leftmost// cell (cell at 1, 1)function numberOfPaths($m, $n){ // Create a 2D table to store // results of subproblems $count = array(); // Count of paths to reach any cell // in first column is 1 for ($i = 0; $i < $m; $i++) $count[$i][0] = 1; // Count of paths to reach any cell // in first column is 1 for ($j = 0; $j < $n; $j++) $count[0][$j] = 1; // Calculate count of paths for other // cells in bottom-up manner using the // recursive solution for ($i = 1; $i < $m; $i++) { for ($j = 1; $j < $n; $j++) // By uncommenting the last part the // code calculated the total possible // paths if the diagonal Movements are allowed $count[$i][$j] = $count[$i - 1][$j] + $count[$i][$j - 1]; //+ count[i-1][j-1]; } return $count[$m - 1][$n - 1];} // Driver Codeecho numberOfPaths(3, 3); // This code is contributed// by Mukul Singh?>",
"e": 11615,
"s": 10453,
"text": null
},
{
"code": "<script> // A javascript program to count all possible paths// from top left to bottom right // Returns count of possible paths to reach// cell at row number m and column number n from// the topmost leftmost cell (cell at 1, 1)function numberOfPaths(m , n){ // Create a 2D table to store results // of subproblems var count = Array(m).fill(0).map(x => Array(n).fill(0)); // Count of paths to reach any cell in // first column is 1 for (i = 0; i < m; i++) count[i][0] = 1; // Count of paths to reach any cell in // first column is 1 for (j = 0; j < n; j++) count[0][j] = 1; // Calculate count of paths for other // cells in bottom-up manner using // the recursive solution for (i = 1; i < m; i++) { for (j = 1; j < n; j++) // By uncommenting the last part the // code calculates the total possible paths // if the diagonal Movements are allowed //+ count[i-1][j-1]; count[i][j] = count[i - 1][j] + count[i][j - 1]; } return count[m - 1][n - 1];} // Driver program to test above functiondocument.write(numberOfPaths(3, 3)); // This code is contributed by 29AjayKumar </script>",
"e": 12828,
"s": 11615,
"text": null
},
{
"code": null,
"e": 12830,
"s": 12828,
"text": "6"
},
{
"code": null,
"e": 12945,
"s": 12830,
"text": "Time Complexity: O(M*N) – Due to nested for loops. Auxiliary Space : O(M*N) – We have used a 2D array of size MxN."
},
{
"code": null,
"e": 13049,
"s": 12945,
"text": "Recursive Dynamic Programming solution. The following implementation is based on the Top-Down approach."
},
{
"code": null,
"e": 13053,
"s": 13049,
"text": "C++"
},
{
"code": null,
"e": 13058,
"s": 13053,
"text": "Java"
},
{
"code": null,
"e": 13066,
"s": 13058,
"text": "Python3"
},
{
"code": null,
"e": 13069,
"s": 13066,
"text": "C#"
},
{
"code": null,
"e": 13080,
"s": 13069,
"text": "Javascript"
},
{
"code": "// A C++ program to count all possible paths from// top left to top bottom right using// Recursive Dynamic Programming#include <iostream>#include <cstring>using namespace std; // Returns count of possible paths to reach// cell at row number m and column number n from// the topmost leftmost cell (cell at 1, 1)int numberOfPaths(int n,int m,int DP[4][4]){ if(n == 1 || m == 1) return DP[n][m] = 1; // Add the element in the DP table // If it is was not computed before if(DP[n][m] == 0) DP[n][m] = numberOfPaths(n - 1, m,DP) + numberOfPaths(n, m - 1,DP); return DP[n][m];} // Driver codeint main(){ // Create an empty 2D table int DP[4][4] = {0}; memset(DP, 0, sizeof(DP)); cout << numberOfPaths(3, 3,DP); return 0;} // This code is contributed // by Gatea David",
"e": 13897,
"s": 13080,
"text": null
},
{
"code": "// Java program to count all possible paths from// top left to top bottom right using// Recursive Dynamic Programmingimport java.util.*;public class GFG{ // Returns count of possible paths to reach // cell at row number m and column number n from // the topmost leftmost cell (cell at 1, 1) static int numberOfPaths(int n, int m, int DP[][]) { if (n == 1 || m == 1) return DP[n][m] = 1; // Add the element in the DP table // If it is was not computed before if (DP[n][m] == 0) DP[n][m] = numberOfPaths(n - 1, m, DP) + numberOfPaths(n, m - 1, DP); return DP[n][m]; } // Driver code public static void main(String args[]) { // Create an empty 2D table int DP[][] = new int[4][4]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { DP[i][j] = 0; } } System.out.println(numberOfPaths(3, 3, DP)); }} // This code is contributed// by Samim Hossain Mondal.",
"e": 14945,
"s": 13897,
"text": null
},
{
"code": "# Python program to count all possible paths from# top left to top bottom right using# Recursive Dynamic Programming # Returns count of possible paths to reach# cell at row number m and column number n from# the topmost leftmost cell (cell at 1, 1)def numberOfPaths(n, m, DP): if (n == 1 or m == 1): DP[n][m] = 1; return 1; # Add the element in the DP table # If it is was not computed before if (DP[n][m] == 0): DP[n][m] = numberOfPaths(n - 1, m, DP) + numberOfPaths(n, m - 1, DP); return DP[n][m]; # Driver codeif __name__ == '__main__': # Create an empty 2D table DP = [[0 for i in range(4)] for j in range(4)] ; print(numberOfPaths(3, 3, DP)); # This code is contributed by gauravrajput1",
"e": 15690,
"s": 14945,
"text": null
},
{
"code": "// C# program to count all possible paths from// top left to top bottom right using// Recursive Dynamic Programmingusing System;class GFG { // Returns count of possible paths to reach // cell at row number m and column number n from // the topmost leftmost cell (cell at 1, 1) static int numberOfPaths(int n, int m, int[, ] DP) { if (n == 1 || m == 1) return DP[n, m] = 1; // Add the element in the DP table // If it is was not computed before if (DP[n, m] == 0) DP[n, m] = numberOfPaths(n - 1, m, DP) + numberOfPaths(n, m - 1, DP); return DP[n, m]; } // Driver code public static void Main() { // Create an empty 2D table int[, ] DP = new int[4, 4]; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { DP[i, j] = 0; } } Console.WriteLine(numberOfPaths(3, 3, DP)); }} // This code is contributed// by Samim Hossain Mondal.",
"e": 16708,
"s": 15690,
"text": null
},
{
"code": "<script>// Javascript program to count all possible paths from// top left to top bottom right using// Recursive Dynamic Programming // Create an empty 2D tablelet DP = new Array(4);for(let i = 0; i < 4; i++) { DP[i] = new Array(4); for(let j = 0; j < 4; j++) { DP[i][j] = 0; }} // Returns count of possible paths to reach// cell at row number m and column number n from// the topmost leftmost cell (cell at 1, 1)function numberOfPaths(n, m, DP){ if(n == 1 || m == 1) return DP[n][m] = 1; // Add the element in the DP table // If it is was not computed before if(DP[n][m] == 0) DP[n][m] = numberOfPaths(n - 1, m,DP) + numberOfPaths(n, m - 1,DP); return DP[n][m];} // Driver code document.write(numberOfPaths(3, 3,DP)); // This code is contributed// by Samim Hossain Mondal. </script>",
"e": 17548,
"s": 16708,
"text": null
},
{
"code": null,
"e": 17550,
"s": 17548,
"text": "6"
},
{
"code": null,
"e": 17735,
"s": 17550,
"text": "Time complexity of the above 2 dynamic programming solutions is O(mn). The space complexity of the above 2 solutions is O(mn) which is a stack space.Space Optimization of DP solution. "
},
{
"code": null,
"e": 17850,
"s": 17735,
"text": "Above solution is more intuitive but we can also reduce the space by O(n); where n is column size. Implementation:"
},
{
"code": null,
"e": 17854,
"s": 17850,
"text": "C++"
},
{
"code": null,
"e": 17859,
"s": 17854,
"text": "Java"
},
{
"code": null,
"e": 17867,
"s": 17859,
"text": "Python3"
},
{
"code": null,
"e": 17870,
"s": 17867,
"text": "C#"
},
{
"code": null,
"e": 17874,
"s": 17870,
"text": "PHP"
},
{
"code": null,
"e": 17885,
"s": 17874,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h> using namespace std; // Returns count of possible paths to reach// cell at row number m and column number n from// the topmost leftmost cell (cell at 1, 1)int numberOfPaths(int m, int n){ // Create a 1D array to store results of subproblems int dp[n] = { 1 }; dp[0] = 1; for (int i = 0; i < m; i++) { for (int j = 1; j < n; j++) { dp[j] += dp[j - 1]; } } return dp[n - 1];} // Driver codeint main(){ cout << numberOfPaths(3, 3);} // This code is contributed by mohit kumar 29",
"e": 18434,
"s": 17885,
"text": null
},
{
"code": "class GFG { // Returns count of possible paths to reach // cell at row number m and column number n from // the topmost leftmost cell (cell at 1, 1) static int numberOfPaths(int m, int n) { // Create a 1D array to store results of subproblems int[] dp = new int[n]; dp[0] = 1; for (int i = 0; i < m; i++) { for (int j = 1; j < n; j++) { dp[j] += dp[j - 1]; } } return dp[n - 1]; } // Driver program to test above function public static void main(String args[]) { System.out.println(numberOfPaths(3, 3)); }}",
"e": 19060,
"s": 18434,
"text": null
},
{
"code": "# Returns count of possible paths# to reach cell at row number m and# column number n from the topmost# leftmost cell (cell at 1, 1)def numberOfPaths(p, q): # Create a 1D array to store # results of subproblems dp = [1 for i in range(q)] for i in range(p - 1): for j in range(1, q): dp[j] += dp[j - 1] return dp[q - 1] # Driver Codeprint(numberOfPaths(3, 3)) # This code is contributed# by Ankit Yadav",
"e": 19500,
"s": 19060,
"text": null
},
{
"code": "using System; class GFG { // Returns count of possible paths // to reach cell at row number m // and column number n from the // topmost leftmost cell (cell at 1, 1) static int numberOfPaths(int m, int n) { // Create a 1D array to store // results of subproblems int[] dp = new int[n]; dp[0] = 1; for (int i = 0; i < m; i++) { for (int j = 1; j < n; j++) { dp[j] += dp[j - 1]; } } return dp[n - 1]; } // Driver Code public static void Main() { Console.Write(numberOfPaths(3, 3)); }} // This code is contributed// by ChitraNayal",
"e": 20157,
"s": 19500,
"text": null
},
{
"code": "<?php// Returns count of possible paths to// reach cell at row number m and// column number n from the topmost// leftmost cell (cell at 1, 1)function numberOfPaths($m, $n){ // Create a 1D array to store // results of subproblems $dp = array(); $dp[0] = 1; for ($i = 0; $i < $m; $i++) { for ($j = 1; $j < $n; $j++) { $dp[$j] += $dp[$j - 1]; } } return $dp[$n - 1];} // Driver Codeecho numberOfPaths(3, 3); // This code is contributed// by Akanksha Rai?>",
"e": 20652,
"s": 20157,
"text": null
},
{
"code": "<script> // Returns count of possible paths to reach// cell at row number m and column number n from// the topmost leftmost cell (cell at 1, 1)function numberOfPaths(m , n){ // Create a 1D array to store results of subproblems dp = Array.from({length: n}, (_, i) => 0); dp[0] = 1; for (i = 0; i < m; i++) { for (j = 1; j < n; j++) { dp[j] += dp[j - 1]; } } return dp[n - 1];} // Driver program to test above functiondocument.write(numberOfPaths(3, 3)); // This code contributed by Princi Singh </script>",
"e": 21201,
"s": 20652,
"text": null
},
{
"code": null,
"e": 21203,
"s": 21201,
"text": "6"
},
{
"code": null,
"e": 21248,
"s": 21203,
"text": "Time Complexity: O(m*n)Auxiliary Space: O(n)"
},
{
"code": null,
"e": 21288,
"s": 21248,
"text": "This code is contributed by Vivek Singh"
},
{
"code": null,
"e": 21372,
"s": 21288,
"text": "Note the count can also be calculated using the formula (m-1 + n-1)!/(m-1)!(n-1)!. "
},
{
"code": null,
"e": 21505,
"s": 21372,
"text": "Another Approach: (Using combinatorics) In this approach We have to calculate m+n-2Cn-1 here which will be (m+n-2)! / (n-1)! (m-1)! "
},
{
"code": null,
"e": 21655,
"s": 21505,
"text": "Now, let us see how this formula is giving the correct answer (Reference 1) (Reference 2) read reference 1 and reference 2 for a better understanding"
},
{
"code": null,
"e": 21697,
"s": 21655,
"text": "m = number of rows, n = number of columns"
},
{
"code": null,
"e": 21844,
"s": 21697,
"text": "Total number of moves in which we have to move down to reach the last row = m – 1 (m rows, since we are starting from (1, 1) that is not included)"
},
{
"code": null,
"e": 21997,
"s": 21844,
"text": "Total number of moves in which we have to move right to reach the last column = n – 1 (n column, since we are starting from (1, 1) that is not included)"
},
{
"code": null,
"e": 22039,
"s": 21997,
"text": "Down moves = (m – 1)Right moves = (n – 1)"
},
{
"code": null,
"e": 22099,
"s": 22039,
"text": "Total moves = Down moves + Right moves = (m – 1) + (n – 1) "
},
{
"code": null,
"e": 22244,
"s": 22099,
"text": "Now think moves as a string of ‘R’ and ‘D’ character where ‘R’ at any ith index will tell us to move ‘Right’ and ‘D’ will tell us to move ‘Down’"
},
{
"code": null,
"e": 22429,
"s": 22244,
"text": "Now think of how many unique strings (moves) we can make where in total there should be (n – 1 + m – 1) characters and there should be (m – 1) ‘D’ character and (n – 1) ‘R’ character? "
},
{
"code": null,
"e": 22541,
"s": 22429,
"text": "Choosing positions of (n – 1) ‘R’ characters, results in automatic choosing of (m – 1) ‘D’ character positions "
},
{
"code": null,
"e": 22691,
"s": 22541,
"text": "Calculate nCr Number of ways to choose positions for (n – 1) ‘R’ character = Total positions C n – 1 = Total positions C m – 1 = (n – 1 + m – 1) != "
},
{
"code": null,
"e": 22956,
"s": 22691,
"text": "Another way to think about this problem: Count the Number of ways to make an N digit Binary String (String with 0s and 1s only) with ‘X’ zeros and ‘Y’ ones (here we have replaced ‘R’ with ‘0’ or ‘1’ and ‘D’ with ‘1’ or ‘0’ respectively whichever suits you better) "
},
{
"code": null,
"e": 22962,
"s": 22958,
"text": "C++"
},
{
"code": null,
"e": 22967,
"s": 22962,
"text": "Java"
},
{
"code": null,
"e": 22975,
"s": 22967,
"text": "Python3"
},
{
"code": null,
"e": 22978,
"s": 22975,
"text": "C#"
},
{
"code": null,
"e": 22982,
"s": 22978,
"text": "PHP"
},
{
"code": null,
"e": 22993,
"s": 22982,
"text": "Javascript"
},
{
"code": "// A C++ program to count all possible paths from// top left to top bottom using combinatorics #include <iostream>using namespace std; int numberOfPaths(int m, int n){ // We have to calculate m+n-2 C n-1 here // which will be (m+n-2)! / (n-1)! (m-1)! int path = 1; for (int i = n; i < (m + n - 1); i++) { path *= i; path /= (i - n + 1); } return path;} // Driver codeint main(){ cout << numberOfPaths(3, 3); return 0;} // This code is suggested by Kartik Sapra",
"e": 23492,
"s": 22993,
"text": null
},
{
"code": "// Java program to count all possible paths from// top left to top bottom using combinatoricsclass GFG { static int numberOfPaths(int m, int n) { // We have to calculate m+n-2 C n-1 here // which will be (m+n-2)! / (n-1)! (m-1)! int path = 1; for (int i = n; i < (m + n - 1); i++) { path *= i; path /= (i - n + 1); } return path; } // Driver code public static void main(String[] args) { System.out.println(numberOfPaths(3, 3)); }} // This code is contributed by Code_Mech.",
"e": 24060,
"s": 23492,
"text": null
},
{
"code": "# Python3 program to count all possible# paths from top left to top bottom# using combinatoricsdef numberOfPaths(m, n) : path = 1 # We have to calculate m + n-2 C n-1 here # which will be (m + n-2)! / (n-1)! (m-1)! path = 1; for i in range(n, (m + n - 1)): path *= i; path //= (i - n + 1); return path; # Driver codeprint(numberOfPaths(3, 3)); # This code is contributed# by Akanksha Rai",
"e": 24482,
"s": 24060,
"text": null
},
{
"code": "// C# program to count all possible paths from// top left to top bottom using combinatoricsusing System; class GFG { static int numberOfPaths(int m, int n) { // We have to calculate m+n-2 C n-1 here // which will be (m+n-2)! / (n-1)! (m-1)! int path = 1; for (int i = n; i < (m + n - 1); i++) { path *= i; path /= (i - n + 1); } return path; } // Driver code public static void Main() { Console.WriteLine(numberOfPaths(3, 3)); }} // This code is contributed by Code_Mech.",
"e": 25048,
"s": 24482,
"text": null
},
{
"code": "<?php // PHP program to count all possible paths from// top left to top bottom using combinatoricsfunction numberOfPaths($m, $n){ // We have to calculate m+n-2 C n-1 here // which will be (m+n-2)! / (n-1)! (m-1)! $path = 1; for ($i = $n; $i < ($m + $n - 1); $i++) { $path *= $i; $path /= ($i - $n + 1); } return $path;} // Driver code{ echo(numberOfPaths(3, 3));} // This code is contributed by Code_Mech.",
"e": 25492,
"s": 25048,
"text": null
},
{
"code": "<script> // javascript program to count all possible paths from// top left to top bottom using combinatorics function numberOfPaths(m , n) { // We have to calculate m+n-2 C n-1 here // which will be (m+n-2)! / (n-1)! (m-1)! var path = 1; for (i = n; i < (m + n - 1); i++) { path *= i; path = parseInt(path/(i - n + 1)); } return path; } // Driver codedocument.write(numberOfPaths(3, 3)); // This code contributed by Princi Singh</script>",
"e": 26001,
"s": 25492,
"text": null
},
{
"code": null,
"e": 26003,
"s": 26001,
"text": "6"
},
{
"code": null,
"e": 26027,
"s": 26003,
"text": "Time Complexity: O(m+n)"
},
{
"code": null,
"e": 26049,
"s": 26027,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 27010,
"s": 26049,
"text": "Count of Sum of Consecutives | Recently asked questions in DE Shaw & Co. Interviews - YouTubeGeeksforGeeks Practice29K subscribersCount of Sum of Consecutives | Recently asked questions in DE Shaw & Co. InterviewsWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 53:14•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=uKcvoXmfXZc\" 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": 27181,
"s": 27010,
"text": "This article is contributed by Hariprasad NG. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27194,
"s": 27181,
"text": "viveksingh14"
},
{
"code": null,
"e": 27200,
"s": 27194,
"text": "jit_t"
},
{
"code": null,
"e": 27206,
"s": 27200,
"text": "ukasp"
},
{
"code": null,
"e": 27216,
"s": 27206,
"text": "Code_Mech"
},
{
"code": null,
"e": 27229,
"s": 27216,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 27243,
"s": 27229,
"text": "TheAlchemist0"
},
{
"code": null,
"e": 27253,
"s": 27243,
"text": "clumsyowl"
},
{
"code": null,
"e": 27268,
"s": 27253,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 27275,
"s": 27268,
"text": "xRahul"
},
{
"code": null,
"e": 27284,
"s": 27275,
"text": "Majorssn"
},
{
"code": null,
"e": 27298,
"s": 27284,
"text": "parthbanathia"
},
{
"code": null,
"e": 27306,
"s": 27298,
"text": "rag2127"
},
{
"code": null,
"e": 27319,
"s": 27306,
"text": "princi singh"
},
{
"code": null,
"e": 27331,
"s": 27319,
"text": "29AjayKumar"
},
{
"code": null,
"e": 27346,
"s": 27331,
"text": "nareshsaharan1"
},
{
"code": null,
"e": 27359,
"s": 27346,
"text": "swapnilkr099"
},
{
"code": null,
"e": 27370,
"s": 27359,
"text": "anshkush92"
},
{
"code": null,
"e": 27383,
"s": 27370,
"text": "davidgatea21"
},
{
"code": null,
"e": 27399,
"s": 27383,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 27417,
"s": 27399,
"text": "ShaktiVishwakarma"
},
{
"code": null,
"e": 27427,
"s": 27417,
"text": "samim2000"
},
{
"code": null,
"e": 27441,
"s": 27427,
"text": "GauravRajput1"
},
{
"code": null,
"e": 27445,
"s": 27441,
"text": "r_c"
},
{
"code": null,
"e": 27455,
"s": 27445,
"text": "ayush0212"
},
{
"code": null,
"e": 27472,
"s": 27455,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 27479,
"s": 27472,
"text": "Amazon"
},
{
"code": null,
"e": 27488,
"s": 27479,
"text": "Linkedin"
},
{
"code": null,
"e": 27498,
"s": 27488,
"text": "Microsoft"
},
{
"code": null,
"e": 27504,
"s": 27498,
"text": "Paytm"
},
{
"code": null,
"e": 27512,
"s": 27504,
"text": "Walmart"
},
{
"code": null,
"e": 27532,
"s": 27512,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 27545,
"s": 27532,
"text": "Mathematical"
},
{
"code": null,
"e": 27552,
"s": 27545,
"text": "Matrix"
},
{
"code": null,
"e": 27562,
"s": 27552,
"text": "Recursion"
},
{
"code": null,
"e": 27568,
"s": 27562,
"text": "Paytm"
},
{
"code": null,
"e": 27575,
"s": 27568,
"text": "Amazon"
},
{
"code": null,
"e": 27585,
"s": 27575,
"text": "Microsoft"
},
{
"code": null,
"e": 27593,
"s": 27585,
"text": "Walmart"
},
{
"code": null,
"e": 27602,
"s": 27593,
"text": "Linkedin"
},
{
"code": null,
"e": 27622,
"s": 27602,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 27635,
"s": 27622,
"text": "Mathematical"
},
{
"code": null,
"e": 27645,
"s": 27635,
"text": "Recursion"
},
{
"code": null,
"e": 27652,
"s": 27645,
"text": "Matrix"
},
{
"code": null,
"e": 27750,
"s": 27652,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27783,
"s": 27750,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 27818,
"s": 27783,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 27886,
"s": 27818,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 27954,
"s": 27886,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 28007,
"s": 27954,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 28050,
"s": 28007,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28110,
"s": 28050,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 28125,
"s": 28110,
"text": "C++ Data Types"
},
{
"code": null,
"e": 28149,
"s": 28125,
"text": "Merge two sorted arrays"
}
] |
Split numbers from 1 to N into two equal sum subsets
|
17 Aug, 2021
Given an integer N, the task is to divide the numbers from 1 to N into two nonempty subsets such that the sum of elements in the set is equal. Print the element in the subset. If we can’t form any subset then print -1.
Examples:
Input N = 4 Output: Size of subset 1 is: 2 Elements of the subset are: 1 4 Size of subset 2 is: 2 Elements of the subset are: 2 3 Explanation: The first and the second set have equal sum that is 5.
Input: N = 8 Output: Size of subset 1 is: 4 Elements of the subset are: 1 8 3 6 Size of subset 2 is: 4 Elements of the subset are: 2 7 4 5 Explanation: The first and the second set have equal sum that is 18.
Approach: To solve the problem mentioned above we have to observe the three cases for integer N. Below are the observations:
Sum of First N natural numbers is odd: Solution is not possible and the answer will be -1. Because we can’t split the odd sum into 2 equal halfs.Sum of First N natural numbers is even: just loop from last element to first element and take the elements in the set-1 whose value is less than the half of sum , Maintain another set-2 to store the ans which are not included in set-1.
Sum of First N natural numbers is odd: Solution is not possible and the answer will be -1. Because we can’t split the odd sum into 2 equal halfs.
Sum of First N natural numbers is even: just loop from last element to first element and take the elements in the set-1 whose value is less than the half of sum , Maintain another set-2 to store the ans which are not included in set-1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // function to display elementsvoid display(vector<int> &v) { for (auto i : v) { cout << i << " "; } cout << endl;} void FindAns(int n) { // sum of first n natural numbers int sum = n * (n + 1) / 2; // two array to store two sets vector<int> a, b; // if sum is odd then we can't split in two sets if (sum % 2 == 1) { cout << -1 << endl; return; } else { int ans = sum / 2; // for dividing into two sets // traverse from last element and include those who's values are less than or equal to ans for (int i = n; i >= 1; i--) { // if we can include in our set then take it if (i <= ans) { a.push_back(i); ans -= i; } // else move it to other set else { b.push_back(i); } } // print the elements of first set cout << "Size of subset 1 is : "; cout << a.size() << endl; cout << "Elements of subset are : "; display(a); // print the elements of second set cout << "Size of subset 2 is : "; cout << b.size() << endl; cout << "Elements of subset are : "; display(b); }} // Driver codeint main() { // Given number int n = 8; // function call FindAns(n); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to print the two setpublic static void findAns(int N){ // Base case if (N <= 2) { System.out.print("-1"); return; } // Sum of first numbers upto N int value = (N * (N + 1)) / 2; // Answer don't exist if(value&1) { System.out.print("-1"); return; } // To store the first set Vector<Integer> v1 = new Vector<Integer>(); // To store the second set Vector<Integer> v2 = new Vector<Integer>(); // When N is even if ((N & 1) == 0) { int turn = 1; int start = 1; int last = N; while (start < last) { if (turn == 1) { v1.add(start); v1.add(last); turn = 0; } else { v2.add(start); v2.add(last); turn = 1; } // Increment start start++; // Decrement last last--; } } // When N is odd else { // Required sum of the subset int rem = value / 2; // Boolean array to keep // track of used elements boolean[] vis = new boolean[N + 1]; for(int i = 1; i <= N; i++) vis[i] = false; vis[0] = true; // Iterate from N to 1 for(int i = N; i >= 1; i--) { if (rem > i) { v1.add(i); vis[i] = true; rem -= i; } else { v1.add(rem); vis[rem] = true; break; } } // Assigning the unused // elements to second subset for(int i = 1; i <= N; i++) { if (!vis[i]) v2.add(i); } } // Print the elements of first set System.out.print("Size of subset 1 is: "); System.out.println(v1.size()); System.out.print("Elements of the subset are: "); for(Integer c : v1) System.out.print(c + " "); System.out.println(); // Print the elements of second set System.out.print("Size of subset 2 is: "); System.out.println(v2.size()); System.out.print("Elements of the subset are: "); for(Integer c : v2) System.out.print(c + " ");} // Driver codepublic static void main(String[] args){ // Given Number int N = 8; // Function Call findAns(N);}} // This code is contributed by divyeshrabadiya07
# Python3 program for the# above approach # Function to print# the two setdef findAns(N): # Base case if (N <= 2): print ("-1") return # Sum of first numbers upto N value = (N * (N + 1)) // 2 # Answer don't exist if(value & 1): print ("-1") return # To store the first set v1 = [] # To store the second set v2 = [] # When N is even if (not (N & 1)): turn = 1 start = 1 last = N while (start < last): if (turn): v1.append(start) v1.append(last) turn = 0 else: v2.append(start) v2.append(last) turn = 1 # Increment start start += 1 # Decrement last last -= 1 # When N is odd else: # Required sum of # the subset rem = value // 2 # Boolean array to keep # track of used elements vis = [False] * (N + 1) for i in range (1, N + 1): vis[i] = False vis[0] = True # Iterate from N to 1 for i in range (N , 0, -1): if (rem > i): v1.append(i) vis[i] = True rem -= i else: v1.append(rem) vis[rem] = True break # Assigning the unused # elements to second subset for i in range (1, N + 1): if (not vis[i]): v2.append(i) # Print the elements of # first set print ("Size of subset 1 is: ", end = "") print (len( v1)) print ("Elements of the subset are: ", end = "") for c in v1: print (c, end = " ") print () # Print the elements of # second set print ("Size of subset 2 is: ", end = "") print(len( v2)) print ("Elements of the subset are: ", end = "") for c in v2: print (c, end = " ") # Driver Codeif __name__ == "__main__": # Given Number N = 8 # Function Call findAns(N) # This code is contributed by Chitranayal
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to print the two setpublic static void findAns(int N){ // Base case if (N <= 2) { Console.Write("-1"); return; } // Sum of first numbers upto N int value = (N * (N + 1)) / 2; // Answer don't exist if(value&1) { Console.Write("-1"); return; } // To store the first set List<int> v1 = new List<int>(); // To store the second set List<int> v2 = new List<int>(); // When N is even if ((N & 1) == 0) { int turn = 1; int start = 1; int last = N; while (start < last) { if (turn == 1) { v1.Add(start); v1.Add(last); turn = 0; } else { v2.Add(start); v2.Add(last); turn = 1; } // Increment start start++; // Decrement last last--; } } // When N is odd else { // Required sum of the subset int rem = value / 2; // Boolean array to keep // track of used elements bool[] vis = new bool[N + 1]; for(int i = 1; i <= N; i++) vis[i] = false; vis[0] = true; // Iterate from N to 1 for(int i = N; i >= 1; i--) { if (rem > i) { v1.Add(i); vis[i] = true; rem -= i; } else { v1.Add(rem); vis[rem] = true; break; } } // Assigning the unused // elements to second subset for(int i = 1; i <= N; i++) { if (!vis[i]) v2.Add(i); } } // Print the elements of first set Console.Write("Size of subset 1 is: "); Console.WriteLine(v1.Count); Console.Write("Elements of the subset are: "); foreach(int c in v1) Console.Write(c + " "); Console.WriteLine(); // Print the elements of second set Console.Write("Size of subset 2 is: "); Console.WriteLine(v2.Count); Console.Write("Elements of the subset are: "); foreach(int c in v2) Console.Write(c + " ");} // Driver codepublic static void Main(String[] args){ // Given number int N = 8; // Function call findAns(N);}} // This code is contributed by Amit Katiyar
<script>// Javascript program for the above approach // Function to print the two setfunction findAns(N){ // Base case if (N <= 2) { document.write("-1"); return; } // Sum of first numbers upto N let value = Math.floor((N * (N + 1)) / 2); // Answer don't exist if(value&1) { document.write("-1"); return; } // To store the first set let v1 = []; // To store the second set let v2 = []; // When N is even if ((N & 1) == 0) { let turn = 1; let start = 1; let last = N; while (start < last) { if (turn == 1) { v1.push(start); v1.push(last); turn = 0; } else { v2.push(start); v2.push(last); turn = 1; } // Increment start start++; // Decrement last last--; } } // When N is odd else { // Required sum of the subset let rem = Math.floor(value / 2); // Boolean array to keep // track of used elements let vis = new Array(N + 1); for(let i = 1; i <= N; i++) vis[i] = false; vis[0] = true; // Iterate from N to 1 for(let i = N; i >= 1; i--) { if (rem > i) { v1.push(i); vis[i] = true; rem -= i; } else { v1.push(rem); vis[rem] = true; break; } } // Assigning the unused // elements to second subset for(let i = 1; i <= N; i++) { if (!vis[i]) v2.push(i); } } // Print the elements of first set document.write("Size of subset 1 is: "); document.write(v1.length+'<br>'); document.write("Elements of the subset are: "); for(let c=0;c<v1.length;c++) document.write(v1 + " "); document.write("<br>"); // Print the elements of second set document.write("Size of subset 2 is: "); document.write(v2.length+"<br>"); document.write("Elements of the subset are: "); for(let c=0;c< v2.length;c++) document.write(v2 + " ");} // Driver code// Given Numberlet N = 8; // Function CallfindAns(N); // This code is contributed by avanitrachhadiya2155</script>
Size of subset 1 is: 4
Elements of the subset are: 1 8 3 6
Size of subset 2 is: 4
Elements of the subset are: 2 7 4 5
Time Complexity: O(N) Auxiliary Space: O(N)
divyeshrabadiya07
amit143katiyar
praveenchiliveri
ukasp
satyambsingh93
avanitrachhadiya2155
simmytarika5
Natural Numbers
Numbers
subset
Analysis
Arrays
Arrays
subset
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Understanding Time Complexity with Simple Examples
Time Complexity and Space Complexity
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Analysis of Algorithms | Set 4 (Analysis of Loops)
Cyclomatic Complexity
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Aug, 2021"
},
{
"code": null,
"e": 273,
"s": 54,
"text": "Given an integer N, the task is to divide the numbers from 1 to N into two nonempty subsets such that the sum of elements in the set is equal. Print the element in the subset. If we can’t form any subset then print -1."
},
{
"code": null,
"e": 283,
"s": 273,
"text": "Examples:"
},
{
"code": null,
"e": 481,
"s": 283,
"text": "Input N = 4 Output: Size of subset 1 is: 2 Elements of the subset are: 1 4 Size of subset 2 is: 2 Elements of the subset are: 2 3 Explanation: The first and the second set have equal sum that is 5."
},
{
"code": null,
"e": 689,
"s": 481,
"text": "Input: N = 8 Output: Size of subset 1 is: 4 Elements of the subset are: 1 8 3 6 Size of subset 2 is: 4 Elements of the subset are: 2 7 4 5 Explanation: The first and the second set have equal sum that is 18."
},
{
"code": null,
"e": 815,
"s": 689,
"text": "Approach: To solve the problem mentioned above we have to observe the three cases for integer N. Below are the observations: "
},
{
"code": null,
"e": 1197,
"s": 815,
"text": "Sum of First N natural numbers is odd: Solution is not possible and the answer will be -1. Because we can’t split the odd sum into 2 equal halfs.Sum of First N natural numbers is even: just loop from last element to first element and take the elements in the set-1 whose value is less than the half of sum , Maintain another set-2 to store the ans which are not included in set-1."
},
{
"code": null,
"e": 1343,
"s": 1197,
"text": "Sum of First N natural numbers is odd: Solution is not possible and the answer will be -1. Because we can’t split the odd sum into 2 equal halfs."
},
{
"code": null,
"e": 1580,
"s": 1343,
"text": "Sum of First N natural numbers is even: just loop from last element to first element and take the elements in the set-1 whose value is less than the half of sum , Maintain another set-2 to store the ans which are not included in set-1."
},
{
"code": null,
"e": 1631,
"s": 1580,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1635,
"s": 1631,
"text": "C++"
},
{
"code": null,
"e": 1640,
"s": 1635,
"text": "Java"
},
{
"code": null,
"e": 1648,
"s": 1640,
"text": "Python3"
},
{
"code": null,
"e": 1651,
"s": 1648,
"text": "C#"
},
{
"code": null,
"e": 1662,
"s": 1651,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // function to display elementsvoid display(vector<int> &v) { for (auto i : v) { cout << i << \" \"; } cout << endl;} void FindAns(int n) { // sum of first n natural numbers int sum = n * (n + 1) / 2; // two array to store two sets vector<int> a, b; // if sum is odd then we can't split in two sets if (sum % 2 == 1) { cout << -1 << endl; return; } else { int ans = sum / 2; // for dividing into two sets // traverse from last element and include those who's values are less than or equal to ans for (int i = n; i >= 1; i--) { // if we can include in our set then take it if (i <= ans) { a.push_back(i); ans -= i; } // else move it to other set else { b.push_back(i); } } // print the elements of first set cout << \"Size of subset 1 is : \"; cout << a.size() << endl; cout << \"Elements of subset are : \"; display(a); // print the elements of second set cout << \"Size of subset 2 is : \"; cout << b.size() << endl; cout << \"Elements of subset are : \"; display(b); }} // Driver codeint main() { // Given number int n = 8; // function call FindAns(n); return 0;}",
"e": 2930,
"s": 1662,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to print the two setpublic static void findAns(int N){ // Base case if (N <= 2) { System.out.print(\"-1\"); return; } // Sum of first numbers upto N int value = (N * (N + 1)) / 2; // Answer don't exist if(value&1) { System.out.print(\"-1\"); return; } // To store the first set Vector<Integer> v1 = new Vector<Integer>(); // To store the second set Vector<Integer> v2 = new Vector<Integer>(); // When N is even if ((N & 1) == 0) { int turn = 1; int start = 1; int last = N; while (start < last) { if (turn == 1) { v1.add(start); v1.add(last); turn = 0; } else { v2.add(start); v2.add(last); turn = 1; } // Increment start start++; // Decrement last last--; } } // When N is odd else { // Required sum of the subset int rem = value / 2; // Boolean array to keep // track of used elements boolean[] vis = new boolean[N + 1]; for(int i = 1; i <= N; i++) vis[i] = false; vis[0] = true; // Iterate from N to 1 for(int i = N; i >= 1; i--) { if (rem > i) { v1.add(i); vis[i] = true; rem -= i; } else { v1.add(rem); vis[rem] = true; break; } } // Assigning the unused // elements to second subset for(int i = 1; i <= N; i++) { if (!vis[i]) v2.add(i); } } // Print the elements of first set System.out.print(\"Size of subset 1 is: \"); System.out.println(v1.size()); System.out.print(\"Elements of the subset are: \"); for(Integer c : v1) System.out.print(c + \" \"); System.out.println(); // Print the elements of second set System.out.print(\"Size of subset 2 is: \"); System.out.println(v2.size()); System.out.print(\"Elements of the subset are: \"); for(Integer c : v2) System.out.print(c + \" \");} // Driver codepublic static void main(String[] args){ // Given Number int N = 8; // Function Call findAns(N);}} // This code is contributed by divyeshrabadiya07",
"e": 5517,
"s": 2930,
"text": null
},
{
"code": "# Python3 program for the# above approach # Function to print# the two setdef findAns(N): # Base case if (N <= 2): print (\"-1\") return # Sum of first numbers upto N value = (N * (N + 1)) // 2 # Answer don't exist if(value & 1): print (\"-1\") return # To store the first set v1 = [] # To store the second set v2 = [] # When N is even if (not (N & 1)): turn = 1 start = 1 last = N while (start < last): if (turn): v1.append(start) v1.append(last) turn = 0 else: v2.append(start) v2.append(last) turn = 1 # Increment start start += 1 # Decrement last last -= 1 # When N is odd else: # Required sum of # the subset rem = value // 2 # Boolean array to keep # track of used elements vis = [False] * (N + 1) for i in range (1, N + 1): vis[i] = False vis[0] = True # Iterate from N to 1 for i in range (N , 0, -1): if (rem > i): v1.append(i) vis[i] = True rem -= i else: v1.append(rem) vis[rem] = True break # Assigning the unused # elements to second subset for i in range (1, N + 1): if (not vis[i]): v2.append(i) # Print the elements of # first set print (\"Size of subset 1 is: \", end = \"\") print (len( v1)) print (\"Elements of the subset are: \", end = \"\") for c in v1: print (c, end = \" \") print () # Print the elements of # second set print (\"Size of subset 2 is: \", end = \"\") print(len( v2)) print (\"Elements of the subset are: \", end = \"\") for c in v2: print (c, end = \" \") # Driver Codeif __name__ == \"__main__\": # Given Number N = 8 # Function Call findAns(N) # This code is contributed by Chitranayal",
"e": 7697,
"s": 5517,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to print the two setpublic static void findAns(int N){ // Base case if (N <= 2) { Console.Write(\"-1\"); return; } // Sum of first numbers upto N int value = (N * (N + 1)) / 2; // Answer don't exist if(value&1) { Console.Write(\"-1\"); return; } // To store the first set List<int> v1 = new List<int>(); // To store the second set List<int> v2 = new List<int>(); // When N is even if ((N & 1) == 0) { int turn = 1; int start = 1; int last = N; while (start < last) { if (turn == 1) { v1.Add(start); v1.Add(last); turn = 0; } else { v2.Add(start); v2.Add(last); turn = 1; } // Increment start start++; // Decrement last last--; } } // When N is odd else { // Required sum of the subset int rem = value / 2; // Boolean array to keep // track of used elements bool[] vis = new bool[N + 1]; for(int i = 1; i <= N; i++) vis[i] = false; vis[0] = true; // Iterate from N to 1 for(int i = N; i >= 1; i--) { if (rem > i) { v1.Add(i); vis[i] = true; rem -= i; } else { v1.Add(rem); vis[rem] = true; break; } } // Assigning the unused // elements to second subset for(int i = 1; i <= N; i++) { if (!vis[i]) v2.Add(i); } } // Print the elements of first set Console.Write(\"Size of subset 1 is: \"); Console.WriteLine(v1.Count); Console.Write(\"Elements of the subset are: \"); foreach(int c in v1) Console.Write(c + \" \"); Console.WriteLine(); // Print the elements of second set Console.Write(\"Size of subset 2 is: \"); Console.WriteLine(v2.Count); Console.Write(\"Elements of the subset are: \"); foreach(int c in v2) Console.Write(c + \" \");} // Driver codepublic static void Main(String[] args){ // Given number int N = 8; // Function call findAns(N);}} // This code is contributed by Amit Katiyar",
"e": 10254,
"s": 7697,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to print the two setfunction findAns(N){ // Base case if (N <= 2) { document.write(\"-1\"); return; } // Sum of first numbers upto N let value = Math.floor((N * (N + 1)) / 2); // Answer don't exist if(value&1) { document.write(\"-1\"); return; } // To store the first set let v1 = []; // To store the second set let v2 = []; // When N is even if ((N & 1) == 0) { let turn = 1; let start = 1; let last = N; while (start < last) { if (turn == 1) { v1.push(start); v1.push(last); turn = 0; } else { v2.push(start); v2.push(last); turn = 1; } // Increment start start++; // Decrement last last--; } } // When N is odd else { // Required sum of the subset let rem = Math.floor(value / 2); // Boolean array to keep // track of used elements let vis = new Array(N + 1); for(let i = 1; i <= N; i++) vis[i] = false; vis[0] = true; // Iterate from N to 1 for(let i = N; i >= 1; i--) { if (rem > i) { v1.push(i); vis[i] = true; rem -= i; } else { v1.push(rem); vis[rem] = true; break; } } // Assigning the unused // elements to second subset for(let i = 1; i <= N; i++) { if (!vis[i]) v2.push(i); } } // Print the elements of first set document.write(\"Size of subset 1 is: \"); document.write(v1.length+'<br>'); document.write(\"Elements of the subset are: \"); for(let c=0;c<v1.length;c++) document.write(v1 + \" \"); document.write(\"<br>\"); // Print the elements of second set document.write(\"Size of subset 2 is: \"); document.write(v2.length+\"<br>\"); document.write(\"Elements of the subset are: \"); for(let c=0;c< v2.length;c++) document.write(v2 + \" \");} // Driver code// Given Numberlet N = 8; // Function CallfindAns(N); // This code is contributed by avanitrachhadiya2155</script>",
"e": 12748,
"s": 10254,
"text": null
},
{
"code": null,
"e": 12867,
"s": 12748,
"text": "Size of subset 1 is: 4\nElements of the subset are: 1 8 3 6 \nSize of subset 2 is: 4\nElements of the subset are: 2 7 4 5"
},
{
"code": null,
"e": 12911,
"s": 12867,
"text": "Time Complexity: O(N) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 12929,
"s": 12911,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 12944,
"s": 12929,
"text": "amit143katiyar"
},
{
"code": null,
"e": 12961,
"s": 12944,
"text": "praveenchiliveri"
},
{
"code": null,
"e": 12967,
"s": 12961,
"text": "ukasp"
},
{
"code": null,
"e": 12982,
"s": 12967,
"text": "satyambsingh93"
},
{
"code": null,
"e": 13003,
"s": 12982,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 13016,
"s": 13003,
"text": "simmytarika5"
},
{
"code": null,
"e": 13032,
"s": 13016,
"text": "Natural Numbers"
},
{
"code": null,
"e": 13040,
"s": 13032,
"text": "Numbers"
},
{
"code": null,
"e": 13047,
"s": 13040,
"text": "subset"
},
{
"code": null,
"e": 13056,
"s": 13047,
"text": "Analysis"
},
{
"code": null,
"e": 13063,
"s": 13056,
"text": "Arrays"
},
{
"code": null,
"e": 13070,
"s": 13063,
"text": "Arrays"
},
{
"code": null,
"e": 13077,
"s": 13070,
"text": "subset"
},
{
"code": null,
"e": 13085,
"s": 13077,
"text": "Numbers"
},
{
"code": null,
"e": 13183,
"s": 13085,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13234,
"s": 13183,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 13271,
"s": 13234,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 13338,
"s": 13271,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 13389,
"s": 13338,
"text": "Analysis of Algorithms | Set 4 (Analysis of Loops)"
},
{
"code": null,
"e": 13411,
"s": 13389,
"text": "Cyclomatic Complexity"
},
{
"code": null,
"e": 13426,
"s": 13411,
"text": "Arrays in Java"
},
{
"code": null,
"e": 13472,
"s": 13426,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 13540,
"s": 13472,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 13584,
"s": 13540,
"text": "Top 50 Array Coding Problems for Interviews"
}
] |
Generate Waffle chart using pyWaffle in Python
|
21 Apr, 2020
A Waffle Chart is a gripping visualization technique that is normally created to display progress towards goals. Where each cell in the Waffle Chart constitutes of 10 X 10 cell grid in which each cell represents one percentage point summing up to total 100%. It is commonly an effective option when you are trying to add interesting visualization features to a visual. Waffle Charts are widely used as an Excel dashboard.
For generating Waffle Chart in Python, modules needed are – matplotlib, pandas and pyWaffle.To install these packages, run the following commands :
pip install matplotlib
pip install pandas
pip install pywaffle
Below is the implementation:
# python program to generate Waffle Chart # importing all necessary requirementsimport pandas as pdimport matplotlib.pyplot as pltfrom pywaffle import Waffle # creation of a dataframedata ={'phone': ['Xiaomi', 'Samsung', 'Apple', 'Nokia', 'Realme'], 'stock': [44, 12, 8, 5, 3] } df = pd.DataFrame(data) # To plot the waffle Chartfig = plt.figure( FigureClass = Waffle, rows = 5, values = df.stock, labels = list(df.phone))
Output:The above Waffle Chart has been generated for the data in the DataFrame
Advantages:
More visually attractive.
Used for attractive Dashboards.
Disadvantages:
Waffle Chart becomes too complicated when too many segments are involved.
individualized spaces do not leave a spot to put numbers or text within the visual itself.
python-modules
Python
Write From Home
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
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Factory method design pattern in Java
Similarities and Difference between Java and C++
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 450,
"s": 28,
"text": "A Waffle Chart is a gripping visualization technique that is normally created to display progress towards goals. Where each cell in the Waffle Chart constitutes of 10 X 10 cell grid in which each cell represents one percentage point summing up to total 100%. It is commonly an effective option when you are trying to add interesting visualization features to a visual. Waffle Charts are widely used as an Excel dashboard."
},
{
"code": null,
"e": 598,
"s": 450,
"text": "For generating Waffle Chart in Python, modules needed are – matplotlib, pandas and pyWaffle.To install these packages, run the following commands :"
},
{
"code": null,
"e": 662,
"s": 598,
"text": "pip install matplotlib\npip install pandas\npip install pywaffle\n"
},
{
"code": null,
"e": 691,
"s": 662,
"text": "Below is the implementation:"
},
{
"code": "# python program to generate Waffle Chart # importing all necessary requirementsimport pandas as pdimport matplotlib.pyplot as pltfrom pywaffle import Waffle # creation of a dataframedata ={'phone': ['Xiaomi', 'Samsung', 'Apple', 'Nokia', 'Realme'], 'stock': [44, 12, 8, 5, 3] } df = pd.DataFrame(data) # To plot the waffle Chartfig = plt.figure( FigureClass = Waffle, rows = 5, values = df.stock, labels = list(df.phone))",
"e": 1156,
"s": 691,
"text": null
},
{
"code": null,
"e": 1235,
"s": 1156,
"text": "Output:The above Waffle Chart has been generated for the data in the DataFrame"
},
{
"code": null,
"e": 1247,
"s": 1235,
"text": "Advantages:"
},
{
"code": null,
"e": 1273,
"s": 1247,
"text": "More visually attractive."
},
{
"code": null,
"e": 1305,
"s": 1273,
"text": "Used for attractive Dashboards."
},
{
"code": null,
"e": 1320,
"s": 1305,
"text": "Disadvantages:"
},
{
"code": null,
"e": 1394,
"s": 1320,
"text": "Waffle Chart becomes too complicated when too many segments are involved."
},
{
"code": null,
"e": 1485,
"s": 1394,
"text": "individualized spaces do not leave a spot to put numbers or text within the visual itself."
},
{
"code": null,
"e": 1500,
"s": 1485,
"text": "python-modules"
},
{
"code": null,
"e": 1507,
"s": 1500,
"text": "Python"
},
{
"code": null,
"e": 1523,
"s": 1507,
"text": "Write From Home"
},
{
"code": null,
"e": 1621,
"s": 1523,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1653,
"s": 1621,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1680,
"s": 1653,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1701,
"s": 1680,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1724,
"s": 1701,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1755,
"s": 1724,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1791,
"s": 1755,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 1852,
"s": 1791,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 1868,
"s": 1852,
"text": "Python infinity"
},
{
"code": null,
"e": 1906,
"s": 1868,
"text": "Factory method design pattern in Java"
}
] |
How to iterate over files in directory using Python?
|
17 May, 2021
Directory also sometimes known as a folder are unit organizational structure in a system’s file system for storing and locating files or more folders. Python as a scripting language provides various methods to iterate over files in a directory.
Below are the various approaches by using which one can iterate over files in a directory using python:
Method 1: os.listdir()
This function returns the list of files and subdirectories present in the given directory. We can filter the list to get only the files using os.path.isfile() function:
Example:
Python3
# import required moduleimport os# assign directorydirectory = 'files' # iterate over files in# that directoryfor filename in os.listdir(directory): f = os.path.join(directory, filename) # checking if it is a file if os.path.isfile(f): print(f)
Output:
Method 2: os.scandir()
This method is used to get an iterator of os.DirEntry objects corresponding to the entries in the directory given by specified path.
Example:
Python3
# import required moduleimport os # assign directorydirectory = 'files' # iterate over files in# that directoryfor filename in os.scandir(directory): if filename.is_file(): print(filename.path)
Output:
Method 3: pathlib module
We can iterate over files in a directory using Path.glob() function which glob the specified pattern in the given directory and yields the matching files. Path.glob(‘*’) yield all the files in the given directory
Example:
Python3
# import required modulefrom pathlib import Path # assign directorydirectory = 'files' # iterate over files in# that directoryfiles = Path(directory).glob('*')for file in files: print(file)
Output:
Method 4: os.walk()
We can also search for subdirectories using this method as it yields a 3-tuple (dirpath, dirnames, filenames).
root: Prints out directories only from what you specified.
dirs: Prints out sub-directories from the root.
files: Prints out all files from root and directories.
Python3
# import required moduleimport os # assign directorydirectory = 'files' # iterate over files in# that directoryfor root, dirs, files in os.walk(directory): for filename in files: print(os.path.join(root, filename))
Output:
Method 5: glob module
The glob.iglob() function returns an iterator over the list of pathnames that match the given pattern.
Example:
Python3
# import required moduleimport glob # assign directorydirectory = 'files' # iterate over files in# that directoryfor filename in glob.iglob(f'{directory}/*'): print(filename)
Output:
saurabh1990aror
Picked
Python file-handling-programs
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": "\n17 May, 2021"
},
{
"code": null,
"e": 273,
"s": 28,
"text": "Directory also sometimes known as a folder are unit organizational structure in a system’s file system for storing and locating files or more folders. Python as a scripting language provides various methods to iterate over files in a directory."
},
{
"code": null,
"e": 377,
"s": 273,
"text": "Below are the various approaches by using which one can iterate over files in a directory using python:"
},
{
"code": null,
"e": 400,
"s": 377,
"text": "Method 1: os.listdir()"
},
{
"code": null,
"e": 569,
"s": 400,
"text": "This function returns the list of files and subdirectories present in the given directory. We can filter the list to get only the files using os.path.isfile() function:"
},
{
"code": null,
"e": 578,
"s": 569,
"text": "Example:"
},
{
"code": null,
"e": 586,
"s": 578,
"text": "Python3"
},
{
"code": "# import required moduleimport os# assign directorydirectory = 'files' # iterate over files in# that directoryfor filename in os.listdir(directory): f = os.path.join(directory, filename) # checking if it is a file if os.path.isfile(f): print(f)",
"e": 847,
"s": 586,
"text": null
},
{
"code": null,
"e": 855,
"s": 847,
"text": "Output:"
},
{
"code": null,
"e": 878,
"s": 855,
"text": "Method 2: os.scandir()"
},
{
"code": null,
"e": 1011,
"s": 878,
"text": "This method is used to get an iterator of os.DirEntry objects corresponding to the entries in the directory given by specified path."
},
{
"code": null,
"e": 1020,
"s": 1011,
"text": "Example:"
},
{
"code": null,
"e": 1028,
"s": 1020,
"text": "Python3"
},
{
"code": "# import required moduleimport os # assign directorydirectory = 'files' # iterate over files in# that directoryfor filename in os.scandir(directory): if filename.is_file(): print(filename.path)",
"e": 1232,
"s": 1028,
"text": null
},
{
"code": null,
"e": 1240,
"s": 1232,
"text": "Output:"
},
{
"code": null,
"e": 1265,
"s": 1240,
"text": "Method 3: pathlib module"
},
{
"code": null,
"e": 1479,
"s": 1265,
"text": "We can iterate over files in a directory using Path.glob() function which glob the specified pattern in the given directory and yields the matching files. Path.glob(‘*’) yield all the files in the given directory "
},
{
"code": null,
"e": 1488,
"s": 1479,
"text": "Example:"
},
{
"code": null,
"e": 1496,
"s": 1488,
"text": "Python3"
},
{
"code": "# import required modulefrom pathlib import Path # assign directorydirectory = 'files' # iterate over files in# that directoryfiles = Path(directory).glob('*')for file in files: print(file)",
"e": 1689,
"s": 1496,
"text": null
},
{
"code": null,
"e": 1697,
"s": 1689,
"text": "Output:"
},
{
"code": null,
"e": 1717,
"s": 1697,
"text": "Method 4: os.walk()"
},
{
"code": null,
"e": 1828,
"s": 1717,
"text": "We can also search for subdirectories using this method as it yields a 3-tuple (dirpath, dirnames, filenames)."
},
{
"code": null,
"e": 1887,
"s": 1828,
"text": "root: Prints out directories only from what you specified."
},
{
"code": null,
"e": 1935,
"s": 1887,
"text": "dirs: Prints out sub-directories from the root."
},
{
"code": null,
"e": 1990,
"s": 1935,
"text": "files: Prints out all files from root and directories."
},
{
"code": null,
"e": 1998,
"s": 1990,
"text": "Python3"
},
{
"code": "# import required moduleimport os # assign directorydirectory = 'files' # iterate over files in# that directoryfor root, dirs, files in os.walk(directory): for filename in files: print(os.path.join(root, filename))",
"e": 2223,
"s": 1998,
"text": null
},
{
"code": null,
"e": 2231,
"s": 2223,
"text": "Output:"
},
{
"code": null,
"e": 2253,
"s": 2231,
"text": "Method 5: glob module"
},
{
"code": null,
"e": 2356,
"s": 2253,
"text": "The glob.iglob() function returns an iterator over the list of pathnames that match the given pattern."
},
{
"code": null,
"e": 2365,
"s": 2356,
"text": "Example:"
},
{
"code": null,
"e": 2373,
"s": 2365,
"text": "Python3"
},
{
"code": "# import required moduleimport glob # assign directorydirectory = 'files' # iterate over files in# that directoryfor filename in glob.iglob(f'{directory}/*'): print(filename)",
"e": 2551,
"s": 2373,
"text": null
},
{
"code": null,
"e": 2559,
"s": 2551,
"text": "Output:"
},
{
"code": null,
"e": 2575,
"s": 2559,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 2582,
"s": 2575,
"text": "Picked"
},
{
"code": null,
"e": 2612,
"s": 2582,
"text": "Python file-handling-programs"
},
{
"code": null,
"e": 2619,
"s": 2612,
"text": "Python"
},
{
"code": null,
"e": 2717,
"s": 2619,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2749,
"s": 2717,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2776,
"s": 2749,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2797,
"s": 2776,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2820,
"s": 2797,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2876,
"s": 2820,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2907,
"s": 2876,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2949,
"s": 2907,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2991,
"s": 2949,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3030,
"s": 2991,
"text": "Python | Get unique values from a list"
}
] |
Zigzag (or diagonal) traversal of Matrix
|
20 Jun, 2022
Given a 2D matrix, print all elements of the given matrix in diagonal order. For example, consider the following 5 X 4 input matrix.
Example:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
Diagonal printing of the above matrix is
1
5 2
9 6 3
13 10 7 4
17 14 11 8
18 15 12
19 16
20
Another example:
Following is the code for diagonal printing.The diagonal printing of a given matrix “matrix[ROW][COL]” always has “ROW + COL – 1” lines in output.
Implementation:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to print all elements// of given matrix in diagonal order#include <bits/stdc++.h>using namespace std; #define ROW 5#define COL 4 // A utility function to find min// of two integersint minu(int a, int b){ return (a < b) ? a : b;} // A utility function to find min// of three integersint min(int a, int b, int c){ return minu(minu(a, b), c);} // A utility function to find// max of two integersint max(int a, int b){ return (a > b) ? a : b;} // The main function that prints given// matrix in diagonal ordervoid diagonalOrder(int matrix[][COL]){ // There will be ROW+COL-1 lines // in the output for(int line = 1; line <= (ROW + COL - 1); line++) { /* Get column index of the first element in this line of output. The index is 0 for first ROW lines and line - ROW for remaining lines */ int start_col = max(0, line - ROW); /* Get count of elements in this line. The count of elements is equal to minimum of line number, COL-start_col and ROW */ int count = min(line, (COL - start_col), ROW); /* Print elements of this line */ for(int j = 0; j < count; j++) cout << setw(5) << matrix[minu(ROW, line) - j - 1][start_col + j]; /* Print elements of next diagonal on next line */ cout << "\n"; }} // Utility function to print a matrixvoid printMatrix(int matrix[ROW][COL]){ for(int i = 0; i < ROW; i++) { for(int j = 0; j < COL; j++) cout << setw(5) << matrix[i][j]; cout << "\n"; }} // Driver codeint main(){ int M[ROW][COL] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 },}; cout << "Given matrix is " << endl; printMatrix(M); cout << "\nDiagonal printing of matrix is " << endl; diagonalOrder(M); return 0;} // This code is contributed by shubhamsingh10
// C program to print all elements// of given matrix in diagonal order#include <stdlib.h> #define ROW 5#define COL 4 // A utility function to find min of two integersint minu(int a, int b){ return (a < b)? a: b; } // A utility function to find min of three integersint min(int a, int b, int c){ return minu(minu(a, b), c);} // A utility function to find max of two integersint max(int a, int b){ return (a > b)? a: b; } // The main function that prints given matrix in// diagonal ordervoid diagonalOrder(int matrix[][COL]){ // There will be ROW+COL-1 lines in the output for (int line=1; line<=(ROW + COL -1); line++) { /* Get column index of the first element in this line of output. The index is 0 for first ROW lines and line - ROW for remaining lines */ int start_col = max(0, line-ROW); /* Get count of elements in this line. The count of elements is equal to minimum of line number, COL-start_col and ROW */ int count = min(line, (COL-start_col), ROW); /* Print elements of this line */ for (int j=0; j<count; j++) printf("%5d ", matrix[minu(ROW, line)-j-1][start_col+j]); /* Print elements of next diagonal on next line */ printf("\n"); }} // Utility function to print a matrixvoid printMatrix(int matrix[ROW][COL]){ for (int i=0; i< ROW; i++) { for (int j=0; j<COL; j++) printf("%5d ", matrix[i][j]); printf("\n"); }} // Driver codeint main(){ int M[ROW][COL] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}, {17, 18, 19, 20}, }; printf ("Given matrix is \n"); printMatrix(M); printf ("\nDiagonal printing of matrix is \n"); diagonalOrder(M); return 0;}
// Java program to print all elements// of given matrix in diagonal orderclass GFG { static final int ROW = 5; static final int COL = 4; // A utility function to find min // of two integers static int min(int a, int b) { return (a < b) ? a : b; } // A utility function to find min // of three integers static int min(int a, int b, int c) { return min(min(a, b), c); } // A utility function to find max // of two integers static int max(int a, int b) { return (a > b) ? a : b; } // The main function that prints given // matrix in diagonal order static void diagonalOrder(int matrix[][]) { // There will be ROW+COL-1 lines in the output for (int line = 1; line <= (ROW + COL - 1); line++) { // Get column index of the first // element in this line of output. // The index is 0 for first ROW // lines and line - ROW for remaining lines int start_col = max(0, line - ROW); // Get count of elements in this line. // The count of elements is equal to // minimum of line number, COL-start_col and ROW int count = min(line, (COL - start_col), ROW); // Print elements of this line for (int j = 0; j < count; j++) System.out.print(matrix[min(ROW, line) - j- 1][start_col + j] + " "); // Print elements of next diagonal on next line System.out.println(); } } // Utility function to print a matrix static void printMatrix(int matrix[][]) { for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) System.out.print(matrix[i][j] + " "); System.out.print("\n"); } } // Driver code public static void main(String[] args) { int M[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 }, }; System.out.print("Given matrix is \n"); printMatrix(M); System.out.print( "\nDiagonal printing of matrix is \n"); diagonalOrder(M); }}// This code is contributed by Anant Agarwal.
# Python3 program to print all elements# of given matrix in diagonal orderROW = 5COL = 4 # Main function that prints given# matrix in diagonal order def diagonalOrder(matrix): # There will be ROW+COL-1 lines in the output for line in range(1, (ROW + COL)): # Get column index of the first element # in this line of output. The index is 0 # for first ROW lines and line - ROW for # remaining lines start_col = max(0, line - ROW) # Get count of elements in this line. # The count of elements is equal to # minimum of line number, COL-start_col and ROW count = min(line, (COL - start_col), ROW) # Print elements of this line for j in range(0, count): print(matrix[min(ROW, line) - j - 1] [start_col + j], end="\t") print() # Utility function to print a matrixdef printMatrix(matrix): for i in range(0, ROW): for j in range(0, COL): print(matrix[i][j], end="\t") print() # Driver CodeM = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]print("Given matrix is ")printMatrix(M) print("\nDiagonal printing of matrix is ")diagonalOrder(M) # This code is contributed by Nikita Tiwari.
// C# program to print all elements// of given matrix in diagonal orderusing System;using static System.Math; class GFG { static int ROW = 5; static int COL = 4; // The main function that prints given // matrix in diagonal order static void diagonalOrder(int[, ] matrix) { // There will be ROW+COL-1 lines in the output for (int line = 1; line <= (ROW + COL - 1); line++) { // Get column index of the first element // in this line of output.The index is 0 // for first ROW lines and line - ROW for // remaining lines int start_col = Max(0, line - ROW); // Get count of elements in this line. The // count of elements is equal to minimum of // line number, COL-start_col and ROW int count = Min(line, Math.Min((COL - start_col), ROW)); // Print elements of this line for (int j = 0; j < count; j++) Console.Write(matrix[Min(ROW, line) - j - 1, start_col + j] + " "); // Print elements of next diagonal // on next line Console.WriteLine(); } } // Utility function to print a matrix static void printMatrix(int[, ] matrix) { for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) Console.Write(matrix[i, j] + " "); Console.WriteLine("\n"); } } // Driver code public static void Main() { int[, ] M = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 } }; Console.Write("Given matrix is \n"); printMatrix(M); Console.Write("\nDiagonal printing" + " of matrix is \n"); diagonalOrder(M); }} // This code is contributed by Sam007.
<?php// PHP Code for Zigzag (or diagonal)// traversal of Matrix$ROW = 5;$COL = 4; // The main function that prints// given matrix in diagonal orderfunction diagonalOrder(&$matrix){ global $ROW, $COL; // There will be ROW+COL-1 // lines in the output for ($line = 1; $line <= ($ROW + $COL - 1); $line++) { /* Get column index of the first element in this line of output. The index is 0 for first ROW lines and line - ROW for remaining lines */ $start_col = max(0, $line - $ROW); /* Get count of elements in this line. The count of elements is equal to minimum of line number, COL-start_col and ROW */ $count = min($line, ($COL - $start_col), $ROW); /* Print elements of this line */ for ($j = 0; $j < $count; $j++) { echo $matrix[min($ROW, $line) - $j - 1][$start_col + $j]; echo "\t"; } /* Print elements of next diagonal on next line */ print("\n"); }} // Utility function// to print a matrixfunction printMatrix(&$matrix){ global $ROW, $COL; for ($i = 0; $i < $ROW; $i++) { for ($j = 0; $j < $COL; $j++) { echo $matrix[$i][$j] ; echo "\t"; } print("\n"); }} // Driver Code$M = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16), array(17, 18, 19, 20));echo "Given matrix is \n";printMatrix($M); printf ("\nDiagonal printing " . "of matrix is \n");diagonalOrder($M); // This code is contributed// by ChitraNayal?>
<script>// Javascript program to print all elements// of given matrix in diagonal order let ROW = 5;let COL = 4; // A utility function to find min // of two integersfunction min(a, b){ return (a < b) ? a : b;} // A utility function to find min // of three integerfunction _min(a, b, c){ return min(min(a, b), c);} // A utility function to find max // of two integersfunction max(a,b){ return (a > b) ? a : b;} // The main function that prints given // matrix in diagonal orderfunction diagonalOrder(matrix){ // There will be ROW+COL-1 lines in the output for (let line = 1; line <= (ROW + COL - 1); line++) { // Get column index of the first // element in this line of output. // The index is 0 for first ROW // lines and line - ROW for remaining lines let start_col = max(0, line - ROW); // Get count of elements in this line. // The count of elements is equal to // minimum of line number, COL-start_col and ROW let count = min(line, (COL - start_col), ROW); // Print elements of this line for (let j = 0; j < count; j++) document.write(matrix[min(ROW, line) - j- 1][start_col + j] + " "); // Print elements of next diagonal on next line document.write("<br>"); }} // Utility function to print a matrixfunction printMatrix(matrix){ for (let i = 0; i < ROW; i++) { for (let j = 0; j < COL; j++) document.write(matrix[i][j] + " "); document.write("<br>"); }} // Driver codelet M = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ], [ 17, 18, 19, 20 ]];document.write("Given matrix is <br>");printMatrix(M); document.write("<br>Diagonal printing of matrix is <br>");diagonalOrder(M); // This code is contributed by ab2127</script>
Given matrix is
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
Diagonal printing of matrix is
1
5 2
9 6 3
13 10 7 4
17 14 11 8
18 15 12
19 16
20
Time Complexity: O(row x col) Auxiliary Space: O(1)
Below is an Alternate Method to solve the above problem.
Matrix => 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
Observe the sequence
1 / 2 / 3 / 4
/ 5 / 6 / 7 / 8
/ 9 / 10 / 11 / 12
/ 13 / 14 / 15 / 16
/ 17 / 18 / 19 / 20
Implementation:
C++
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>#define R 5#define C 4using namespace std; bool isValid(int i, int j){ if (i < 0 || i >= R || j >= C || j < 0) return false; return true;} void diagonalOrder(int arr[][C]){ /* through this for loop we choose each element of first column as starting point and print diagonal starting at it. arr[0][0], arr[1][0]....arr[R-1][0] are all starting points */ for (int k = 0; k < R; k++) { cout << arr[k][0] << " "; // set row index for next point in // diagonal int i = k - 1; // set column index for next point in // diagonal int j = 1; /* Print Diagonally upward */ while (isValid(i, j)) { cout << arr[i][j] << " "; i--; // move in upright direction j++; } cout << endl; } /* through this for loop we choose each element of last row as starting point (except the [0][c-1] it has already been processed in previous for loop) and print diagonal starting at it. arr[R-1][0], arr[R-1][1]....arr[R-1][c-1] are all starting points */ // Note : we start from k = 1 to C-1; for (int k = 1; k < C; k++) { cout << arr[R - 1][k] << " "; // set row index for next point in // diagonal int i = R - 2; // set column index for next point in // diagonal int j = k + 1; /* Print Diagonally upward */ while (isValid(i, j)) { cout << arr[i][j] << " "; i--; // move in upright direction j++; } cout << endl; }} // Driver Codeint main(){ int arr[][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 }, }; diagonalOrder(arr); return 0;}
// JAVA Code for Zigzag (or diagonal)// traversal of Matrix class GFG { public static int R, C; private static void diagonalOrder(int[][] arr) { /* through this for loop we choose each element of first column as starting point and print diagonal starting at it. arr[0][0], arr[1][0]....arr[R-1][0] are all starting points */ for (int k = 0; k < R; k++) { System.out.print(arr[k][0] + " "); // set row index for next // point in diagonal int i = k - 1; // set column index for // next point in diagonal int j = 1; /* Print Diagonally upward */ while (isValid(i, j)) { System.out.print(arr[i][j] + " "); i--; // move in upright direction j++; } System.out.println(""); } /* through this for loop we choose each element of last row as starting point (except the [0][c-1] it has already been processed in previous for loop) and print diagonal starting at it. arr[R-1][0], arr[R-1][1].... arr[R-1][c-1] are all starting points */ // Note : we start from k = 1 to C-1; for (int k = 1; k < C; k++) { System.out.print(arr[R - 1][k] + " "); // set row index for next // point in diagonal int i = R - 2; // set column index for // next point in diagonal int j = k + 1; /* Print Diagonally upward */ while (isValid(i, j)) { System.out.print(arr[i][j] + " "); // move in upright direction i--; j++; } System.out.println(""); } } public static boolean isValid(int i, int j) { if (i < 0 || i >= R || j >= C || j < 0) return false; return true; } // Driver code public static void main(String[] args) { int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 }, }; R = arr.length; C = arr[0].length; // Function call diagonalOrder(arr); }} // This code is contributed by Arnav Kr. Mandal.
# Python3 program to print all elements# of given matrix in diagonal orderR = 5C = 4 def isValid(i, j): if (i < 0 or i >= R or j >= C or j < 0): return False return True def diagonalOrder(arr): # through this for loop we choose each element # of first column as starting point and print # diagonal starting at it. # arr[0][0], arr[1][0]....arr[R-1][0] # are all starting points for k in range(0, R): print(arr[k][0], end=" ") # set row index for next point in diagonal i = k - 1 # set column index for next point in diagonal j = 1 # Print Diagonally upward while (isValid(i, j)): print(arr[i][j], end=" ") i -= 1 j += 1 # move in upright direction print() # Through this for loop we choose each # element of last row as starting point # (except the [0][c-1] it has already been # processed in previous for loop) and print # diagonal starting at it. # arr[R-1][0], arr[R-1][1]....arr[R-1][c-1] # are all starting points # Note : we start from k = 1 to C-1; for k in range(1, C): print(arr[R-1][k], end=" ") # set row index for next point in diagonal i = R - 2 # set column index for next point in diagonal j = k + 1 # Print Diagonally upward while (isValid(i, j)): print(arr[i][j], end=" ") i -= 1 j += 1 # move in upright direction print() # Driver Codearr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]] # Function calldiagonalOrder(arr) # This code is contributed by Nikita Tiwari.
// C# Code for Zigzag (or diagonal)// traversal of Matrixusing System; class GFG { public static int R, C; private static void diagonalOrder(int[, ] arr) { /* through this for loop we choose each element of first column as starting point and print diagonal starting at it. arr[0,0], arr[1,0]....arr[R-1,0] are all starting points */ for (int k = 0; k < R; k++) { Console.Write(arr[k, 0] + " "); // set row index for next // point in diagonal int i = k - 1; // set column index for // next point in diagonal int j = 1; /* Print Diagonally upward */ while (isValid(i, j)) { Console.Write(arr[i, j] + " "); i--; // move in upright direction j++; } Console.Write("\n"); } /* through this for loop we choose each element of last row as starting point (except the [0][c-1] it has already been processed in previous for loop) and print diagonal starting at it. arr[R-1,0], arr[R-1,1].... arr[R-1,c-1] are all starting points */ // Note : we start from k = 1 to C-1; for (int k = 1; k < C; k++) { Console.Write(arr[R - 1, k] + " "); // set row index for next // point in diagonal int i = R - 2; // set column index for // next point in diagonal int j = k + 1; /* Print Diagonally upward */ while (isValid(i, j)) { Console.Write(arr[i, j] + " "); i--; j++; // move in upright direction } Console.Write("\n"); } } public static bool isValid(int i, int j) { if (i < 0 || i >= R || j >= C || j < 0) return false; return true; } // Driver code public static void Main() { int[, ] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 } }; R = arr.GetLength(0); C = arr.GetLength(1); // Function call diagonalOrder(arr); }} // This code is contributed// by ChitraNayal
<?php// PHP code for Zigzag (or diagonal)// traversal of Matrixdefine("R", 5);define("C", 4); function isValid($i, $j){ if ($i < 0 || $i >= R || $j >= C || $j < 0) return false; return true;} function diagonalOrder(&$arr){ /* through this for loop we choose each element of first column as starting point and print diagonal starting at it. arr[0][0], arr[1][0]....arr[R-1][0] are all starting points */ for ($k = 0; $k < R; $k++) { echo $arr[$k][0] . " "; $i = $k - 1; // set row index for next // point in diagonal $j = 1; // set column index for next // point in diagonal /* Print Diagonally upward */ while (isValid($i,$j)) { echo $arr[$i][$j] . " "; $i--; $j++; // move in upright direction } echo "\n"; } /* through this for loop we choose each element of last row as starting point (except the [0][c-1] it has already been processed in previous for loop) and print diagonal starting at it. arr[R-1][0], arr[R-1][1]....arr[R-1][c-1] are all starting points */ //Note : we start from k = 1 to C-1; for ($k = 1; $k < C; $k++) { echo $arr[R - 1][$k] . " "; $i = R - 2; // set row index for next // point in diagonal $j = $k + 1; // set column index for next // point in diagonal /* Print Diagonally upward */ while (isValid($i, $j)) { echo $arr[$i][$j] . " "; $i--; $j++; // move in upright direction } echo "\n"; }} // Driver Code$arr = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16), array(17, 18, 19, 20)); // Function calldiagonalOrder($arr); // This code is contributed// by rathbhupendra?>
<script>// JAVA Code for Zigzag (or diagonal)// traversal of Matrix var R, C; function diagonalOrder( arr) { /* through this for loop we choose each element of first column as starting point and print diagonal starting at it. arr[0][0], arr[1][0]....arr[R-1][0] are all starting points */ for (var k = 0; k < R; k++) { document.write(arr[k][0] + " "); // set row index for next // point in diagonal var i = k - 1; // set column index for // next point in diagonal var j = 1; /* Print Diagonally upward */ while (isValid(i, j)) { document.write(arr[i][j] + " "); i--; // move in upright direction j++; } document.writeln("<br>"); } /* through this for loop we choose each element of last row as starting point (except the [0][c-1] it has already been processed in previous for loop) and print diagonal starting at it. arr[R-1][0], arr[R-1][1].... arr[R-1][c-1] are all starting points */ // Note : we start from k = 1 to C-1; for (var k = 1; k < C; k++) { document.write(arr[R - 1][k] + " "); // set row index for next // point in diagonal var i = R - 2; // set column index for // next point in diagonal var j = k + 1; /* Print Diagonally upward */ while (isValid(i, j)) { document.write(arr[i][j] + " "); // move in upright direction i--; j++; } document.writeln("<br>"); } } function isValid( i, j) { if (i < 0 || i >= R || j >= C || j < 0) return false; return true; } // Driver code var arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ], [ 17, 18, 19, 20 ], ]; R = arr.length; C = arr[0].length; // Function call diagonalOrder(arr); // This code is contributed by shivanisinghss2110</script>
1
5 2
9 6 3
13 10 7 4
17 14 11 8
18 15 12
19 16
20
Time Complexity: O(row x col) Auxiliary Space: O(1)
Thanks to Gaurav Ahirwar for suggesting this method.
Print matrix in antispiral form
Print matrix in spiral form
Print a given matrix in zigzag form
This article is compiled by Ashish Anand and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
It’s a keen observation that the sum of [i+j] that is the indexes of the array remains the same throughout the diagonal. So we will exploit this property of the matrix to make our code short and simple.
Below is the implementation of the above idea:
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>#define R 5#define C 4using namespace std; void diagonalOrder(int arr[][C], int n, int m){ // we will use a 2D vector to // store the diagonals of our array // the 2D vector will have (n+m-1) // rows that is equal to the number of // diagonals vector<vector<int> > ans(n + m - 1); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { ans[i + j].push_back(arr[j][i]); } } for (int i = 0; i < ans.size(); i++) { for (int j = 0; j < ans[i].size(); j++) cout << ans[i][j] << " "; cout << endl; }} // Driver Codeint main(){ // we have a matrix of n rows // and m columns int n = 5, m = 4; int arr[][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 }, }; // Function call diagonalOrder(arr, n, m); return 0;}
import java.util.*;import java.io.*; class GFG{ public static int R = 5, C = 4; public static void diagonalOrder(int[][] arr, int n, int m) { // we will use a 2D vector to // store the diagonals of our array // the 2D vector will have (n+m-1) // rows that is equal to the number of // diagonals ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>(n+m-1); for(int i = 0; i < n + m - 1; i++) { ans.add(new ArrayList<Integer>()); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { (ans.get(i+j)).add(arr[i][j]); } } for (int i = 0; i < ans.size(); i++) { for (int j = ans.get(i).size() - 1; j >= 0; j--) { System.out.print(ans.get(i).get(j)+ " "); } System.out.println(); } } // Driver code public static void main (String[] args) { int n = 5, m = 4; int[][] arr={ { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 }, }; // Function call diagonalOrder(arr, n, m); }} // This code is contributed by Manu Pathria
R = 5C = 5def diagonalOrder(arr, n, m): # we will use a 2D vector to # store the diagonals of our array # the 2D vector will have (n+m-1) # rows that is equal to the number of # diagonals ans = [[] for i in range(n + m - 1)] for i in range(m): for j in range(n): ans[i + j].append(arr[j][i]) for i in range(len(ans)): for j in range(len(ans[i])): print(ans[i][j], end = " ") print() # Driver Code# we have a matrix of n rows# and m columnsn = 5m = 4 # Function callarr = [[1, 2, 3, 4],[ 5, 6, 7, 8],[9, 10, 11, 12 ],[13, 14, 15, 16 ],[ 17, 18, 19, 20]]diagonalOrder(arr, n, m) # This code is contributed by rag2127
using System;using System.Collections.Generic; public class GFG{ public static int R = 5, C = 4; public static void diagonalOrder(int[,] arr, int n, int m) { // we will use a 2D vector to // store the diagonals of our array // the 2D vector will have (n+m-1) // rows that is equal to the number of // diagonals List<List<int>> ans = new List<List<int>>(n+m-1); for(int i = 0; i < n + m - 1; i++) { ans.Add(new List<int>()); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { (ans[i + j]).Add(arr[i, j]); } } for (int i = 0; i < ans.Count; i++) { for (int j = ans[i].Count - 1; j >= 0; j--) { Console.Write(ans[i][j] + " "); } Console.WriteLine(); } } // Driver code static public void Main () { int n = 5, m = 4; int[,] arr={ { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 }, }; // Function call diagonalOrder(arr, n, m); }} // This code is contributed by avanitrachhadiya2155
<script> var R = 5;var C = 4; function diagonalOrder(arr, n, m){ // we will use a 2D vector to // store the diagonals of our array // the 2D vector will have (n+m-1) // rows that is equal to the number of // diagonals var ans = Array.from(Array(n+m-1), ()=>Array()); for (var i = 0; i < n; i++) { for (var j = 0; j < m; j++) { ans[i + j].push(arr[i][j]); } } for (var i = 0; i < ans.length; i++) { for (var j = ans[i].length - 1; j >= 0; j--) { document.write(ans[i][j] + " "); } document.write("<br>"); }} // Driver Code// we have a matrix of n rows// and m columnsvar n = 5, m = 4;var arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ], [ 17, 18, 19, 20 ],]; // Function calldiagonalOrder(arr, n, m); // This code is contributed by rrrtnx.</script>
1
5 2
9 6 3
13 10 7 4
17 14 11 8
18 15 12
19 16
20
Time Complexity: O(row x col) Auxiliary Space: O(row + col)
ukasp
rathbhupendra
ShubhamAgarwal23
red_devil09
manupathria
avanitrachhadiya2155
rag2127
SHUBHAMSINGH10
ab2127
gabaa406
shivanisinghss2110
rrrtnx
arorakashish0911
sachinvinod1904
hardikkoriintern
Amazon
pattern-printing
Matrix
Misc
Amazon
Misc
pattern-printing
Misc
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sudoku | Backtracking-7
The Celebrity Problem
Rotate a matrix by 90 degree in clockwise direction without using any extra space
Maximum size rectangle binary sub-matrix with all 1s
Inplace rotate square matrix by 90 degrees | Set 1
Overview of Data Structures | Set 1 (Linear Data Structures)
vector::push_back() and vector::pop_back() in C++ STL
Top 10 algorithms in Interview Questions
Virtualization In Cloud Computing and Types
How to write Regular Expressions?
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Jun, 2022"
},
{
"code": null,
"e": 189,
"s": 54,
"text": "Given a 2D matrix, print all elements of the given matrix in diagonal order. For example, consider the following 5 X 4 input matrix. "
},
{
"code": null,
"e": 198,
"s": 189,
"text": "Example:"
},
{
"code": null,
"e": 300,
"s": 198,
"text": "1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16\n17 18 19 20"
},
{
"code": null,
"e": 341,
"s": 300,
"text": "Diagonal printing of the above matrix is"
},
{
"code": null,
"e": 392,
"s": 341,
"text": "1\n5 2\n9 6 3\n13 10 7 4\n17 14 11 8\n18 15 12\n19 16\n20"
},
{
"code": null,
"e": 410,
"s": 392,
"text": "Another example: "
},
{
"code": null,
"e": 558,
"s": 410,
"text": "Following is the code for diagonal printing.The diagonal printing of a given matrix “matrix[ROW][COL]” always has “ROW + COL – 1” lines in output. "
},
{
"code": null,
"e": 574,
"s": 558,
"text": "Implementation:"
},
{
"code": null,
"e": 578,
"s": 574,
"text": "C++"
},
{
"code": null,
"e": 580,
"s": 578,
"text": "C"
},
{
"code": null,
"e": 585,
"s": 580,
"text": "Java"
},
{
"code": null,
"e": 593,
"s": 585,
"text": "Python3"
},
{
"code": null,
"e": 596,
"s": 593,
"text": "C#"
},
{
"code": null,
"e": 600,
"s": 596,
"text": "PHP"
},
{
"code": null,
"e": 611,
"s": 600,
"text": "Javascript"
},
{
"code": "// C++ program to print all elements// of given matrix in diagonal order#include <bits/stdc++.h>using namespace std; #define ROW 5#define COL 4 // A utility function to find min// of two integersint minu(int a, int b){ return (a < b) ? a : b;} // A utility function to find min// of three integersint min(int a, int b, int c){ return minu(minu(a, b), c);} // A utility function to find// max of two integersint max(int a, int b){ return (a > b) ? a : b;} // The main function that prints given// matrix in diagonal ordervoid diagonalOrder(int matrix[][COL]){ // There will be ROW+COL-1 lines // in the output for(int line = 1; line <= (ROW + COL - 1); line++) { /* Get column index of the first element in this line of output. The index is 0 for first ROW lines and line - ROW for remaining lines */ int start_col = max(0, line - ROW); /* Get count of elements in this line. The count of elements is equal to minimum of line number, COL-start_col and ROW */ int count = min(line, (COL - start_col), ROW); /* Print elements of this line */ for(int j = 0; j < count; j++) cout << setw(5) << matrix[minu(ROW, line) - j - 1][start_col + j]; /* Print elements of next diagonal on next line */ cout << \"\\n\"; }} // Utility function to print a matrixvoid printMatrix(int matrix[ROW][COL]){ for(int i = 0; i < ROW; i++) { for(int j = 0; j < COL; j++) cout << setw(5) << matrix[i][j]; cout << \"\\n\"; }} // Driver codeint main(){ int M[ROW][COL] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 },}; cout << \"Given matrix is \" << endl; printMatrix(M); cout << \"\\nDiagonal printing of matrix is \" << endl; diagonalOrder(M); return 0;} // This code is contributed by shubhamsingh10",
"e": 2684,
"s": 611,
"text": null
},
{
"code": "// C program to print all elements// of given matrix in diagonal order#include <stdlib.h> #define ROW 5#define COL 4 // A utility function to find min of two integersint minu(int a, int b){ return (a < b)? a: b; } // A utility function to find min of three integersint min(int a, int b, int c){ return minu(minu(a, b), c);} // A utility function to find max of two integersint max(int a, int b){ return (a > b)? a: b; } // The main function that prints given matrix in// diagonal ordervoid diagonalOrder(int matrix[][COL]){ // There will be ROW+COL-1 lines in the output for (int line=1; line<=(ROW + COL -1); line++) { /* Get column index of the first element in this line of output. The index is 0 for first ROW lines and line - ROW for remaining lines */ int start_col = max(0, line-ROW); /* Get count of elements in this line. The count of elements is equal to minimum of line number, COL-start_col and ROW */ int count = min(line, (COL-start_col), ROW); /* Print elements of this line */ for (int j=0; j<count; j++) printf(\"%5d \", matrix[minu(ROW, line)-j-1][start_col+j]); /* Print elements of next diagonal on next line */ printf(\"\\n\"); }} // Utility function to print a matrixvoid printMatrix(int matrix[ROW][COL]){ for (int i=0; i< ROW; i++) { for (int j=0; j<COL; j++) printf(\"%5d \", matrix[i][j]); printf(\"\\n\"); }} // Driver codeint main(){ int M[ROW][COL] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}, {17, 18, 19, 20}, }; printf (\"Given matrix is \\n\"); printMatrix(M); printf (\"\\nDiagonal printing of matrix is \\n\"); diagonalOrder(M); return 0;}",
"e": 4578,
"s": 2684,
"text": null
},
{
"code": "// Java program to print all elements// of given matrix in diagonal orderclass GFG { static final int ROW = 5; static final int COL = 4; // A utility function to find min // of two integers static int min(int a, int b) { return (a < b) ? a : b; } // A utility function to find min // of three integers static int min(int a, int b, int c) { return min(min(a, b), c); } // A utility function to find max // of two integers static int max(int a, int b) { return (a > b) ? a : b; } // The main function that prints given // matrix in diagonal order static void diagonalOrder(int matrix[][]) { // There will be ROW+COL-1 lines in the output for (int line = 1; line <= (ROW + COL - 1); line++) { // Get column index of the first // element in this line of output. // The index is 0 for first ROW // lines and line - ROW for remaining lines int start_col = max(0, line - ROW); // Get count of elements in this line. // The count of elements is equal to // minimum of line number, COL-start_col and ROW int count = min(line, (COL - start_col), ROW); // Print elements of this line for (int j = 0; j < count; j++) System.out.print(matrix[min(ROW, line) - j- 1][start_col + j] + \" \"); // Print elements of next diagonal on next line System.out.println(); } } // Utility function to print a matrix static void printMatrix(int matrix[][]) { for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) System.out.print(matrix[i][j] + \" \"); System.out.print(\"\\n\"); } } // Driver code public static void main(String[] args) { int M[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 }, }; System.out.print(\"Given matrix is \\n\"); printMatrix(M); System.out.print( \"\\nDiagonal printing of matrix is \\n\"); diagonalOrder(M); }}// This code is contributed by Anant Agarwal.",
"e": 6953,
"s": 4578,
"text": null
},
{
"code": "# Python3 program to print all elements# of given matrix in diagonal orderROW = 5COL = 4 # Main function that prints given# matrix in diagonal order def diagonalOrder(matrix): # There will be ROW+COL-1 lines in the output for line in range(1, (ROW + COL)): # Get column index of the first element # in this line of output. The index is 0 # for first ROW lines and line - ROW for # remaining lines start_col = max(0, line - ROW) # Get count of elements in this line. # The count of elements is equal to # minimum of line number, COL-start_col and ROW count = min(line, (COL - start_col), ROW) # Print elements of this line for j in range(0, count): print(matrix[min(ROW, line) - j - 1] [start_col + j], end=\"\\t\") print() # Utility function to print a matrixdef printMatrix(matrix): for i in range(0, ROW): for j in range(0, COL): print(matrix[i][j], end=\"\\t\") print() # Driver CodeM = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]print(\"Given matrix is \")printMatrix(M) print(\"\\nDiagonal printing of matrix is \")diagonalOrder(M) # This code is contributed by Nikita Tiwari.",
"e": 8238,
"s": 6953,
"text": null
},
{
"code": "// C# program to print all elements// of given matrix in diagonal orderusing System;using static System.Math; class GFG { static int ROW = 5; static int COL = 4; // The main function that prints given // matrix in diagonal order static void diagonalOrder(int[, ] matrix) { // There will be ROW+COL-1 lines in the output for (int line = 1; line <= (ROW + COL - 1); line++) { // Get column index of the first element // in this line of output.The index is 0 // for first ROW lines and line - ROW for // remaining lines int start_col = Max(0, line - ROW); // Get count of elements in this line. The // count of elements is equal to minimum of // line number, COL-start_col and ROW int count = Min(line, Math.Min((COL - start_col), ROW)); // Print elements of this line for (int j = 0; j < count; j++) Console.Write(matrix[Min(ROW, line) - j - 1, start_col + j] + \" \"); // Print elements of next diagonal // on next line Console.WriteLine(); } } // Utility function to print a matrix static void printMatrix(int[, ] matrix) { for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) Console.Write(matrix[i, j] + \" \"); Console.WriteLine(\"\\n\"); } } // Driver code public static void Main() { int[, ] M = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 } }; Console.Write(\"Given matrix is \\n\"); printMatrix(M); Console.Write(\"\\nDiagonal printing\" + \" of matrix is \\n\"); diagonalOrder(M); }} // This code is contributed by Sam007.",
"e": 10166,
"s": 8238,
"text": null
},
{
"code": "<?php// PHP Code for Zigzag (or diagonal)// traversal of Matrix$ROW = 5;$COL = 4; // The main function that prints// given matrix in diagonal orderfunction diagonalOrder(&$matrix){ global $ROW, $COL; // There will be ROW+COL-1 // lines in the output for ($line = 1; $line <= ($ROW + $COL - 1); $line++) { /* Get column index of the first element in this line of output. The index is 0 for first ROW lines and line - ROW for remaining lines */ $start_col = max(0, $line - $ROW); /* Get count of elements in this line. The count of elements is equal to minimum of line number, COL-start_col and ROW */ $count = min($line, ($COL - $start_col), $ROW); /* Print elements of this line */ for ($j = 0; $j < $count; $j++) { echo $matrix[min($ROW, $line) - $j - 1][$start_col + $j]; echo \"\\t\"; } /* Print elements of next diagonal on next line */ print(\"\\n\"); }} // Utility function// to print a matrixfunction printMatrix(&$matrix){ global $ROW, $COL; for ($i = 0; $i < $ROW; $i++) { for ($j = 0; $j < $COL; $j++) { echo $matrix[$i][$j] ; echo \"\\t\"; } print(\"\\n\"); }} // Driver Code$M = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16), array(17, 18, 19, 20));echo \"Given matrix is \\n\";printMatrix($M); printf (\"\\nDiagonal printing \" . \"of matrix is \\n\");diagonalOrder($M); // This code is contributed// by ChitraNayal?>",
"e": 11859,
"s": 10166,
"text": null
},
{
"code": "<script>// Javascript program to print all elements// of given matrix in diagonal order let ROW = 5;let COL = 4; // A utility function to find min // of two integersfunction min(a, b){ return (a < b) ? a : b;} // A utility function to find min // of three integerfunction _min(a, b, c){ return min(min(a, b), c);} // A utility function to find max // of two integersfunction max(a,b){ return (a > b) ? a : b;} // The main function that prints given // matrix in diagonal orderfunction diagonalOrder(matrix){ // There will be ROW+COL-1 lines in the output for (let line = 1; line <= (ROW + COL - 1); line++) { // Get column index of the first // element in this line of output. // The index is 0 for first ROW // lines and line - ROW for remaining lines let start_col = max(0, line - ROW); // Get count of elements in this line. // The count of elements is equal to // minimum of line number, COL-start_col and ROW let count = min(line, (COL - start_col), ROW); // Print elements of this line for (let j = 0; j < count; j++) document.write(matrix[min(ROW, line) - j- 1][start_col + j] + \" \"); // Print elements of next diagonal on next line document.write(\"<br>\"); }} // Utility function to print a matrixfunction printMatrix(matrix){ for (let i = 0; i < ROW; i++) { for (let j = 0; j < COL; j++) document.write(matrix[i][j] + \" \"); document.write(\"<br>\"); }} // Driver codelet M = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ], [ 17, 18, 19, 20 ]];document.write(\"Given matrix is <br>\");printMatrix(M); document.write(\"<br>Diagonal printing of matrix is <br>\");diagonalOrder(M); // This code is contributed by ab2127</script>",
"e": 13913,
"s": 11859,
"text": null
},
{
"code": null,
"e": 14216,
"s": 13913,
"text": "Given matrix is \n 1 2 3 4 \n 5 6 7 8 \n 9 10 11 12 \n 13 14 15 16 \n 17 18 19 20 \n\nDiagonal printing of matrix is \n 1 \n 5 2 \n 9 6 3 \n 13 10 7 4 \n 17 14 11 8 \n 18 15 12 \n 19 16 \n 20 "
},
{
"code": null,
"e": 14268,
"s": 14216,
"text": "Time Complexity: O(row x col) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 14325,
"s": 14268,
"text": "Below is an Alternate Method to solve the above problem."
},
{
"code": null,
"e": 14706,
"s": 14325,
"text": "Matrix => 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n 13 14 15 16\n 17 18 19 20 \n \nObserve the sequence\n 1 / 2 / 3 / 4\n / 5 / 6 / 7 / 8\n / 9 / 10 / 11 / 12\n / 13 / 14 / 15 / 16\n / 17 / 18 / 19 / 20"
},
{
"code": null,
"e": 14722,
"s": 14706,
"text": "Implementation:"
},
{
"code": null,
"e": 14726,
"s": 14722,
"text": "C++"
},
{
"code": null,
"e": 14731,
"s": 14726,
"text": "Java"
},
{
"code": null,
"e": 14739,
"s": 14731,
"text": "Python3"
},
{
"code": null,
"e": 14742,
"s": 14739,
"text": "C#"
},
{
"code": null,
"e": 14746,
"s": 14742,
"text": "PHP"
},
{
"code": null,
"e": 14757,
"s": 14746,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>#define R 5#define C 4using namespace std; bool isValid(int i, int j){ if (i < 0 || i >= R || j >= C || j < 0) return false; return true;} void diagonalOrder(int arr[][C]){ /* through this for loop we choose each element of first column as starting point and print diagonal starting at it. arr[0][0], arr[1][0]....arr[R-1][0] are all starting points */ for (int k = 0; k < R; k++) { cout << arr[k][0] << \" \"; // set row index for next point in // diagonal int i = k - 1; // set column index for next point in // diagonal int j = 1; /* Print Diagonally upward */ while (isValid(i, j)) { cout << arr[i][j] << \" \"; i--; // move in upright direction j++; } cout << endl; } /* through this for loop we choose each element of last row as starting point (except the [0][c-1] it has already been processed in previous for loop) and print diagonal starting at it. arr[R-1][0], arr[R-1][1]....arr[R-1][c-1] are all starting points */ // Note : we start from k = 1 to C-1; for (int k = 1; k < C; k++) { cout << arr[R - 1][k] << \" \"; // set row index for next point in // diagonal int i = R - 2; // set column index for next point in // diagonal int j = k + 1; /* Print Diagonally upward */ while (isValid(i, j)) { cout << arr[i][j] << \" \"; i--; // move in upright direction j++; } cout << endl; }} // Driver Codeint main(){ int arr[][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 }, }; diagonalOrder(arr); return 0;}",
"e": 16709,
"s": 14757,
"text": null
},
{
"code": "// JAVA Code for Zigzag (or diagonal)// traversal of Matrix class GFG { public static int R, C; private static void diagonalOrder(int[][] arr) { /* through this for loop we choose each element of first column as starting point and print diagonal starting at it. arr[0][0], arr[1][0]....arr[R-1][0] are all starting points */ for (int k = 0; k < R; k++) { System.out.print(arr[k][0] + \" \"); // set row index for next // point in diagonal int i = k - 1; // set column index for // next point in diagonal int j = 1; /* Print Diagonally upward */ while (isValid(i, j)) { System.out.print(arr[i][j] + \" \"); i--; // move in upright direction j++; } System.out.println(\"\"); } /* through this for loop we choose each element of last row as starting point (except the [0][c-1] it has already been processed in previous for loop) and print diagonal starting at it. arr[R-1][0], arr[R-1][1].... arr[R-1][c-1] are all starting points */ // Note : we start from k = 1 to C-1; for (int k = 1; k < C; k++) { System.out.print(arr[R - 1][k] + \" \"); // set row index for next // point in diagonal int i = R - 2; // set column index for // next point in diagonal int j = k + 1; /* Print Diagonally upward */ while (isValid(i, j)) { System.out.print(arr[i][j] + \" \"); // move in upright direction i--; j++; } System.out.println(\"\"); } } public static boolean isValid(int i, int j) { if (i < 0 || i >= R || j >= C || j < 0) return false; return true; } // Driver code public static void main(String[] args) { int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 }, }; R = arr.length; C = arr[0].length; // Function call diagonalOrder(arr); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 19162,
"s": 16709,
"text": null
},
{
"code": "# Python3 program to print all elements# of given matrix in diagonal orderR = 5C = 4 def isValid(i, j): if (i < 0 or i >= R or j >= C or j < 0): return False return True def diagonalOrder(arr): # through this for loop we choose each element # of first column as starting point and print # diagonal starting at it. # arr[0][0], arr[1][0]....arr[R-1][0] # are all starting points for k in range(0, R): print(arr[k][0], end=\" \") # set row index for next point in diagonal i = k - 1 # set column index for next point in diagonal j = 1 # Print Diagonally upward while (isValid(i, j)): print(arr[i][j], end=\" \") i -= 1 j += 1 # move in upright direction print() # Through this for loop we choose each # element of last row as starting point # (except the [0][c-1] it has already been # processed in previous for loop) and print # diagonal starting at it. # arr[R-1][0], arr[R-1][1]....arr[R-1][c-1] # are all starting points # Note : we start from k = 1 to C-1; for k in range(1, C): print(arr[R-1][k], end=\" \") # set row index for next point in diagonal i = R - 2 # set column index for next point in diagonal j = k + 1 # Print Diagonally upward while (isValid(i, j)): print(arr[i][j], end=\" \") i -= 1 j += 1 # move in upright direction print() # Driver Codearr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]] # Function calldiagonalOrder(arr) # This code is contributed by Nikita Tiwari.",
"e": 20862,
"s": 19162,
"text": null
},
{
"code": "// C# Code for Zigzag (or diagonal)// traversal of Matrixusing System; class GFG { public static int R, C; private static void diagonalOrder(int[, ] arr) { /* through this for loop we choose each element of first column as starting point and print diagonal starting at it. arr[0,0], arr[1,0]....arr[R-1,0] are all starting points */ for (int k = 0; k < R; k++) { Console.Write(arr[k, 0] + \" \"); // set row index for next // point in diagonal int i = k - 1; // set column index for // next point in diagonal int j = 1; /* Print Diagonally upward */ while (isValid(i, j)) { Console.Write(arr[i, j] + \" \"); i--; // move in upright direction j++; } Console.Write(\"\\n\"); } /* through this for loop we choose each element of last row as starting point (except the [0][c-1] it has already been processed in previous for loop) and print diagonal starting at it. arr[R-1,0], arr[R-1,1].... arr[R-1,c-1] are all starting points */ // Note : we start from k = 1 to C-1; for (int k = 1; k < C; k++) { Console.Write(arr[R - 1, k] + \" \"); // set row index for next // point in diagonal int i = R - 2; // set column index for // next point in diagonal int j = k + 1; /* Print Diagonally upward */ while (isValid(i, j)) { Console.Write(arr[i, j] + \" \"); i--; j++; // move in upright direction } Console.Write(\"\\n\"); } } public static bool isValid(int i, int j) { if (i < 0 || i >= R || j >= C || j < 0) return false; return true; } // Driver code public static void Main() { int[, ] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 } }; R = arr.GetLength(0); C = arr.GetLength(1); // Function call diagonalOrder(arr); }} // This code is contributed// by ChitraNayal",
"e": 23342,
"s": 20862,
"text": null
},
{
"code": "<?php// PHP code for Zigzag (or diagonal)// traversal of Matrixdefine(\"R\", 5);define(\"C\", 4); function isValid($i, $j){ if ($i < 0 || $i >= R || $j >= C || $j < 0) return false; return true;} function diagonalOrder(&$arr){ /* through this for loop we choose each element of first column as starting point and print diagonal starting at it. arr[0][0], arr[1][0]....arr[R-1][0] are all starting points */ for ($k = 0; $k < R; $k++) { echo $arr[$k][0] . \" \"; $i = $k - 1; // set row index for next // point in diagonal $j = 1; // set column index for next // point in diagonal /* Print Diagonally upward */ while (isValid($i,$j)) { echo $arr[$i][$j] . \" \"; $i--; $j++; // move in upright direction } echo \"\\n\"; } /* through this for loop we choose each element of last row as starting point (except the [0][c-1] it has already been processed in previous for loop) and print diagonal starting at it. arr[R-1][0], arr[R-1][1]....arr[R-1][c-1] are all starting points */ //Note : we start from k = 1 to C-1; for ($k = 1; $k < C; $k++) { echo $arr[R - 1][$k] . \" \"; $i = R - 2; // set row index for next // point in diagonal $j = $k + 1; // set column index for next // point in diagonal /* Print Diagonally upward */ while (isValid($i, $j)) { echo $arr[$i][$j] . \" \"; $i--; $j++; // move in upright direction } echo \"\\n\"; }} // Driver Code$arr = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16), array(17, 18, 19, 20)); // Function calldiagonalOrder($arr); // This code is contributed// by rathbhupendra?>",
"e": 25259,
"s": 23342,
"text": null
},
{
"code": "<script>// JAVA Code for Zigzag (or diagonal)// traversal of Matrix var R, C; function diagonalOrder( arr) { /* through this for loop we choose each element of first column as starting point and print diagonal starting at it. arr[0][0], arr[1][0]....arr[R-1][0] are all starting points */ for (var k = 0; k < R; k++) { document.write(arr[k][0] + \" \"); // set row index for next // point in diagonal var i = k - 1; // set column index for // next point in diagonal var j = 1; /* Print Diagonally upward */ while (isValid(i, j)) { document.write(arr[i][j] + \" \"); i--; // move in upright direction j++; } document.writeln(\"<br>\"); } /* through this for loop we choose each element of last row as starting point (except the [0][c-1] it has already been processed in previous for loop) and print diagonal starting at it. arr[R-1][0], arr[R-1][1].... arr[R-1][c-1] are all starting points */ // Note : we start from k = 1 to C-1; for (var k = 1; k < C; k++) { document.write(arr[R - 1][k] + \" \"); // set row index for next // point in diagonal var i = R - 2; // set column index for // next point in diagonal var j = k + 1; /* Print Diagonally upward */ while (isValid(i, j)) { document.write(arr[i][j] + \" \"); // move in upright direction i--; j++; } document.writeln(\"<br>\"); } } function isValid( i, j) { if (i < 0 || i >= R || j >= C || j < 0) return false; return true; } // Driver code var arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ], [ 17, 18, 19, 20 ], ]; R = arr.length; C = arr[0].length; // Function call diagonalOrder(arr); // This code is contributed by shivanisinghss2110</script>",
"e": 27606,
"s": 25259,
"text": null
},
{
"code": null,
"e": 27665,
"s": 27606,
"text": "1 \n5 2 \n9 6 3 \n13 10 7 4 \n17 14 11 8 \n18 15 12 \n19 16 \n20 "
},
{
"code": null,
"e": 27717,
"s": 27665,
"text": "Time Complexity: O(row x col) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 27771,
"s": 27717,
"text": "Thanks to Gaurav Ahirwar for suggesting this method. "
},
{
"code": null,
"e": 27803,
"s": 27771,
"text": "Print matrix in antispiral form"
},
{
"code": null,
"e": 27831,
"s": 27803,
"text": "Print matrix in spiral form"
},
{
"code": null,
"e": 27867,
"s": 27831,
"text": "Print a given matrix in zigzag form"
},
{
"code": null,
"e": 28069,
"s": 27867,
"text": "This article is compiled by Ashish Anand and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 28272,
"s": 28069,
"text": "It’s a keen observation that the sum of [i+j] that is the indexes of the array remains the same throughout the diagonal. So we will exploit this property of the matrix to make our code short and simple."
},
{
"code": null,
"e": 28319,
"s": 28272,
"text": "Below is the implementation of the above idea:"
},
{
"code": null,
"e": 28323,
"s": 28319,
"text": "C++"
},
{
"code": null,
"e": 28328,
"s": 28323,
"text": "Java"
},
{
"code": null,
"e": 28336,
"s": 28328,
"text": "Python3"
},
{
"code": null,
"e": 28339,
"s": 28336,
"text": "C#"
},
{
"code": null,
"e": 28350,
"s": 28339,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>#define R 5#define C 4using namespace std; void diagonalOrder(int arr[][C], int n, int m){ // we will use a 2D vector to // store the diagonals of our array // the 2D vector will have (n+m-1) // rows that is equal to the number of // diagonals vector<vector<int> > ans(n + m - 1); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { ans[i + j].push_back(arr[j][i]); } } for (int i = 0; i < ans.size(); i++) { for (int j = 0; j < ans[i].size(); j++) cout << ans[i][j] << \" \"; cout << endl; }} // Driver Codeint main(){ // we have a matrix of n rows // and m columns int n = 5, m = 4; int arr[][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 }, }; // Function call diagonalOrder(arr, n, m); return 0;}",
"e": 29307,
"s": 28350,
"text": null
},
{
"code": "import java.util.*;import java.io.*; class GFG{ public static int R = 5, C = 4; public static void diagonalOrder(int[][] arr, int n, int m) { // we will use a 2D vector to // store the diagonals of our array // the 2D vector will have (n+m-1) // rows that is equal to the number of // diagonals ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>(n+m-1); for(int i = 0; i < n + m - 1; i++) { ans.add(new ArrayList<Integer>()); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { (ans.get(i+j)).add(arr[i][j]); } } for (int i = 0; i < ans.size(); i++) { for (int j = ans.get(i).size() - 1; j >= 0; j--) { System.out.print(ans.get(i).get(j)+ \" \"); } System.out.println(); } } // Driver code public static void main (String[] args) { int n = 5, m = 4; int[][] arr={ { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 }, }; // Function call diagonalOrder(arr, n, m); }} // This code is contributed by Manu Pathria",
"e": 30431,
"s": 29307,
"text": null
},
{
"code": "R = 5C = 5def diagonalOrder(arr, n, m): # we will use a 2D vector to # store the diagonals of our array # the 2D vector will have (n+m-1) # rows that is equal to the number of # diagonals ans = [[] for i in range(n + m - 1)] for i in range(m): for j in range(n): ans[i + j].append(arr[j][i]) for i in range(len(ans)): for j in range(len(ans[i])): print(ans[i][j], end = \" \") print() # Driver Code# we have a matrix of n rows# and m columnsn = 5m = 4 # Function callarr = [[1, 2, 3, 4],[ 5, 6, 7, 8],[9, 10, 11, 12 ],[13, 14, 15, 16 ],[ 17, 18, 19, 20]]diagonalOrder(arr, n, m) # This code is contributed by rag2127",
"e": 31128,
"s": 30431,
"text": null
},
{
"code": "using System;using System.Collections.Generic; public class GFG{ public static int R = 5, C = 4; public static void diagonalOrder(int[,] arr, int n, int m) { // we will use a 2D vector to // store the diagonals of our array // the 2D vector will have (n+m-1) // rows that is equal to the number of // diagonals List<List<int>> ans = new List<List<int>>(n+m-1); for(int i = 0; i < n + m - 1; i++) { ans.Add(new List<int>()); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { (ans[i + j]).Add(arr[i, j]); } } for (int i = 0; i < ans.Count; i++) { for (int j = ans[i].Count - 1; j >= 0; j--) { Console.Write(ans[i][j] + \" \"); } Console.WriteLine(); } } // Driver code static public void Main () { int n = 5, m = 4; int[,] arr={ { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 }, }; // Function call diagonalOrder(arr, n, m); }} // This code is contributed by avanitrachhadiya2155",
"e": 32215,
"s": 31128,
"text": null
},
{
"code": "<script> var R = 5;var C = 4; function diagonalOrder(arr, n, m){ // we will use a 2D vector to // store the diagonals of our array // the 2D vector will have (n+m-1) // rows that is equal to the number of // diagonals var ans = Array.from(Array(n+m-1), ()=>Array()); for (var i = 0; i < n; i++) { for (var j = 0; j < m; j++) { ans[i + j].push(arr[i][j]); } } for (var i = 0; i < ans.length; i++) { for (var j = ans[i].length - 1; j >= 0; j--) { document.write(ans[i][j] + \" \"); } document.write(\"<br>\"); }} // Driver Code// we have a matrix of n rows// and m columnsvar n = 5, m = 4;var arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ], [ 17, 18, 19, 20 ],]; // Function calldiagonalOrder(arr, n, m); // This code is contributed by rrrtnx.</script>",
"e": 33110,
"s": 32215,
"text": null
},
{
"code": null,
"e": 33169,
"s": 33110,
"text": "1 \n5 2 \n9 6 3 \n13 10 7 4 \n17 14 11 8 \n18 15 12 \n19 16 \n20 "
},
{
"code": null,
"e": 33230,
"s": 33169,
"text": " Time Complexity: O(row x col) Auxiliary Space: O(row + col)"
},
{
"code": null,
"e": 33236,
"s": 33230,
"text": "ukasp"
},
{
"code": null,
"e": 33250,
"s": 33236,
"text": "rathbhupendra"
},
{
"code": null,
"e": 33267,
"s": 33250,
"text": "ShubhamAgarwal23"
},
{
"code": null,
"e": 33279,
"s": 33267,
"text": "red_devil09"
},
{
"code": null,
"e": 33291,
"s": 33279,
"text": "manupathria"
},
{
"code": null,
"e": 33312,
"s": 33291,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 33320,
"s": 33312,
"text": "rag2127"
},
{
"code": null,
"e": 33335,
"s": 33320,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 33342,
"s": 33335,
"text": "ab2127"
},
{
"code": null,
"e": 33351,
"s": 33342,
"text": "gabaa406"
},
{
"code": null,
"e": 33370,
"s": 33351,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 33377,
"s": 33370,
"text": "rrrtnx"
},
{
"code": null,
"e": 33394,
"s": 33377,
"text": "arorakashish0911"
},
{
"code": null,
"e": 33410,
"s": 33394,
"text": "sachinvinod1904"
},
{
"code": null,
"e": 33427,
"s": 33410,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 33434,
"s": 33427,
"text": "Amazon"
},
{
"code": null,
"e": 33451,
"s": 33434,
"text": "pattern-printing"
},
{
"code": null,
"e": 33458,
"s": 33451,
"text": "Matrix"
},
{
"code": null,
"e": 33463,
"s": 33458,
"text": "Misc"
},
{
"code": null,
"e": 33470,
"s": 33463,
"text": "Amazon"
},
{
"code": null,
"e": 33475,
"s": 33470,
"text": "Misc"
},
{
"code": null,
"e": 33492,
"s": 33475,
"text": "pattern-printing"
},
{
"code": null,
"e": 33497,
"s": 33492,
"text": "Misc"
},
{
"code": null,
"e": 33504,
"s": 33497,
"text": "Matrix"
},
{
"code": null,
"e": 33602,
"s": 33504,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33626,
"s": 33602,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 33648,
"s": 33626,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 33730,
"s": 33648,
"text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space"
},
{
"code": null,
"e": 33783,
"s": 33730,
"text": "Maximum size rectangle binary sub-matrix with all 1s"
},
{
"code": null,
"e": 33834,
"s": 33783,
"text": "Inplace rotate square matrix by 90 degrees | Set 1"
},
{
"code": null,
"e": 33895,
"s": 33834,
"text": "Overview of Data Structures | Set 1 (Linear Data Structures)"
},
{
"code": null,
"e": 33949,
"s": 33895,
"text": "vector::push_back() and vector::pop_back() in C++ STL"
},
{
"code": null,
"e": 33990,
"s": 33949,
"text": "Top 10 algorithms in Interview Questions"
},
{
"code": null,
"e": 34034,
"s": 33990,
"text": "Virtualization In Cloud Computing and Types"
}
] |
Difference Between CountDownLatch And CyclicBarrier in Java
|
10 May, 2022
In spite of the fact that both CountDownLatch and CyclicBarrier are utilized as a synchronization help that permits at least one thread to wait however there are sure contrasts between them. Knowing those contrasts between CountDownLatch and CyclicBarrier in Java will assist you with choosing when one of these utilities will serve you better and obviously it is a decent java inquiry question as well.
CountDownLatch is a thread waiting for multiple threads to finish or calling countDown(). When all threads have called countDown(), the awaiting thread continues to execute.
Example:
Java
// Java Program to demonstrate Usage of CountDownLatch// Its used when a thread needs to wait for other// threads before starting its work // Importing required classesimport java.util.concurrent.CountDownLatch; // Main classpublic class CountDownLatchDemo { // Main driver method public static void main(String args[]) throws InterruptedException { // Let us create task that is going to // wait for four threads before it starts CountDownLatch latch = new CountDownLatch(4); // Creating worker threads Worker first = new Worker(1000, latch, "WORKER-1"); Worker second = new Worker(2000, latch, "WORKER-2"); Worker third = new Worker(3000, latch, "WORKER-3"); Worker fourth = new Worker(4000, latch, "WORKER-4"); // Starting above 4 threads first.start(); second.start(); third.start(); fourth.start(); // The main task waits for four threads latch.await(); // Main thread has started System.out.println(Thread.currentThread().getName() + " has finished"); }} // A class to represent threads for which// the main thread waits.class Worker extends Thread { private int delay; private CountDownLatch latch; public Worker(int delay, CountDownLatch latch, String name) { super(name); this.delay = delay; this.latch = latch; } @Override public void run() { try { Thread.sleep(delay); latch.countDown(); System.out.println( Thread.currentThread().getName() + " finished"); } catch (InterruptedException e) { e.printStackTrace(); } }}
WORKER-1 finished
WORKER-2 finished
WORKER-3 finished
main has finished
WORKER-4 finished
CyclicBarrier is when different threads hang tight for one another(wait for each other)and when all have finished their execution, the result needs to be combined in the parent thread.
Example
Java
// Java program to demonstrate Execution on Cyclic Barrier // Importing required classesimport java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException; // Class 1// Class implementing Runnable interfaceclass Computation1 implements Runnable { public static int product = 0; public void run() { product = 2 * 3; try { // thread1 awaits for other threads Tester.newBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } }} // Class 2// Implementing Runnable interfaceclass Computation2 implements Runnable { public static int sum = 0; public void run() { // check if newBarrier is broken or not System.out.println("Is the barrier broken? - " + Tester.newBarrier.isBroken()); sum = 10 + 20; try { Tester.newBarrier.await(3000, TimeUnit.MILLISECONDS); // number of parties waiting at the barrier System.out.println( "Number of parties waiting at the barrier " + "at this point = " + Tester.newBarrier.getNumberWaiting()); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } }} public class Tester implements Runnable { // create a static CyclicBarrier instance public static CyclicBarrier newBarrier = new CyclicBarrier(3); public static void main(String[] args) { // parent thread Tester test = new Tester(); Thread t1 = new Thread(test); // Starting the thread using start() method t1.start(); } // Method public void run() { // Print statement System.out.println( "Number of parties required to trip the barrier = " + newBarrier.getParties()); System.out.println( "Sum of product and sum = " + (Computation1.product + Computation2.sum)); // Creating object of class 1 objects // on which the child thread has to run Computation1 comp1 = new Computation1(); Computation2 comp2 = new Computation2(); // creation of child thread Thread t1 = new Thread(comp1); Thread t2 = new Thread(comp2); // Moving child thread to runnable state t1.start(); t2.start(); try { // parent thread awaits Tester.newBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { // Display exceptions along with line number // using printStackTrace() method e.printStackTrace(); } // barrier breaks as the number of thread waiting // for the barrier at this point = 3 System.out.println( "Sum of product and sum = " + (Computation1.product + Computation2.sum)); // Resetting the newBarrier newBarrier.reset(); System.out.println("Barrier reset successful"); }}
Number of parties required to trip the barrier = 3
Sum of product and sum = 0
Is the barrier broken? - false
Number of parties waiting at the barrier at this point = 0
Sum of product and sum = 36
Barrier reset successful
Difference between CountDownLatch and CyclicBarrier
CountDownLatch
CyclicBarrier
thejavamentor
Java-Multithreading
Difference Between
Java
Java
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
Difference Between Method Overloading and Method Overriding in Java
Difference between Compile-time and Run-time Polymorphism in Java
Similarities and Difference between Java and C++
Difference between Internal and External fragmentation
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 May, 2022"
},
{
"code": null,
"e": 456,
"s": 52,
"text": "In spite of the fact that both CountDownLatch and CyclicBarrier are utilized as a synchronization help that permits at least one thread to wait however there are sure contrasts between them. Knowing those contrasts between CountDownLatch and CyclicBarrier in Java will assist you with choosing when one of these utilities will serve you better and obviously it is a decent java inquiry question as well."
},
{
"code": null,
"e": 630,
"s": 456,
"text": "CountDownLatch is a thread waiting for multiple threads to finish or calling countDown(). When all threads have called countDown(), the awaiting thread continues to execute."
},
{
"code": null,
"e": 640,
"s": 630,
"text": "Example: "
},
{
"code": null,
"e": 645,
"s": 640,
"text": "Java"
},
{
"code": "// Java Program to demonstrate Usage of CountDownLatch// Its used when a thread needs to wait for other// threads before starting its work // Importing required classesimport java.util.concurrent.CountDownLatch; // Main classpublic class CountDownLatchDemo { // Main driver method public static void main(String args[]) throws InterruptedException { // Let us create task that is going to // wait for four threads before it starts CountDownLatch latch = new CountDownLatch(4); // Creating worker threads Worker first = new Worker(1000, latch, \"WORKER-1\"); Worker second = new Worker(2000, latch, \"WORKER-2\"); Worker third = new Worker(3000, latch, \"WORKER-3\"); Worker fourth = new Worker(4000, latch, \"WORKER-4\"); // Starting above 4 threads first.start(); second.start(); third.start(); fourth.start(); // The main task waits for four threads latch.await(); // Main thread has started System.out.println(Thread.currentThread().getName() + \" has finished\"); }} // A class to represent threads for which// the main thread waits.class Worker extends Thread { private int delay; private CountDownLatch latch; public Worker(int delay, CountDownLatch latch, String name) { super(name); this.delay = delay; this.latch = latch; } @Override public void run() { try { Thread.sleep(delay); latch.countDown(); System.out.println( Thread.currentThread().getName() + \" finished\"); } catch (InterruptedException e) { e.printStackTrace(); } }}",
"e": 2409,
"s": 645,
"text": null
},
{
"code": null,
"e": 2500,
"s": 2409,
"text": "WORKER-1 finished\nWORKER-2 finished\nWORKER-3 finished\nmain has finished\nWORKER-4 finished\n"
},
{
"code": null,
"e": 2685,
"s": 2500,
"text": "CyclicBarrier is when different threads hang tight for one another(wait for each other)and when all have finished their execution, the result needs to be combined in the parent thread."
},
{
"code": null,
"e": 2693,
"s": 2685,
"text": "Example"
},
{
"code": null,
"e": 2698,
"s": 2693,
"text": "Java"
},
{
"code": "// Java program to demonstrate Execution on Cyclic Barrier // Importing required classesimport java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException; // Class 1// Class implementing Runnable interfaceclass Computation1 implements Runnable { public static int product = 0; public void run() { product = 2 * 3; try { // thread1 awaits for other threads Tester.newBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } }} // Class 2// Implementing Runnable interfaceclass Computation2 implements Runnable { public static int sum = 0; public void run() { // check if newBarrier is broken or not System.out.println(\"Is the barrier broken? - \" + Tester.newBarrier.isBroken()); sum = 10 + 20; try { Tester.newBarrier.await(3000, TimeUnit.MILLISECONDS); // number of parties waiting at the barrier System.out.println( \"Number of parties waiting at the barrier \" + \"at this point = \" + Tester.newBarrier.getNumberWaiting()); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } }} public class Tester implements Runnable { // create a static CyclicBarrier instance public static CyclicBarrier newBarrier = new CyclicBarrier(3); public static void main(String[] args) { // parent thread Tester test = new Tester(); Thread t1 = new Thread(test); // Starting the thread using start() method t1.start(); } // Method public void run() { // Print statement System.out.println( \"Number of parties required to trip the barrier = \" + newBarrier.getParties()); System.out.println( \"Sum of product and sum = \" + (Computation1.product + Computation2.sum)); // Creating object of class 1 objects // on which the child thread has to run Computation1 comp1 = new Computation1(); Computation2 comp2 = new Computation2(); // creation of child thread Thread t1 = new Thread(comp1); Thread t2 = new Thread(comp2); // Moving child thread to runnable state t1.start(); t2.start(); try { // parent thread awaits Tester.newBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { // Display exceptions along with line number // using printStackTrace() method e.printStackTrace(); } // barrier breaks as the number of thread waiting // for the barrier at this point = 3 System.out.println( \"Sum of product and sum = \" + (Computation1.product + Computation2.sum)); // Resetting the newBarrier newBarrier.reset(); System.out.println(\"Barrier reset successful\"); }}",
"e": 6014,
"s": 2698,
"text": null
},
{
"code": null,
"e": 6235,
"s": 6014,
"text": "Number of parties required to trip the barrier = 3\nSum of product and sum = 0\nIs the barrier broken? - false\nNumber of parties waiting at the barrier at this point = 0\nSum of product and sum = 36\nBarrier reset successful"
},
{
"code": null,
"e": 6288,
"s": 6235,
"text": "Difference between CountDownLatch and CyclicBarrier "
},
{
"code": null,
"e": 6303,
"s": 6288,
"text": "CountDownLatch"
},
{
"code": null,
"e": 6317,
"s": 6303,
"text": "CyclicBarrier"
},
{
"code": null,
"e": 6331,
"s": 6317,
"text": "thejavamentor"
},
{
"code": null,
"e": 6351,
"s": 6331,
"text": "Java-Multithreading"
},
{
"code": null,
"e": 6370,
"s": 6351,
"text": "Difference Between"
},
{
"code": null,
"e": 6375,
"s": 6370,
"text": "Java"
},
{
"code": null,
"e": 6380,
"s": 6375,
"text": "Java"
},
{
"code": null,
"e": 6478,
"s": 6380,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6539,
"s": 6478,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 6607,
"s": 6539,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 6673,
"s": 6607,
"text": "Difference between Compile-time and Run-time Polymorphism in Java"
},
{
"code": null,
"e": 6722,
"s": 6673,
"text": "Similarities and Difference between Java and C++"
},
{
"code": null,
"e": 6777,
"s": 6722,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 6792,
"s": 6777,
"text": "Arrays in Java"
},
{
"code": null,
"e": 6836,
"s": 6792,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 6872,
"s": 6836,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 6897,
"s": 6872,
"text": "Reverse a string in Java"
}
] |
Change column name of a given DataFrame in R
|
16 Mar, 2021
A data frame is a tabular structure with fixed dimensions, of each rows as well as columns. It is a two-dimensional array like object with numerical, character based or factor-type data. Each element belonging to the data frame is indexed by a unique combination of the row and column number respectively. Column names are addressed by unique names.
colnames() method in R is used to rename and replace the column names of the data frame in R.
The columns of the data frame can be renamed by specifying the new column names as a vector. The new name replaces the corresponding old name of the column in the data frame. The length of new column vector should be equivalent to the number of columns originally. Changes are made to the original data frame.
Syntax:
colnames(df) <- c(new_col1_name,new_col2_name,new_col3_name)
Example:
R
# declaring the columns of data framedf = data.frame(col1 = c('A', 'B', 'C', 'J', 'E', NA,'M'),col2 = c(12.5, 9, 16.5, NA, 9, 20, 14.5),col3 = c(NA, 3, 2, NA, 1, NA, 0)) # printing original data frameprint("Original data frame : ")print(df) print("Renaming columns names ") # assigning new names to the columns of the data framecolnames(df) <- c('C1','C2','C3') # printing new data frameprint("New data frame : ")print(df)
Output:
[1] “Original data frame : “
col1 col2 col3
1 A 12.5 NA
2 B 9.0 3
3 C 16.5 2
4 J NA NA
5 E 9.0 1
6 <NA> 20.0 NA
7 M 14.5 0
[1] “Renaming columns names “
[1] “New data frame : “
C1 C2 C3
1 A 12.5 NA
2 B 9.0 3
3 C 16.5 2
4 J NA NA
5 E 9.0 1
6 <NA> 20.0 NA
7 M 14.5 0
1(A) .Specific columns of the data frame can also be renamed using the position index of the respective column.
Syntax:
colnames(df)[col_indx] <- “new_col_name_at_col_indx”
Approach
Create dataframe
Select the column to be renamed by index
Provide a suitable name
Change using colnames() function
Example:
R
# declaring the columns of data framedf = data.frame(col1 = c('A', 'B', 'C', 'J', 'E', NA,'M'),col2 = c(12.5, 9, 16.5, NA, 9, 20, 14.5),col3 = c(NA, 3, 2, NA, 1, NA, 0)) # printing original data frameprint("Original data frame : ")print(df) print("Renaming columns names ") # assigning the second column name to a new namecolnames(df)[2] <- "new_col2" # printing new data frameprint("New data frame : ")print(df)
Output:
[1] “Original data frame : “
col1 col2 col3
1 A 12.5 NA
2 B 9.0 3
3 C 16.5 2
4 J NA NA
5 E 9.0 1
6 <NA> 20.0 NA
7 M 14.5 0
[1] “Renaming columns names “
[1] “New data frame : “
col1 new_col2 col3
1 A 12.5 NA
2 B 9.0 3
3 C 16.5 2
4 J NA NA
5 E 9.0 1
6 <NA> 20.0 NA
7 M 14.5 0
1(B). Column names can also be replaced by using the which(names(df)) function, which searches for the column with the specified old name and then replaces it with the new specified name instance.
Syntax:
colnames(dataframe)[which(names(dataframe) == “oldColName”)] <- “newColName”
Approach
Create data frame
Select name of the columns to be changed
Provide a suitable name
Use the function
Example:
R
# declaring the columns of data framedf = data.frame(col1 = c('A', 'B', 'C', NA,'M'),col2 = c(12.5, 9, 16.5, 20, 14.5),col3 = c(NA, 3, 2, NA, 0)) # printing original data frameprint("Original data frame : ")print(df) print("Renaming columns names ")# assigning the second column name to a new name colnames(df)[2] <- "new_col2" # printing new data frameprint("After changing the data frame col2 name : ")print(df) # replacing first column namecolnames(df)[which(names(df) == "col1")] <- "new_col1" # printing new data frameprint("After changing the data frame col1 name : ")print(df)
Output
[1] “Original data frame : “
col1 col2 col3
1 A 12.5 NA
2 B 9.0 3
3 C 16.5 2
4 <NA> 20.0 NA
5 M 14.5 0
[1] “Renaming columns names “
[1] “After changing the data frame col2 name : “
col1 new_col2 col3
1 A 12.5 NA
2 B 9.0 3
3 C 16.5 2
4 <NA> 20.0 NA
5 M 14.5 0
[1] “After changing the data frame col1 name : “
new_col1 new_col2 col3
1 A 12.5 NA
2 B 9.0 3
3 C 16.5 2
4 <NA> 20.0 NA
5 M 14.5 0
setNames() method in R can also be used to assign new names to the columns contained within a list, vector or tuple. The changes have to be saved back then to the original data frame, because they are not retained.
Syntax:
setnames(df, c(names of new columns))
Approach
Create data frame
Rename column using function
Display modified data frame
Example:
R
# declaring the columns of data framedf = data.frame(col1 = c('A', 'B', 'C', NA,'M'),col2 = c(12.5, 9, 16.5, 20, 14.5),col3 = c(NA, 3, 2, NA, 0)) # printing original data frameprint("Original data frame : ")print(df) # print("Renaming columns names ")# renaming all the column names of data framedf <- setNames(df, c("changed_Col1","changed_Col2","changed_Col3")) print("Renamed data frame : ")print(df)
Output
[1] “Original data frame : “
col1 col2 col3
1 A 12.5 NA
2 B 9.0 3
3 C 16.5 2
4 <NA> 20.0 NA
5 M 14.5 0
[1] “Renamed data frame : “
changed_Col1 changed_Col2 changed_Col3
1 A 12.5 NA
2 B 9.0 3
3 C 16.5 2
4 <NA> 20.0 NA
5 M 14.5 0
Picked
R-DataFrame
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n16 Mar, 2021"
},
{
"code": null,
"e": 403,
"s": 53,
"text": "A data frame is a tabular structure with fixed dimensions, of each rows as well as columns. It is a two-dimensional array like object with numerical, character based or factor-type data. Each element belonging to the data frame is indexed by a unique combination of the row and column number respectively. Column names are addressed by unique names."
},
{
"code": null,
"e": 497,
"s": 403,
"text": "colnames() method in R is used to rename and replace the column names of the data frame in R."
},
{
"code": null,
"e": 808,
"s": 497,
"text": "The columns of the data frame can be renamed by specifying the new column names as a vector. The new name replaces the corresponding old name of the column in the data frame. The length of new column vector should be equivalent to the number of columns originally. Changes are made to the original data frame. "
},
{
"code": null,
"e": 816,
"s": 808,
"text": "Syntax:"
},
{
"code": null,
"e": 877,
"s": 816,
"text": "colnames(df) <- c(new_col1_name,new_col2_name,new_col3_name)"
},
{
"code": null,
"e": 886,
"s": 877,
"text": "Example:"
},
{
"code": null,
"e": 888,
"s": 886,
"text": "R"
},
{
"code": "# declaring the columns of data framedf = data.frame(col1 = c('A', 'B', 'C', 'J', 'E', NA,'M'),col2 = c(12.5, 9, 16.5, NA, 9, 20, 14.5),col3 = c(NA, 3, 2, NA, 1, NA, 0)) # printing original data frameprint(\"Original data frame : \")print(df) print(\"Renaming columns names \") # assigning new names to the columns of the data framecolnames(df) <- c('C1','C2','C3') # printing new data frameprint(\"New data frame : \")print(df)",
"e": 1315,
"s": 888,
"text": null
},
{
"code": null,
"e": 1323,
"s": 1315,
"text": "Output:"
},
{
"code": null,
"e": 1352,
"s": 1323,
"text": "[1] “Original data frame : “"
},
{
"code": null,
"e": 1368,
"s": 1352,
"text": " col1 col2 col3"
},
{
"code": null,
"e": 1385,
"s": 1368,
"text": "1 A 12.5 NA"
},
{
"code": null,
"e": 1402,
"s": 1385,
"text": "2 B 9.0 3"
},
{
"code": null,
"e": 1419,
"s": 1402,
"text": "3 C 16.5 2"
},
{
"code": null,
"e": 1436,
"s": 1419,
"text": "4 J NA NA"
},
{
"code": null,
"e": 1453,
"s": 1436,
"text": "5 E 9.0 1"
},
{
"code": null,
"e": 1470,
"s": 1453,
"text": "6 <NA> 20.0 NA"
},
{
"code": null,
"e": 1487,
"s": 1470,
"text": "7 M 14.5 0"
},
{
"code": null,
"e": 1517,
"s": 1487,
"text": "[1] “Renaming columns names “"
},
{
"code": null,
"e": 1541,
"s": 1517,
"text": "[1] “New data frame : “"
},
{
"code": null,
"e": 1555,
"s": 1541,
"text": " C1 C2 C3"
},
{
"code": null,
"e": 1570,
"s": 1555,
"text": "1 A 12.5 NA"
},
{
"code": null,
"e": 1585,
"s": 1570,
"text": "2 B 9.0 3"
},
{
"code": null,
"e": 1600,
"s": 1585,
"text": "3 C 16.5 2"
},
{
"code": null,
"e": 1615,
"s": 1600,
"text": "4 J NA NA"
},
{
"code": null,
"e": 1630,
"s": 1615,
"text": "5 E 9.0 1"
},
{
"code": null,
"e": 1645,
"s": 1630,
"text": "6 <NA> 20.0 NA"
},
{
"code": null,
"e": 1660,
"s": 1645,
"text": "7 M 14.5 0"
},
{
"code": null,
"e": 1773,
"s": 1660,
"text": "1(A) .Specific columns of the data frame can also be renamed using the position index of the respective column. "
},
{
"code": null,
"e": 1781,
"s": 1773,
"text": "Syntax:"
},
{
"code": null,
"e": 1834,
"s": 1781,
"text": "colnames(df)[col_indx] <- “new_col_name_at_col_indx”"
},
{
"code": null,
"e": 1843,
"s": 1834,
"text": "Approach"
},
{
"code": null,
"e": 1860,
"s": 1843,
"text": "Create dataframe"
},
{
"code": null,
"e": 1901,
"s": 1860,
"text": "Select the column to be renamed by index"
},
{
"code": null,
"e": 1925,
"s": 1901,
"text": "Provide a suitable name"
},
{
"code": null,
"e": 1958,
"s": 1925,
"text": "Change using colnames() function"
},
{
"code": null,
"e": 1967,
"s": 1958,
"text": "Example:"
},
{
"code": null,
"e": 1969,
"s": 1967,
"text": "R"
},
{
"code": "# declaring the columns of data framedf = data.frame(col1 = c('A', 'B', 'C', 'J', 'E', NA,'M'),col2 = c(12.5, 9, 16.5, NA, 9, 20, 14.5),col3 = c(NA, 3, 2, NA, 1, NA, 0)) # printing original data frameprint(\"Original data frame : \")print(df) print(\"Renaming columns names \") # assigning the second column name to a new namecolnames(df)[2] <- \"new_col2\" # printing new data frameprint(\"New data frame : \")print(df)",
"e": 2386,
"s": 1969,
"text": null
},
{
"code": null,
"e": 2394,
"s": 2386,
"text": "Output:"
},
{
"code": null,
"e": 2423,
"s": 2394,
"text": "[1] “Original data frame : “"
},
{
"code": null,
"e": 2439,
"s": 2423,
"text": " col1 col2 col3"
},
{
"code": null,
"e": 2456,
"s": 2439,
"text": "1 A 12.5 NA"
},
{
"code": null,
"e": 2473,
"s": 2456,
"text": "2 B 9.0 3"
},
{
"code": null,
"e": 2490,
"s": 2473,
"text": "3 C 16.5 2"
},
{
"code": null,
"e": 2507,
"s": 2490,
"text": "4 J NA NA"
},
{
"code": null,
"e": 2524,
"s": 2507,
"text": "5 E 9.0 1"
},
{
"code": null,
"e": 2541,
"s": 2524,
"text": "6 <NA> 20.0 NA"
},
{
"code": null,
"e": 2558,
"s": 2541,
"text": "7 M 14.5 0"
},
{
"code": null,
"e": 2588,
"s": 2558,
"text": "[1] “Renaming columns names “"
},
{
"code": null,
"e": 2612,
"s": 2588,
"text": "[1] “New data frame : “"
},
{
"code": null,
"e": 2632,
"s": 2612,
"text": " col1 new_col2 col3"
},
{
"code": null,
"e": 2653,
"s": 2632,
"text": "1 A 12.5 NA"
},
{
"code": null,
"e": 2674,
"s": 2653,
"text": "2 B 9.0 3"
},
{
"code": null,
"e": 2695,
"s": 2674,
"text": "3 C 16.5 2"
},
{
"code": null,
"e": 2716,
"s": 2695,
"text": "4 J NA NA"
},
{
"code": null,
"e": 2737,
"s": 2716,
"text": "5 E 9.0 1"
},
{
"code": null,
"e": 2758,
"s": 2737,
"text": "6 <NA> 20.0 NA"
},
{
"code": null,
"e": 2779,
"s": 2758,
"text": "7 M 14.5 0"
},
{
"code": null,
"e": 2977,
"s": 2779,
"text": "1(B). Column names can also be replaced by using the which(names(df)) function, which searches for the column with the specified old name and then replaces it with the new specified name instance. "
},
{
"code": null,
"e": 2985,
"s": 2977,
"text": "Syntax:"
},
{
"code": null,
"e": 3062,
"s": 2985,
"text": "colnames(dataframe)[which(names(dataframe) == “oldColName”)] <- “newColName”"
},
{
"code": null,
"e": 3071,
"s": 3062,
"text": "Approach"
},
{
"code": null,
"e": 3089,
"s": 3071,
"text": "Create data frame"
},
{
"code": null,
"e": 3130,
"s": 3089,
"text": "Select name of the columns to be changed"
},
{
"code": null,
"e": 3154,
"s": 3130,
"text": "Provide a suitable name"
},
{
"code": null,
"e": 3171,
"s": 3154,
"text": "Use the function"
},
{
"code": null,
"e": 3180,
"s": 3171,
"text": "Example:"
},
{
"code": null,
"e": 3182,
"s": 3180,
"text": "R"
},
{
"code": "# declaring the columns of data framedf = data.frame(col1 = c('A', 'B', 'C', NA,'M'),col2 = c(12.5, 9, 16.5, 20, 14.5),col3 = c(NA, 3, 2, NA, 0)) # printing original data frameprint(\"Original data frame : \")print(df) print(\"Renaming columns names \")# assigning the second column name to a new name colnames(df)[2] <- \"new_col2\" # printing new data frameprint(\"After changing the data frame col2 name : \")print(df) # replacing first column namecolnames(df)[which(names(df) == \"col1\")] <- \"new_col1\" # printing new data frameprint(\"After changing the data frame col1 name : \")print(df)",
"e": 3773,
"s": 3182,
"text": null
},
{
"code": null,
"e": 3780,
"s": 3773,
"text": "Output"
},
{
"code": null,
"e": 3809,
"s": 3780,
"text": "[1] “Original data frame : “"
},
{
"code": null,
"e": 3825,
"s": 3809,
"text": " col1 col2 col3"
},
{
"code": null,
"e": 3842,
"s": 3825,
"text": "1 A 12.5 NA"
},
{
"code": null,
"e": 3859,
"s": 3842,
"text": "2 B 9.0 3"
},
{
"code": null,
"e": 3876,
"s": 3859,
"text": "3 C 16.5 2"
},
{
"code": null,
"e": 3893,
"s": 3876,
"text": "4 <NA> 20.0 NA"
},
{
"code": null,
"e": 3910,
"s": 3893,
"text": "5 M 14.5 0"
},
{
"code": null,
"e": 3940,
"s": 3910,
"text": "[1] “Renaming columns names “"
},
{
"code": null,
"e": 3989,
"s": 3940,
"text": "[1] “After changing the data frame col2 name : “"
},
{
"code": null,
"e": 4009,
"s": 3989,
"text": " col1 new_col2 col3"
},
{
"code": null,
"e": 4030,
"s": 4009,
"text": "1 A 12.5 NA"
},
{
"code": null,
"e": 4051,
"s": 4030,
"text": "2 B 9.0 3"
},
{
"code": null,
"e": 4072,
"s": 4051,
"text": "3 C 16.5 2"
},
{
"code": null,
"e": 4093,
"s": 4072,
"text": "4 <NA> 20.0 NA"
},
{
"code": null,
"e": 4114,
"s": 4093,
"text": "5 M 14.5 0"
},
{
"code": null,
"e": 4163,
"s": 4114,
"text": "[1] “After changing the data frame col1 name : “"
},
{
"code": null,
"e": 4187,
"s": 4163,
"text": " new_col1 new_col2 col3"
},
{
"code": null,
"e": 4212,
"s": 4187,
"text": "1 A 12.5 NA"
},
{
"code": null,
"e": 4237,
"s": 4212,
"text": "2 B 9.0 3"
},
{
"code": null,
"e": 4262,
"s": 4237,
"text": "3 C 16.5 2"
},
{
"code": null,
"e": 4287,
"s": 4262,
"text": "4 <NA> 20.0 NA"
},
{
"code": null,
"e": 4312,
"s": 4287,
"text": "5 M 14.5 0"
},
{
"code": null,
"e": 4527,
"s": 4312,
"text": "setNames() method in R can also be used to assign new names to the columns contained within a list, vector or tuple. The changes have to be saved back then to the original data frame, because they are not retained."
},
{
"code": null,
"e": 4535,
"s": 4527,
"text": "Syntax:"
},
{
"code": null,
"e": 4573,
"s": 4535,
"text": "setnames(df, c(names of new columns))"
},
{
"code": null,
"e": 4582,
"s": 4573,
"text": "Approach"
},
{
"code": null,
"e": 4600,
"s": 4582,
"text": "Create data frame"
},
{
"code": null,
"e": 4629,
"s": 4600,
"text": "Rename column using function"
},
{
"code": null,
"e": 4657,
"s": 4629,
"text": "Display modified data frame"
},
{
"code": null,
"e": 4666,
"s": 4657,
"text": "Example:"
},
{
"code": null,
"e": 4668,
"s": 4666,
"text": "R"
},
{
"code": "# declaring the columns of data framedf = data.frame(col1 = c('A', 'B', 'C', NA,'M'),col2 = c(12.5, 9, 16.5, 20, 14.5),col3 = c(NA, 3, 2, NA, 0)) # printing original data frameprint(\"Original data frame : \")print(df) # print(\"Renaming columns names \")# renaming all the column names of data framedf <- setNames(df, c(\"changed_Col1\",\"changed_Col2\",\"changed_Col3\")) print(\"Renamed data frame : \")print(df)",
"e": 5076,
"s": 4668,
"text": null
},
{
"code": null,
"e": 5083,
"s": 5076,
"text": "Output"
},
{
"code": null,
"e": 5112,
"s": 5083,
"text": "[1] “Original data frame : “"
},
{
"code": null,
"e": 5129,
"s": 5112,
"text": " col1 col2 col3"
},
{
"code": null,
"e": 5146,
"s": 5129,
"text": "1 A 12.5 NA"
},
{
"code": null,
"e": 5163,
"s": 5146,
"text": "2 B 9.0 3"
},
{
"code": null,
"e": 5180,
"s": 5163,
"text": "3 C 16.5 2"
},
{
"code": null,
"e": 5197,
"s": 5180,
"text": "4 <NA> 20.0 NA"
},
{
"code": null,
"e": 5214,
"s": 5197,
"text": "5 M 14.5 0"
},
{
"code": null,
"e": 5242,
"s": 5214,
"text": "[1] “Renamed data frame : “"
},
{
"code": null,
"e": 5283,
"s": 5242,
"text": " changed_Col1 changed_Col2 changed_Col3"
},
{
"code": null,
"e": 5324,
"s": 5283,
"text": "1 A 12.5 NA"
},
{
"code": null,
"e": 5365,
"s": 5324,
"text": "2 B 9.0 3"
},
{
"code": null,
"e": 5406,
"s": 5365,
"text": "3 C 16.5 2"
},
{
"code": null,
"e": 5447,
"s": 5406,
"text": "4 <NA> 20.0 NA"
},
{
"code": null,
"e": 5488,
"s": 5447,
"text": "5 M 14.5 0"
},
{
"code": null,
"e": 5495,
"s": 5488,
"text": "Picked"
},
{
"code": null,
"e": 5507,
"s": 5495,
"text": "R-DataFrame"
},
{
"code": null,
"e": 5518,
"s": 5507,
"text": "R Language"
},
{
"code": null,
"e": 5616,
"s": 5518,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5668,
"s": 5616,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 5720,
"s": 5668,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 5778,
"s": 5720,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 5810,
"s": 5778,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 5845,
"s": 5810,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 5889,
"s": 5845,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 5927,
"s": 5889,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 5976,
"s": 5927,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 5993,
"s": 5976,
"text": "R - if statement"
}
] |
Qt Alignment in PyQt5
|
01 Jul, 2021
In PyQt5, Qt alignment is used to set the alignment of the widgets. In order to use the Qt alignment methods, we have to import Qt from the QtCore class.
from PyQt5.QtCore import Qt
There are many methods in Qt alignment :1. Qt.AlignLeft 2. Qt.AlignRight 3. Qt.AlignBottom 4. Qt.AlignTop 5. Qt.AlignCenter 6. Qt.AlignHCenter 7. Qt.AlignVCenter
Note: There are also some alignment methods like Qt.AlignJustify but they works in PyQt4 not in PyQt5. Code : The code will show all these methods and helps in better understanding the differences.
Python3
# importing the required libraries from PyQt5.QtWidgets import *from PyQt5.QtCore import Qtfrom PyQt5.QtGui import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Label") # setting the geometry of window self.setGeometry(0, 0, 650, 400) # creating a label widget and setting properties self.label_1 = QLabel("Bottom", self) self.label_1.move(20, 100) self.label_1.resize(60, 60) self.label_1.setStyleSheet("border: 1px solid black;") # aligning label to the bottom self.label_1.setAlignment(Qt.AlignBottom) # creating a label widget and setting properties self.label_2 = QLabel("Center", self) self.label_2.move(90, 100) self.label_2.resize(60, 60) self.label_2.setStyleSheet("border: 1px solid black;") # aligning label to the center self.label_2.setAlignment(Qt.AlignCenter) # creating a label widget and setting properties self.label_3 = QLabel("Left", self) self.label_3.move(160, 100) self.label_3.resize(60, 60) self.label_3.setStyleSheet("border: 1px solid black;") # aligning label to the left self.label_3.setAlignment(Qt.AlignLeft) # creating a label widget and setting properties self.label_4 = QLabel("Right", self) self.label_4.move(230, 100) self.label_4.resize(60, 60) self.label_4.setStyleSheet("border: 1px solid black;") # aligning label to the right self.label_4.setAlignment(Qt.AlignRight) # creating a label widget and setting properties self.label_5 = QLabel("Top", self) self.label_5.move(300, 100) self.label_5.resize(60, 60) self.label_5.setStyleSheet("border: 1px solid black;") # aligning label to the top self.label_5.setAlignment(Qt.AlignTop) # creating a label widget and setting properties self.label_6 = QLabel("H center", self) self.label_6.move(370, 100) self.label_6.resize(60, 60) self.label_6.setStyleSheet("border: 1px solid black;") # aligning label to the Hcenter self.label_6.setAlignment(Qt.AlignHCenter) # creating a label widget and setting properties self.label_7 = QLabel("V center", self) self.label_7.move(440, 100) self.label_7.resize(60, 60) self.label_7.setStyleSheet("border: 1px solid black;") # aligning label to the Vcenter self.label_7.setAlignment(Qt.AlignVCenter) # 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 :
anupamjaiswall
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n01 Jul, 2021"
},
{
"code": null,
"e": 209,
"s": 53,
"text": "In PyQt5, Qt alignment is used to set the alignment of the widgets. In order to use the Qt alignment methods, we have to import Qt from the QtCore class. "
},
{
"code": null,
"e": 237,
"s": 209,
"text": "from PyQt5.QtCore import Qt"
},
{
"code": null,
"e": 401,
"s": 239,
"text": "There are many methods in Qt alignment :1. Qt.AlignLeft 2. Qt.AlignRight 3. Qt.AlignBottom 4. Qt.AlignTop 5. Qt.AlignCenter 6. Qt.AlignHCenter 7. Qt.AlignVCenter"
},
{
"code": null,
"e": 602,
"s": 401,
"text": "Note: There are also some alignment methods like Qt.AlignJustify but they works in PyQt4 not in PyQt5. Code : The code will show all these methods and helps in better understanding the differences. "
},
{
"code": null,
"e": 610,
"s": 602,
"text": "Python3"
},
{
"code": "# importing the required libraries from PyQt5.QtWidgets import *from PyQt5.QtCore import Qtfrom PyQt5.QtGui import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Label\") # setting the geometry of window self.setGeometry(0, 0, 650, 400) # creating a label widget and setting properties self.label_1 = QLabel(\"Bottom\", self) self.label_1.move(20, 100) self.label_1.resize(60, 60) self.label_1.setStyleSheet(\"border: 1px solid black;\") # aligning label to the bottom self.label_1.setAlignment(Qt.AlignBottom) # creating a label widget and setting properties self.label_2 = QLabel(\"Center\", self) self.label_2.move(90, 100) self.label_2.resize(60, 60) self.label_2.setStyleSheet(\"border: 1px solid black;\") # aligning label to the center self.label_2.setAlignment(Qt.AlignCenter) # creating a label widget and setting properties self.label_3 = QLabel(\"Left\", self) self.label_3.move(160, 100) self.label_3.resize(60, 60) self.label_3.setStyleSheet(\"border: 1px solid black;\") # aligning label to the left self.label_3.setAlignment(Qt.AlignLeft) # creating a label widget and setting properties self.label_4 = QLabel(\"Right\", self) self.label_4.move(230, 100) self.label_4.resize(60, 60) self.label_4.setStyleSheet(\"border: 1px solid black;\") # aligning label to the right self.label_4.setAlignment(Qt.AlignRight) # creating a label widget and setting properties self.label_5 = QLabel(\"Top\", self) self.label_5.move(300, 100) self.label_5.resize(60, 60) self.label_5.setStyleSheet(\"border: 1px solid black;\") # aligning label to the top self.label_5.setAlignment(Qt.AlignTop) # creating a label widget and setting properties self.label_6 = QLabel(\"H center\", self) self.label_6.move(370, 100) self.label_6.resize(60, 60) self.label_6.setStyleSheet(\"border: 1px solid black;\") # aligning label to the Hcenter self.label_6.setAlignment(Qt.AlignHCenter) # creating a label widget and setting properties self.label_7 = QLabel(\"V center\", self) self.label_7.move(440, 100) self.label_7.resize(60, 60) self.label_7.setStyleSheet(\"border: 1px solid black;\") # aligning label to the Vcenter self.label_7.setAlignment(Qt.AlignVCenter) # 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": 3384,
"s": 610,
"text": null
},
{
"code": null,
"e": 3395,
"s": 3384,
"text": "Output : "
},
{
"code": null,
"e": 3412,
"s": 3397,
"text": "anupamjaiswall"
},
{
"code": null,
"e": 3423,
"s": 3412,
"text": "Python-gui"
},
{
"code": null,
"e": 3435,
"s": 3423,
"text": "Python-PyQt"
},
{
"code": null,
"e": 3442,
"s": 3435,
"text": "Python"
}
] |
Longest substring with count of 1s more than 0s
|
20 Jul, 2021
Given a binary string find the longest substring which contains 1’s more than 0’s.Examples:
Input : 1010
Output : 3
Substring 101 has 1 occurring more number of times than 0.
Input : 101100
Output : 5
Substring 10110 has 1 occurring more number of times than 0.
A simple solution is to one by one consider all the substrings and check if that substring has a count of 1 more than 0. If the count is more than comparing its length with maximum length substring found till now. The time complexity of this solution is O(n^2).An efficient solution is to use hashing. The idea is to find the sum of string traversed until now. Add 1 to the result if the current character is ‘1’ else subtract 1. Now the problem reduces to finding the largest subarray having a sum greater than zero. To find the largest subarray having a sum greater than zero, we check the value of the sum. If sum is greater than zero, then the largest subarray with a sum greater than zero is arr[0..i]. If the sum is less than zero, then find the size of subarray arr[j+1..i], where j is index up to which sum of subarray arr[0..j] is sum -1 and j < i and compare that size with largest subarray size found so far. To find index j, store values of sum for arr[0..j] in hash table for all 0 <= j <= i. There might be a possibility that a given value of sum repeats. In that case store only first index for which that sum is obtained as it is required to get the length of largest subarray and that is obtained from first index occurrence.Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// CPP program to find largest substring// having count of 1s more than count// count of 0s.#include <bits/stdc++.h>using namespace std; // Function to find longest substring// having count of 1s more than count// of 0s.int findLongestSub(string bin){ int n = bin.length(), i; // To store sum. int sum = 0; // To store first occurrence of each // sum value. unordered_map<int, int> prevSum; // To store maximum length. int maxlen = 0; // To store current substring length. int currlen; for (i = 0; i < n; i++) { // Add 1 if current character is 1 // else subtract 1. if (bin[i] == '1') sum++; else sum--; // If sum is positive, then maximum // length substring is bin[0..i] if (sum > 0) { maxlen = i + 1; } // If sum is negative, then maximum // length substring is bin[j+1..i], where // sum of substring bin[0..j] is sum-1. else if (sum <= 0) { if (prevSum.find(sum - 1) != prevSum.end()) { currlen = i - prevSum[sum - 1]; maxlen = max(maxlen, currlen); } } // Make entry for this sum value in hash // table if this value is not present. if (prevSum.find(sum) == prevSum.end()) prevSum[sum] = i; } return maxlen;} // Driver codeint main(){ string bin = "1010"; cout << findLongestSub(bin); return 0;}
// Java program to find largest substring// having count of 1s more than count// count of 0s.import java.util.HashMap; class GFG{ // Function to find longest substring // having count of 1s more than count // of 0s. static int findLongestSub(String bin) { int n = bin.length(), i; // To store sum. int sum = 0; // To store first occurrence of each // sum value. HashMap<Integer, Integer> prevSum = new HashMap<>(); // To store maximum length. int maxlen = 0; // To store current substring length. int currlen; for (i = 0; i < n; i++) { // Add 1 if current character is 1 // else subtract 1. if (bin.charAt(i) == '1') sum++; else sum--; // If sum is positive, then maximum // length substring is bin[0..i] if (sum > 0) { maxlen = i + 1; } // If sum is negative, then maximum // length substring is bin[j+1..i], where // sum of substring bin[0..j] is sum-1. else if (sum <= 0) { if (prevSum.containsKey(sum - 1)) { currlen = i - (prevSum.get(sum - 1) == null ? 1 : prevSum.get(sum - 1)); maxlen = Math.max(maxlen, currlen); } } // Make entry for this sum value in hash // table if this value is not present. if (!prevSum.containsKey(sum)) prevSum.put(sum, i); } return maxlen; } // Driver code public static void main(String[] args) { String bin = "1010"; System.out.println(findLongestSub(bin)); }} // This code is contributed by// sanjeev2552
# Python 3 program to find largest substring# having count of 1s more than count# count of 0s. # Function to find longest substring# having count of 1s more than count# of 0s.def findLongestSub(bin1): n = len(bin1) # To store sum. sum = 0 # To store first occurrence of each # sum value. prevSum = {i:0 for i in range(n)} # To store maximum length. maxlen = 0 # To store current substring length. for i in range(n): # Add 1 if current character is 1 # else subtract 1. if (bin1[i] == '1'): sum += 1 else: sum -= 1 # If sum is positive, then maximum # length substring is bin1[0..i] if (sum > 0): maxlen = i + 1 # If sum is negative, then maximum # length substring is bin1[j+1..i], where # sum of substring bin1[0..j] is sum-1. elif (sum <= 0): if ((sum - 1) in prevSum): currlen = i - prevSum[sum - 1] maxlen = max(maxlen, currlen) # Make entry for this sum value in hash # table if this value is not present. if ((sum) not in prevSum): prevSum[sum] = i return maxlen # Driver codeif __name__ == '__main__': bin1 = "1010" print(findLongestSub(bin1)) # This code is contributed by# Surendra_Gangwar
// C# program to find largest substring// having count of 1s more than count// count of 0s.using System;using System.Collections.Generic;class GFG{ // Function to find longest substring // having count of 1s more than count // of 0s. static int findLongestSub(String bin) { int n = bin.Length, i; // To store sum. int sum = 0; // To store first occurrence of each // sum value. Dictionary<int, int> prevSum = new Dictionary<int, int>(); // To store maximum length. int maxlen = 0; // To store current substring length. int currlen; for (i = 0; i < n; i++) { // Add 1 if current character is 1 // else subtract 1. if (bin[i] == '1') sum++; else sum--; // If sum is positive, then maximum // length substring is bin[0..i] if (sum > 0) { maxlen = i + 1; } // If sum is negative, then maximum // length substring is bin[j+1..i], where // sum of substring bin[0..j] is sum-1. else if (sum <= 0) { if (prevSum.ContainsKey(sum - 1)) { currlen = i - (prevSum[sum - 1] == 0 ? 1 : prevSum[sum - 1]); maxlen = Math.Max(maxlen, currlen); } } // Make entry for this sum value in hash // table if this value is not present. if (!prevSum.ContainsKey(sum)) prevSum.Add(sum, i); } return maxlen; } // Driver code public static void Main(String[] args) { String bin = "1010"; Console.WriteLine(findLongestSub(bin)); }} // This code is contributed by 29AjayKumar
<script>// Javascript program to find largest substring// having count of 1s more than count// count of 0s. // Function to find longest substring // having count of 1s more than count // of 0s.function findLongestSub(bin){ let n = bin.length, i; // To store sum. let sum = 0; // To store first occurrence of each // sum value. let prevSum = new Map(); // To store maximum length. let maxlen = 0; // To store current substring length. let currlen; for (i = 0; i < n; i++) { // Add 1 if current character is 1 // else subtract 1. if (bin[i] == '1') sum++; else sum--; // If sum is positive, then maximum // length substring is bin[0..i] if (sum > 0) { maxlen = i + 1; } // If sum is negative, then maximum // length substring is bin[j+1..i], where // sum of substring bin[0..j] is sum-1. else if (sum <= 0) { if (prevSum.has(sum - 1)) { currlen = i - (prevSum.get(sum - 1) == null ? 1 : prevSum.get(sum - 1)); maxlen = Math.max(maxlen, currlen); } } // Make entry for this sum value in hash // table if this value is not present. if (!prevSum.has(sum)) prevSum.set(sum, i); } return maxlen;} // Driver codelet bin = "1010";document.write(findLongestSub(bin)); // This code is contributed by rag2127</script>
Output:
3
Time Complexity: O(n) Auxiliary Space: O(n)
nik1996
SURENDRA_GANGWAR
sanjeev2552
29AjayKumar
rag2127
D-E-Shaw
prefix-sum
Hash
Strings
D-E-Shaw
prefix-sum
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find k numbers with most occurrences in the given array
Real-time application of Data Structures
Non-Repeating Element
Find the length of largest subarray with 0 sum
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 146,
"s": 52,
"text": "Given a binary string find the longest substring which contains 1’s more than 0’s.Examples: "
},
{
"code": null,
"e": 317,
"s": 146,
"text": "Input : 1010\nOutput : 3\nSubstring 101 has 1 occurring more number of times than 0.\n\nInput : 101100\nOutput : 5\nSubstring 10110 has 1 occurring more number of times than 0."
},
{
"code": null,
"e": 1610,
"s": 319,
"text": "A simple solution is to one by one consider all the substrings and check if that substring has a count of 1 more than 0. If the count is more than comparing its length with maximum length substring found till now. The time complexity of this solution is O(n^2).An efficient solution is to use hashing. The idea is to find the sum of string traversed until now. Add 1 to the result if the current character is ‘1’ else subtract 1. Now the problem reduces to finding the largest subarray having a sum greater than zero. To find the largest subarray having a sum greater than zero, we check the value of the sum. If sum is greater than zero, then the largest subarray with a sum greater than zero is arr[0..i]. If the sum is less than zero, then find the size of subarray arr[j+1..i], where j is index up to which sum of subarray arr[0..j] is sum -1 and j < i and compare that size with largest subarray size found so far. To find index j, store values of sum for arr[0..j] in hash table for all 0 <= j <= i. There might be a possibility that a given value of sum repeats. In that case store only first index for which that sum is obtained as it is required to get the length of largest subarray and that is obtained from first index occurrence.Below is the implementation of above approach: "
},
{
"code": null,
"e": 1614,
"s": 1610,
"text": "C++"
},
{
"code": null,
"e": 1619,
"s": 1614,
"text": "Java"
},
{
"code": null,
"e": 1627,
"s": 1619,
"text": "Python3"
},
{
"code": null,
"e": 1630,
"s": 1627,
"text": "C#"
},
{
"code": null,
"e": 1641,
"s": 1630,
"text": "Javascript"
},
{
"code": "// CPP program to find largest substring// having count of 1s more than count// count of 0s.#include <bits/stdc++.h>using namespace std; // Function to find longest substring// having count of 1s more than count// of 0s.int findLongestSub(string bin){ int n = bin.length(), i; // To store sum. int sum = 0; // To store first occurrence of each // sum value. unordered_map<int, int> prevSum; // To store maximum length. int maxlen = 0; // To store current substring length. int currlen; for (i = 0; i < n; i++) { // Add 1 if current character is 1 // else subtract 1. if (bin[i] == '1') sum++; else sum--; // If sum is positive, then maximum // length substring is bin[0..i] if (sum > 0) { maxlen = i + 1; } // If sum is negative, then maximum // length substring is bin[j+1..i], where // sum of substring bin[0..j] is sum-1. else if (sum <= 0) { if (prevSum.find(sum - 1) != prevSum.end()) { currlen = i - prevSum[sum - 1]; maxlen = max(maxlen, currlen); } } // Make entry for this sum value in hash // table if this value is not present. if (prevSum.find(sum) == prevSum.end()) prevSum[sum] = i; } return maxlen;} // Driver codeint main(){ string bin = \"1010\"; cout << findLongestSub(bin); return 0;}",
"e": 3109,
"s": 1641,
"text": null
},
{
"code": "// Java program to find largest substring// having count of 1s more than count// count of 0s.import java.util.HashMap; class GFG{ // Function to find longest substring // having count of 1s more than count // of 0s. static int findLongestSub(String bin) { int n = bin.length(), i; // To store sum. int sum = 0; // To store first occurrence of each // sum value. HashMap<Integer, Integer> prevSum = new HashMap<>(); // To store maximum length. int maxlen = 0; // To store current substring length. int currlen; for (i = 0; i < n; i++) { // Add 1 if current character is 1 // else subtract 1. if (bin.charAt(i) == '1') sum++; else sum--; // If sum is positive, then maximum // length substring is bin[0..i] if (sum > 0) { maxlen = i + 1; } // If sum is negative, then maximum // length substring is bin[j+1..i], where // sum of substring bin[0..j] is sum-1. else if (sum <= 0) { if (prevSum.containsKey(sum - 1)) { currlen = i - (prevSum.get(sum - 1) == null ? 1 : prevSum.get(sum - 1)); maxlen = Math.max(maxlen, currlen); } } // Make entry for this sum value in hash // table if this value is not present. if (!prevSum.containsKey(sum)) prevSum.put(sum, i); } return maxlen; } // Driver code public static void main(String[] args) { String bin = \"1010\"; System.out.println(findLongestSub(bin)); }} // This code is contributed by// sanjeev2552",
"e": 5007,
"s": 3109,
"text": null
},
{
"code": "# Python 3 program to find largest substring# having count of 1s more than count# count of 0s. # Function to find longest substring# having count of 1s more than count# of 0s.def findLongestSub(bin1): n = len(bin1) # To store sum. sum = 0 # To store first occurrence of each # sum value. prevSum = {i:0 for i in range(n)} # To store maximum length. maxlen = 0 # To store current substring length. for i in range(n): # Add 1 if current character is 1 # else subtract 1. if (bin1[i] == '1'): sum += 1 else: sum -= 1 # If sum is positive, then maximum # length substring is bin1[0..i] if (sum > 0): maxlen = i + 1 # If sum is negative, then maximum # length substring is bin1[j+1..i], where # sum of substring bin1[0..j] is sum-1. elif (sum <= 0): if ((sum - 1) in prevSum): currlen = i - prevSum[sum - 1] maxlen = max(maxlen, currlen) # Make entry for this sum value in hash # table if this value is not present. if ((sum) not in prevSum): prevSum[sum] = i return maxlen # Driver codeif __name__ == '__main__': bin1 = \"1010\" print(findLongestSub(bin1)) # This code is contributed by# Surendra_Gangwar",
"e": 6353,
"s": 5007,
"text": null
},
{
"code": "// C# program to find largest substring// having count of 1s more than count// count of 0s.using System;using System.Collections.Generic;class GFG{ // Function to find longest substring // having count of 1s more than count // of 0s. static int findLongestSub(String bin) { int n = bin.Length, i; // To store sum. int sum = 0; // To store first occurrence of each // sum value. Dictionary<int, int> prevSum = new Dictionary<int, int>(); // To store maximum length. int maxlen = 0; // To store current substring length. int currlen; for (i = 0; i < n; i++) { // Add 1 if current character is 1 // else subtract 1. if (bin[i] == '1') sum++; else sum--; // If sum is positive, then maximum // length substring is bin[0..i] if (sum > 0) { maxlen = i + 1; } // If sum is negative, then maximum // length substring is bin[j+1..i], where // sum of substring bin[0..j] is sum-1. else if (sum <= 0) { if (prevSum.ContainsKey(sum - 1)) { currlen = i - (prevSum[sum - 1] == 0 ? 1 : prevSum[sum - 1]); maxlen = Math.Max(maxlen, currlen); } } // Make entry for this sum value in hash // table if this value is not present. if (!prevSum.ContainsKey(sum)) prevSum.Add(sum, i); } return maxlen; } // Driver code public static void Main(String[] args) { String bin = \"1010\"; Console.WriteLine(findLongestSub(bin)); }} // This code is contributed by 29AjayKumar",
"e": 8303,
"s": 6353,
"text": null
},
{
"code": "<script>// Javascript program to find largest substring// having count of 1s more than count// count of 0s. // Function to find longest substring // having count of 1s more than count // of 0s.function findLongestSub(bin){ let n = bin.length, i; // To store sum. let sum = 0; // To store first occurrence of each // sum value. let prevSum = new Map(); // To store maximum length. let maxlen = 0; // To store current substring length. let currlen; for (i = 0; i < n; i++) { // Add 1 if current character is 1 // else subtract 1. if (bin[i] == '1') sum++; else sum--; // If sum is positive, then maximum // length substring is bin[0..i] if (sum > 0) { maxlen = i + 1; } // If sum is negative, then maximum // length substring is bin[j+1..i], where // sum of substring bin[0..j] is sum-1. else if (sum <= 0) { if (prevSum.has(sum - 1)) { currlen = i - (prevSum.get(sum - 1) == null ? 1 : prevSum.get(sum - 1)); maxlen = Math.max(maxlen, currlen); } } // Make entry for this sum value in hash // table if this value is not present. if (!prevSum.has(sum)) prevSum.set(sum, i); } return maxlen;} // Driver codelet bin = \"1010\";document.write(findLongestSub(bin)); // This code is contributed by rag2127</script>",
"e": 10023,
"s": 8303,
"text": null
},
{
"code": null,
"e": 10033,
"s": 10023,
"text": "Output: "
},
{
"code": null,
"e": 10035,
"s": 10033,
"text": "3"
},
{
"code": null,
"e": 10080,
"s": 10035,
"text": "Time Complexity: O(n) Auxiliary Space: O(n) "
},
{
"code": null,
"e": 10088,
"s": 10080,
"text": "nik1996"
},
{
"code": null,
"e": 10105,
"s": 10088,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 10117,
"s": 10105,
"text": "sanjeev2552"
},
{
"code": null,
"e": 10129,
"s": 10117,
"text": "29AjayKumar"
},
{
"code": null,
"e": 10137,
"s": 10129,
"text": "rag2127"
},
{
"code": null,
"e": 10146,
"s": 10137,
"text": "D-E-Shaw"
},
{
"code": null,
"e": 10157,
"s": 10146,
"text": "prefix-sum"
},
{
"code": null,
"e": 10162,
"s": 10157,
"text": "Hash"
},
{
"code": null,
"e": 10170,
"s": 10162,
"text": "Strings"
},
{
"code": null,
"e": 10179,
"s": 10170,
"text": "D-E-Shaw"
},
{
"code": null,
"e": 10190,
"s": 10179,
"text": "prefix-sum"
},
{
"code": null,
"e": 10195,
"s": 10190,
"text": "Hash"
},
{
"code": null,
"e": 10203,
"s": 10195,
"text": "Strings"
},
{
"code": null,
"e": 10301,
"s": 10203,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10339,
"s": 10301,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 10395,
"s": 10339,
"text": "Find k numbers with most occurrences in the given array"
},
{
"code": null,
"e": 10436,
"s": 10395,
"text": "Real-time application of Data Structures"
},
{
"code": null,
"e": 10458,
"s": 10436,
"text": "Non-Repeating Element"
},
{
"code": null,
"e": 10505,
"s": 10458,
"text": "Find the length of largest subarray with 0 sum"
},
{
"code": null,
"e": 10551,
"s": 10505,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 10576,
"s": 10551,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 10636,
"s": 10576,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 10651,
"s": 10636,
"text": "C++ Data Types"
}
] |
Find size of a list in Python
|
A list is a collection data type in Python. The elements in a list are change able and there is no specific order associated with the elements. In this article we will see how to find the length of a list in Python. Which means we have to get the count of number of elements present in the list irrespective of whether they are duplicate or not.
In the below example we take a list named as "days". We first find the length of the list using len() function. And then we add few more elements and check the length again using append() function. Finally we remove some elements using remove() function and check the length again. Please note even though the elements are duplicate the remove() function will remove only e the elements at the end of the list
days = ["Mon","Tue","Wed"]
print (len(days))
# Append some list elements
days.append("Sun")
days.append("Mon")
print("Now the list is: ",days)
print("Length after adding more elements: ",len(days))
# Remove some elements
days.remove("Mon")
print("Now the list is: ",days)
print("Length after removing elements: ",len(days))
Running the above code gives us the following result −
3
Now the list is: ['Mon', 'Tue', 'Wed', 'Sun', 'Mon']
Length after adding more elements: 5
Now the list is: ['Tue', 'Wed', 'Sun', 'Mon']
Length after removing elements: 4
|
[
{
"code": null,
"e": 1408,
"s": 1062,
"text": "A list is a collection data type in Python. The elements in a list are change able and there is no specific order associated with the elements. In this article we will see how to find the length of a list in Python. Which means we have to get the count of number of elements present in the list irrespective of whether they are duplicate or not."
},
{
"code": null,
"e": 1818,
"s": 1408,
"text": "In the below example we take a list named as \"days\". We first find the length of the list using len() function. And then we add few more elements and check the length again using append() function. Finally we remove some elements using remove() function and check the length again. Please note even though the elements are duplicate the remove() function will remove only e the elements at the end of the list"
},
{
"code": null,
"e": 2143,
"s": 1818,
"text": "days = [\"Mon\",\"Tue\",\"Wed\"]\nprint (len(days))\n# Append some list elements\ndays.append(\"Sun\")\ndays.append(\"Mon\")\nprint(\"Now the list is: \",days)\nprint(\"Length after adding more elements: \",len(days))\n\n# Remove some elements\ndays.remove(\"Mon\")\nprint(\"Now the list is: \",days)\nprint(\"Length after removing elements: \",len(days))"
},
{
"code": null,
"e": 2198,
"s": 2143,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2370,
"s": 2198,
"text": "3\nNow the list is: ['Mon', 'Tue', 'Wed', 'Sun', 'Mon']\nLength after adding more elements: 5\nNow the list is: ['Tue', 'Wed', 'Sun', 'Mon']\nLength after removing elements: 4"
}
] |
MySQL Tryit Editor v1.0
|
SELECT CustomerName, City, Country FROM Customers;
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
|
[
{
"code": null,
"e": 51,
"s": 0,
"text": "SELECT CustomerName, City, Country FROM Customers;"
},
{
"code": null,
"e": 53,
"s": 51,
"text": ""
},
{
"code": null,
"e": 125,
"s": 62,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 185,
"s": 125,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 253,
"s": 185,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 291,
"s": 253,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 376,
"s": 291,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 550,
"s": 376,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 601,
"s": 550,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 669,
"s": 601,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 840,
"s": 669,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 940,
"s": 840,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 990,
"s": 940,
"text": "WebSQL is supported in Chrome, Safari, and Opera."
}
] |
Encapsulation in Golang - GeeksforGeeks
|
03 Oct, 2019
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield.
In object-oriented languages, the variables or data of a class are hidden from any other class and can be accessed only through any member function of own class in which they are declared. But Go language does not support classes and objects. So, in the Go language, encapsulation is achieved by using packages. Go provides two different types of identifiers, i.e. exported and unexported identifiers. Encapsulation is achieved by exported elements(variables, functions, methods, fields, structures) from the packages, it helps to control the visibility of the elements(variables, functions, methods, fields, structures). The elements are visible if the package in which they are defined is available in your program.
1. Exported Identifiers: Exported identifiers are those identifiers which are exported from the package in which they are defined. The first letter of these identifiers is always in capital letter. This capital letter indicates that the given identifier is exported identifier. Exported identifiers are always limited to the package in which they are defined. When you export the specified identifier from the package you simple just export the name not the implementation of that identifier. This mechanism is also applicable for function, fields, methods, and structures.
Example:
// Go program to illustrate// the concept of encapsulation// using exported functionpackage main import ( "fmt" "strings") // Main functionfunc main() { // Creating a slice of strings slc := []string{"GeeksforGeeks", "geeks", "gfg"} // Convert the case of the // elements of the given slice // Using ToUpper() function for x := 0; x < len(slc); x++ { // Exported Method res := strings.ToUpper(slc[x]) // Exported Method fmt.Println(res) }}
Output:
GEEKSFORGEEKS
GEEKS
GFG
Explanation: In the above example, we convert the case of the elements of the slc slice to uppercase by exporting ToUpper() function from strings package.
res := strings.ToUpper(slc[x])
Here, the first letter of the ToUpper() function is in uppercase, which indicates that this function is exported function. If you try to change the case of the ToUpper() function into lowercase, then the compiler will give an error, as shown below:
res := strings.toUpper(slc[x])
Output:
./prog.go:22:9: cannot refer to unexported name strings.toUpper
./prog.go:22:9: undefined: strings.toUpper
So, this process(exporting of variables, fields, methods, functions, structures) is known as encapsulation. Due to encapsulation we only export the name of the function not the whole definition of the function in our program and the definition of the ToUpper() function is wrapped inside strings package, so for exporting ToUpper() function first you need to import strings package in your program.
2. Unexported Identifiers: Unexported identifiers are those identifiers which are not exported from any package. They are always in lowercase. As shown in the below example addition function is not related to any package, so it is an unexported function and the visibility of this method is limited to this program only.
Example:
// Go program to illustrate// the unexported functionpackage main import "fmt" // The addition function returns// the sum of the elements// Unexported functionfunc addition(val ...int) int { s := 0 for x := range val { s += val[x] } fmt.Println("Total Sum: ", s) return s} // Main functionfunc main() { addition(23, 546, 65, 42, 21, 24, 67)}
Output:
Total Sum: 788
Benefits of Encapsulation:
Hiding implementation details from the user.
Increase the reusability of the code.
It prevents users from setting the function’s variables arbitrarily. It only sets by the function in the same package and the author of that package ensure that the function maintain their internal invariants.
Golang
Golang-OOPs
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
Rune in Golang
Anonymous function in Go Language
Loops in Go Language
Class and Object in Golang
Structures in Golang
Time Durations in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang?
|
[
{
"code": null,
"e": 24069,
"s": 24041,
"text": "\n03 Oct, 2019"
},
{
"code": null,
"e": 24349,
"s": 24069,
"text": "Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield."
},
{
"code": null,
"e": 25067,
"s": 24349,
"text": "In object-oriented languages, the variables or data of a class are hidden from any other class and can be accessed only through any member function of own class in which they are declared. But Go language does not support classes and objects. So, in the Go language, encapsulation is achieved by using packages. Go provides two different types of identifiers, i.e. exported and unexported identifiers. Encapsulation is achieved by exported elements(variables, functions, methods, fields, structures) from the packages, it helps to control the visibility of the elements(variables, functions, methods, fields, structures). The elements are visible if the package in which they are defined is available in your program."
},
{
"code": null,
"e": 25641,
"s": 25067,
"text": "1. Exported Identifiers: Exported identifiers are those identifiers which are exported from the package in which they are defined. The first letter of these identifiers is always in capital letter. This capital letter indicates that the given identifier is exported identifier. Exported identifiers are always limited to the package in which they are defined. When you export the specified identifier from the package you simple just export the name not the implementation of that identifier. This mechanism is also applicable for function, fields, methods, and structures."
},
{
"code": null,
"e": 25650,
"s": 25641,
"text": "Example:"
},
{
"code": "// Go program to illustrate// the concept of encapsulation// using exported functionpackage main import ( \"fmt\" \"strings\") // Main functionfunc main() { // Creating a slice of strings slc := []string{\"GeeksforGeeks\", \"geeks\", \"gfg\"} // Convert the case of the // elements of the given slice // Using ToUpper() function for x := 0; x < len(slc); x++ { // Exported Method res := strings.ToUpper(slc[x]) // Exported Method fmt.Println(res) }}",
"e": 26155,
"s": 25650,
"text": null
},
{
"code": null,
"e": 26163,
"s": 26155,
"text": "Output:"
},
{
"code": null,
"e": 26188,
"s": 26163,
"text": "GEEKSFORGEEKS\nGEEKS\nGFG\n"
},
{
"code": null,
"e": 26343,
"s": 26188,
"text": "Explanation: In the above example, we convert the case of the elements of the slc slice to uppercase by exporting ToUpper() function from strings package."
},
{
"code": null,
"e": 26374,
"s": 26343,
"text": "res := strings.ToUpper(slc[x])"
},
{
"code": null,
"e": 26623,
"s": 26374,
"text": "Here, the first letter of the ToUpper() function is in uppercase, which indicates that this function is exported function. If you try to change the case of the ToUpper() function into lowercase, then the compiler will give an error, as shown below:"
},
{
"code": null,
"e": 26771,
"s": 26623,
"text": "res := strings.toUpper(slc[x])\n\nOutput:\n./prog.go:22:9: cannot refer to unexported name strings.toUpper\n./prog.go:22:9: undefined: strings.toUpper\n"
},
{
"code": null,
"e": 27170,
"s": 26771,
"text": "So, this process(exporting of variables, fields, methods, functions, structures) is known as encapsulation. Due to encapsulation we only export the name of the function not the whole definition of the function in our program and the definition of the ToUpper() function is wrapped inside strings package, so for exporting ToUpper() function first you need to import strings package in your program."
},
{
"code": null,
"e": 27491,
"s": 27170,
"text": "2. Unexported Identifiers: Unexported identifiers are those identifiers which are not exported from any package. They are always in lowercase. As shown in the below example addition function is not related to any package, so it is an unexported function and the visibility of this method is limited to this program only."
},
{
"code": null,
"e": 27500,
"s": 27491,
"text": "Example:"
},
{
"code": "// Go program to illustrate// the unexported functionpackage main import \"fmt\" // The addition function returns// the sum of the elements// Unexported functionfunc addition(val ...int) int { s := 0 for x := range val { s += val[x] } fmt.Println(\"Total Sum: \", s) return s} // Main functionfunc main() { addition(23, 546, 65, 42, 21, 24, 67)}",
"e": 27876,
"s": 27500,
"text": null
},
{
"code": null,
"e": 27884,
"s": 27876,
"text": "Output:"
},
{
"code": null,
"e": 27900,
"s": 27884,
"text": "Total Sum: 788"
},
{
"code": null,
"e": 27927,
"s": 27900,
"text": "Benefits of Encapsulation:"
},
{
"code": null,
"e": 27972,
"s": 27927,
"text": "Hiding implementation details from the user."
},
{
"code": null,
"e": 28010,
"s": 27972,
"text": "Increase the reusability of the code."
},
{
"code": null,
"e": 28220,
"s": 28010,
"text": "It prevents users from setting the function’s variables arbitrarily. It only sets by the function in the same package and the author of that package ensure that the function maintain their internal invariants."
},
{
"code": null,
"e": 28227,
"s": 28220,
"text": "Golang"
},
{
"code": null,
"e": 28239,
"s": 28227,
"text": "Golang-OOPs"
},
{
"code": null,
"e": 28251,
"s": 28239,
"text": "Go Language"
},
{
"code": null,
"e": 28349,
"s": 28251,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28358,
"s": 28349,
"text": "Comments"
},
{
"code": null,
"e": 28371,
"s": 28358,
"text": "Old Comments"
},
{
"code": null,
"e": 28400,
"s": 28371,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 28424,
"s": 28400,
"text": "Defer Keyword in Golang"
},
{
"code": null,
"e": 28439,
"s": 28424,
"text": "Rune in Golang"
},
{
"code": null,
"e": 28473,
"s": 28439,
"text": "Anonymous function in Go Language"
},
{
"code": null,
"e": 28494,
"s": 28473,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 28521,
"s": 28494,
"text": "Class and Object in Golang"
},
{
"code": null,
"e": 28542,
"s": 28521,
"text": "Structures in Golang"
},
{
"code": null,
"e": 28567,
"s": 28542,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 28585,
"s": 28567,
"text": "Strings in Golang"
}
] |
Check if incoming edges in a vertex of directed graph is equal to vertex itself or not - GeeksforGeeks
|
09 Sep, 2021
Given a directed Graph G(V, E) with V vertices and E edges, the task is to check that for all vertices of the given graph, the incoming edges in a vertex is equal to the vertex itself or not.
Examples:
Input:
Output: Yes Explanation: For vertex 0 there are 0 incoming edges, for vertex 1 there is 1 incoming edge. Same for vertex 2 nd 3.
Approach: The idea is to traverse adjacency list for every vertex, and increment the count of edges of every vertex that has an incoming edge from i. Repeat the steps for every vertex and then check the in degrees for all the vertices equal to vertex value or not.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to check if the// incoming edges in a vertex of directed// graph is equal to the vertex itself or not #include <bits/stdc++.h>using namespace std; // A utility function to// add an edge in an// directed graphvoid add_edge(vector<int> adj[], int x, int y){ adj[x].push_back(y);} // Function to check that given graph// in-degree value equal to vertex valuebool Indegree(vector<int> adj[], int v){ // Create array indeg // initialized to zero int indeg[v] = { 0 }; // Traversing across all // vertex to compute // in degree value for (int i = 0; i < v; i++) { for (int j = 0; j < adj[i].size(); j++) { indeg[adj[i][j]]++; } } // check in degree value // equal to vertex value for (int i = 0; i < v; i++) { if (i == indeg[i]) continue; else return false; } return true;} // Driver codeint main(){ int v = 4; // To store adjacency list of graph vector<int> adj[v]; add_edge(adj, 0, 1); add_edge(adj, 1, 2); add_edge(adj, 0, 2); add_edge(adj, 0, 3); add_edge(adj, 1, 3); add_edge(adj, 2, 3); if (Indegree(adj, v)) cout << "Yes"; else cout << "No";}
// Java implementation to check if the// incoming edges in a vertex of directed// graph is equal to the vertex itself or notimport java.util.*; class GFG{ // A utility function to// add an edge in an// directed graphstatic void add_edge(Vector<Integer> adj[], int x, int y){ adj[x].add(y);} // Function to check that given graph// in-degree value equal to vertex valuestatic boolean Indegree(Vector<Integer> adj[], int v){ // Create array indeg // initialized to zero int indeg[] = new int[v]; // Traversing across all // vertex to compute // in degree value for(int i = 0; i < v; i++) { for(int j = 0; j < adj[i].size(); j++) { indeg[adj[i].get(j)]++; } } // Check in degree value // equal to vertex value for(int i = 0; i < v; i++) { if (i == indeg[i]) continue; else return false; } return true;} // Driver codepublic static void main(String[] args){ int v = 4; // To store adjacency list of graph @SuppressWarnings("unchecked") Vector<Integer> []adj = new Vector[v]; for(int i = 0; i < adj.length; i++) adj[i] = new Vector<Integer>(); add_edge(adj, 0, 1); add_edge(adj, 1, 2); add_edge(adj, 0, 2); add_edge(adj, 0, 3); add_edge(adj, 1, 3); add_edge(adj, 2, 3); if (Indegree(adj, v)) System.out.print("Yes"); else System.out.print("No");}} // This code is contributed by Amit Katiyar
# Python3 implementation to check if the# incoming edges in a vertex of directed# graph is equal to the vertex itself or not # A utility function to# add an edge in an# directed graphdef add_edge(adj, x, y): adj[x] = adj[x] + [y] # Function to check that given graph# in-degree value equal to vertex valuedef Indegree(adj, v): # Create array indeg # initialized to zero indeg = [0] * v # Traversing across all # vertex to compute # in degree value for i in range(v): for j in range(len(adj[i])): indeg[adj[i][j]] += 1 # Check in degree value # equal to vertex value for i in range(v): if(i == indeg[i]): continue else: return False return True # Driver codeif __name__ == '__main__': v = 4 # To store adjacency list of graph adj = [[]] * 4 add_edge(adj, 0, 1) add_edge(adj, 1, 2) add_edge(adj, 0, 2) add_edge(adj, 0, 3) add_edge(adj, 1, 3) add_edge(adj, 2, 3) if(Indegree(adj, v)): print("Yes") else: print("No") # This code is contributed by Shivam Singh
// C# implementation to check if the// incoming edges in a vertex of directed// graph is equal to the vertex itself or notusing System;using System.Collections.Generic; class GFG{ // A utility function to// add an edge in an// directed graphstatic void add_edge(List<int> []adj, int x, int y){ adj[x].Add(y);} // Function to check that given graph// in-degree value equal to vertex valuestatic bool Indegree(List<int> []adj, int v){ // Create array indeg // initialized to zero int []indeg = new int[v]; // Traversing across all // vertex to compute // in degree value for(int i = 0; i < v; i++) { for(int j = 0; j < adj[i].Count; j++) { indeg[adj[i][j]]++; } } // Check in degree value // equal to vertex value for(int i = 0; i < v; i++) { if (i == indeg[i]) continue; else return false; } return true;} // Driver codepublic static void Main(String[] args){ int v = 4; // To store adjacency list of graph List<int> []adj = new List<int>[v]; for(int i = 0; i < adj.Length; i++) adj[i] = new List<int>(); add_edge(adj, 0, 1); add_edge(adj, 1, 2); add_edge(adj, 0, 2); add_edge(adj, 0, 3); add_edge(adj, 1, 3); add_edge(adj, 2, 3); if (Indegree(adj, v)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by Amit Katiyar
<script> // JavaScript implementation to check if the// incoming edges in a vertex of directed// graph is equal to the vertex itself or not // A utility function to// add an edge in an// directed graphfunction add_edge(adj, x, y){ adj[x].push(y);} // Function to check that given graph// in-degree value equal to vertex valuefunction Indegree(adj, v){ // Create array indeg // initialized to zero var indeg = Array(v).fill(0); // Traversing across all // vertex to compute // in degree value for (var i = 0; i < v; i++) { for (var j = 0; j < adj[i].length; j++) { indeg[adj[i][j]]++; } } // check in degree value // equal to vertex value for (var i = 0; i < v; i++) { if (i == indeg[i]) continue; else return false; } return true;} // Driver codevar v = 4; // To store adjacency list of graphvar adj = Array.from(Array(v), ()=> new Array());add_edge(adj, 0, 1);add_edge(adj, 1, 2);add_edge(adj, 0, 2);add_edge(adj, 0, 3);add_edge(adj, 1, 3);add_edge(adj, 2, 3);if (Indegree(adj, v)) document.write( "Yes");else document.write( "No"); </script>
Yes
Time Complexity: O(V + E) Auxiliary Space Complexity: O(V)
amit143katiyar
rutvik_56
avtarkumar719
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Best First Search (Informed Search)
Longest Path in a Directed Acyclic Graph
Graph Coloring | Set 2 (Greedy Algorithm)
Find if there is a path between two vertices in a directed graph
Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)
Snake and Ladder Problem
Check if a given graph is tree or not
Tree, Back, Edge and Cross Edges in DFS of Graph
Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
Real-time application of Data Structures
|
[
{
"code": null,
"e": 24675,
"s": 24647,
"text": "\n09 Sep, 2021"
},
{
"code": null,
"e": 24867,
"s": 24675,
"text": "Given a directed Graph G(V, E) with V vertices and E edges, the task is to check that for all vertices of the given graph, the incoming edges in a vertex is equal to the vertex itself or not."
},
{
"code": null,
"e": 24878,
"s": 24867,
"text": "Examples: "
},
{
"code": null,
"e": 24886,
"s": 24878,
"text": "Input: "
},
{
"code": null,
"e": 25017,
"s": 24886,
"text": "Output: Yes Explanation: For vertex 0 there are 0 incoming edges, for vertex 1 there is 1 incoming edge. Same for vertex 2 nd 3. "
},
{
"code": null,
"e": 25282,
"s": 25017,
"text": "Approach: The idea is to traverse adjacency list for every vertex, and increment the count of edges of every vertex that has an incoming edge from i. Repeat the steps for every vertex and then check the in degrees for all the vertices equal to vertex value or not."
},
{
"code": null,
"e": 25334,
"s": 25282,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25338,
"s": 25334,
"text": "C++"
},
{
"code": null,
"e": 25343,
"s": 25338,
"text": "Java"
},
{
"code": null,
"e": 25351,
"s": 25343,
"text": "Python3"
},
{
"code": null,
"e": 25354,
"s": 25351,
"text": "C#"
},
{
"code": null,
"e": 25365,
"s": 25354,
"text": "Javascript"
},
{
"code": "// C++ implementation to check if the// incoming edges in a vertex of directed// graph is equal to the vertex itself or not #include <bits/stdc++.h>using namespace std; // A utility function to// add an edge in an// directed graphvoid add_edge(vector<int> adj[], int x, int y){ adj[x].push_back(y);} // Function to check that given graph// in-degree value equal to vertex valuebool Indegree(vector<int> adj[], int v){ // Create array indeg // initialized to zero int indeg[v] = { 0 }; // Traversing across all // vertex to compute // in degree value for (int i = 0; i < v; i++) { for (int j = 0; j < adj[i].size(); j++) { indeg[adj[i][j]]++; } } // check in degree value // equal to vertex value for (int i = 0; i < v; i++) { if (i == indeg[i]) continue; else return false; } return true;} // Driver codeint main(){ int v = 4; // To store adjacency list of graph vector<int> adj[v]; add_edge(adj, 0, 1); add_edge(adj, 1, 2); add_edge(adj, 0, 2); add_edge(adj, 0, 3); add_edge(adj, 1, 3); add_edge(adj, 2, 3); if (Indegree(adj, v)) cout << \"Yes\"; else cout << \"No\";}",
"e": 26600,
"s": 25365,
"text": null
},
{
"code": "// Java implementation to check if the// incoming edges in a vertex of directed// graph is equal to the vertex itself or notimport java.util.*; class GFG{ // A utility function to// add an edge in an// directed graphstatic void add_edge(Vector<Integer> adj[], int x, int y){ adj[x].add(y);} // Function to check that given graph// in-degree value equal to vertex valuestatic boolean Indegree(Vector<Integer> adj[], int v){ // Create array indeg // initialized to zero int indeg[] = new int[v]; // Traversing across all // vertex to compute // in degree value for(int i = 0; i < v; i++) { for(int j = 0; j < adj[i].size(); j++) { indeg[adj[i].get(j)]++; } } // Check in degree value // equal to vertex value for(int i = 0; i < v; i++) { if (i == indeg[i]) continue; else return false; } return true;} // Driver codepublic static void main(String[] args){ int v = 4; // To store adjacency list of graph @SuppressWarnings(\"unchecked\") Vector<Integer> []adj = new Vector[v]; for(int i = 0; i < adj.length; i++) adj[i] = new Vector<Integer>(); add_edge(adj, 0, 1); add_edge(adj, 1, 2); add_edge(adj, 0, 2); add_edge(adj, 0, 3); add_edge(adj, 1, 3); add_edge(adj, 2, 3); if (Indegree(adj, v)) System.out.print(\"Yes\"); else System.out.print(\"No\");}} // This code is contributed by Amit Katiyar",
"e": 28125,
"s": 26600,
"text": null
},
{
"code": "# Python3 implementation to check if the# incoming edges in a vertex of directed# graph is equal to the vertex itself or not # A utility function to# add an edge in an# directed graphdef add_edge(adj, x, y): adj[x] = adj[x] + [y] # Function to check that given graph# in-degree value equal to vertex valuedef Indegree(adj, v): # Create array indeg # initialized to zero indeg = [0] * v # Traversing across all # vertex to compute # in degree value for i in range(v): for j in range(len(adj[i])): indeg[adj[i][j]] += 1 # Check in degree value # equal to vertex value for i in range(v): if(i == indeg[i]): continue else: return False return True # Driver codeif __name__ == '__main__': v = 4 # To store adjacency list of graph adj = [[]] * 4 add_edge(adj, 0, 1) add_edge(adj, 1, 2) add_edge(adj, 0, 2) add_edge(adj, 0, 3) add_edge(adj, 1, 3) add_edge(adj, 2, 3) if(Indegree(adj, v)): print(\"Yes\") else: print(\"No\") # This code is contributed by Shivam Singh",
"e": 29230,
"s": 28125,
"text": null
},
{
"code": "// C# implementation to check if the// incoming edges in a vertex of directed// graph is equal to the vertex itself or notusing System;using System.Collections.Generic; class GFG{ // A utility function to// add an edge in an// directed graphstatic void add_edge(List<int> []adj, int x, int y){ adj[x].Add(y);} // Function to check that given graph// in-degree value equal to vertex valuestatic bool Indegree(List<int> []adj, int v){ // Create array indeg // initialized to zero int []indeg = new int[v]; // Traversing across all // vertex to compute // in degree value for(int i = 0; i < v; i++) { for(int j = 0; j < adj[i].Count; j++) { indeg[adj[i][j]]++; } } // Check in degree value // equal to vertex value for(int i = 0; i < v; i++) { if (i == indeg[i]) continue; else return false; } return true;} // Driver codepublic static void Main(String[] args){ int v = 4; // To store adjacency list of graph List<int> []adj = new List<int>[v]; for(int i = 0; i < adj.Length; i++) adj[i] = new List<int>(); add_edge(adj, 0, 1); add_edge(adj, 1, 2); add_edge(adj, 0, 2); add_edge(adj, 0, 3); add_edge(adj, 1, 3); add_edge(adj, 2, 3); if (Indegree(adj, v)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by Amit Katiyar",
"e": 30713,
"s": 29230,
"text": null
},
{
"code": "<script> // JavaScript implementation to check if the// incoming edges in a vertex of directed// graph is equal to the vertex itself or not // A utility function to// add an edge in an// directed graphfunction add_edge(adj, x, y){ adj[x].push(y);} // Function to check that given graph// in-degree value equal to vertex valuefunction Indegree(adj, v){ // Create array indeg // initialized to zero var indeg = Array(v).fill(0); // Traversing across all // vertex to compute // in degree value for (var i = 0; i < v; i++) { for (var j = 0; j < adj[i].length; j++) { indeg[adj[i][j]]++; } } // check in degree value // equal to vertex value for (var i = 0; i < v; i++) { if (i == indeg[i]) continue; else return false; } return true;} // Driver codevar v = 4; // To store adjacency list of graphvar adj = Array.from(Array(v), ()=> new Array());add_edge(adj, 0, 1);add_edge(adj, 1, 2);add_edge(adj, 0, 2);add_edge(adj, 0, 3);add_edge(adj, 1, 3);add_edge(adj, 2, 3);if (Indegree(adj, v)) document.write( \"Yes\");else document.write( \"No\"); </script>",
"e": 31869,
"s": 30713,
"text": null
},
{
"code": null,
"e": 31873,
"s": 31869,
"text": "Yes"
},
{
"code": null,
"e": 31935,
"s": 31875,
"text": "Time Complexity: O(V + E) Auxiliary Space Complexity: O(V) "
},
{
"code": null,
"e": 31950,
"s": 31935,
"text": "amit143katiyar"
},
{
"code": null,
"e": 31960,
"s": 31950,
"text": "rutvik_56"
},
{
"code": null,
"e": 31974,
"s": 31960,
"text": "avtarkumar719"
},
{
"code": null,
"e": 31980,
"s": 31974,
"text": "Graph"
},
{
"code": null,
"e": 31986,
"s": 31980,
"text": "Graph"
},
{
"code": null,
"e": 32084,
"s": 31986,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32093,
"s": 32084,
"text": "Comments"
},
{
"code": null,
"e": 32106,
"s": 32093,
"text": "Old Comments"
},
{
"code": null,
"e": 32142,
"s": 32106,
"text": "Best First Search (Informed Search)"
},
{
"code": null,
"e": 32183,
"s": 32142,
"text": "Longest Path in a Directed Acyclic Graph"
},
{
"code": null,
"e": 32225,
"s": 32183,
"text": "Graph Coloring | Set 2 (Greedy Algorithm)"
},
{
"code": null,
"e": 32290,
"s": 32225,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 32360,
"s": 32290,
"text": "Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)"
},
{
"code": null,
"e": 32385,
"s": 32360,
"text": "Snake and Ladder Problem"
},
{
"code": null,
"e": 32423,
"s": 32385,
"text": "Check if a given graph is tree or not"
},
{
"code": null,
"e": 32472,
"s": 32423,
"text": "Tree, Back, Edge and Cross Edges in DFS of Graph"
},
{
"code": null,
"e": 32553,
"s": 32472,
"text": "Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)"
}
] |
Fraud Detection in Python
|
Frauds are really in many transactions. We can apply machine learning algorithms to lies the past data and predict the possibility of a transaction being a fraud transaction. In our example we will take credit card transactions, analyse the data, create the features and labels and finally apply one of the ML algorithms to judge the nature of transaction as being fraud or not. Then we will find out the accuracy, precision as well as f-score of the model we are chosen.
We in this step we read the source data, study the variables present in it and have a look at some sample data. This will help us in knowing the different columns present in the data set and study their features. We will use Pandas is library to create the data frame which will be used in the subsequent steps.
import pandas as pd
#Load the creditcard.csv using pandas
datainput = pd.read_csv('E:\\creditcard.csv')
#https://www.kaggle.com/mlg-ulb/creditcardfraud
# Print the top 5 records
print(datainput[0:5],"\n")
# Print the complete shape of the dataset
print("Shape of Complete Data Set")
print(datainput.shape,"\n")
Running the above code gives us the following result −
Time V1 V2 V3 ... V27 V28 Amount Class
0 0.0 -1.359807 -0.072781 2.536347 ... 0.133558 -0.021053 149.62 0
1 0.0 1.191857 0.266151 0.166480 ... -0.008983 0.014724 2.69 0
2 1.0 -1.358354 -1.340163 1.773209 ... -0.055353 -0.059752 378.66 0
3 1.0 -0.966272 -0.185226 1.792993 ... 0.062723 0.061458 123.50 0
4 2.0 -1.158233 0.877737 1.548718 ... 0.219422 0.215153 69.99 0
[5 rows x 31 columns]
Shape of Complete Data Set
(284807, 31)
Now we check how the data is distributed among fraudulent and genuine transactions. This gives us an idea of of what percentage of data is expected to be fraudulent. In ml algorithm this is is referred as data imbalance. If most of the transactions is not fraudulent then it becomes difficult to judge few transactions as genuine or not. We use the class column to count the number of fraudulent engine in transactions and then figure out the actual percentage of fraudulent transactions.
import pandas as pd
#Load the creditcard.csv using pandas
datainput = pd.read_csv('E:\\creditcard.csv')
false = datainput[datainput['Class'] == 1]
true = datainput[datainput['Class'] == 0]
n = len(false)/float(len(true))
print(n)
print('False Detection Cases: {}'.format(len(datainput[datainput['Class'] == 1])))
print('True Detection Cases: {}'.format(len(datainput[datainput['Class'] == 0])),"\n")
Running the above code gives us the following result −
0.0017304750013189597
False Detection Cases: 492
True Detection Cases: 284315
We investigate further into the nature of the transactions for each category of fraudulent and non-fraudulent transactions. We try to statistically estimate various parameters like mean standard deviation maximum value minimum value and different percentiles. This is achieved by using the described method.
import pandas as pd
#Load the creditcard.csv using pandas
datainput = pd.read_csv('E:\\creditcard.csv')
#Check for imbalance in data
false = datainput[datainput['Class'] == 1]
true = datainput[datainput['Class'] == 0]
#False Detection Cases
print("False Detection Cases")
print("----------------------")
print(false.Amount.describe(),"\n")
#True Detection Cases
print("True Detection Cases")
print("----------------------")
print(true.Amount.describe(),"\n")
Running the above code gives us the following result −
False Detection Cases
----------------------
count 492.000000
mean 122.211321
std 256.683288
min 0.000000
25% 1.000000
50% 9.250000
75% 105.890000
max 2125.870000
Name: Amount, dtype: float64
True Detection Cases
----------------------
count 284315.000000
mean 88.291022
std 250.105092
min 0.000000
25% 5.650000
50% 22.000000
75% 77.050000
max 25691.160000
Name: Amount, dtype: float64
Before we implement the ML algorithm, we need to decide on the features and labels. Which basically means the categorizing the dependent variables and the independent ones. In our dataset the class column is dependent on the rest of all other columns. So we create a data frames for the last column as well as another dataframe for rest of all other columns. These dataframes will be used to train the model that we are going to create.
import pandas as pd
#Load the creditcard.csv using pandas
datainput = pd.read_csv('E:\\creditcard.csv')
#separating features(X) and label(y)
# Select all columns except the last for all rows
X = datainput.iloc[:, :-1].values
# Select the last column of all rows
Y = datainput.iloc[:, -1].values
print(X.shape)
print(Y.shape)
Running the above code gives us the following result −
(284807, 30)
(284807,)
Now we split the data set into two parts. One is for training and another is for testing. The test_size parameter is used to decide what percentage of the data set will be used only for testing. This exercise will help us gain the confidence on the model we are creating.
import pandas as pd
from sklearn.model_selection import train_test_split
#Load the creditcard.csv using pandas
datainput = pd.read_csv('E:\\creditcard.csv')
#separating features(X) and label(y)
X = datainput.iloc[:, :-1].values
# Select the last column of all rows
Y = datainput.iloc[:, -1].values
#train_test_split method
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)
There are many different kinds of algorithms available to be applied to this situation. But we choose decision tree as our algorithm for classification. Which is a max tree depth of 4 and supply the test sample to predict the values. Finally, we calculate the accuracy of the result from the test to decide on whether to continue further with this algorithm or not.
import pandas as pd
from sklearn import metrics
from sklearn.model_selection import train_test_split
#Load the creditcard.csv using pandas
datainput = pd.read_csv('E:\\creditcard.csv')
#separating features(X) and label(y)
X = datainput.iloc[:, :-1].values
Y = datainput.iloc[:, -1].values
#train_test_split method
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)
#DecisionTreeClassifier
from sklearn.tree import DecisionTreeClassifier
classifier=DecisionTreeClassifier(max_depth=4)
classifier.fit(X_train,Y_train)
predicted=classifier.predict(X_test)
print("\npredicted values :\n",predicted)
#Accuracy
DT = metrics.accuracy_score(Y_test, predicted) * 100
print("\nThe accuracy score using the DecisionTreeClassifier : ",DT)
Running the above code gives us the following result −
predicted values :
[0 0 0 ... 0 0 0]
The accuracy score using the DecisionTreeClassifier : 99.9367999719111
Once the accuracy level in the above step is acceptable we go on a further evaluation of the model by finding out different parameters. Which use Precision, recall value and F score as our parameters. precision is the fraction of relevant instances among the retrieved instances, while recall is the fraction of the total amount of relevant instances that were actually retrieved. F score provides a single score that balances both the concerns of precision and recall in one number.
import pandas as pd
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
#Load the creditcard.csv using pandas
datainput = pd.read_csv('E:\\creditcard.csv')
#separating features(X) and label(y)
X = datainput.iloc[:, :-1].values
Y = datainput.iloc[:, -1].values
#train_test_split method
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)
#DecisionTreeClassifier
from sklearn.tree import DecisionTreeClassifier
classifier=DecisionTreeClassifier(max_depth=4)
classifier.fit(X_train,Y_train)
predicted=classifier.predict(X_test)
print("\npredicted values :\n",predicted)
#
# #Accuracy
DT = metrics.accuracy_score(Y_test, predicted) * 100
print("\nThe accuracy score using the DecisionTreeClassifier : ",DT)
#
# #Precision
print('precision')
# Precision = TP / (TP + FP) (Where TP = True Positive, TN = True Negative, FP = False Positive, FN = False Negative).
precision = precision_score(Y_test, predicted, pos_label=1)
print(precision_score(Y_test, predicted, pos_label=1))
#Recall
print('recall')
# Recall = TP / (TP + FN)
recall = recall_score(Y_test, predicted, pos_label=1)
print(recall_score(Y_test, predicted, pos_label=1))
#f1-score
print('f-Score')
# F - scores are a statistical method for determining accuracy accounting for both precision and recall.
fscore = f1_score(Y_test, predicted, pos_label=1)
print(f1_score(Y_test, predicted, pos_label=1))
Running the above code gives us the following result −
The accuracy score using the DecisionTreeClassifier : 99.9403110845827
precision
0.810126582278481
recall
0.7710843373493976
f-Score
0.7901234567901234
|
[
{
"code": null,
"e": 1534,
"s": 1062,
"text": "Frauds are really in many transactions. We can apply machine learning algorithms to lies the past data and predict the possibility of a transaction being a fraud transaction. In our example we will take credit card transactions, analyse the data, create the features and labels and finally apply one of the ML algorithms to judge the nature of transaction as being fraud or not. Then we will find out the accuracy, precision as well as f-score of the model we are chosen."
},
{
"code": null,
"e": 1846,
"s": 1534,
"text": "We in this step we read the source data, study the variables present in it and have a look at some sample data. This will help us in knowing the different columns present in the data set and study their features. We will use Pandas is library to create the data frame which will be used in the subsequent steps."
},
{
"code": null,
"e": 2163,
"s": 1846,
"text": "import pandas as pd\n#Load the creditcard.csv using pandas\ndatainput = pd.read_csv('E:\\\\creditcard.csv')\n#https://www.kaggle.com/mlg-ulb/creditcardfraud\n# Print the top 5 records\nprint(datainput[0:5],\"\\n\")\n# Print the complete shape of the dataset\n print(\"Shape of Complete Data Set\")\n print(datainput.shape,\"\\n\")"
},
{
"code": null,
"e": 2218,
"s": 2163,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2875,
"s": 2218,
"text": " Time V1 V2 V3 ... V27 V28 Amount Class\n0 0.0 -1.359807 -0.072781 2.536347 ... 0.133558 -0.021053 149.62 0\n1 0.0 1.191857 0.266151 0.166480 ... -0.008983 0.014724 2.69 0\n2 1.0 -1.358354 -1.340163 1.773209 ... -0.055353 -0.059752 378.66 0\n3 1.0 -0.966272 -0.185226 1.792993 ... 0.062723 0.061458 123.50 0\n4 2.0 -1.158233 0.877737 1.548718 ... 0.219422 0.215153 69.99 0\n\n[5 rows x 31 columns]\nShape of Complete Data Set\n(284807, 31)"
},
{
"code": null,
"e": 3364,
"s": 2875,
"text": "Now we check how the data is distributed among fraudulent and genuine transactions. This gives us an idea of of what percentage of data is expected to be fraudulent. In ml algorithm this is is referred as data imbalance. If most of the transactions is not fraudulent then it becomes difficult to judge few transactions as genuine or not. We use the class column to count the number of fraudulent engine in transactions and then figure out the actual percentage of fraudulent transactions."
},
{
"code": null,
"e": 3764,
"s": 3364,
"text": "import pandas as pd\n#Load the creditcard.csv using pandas\ndatainput = pd.read_csv('E:\\\\creditcard.csv')\nfalse = datainput[datainput['Class'] == 1]\ntrue = datainput[datainput['Class'] == 0]\nn = len(false)/float(len(true))\nprint(n)\nprint('False Detection Cases: {}'.format(len(datainput[datainput['Class'] == 1])))\nprint('True Detection Cases: {}'.format(len(datainput[datainput['Class'] == 0])),\"\\n\")"
},
{
"code": null,
"e": 3819,
"s": 3764,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3897,
"s": 3819,
"text": "0.0017304750013189597\nFalse Detection Cases: 492\nTrue Detection Cases: 284315"
},
{
"code": null,
"e": 4205,
"s": 3897,
"text": "We investigate further into the nature of the transactions for each category of fraudulent and non-fraudulent transactions. We try to statistically estimate various parameters like mean standard deviation maximum value minimum value and different percentiles. This is achieved by using the described method."
},
{
"code": null,
"e": 4667,
"s": 4205,
"text": "import pandas as pd\n#Load the creditcard.csv using pandas\ndatainput = pd.read_csv('E:\\\\creditcard.csv')\n\n#Check for imbalance in data\nfalse = datainput[datainput['Class'] == 1]\ntrue = datainput[datainput['Class'] == 0]\n\n#False Detection Cases\nprint(\"False Detection Cases\")\nprint(\"----------------------\")\nprint(false.Amount.describe(),\"\\n\")\n\n#True Detection Cases\nprint(\"True Detection Cases\")\nprint(\"----------------------\")\nprint(true.Amount.describe(),\"\\n\")"
},
{
"code": null,
"e": 4722,
"s": 4667,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 5214,
"s": 4722,
"text": "False Detection Cases\n----------------------\ncount 492.000000\nmean 122.211321\nstd 256.683288\nmin 0.000000\n25% 1.000000\n50% 9.250000\n75% 105.890000\nmax 2125.870000\nName: Amount, dtype: float64\n\nTrue Detection Cases\n----------------------\ncount 284315.000000\nmean 88.291022\nstd 250.105092\nmin 0.000000\n25% 5.650000\n50% 22.000000\n75% 77.050000\nmax 25691.160000\nName: Amount, dtype: float64"
},
{
"code": null,
"e": 5651,
"s": 5214,
"text": "Before we implement the ML algorithm, we need to decide on the features and labels. Which basically means the categorizing the dependent variables and the independent ones. In our dataset the class column is dependent on the rest of all other columns. So we create a data frames for the last column as well as another dataframe for rest of all other columns. These dataframes will be used to train the model that we are going to create."
},
{
"code": null,
"e": 5977,
"s": 5651,
"text": "import pandas as pd\n#Load the creditcard.csv using pandas\ndatainput = pd.read_csv('E:\\\\creditcard.csv')\n#separating features(X) and label(y)\n# Select all columns except the last for all rows\nX = datainput.iloc[:, :-1].values\n# Select the last column of all rows\nY = datainput.iloc[:, -1].values\n\nprint(X.shape)\nprint(Y.shape)"
},
{
"code": null,
"e": 6032,
"s": 5977,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 6055,
"s": 6032,
"text": "(284807, 30)\n(284807,)"
},
{
"code": null,
"e": 6327,
"s": 6055,
"text": "Now we split the data set into two parts. One is for training and another is for testing. The test_size parameter is used to decide what percentage of the data set will be used only for testing. This exercise will help us gain the confidence on the model we are creating."
},
{
"code": null,
"e": 6727,
"s": 6327,
"text": "import pandas as pd\nfrom sklearn.model_selection import train_test_split\n\n#Load the creditcard.csv using pandas\ndatainput = pd.read_csv('E:\\\\creditcard.csv')\n\n#separating features(X) and label(y)\nX = datainput.iloc[:, :-1].values\n\n# Select the last column of all rows\nY = datainput.iloc[:, -1].values\n\n#train_test_split method\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)"
},
{
"code": null,
"e": 7093,
"s": 6727,
"text": "There are many different kinds of algorithms available to be applied to this situation. But we choose decision tree as our algorithm for classification. Which is a max tree depth of 4 and supply the test sample to predict the values. Finally, we calculate the accuracy of the result from the test to decide on whether to continue further with this algorithm or not."
},
{
"code": null,
"e": 7847,
"s": 7093,
"text": "import pandas as pd\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\n\n#Load the creditcard.csv using pandas\ndatainput = pd.read_csv('E:\\\\creditcard.csv')\n\n#separating features(X) and label(y)\nX = datainput.iloc[:, :-1].values\nY = datainput.iloc[:, -1].values\n\n#train_test_split method\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)\n\n#DecisionTreeClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nclassifier=DecisionTreeClassifier(max_depth=4)\nclassifier.fit(X_train,Y_train)\npredicted=classifier.predict(X_test)\nprint(\"\\npredicted values :\\n\",predicted)\n\n#Accuracy\nDT = metrics.accuracy_score(Y_test, predicted) * 100\nprint(\"\\nThe accuracy score using the DecisionTreeClassifier : \",DT)"
},
{
"code": null,
"e": 7902,
"s": 7847,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 8010,
"s": 7902,
"text": "predicted values :\n[0 0 0 ... 0 0 0]\nThe accuracy score using the DecisionTreeClassifier : 99.9367999719111"
},
{
"code": null,
"e": 8494,
"s": 8010,
"text": "Once the accuracy level in the above step is acceptable we go on a further evaluation of the model by finding out different parameters. Which use Precision, recall value and F score as our parameters. precision is the fraction of relevant instances among the retrieved instances, while recall is the fraction of the total amount of relevant instances that were actually retrieved. F score provides a single score that balances both the concerns of precision and recall in one number."
},
{
"code": null,
"e": 10029,
"s": 8494,
"text": "import pandas as pd\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import f1_score\n\n#Load the creditcard.csv using pandas\ndatainput = pd.read_csv('E:\\\\creditcard.csv')\n#separating features(X) and label(y)\n\nX = datainput.iloc[:, :-1].values\nY = datainput.iloc[:, -1].values\n\n#train_test_split method\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)\n\n#DecisionTreeClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nclassifier=DecisionTreeClassifier(max_depth=4)\nclassifier.fit(X_train,Y_train)\npredicted=classifier.predict(X_test)\nprint(\"\\npredicted values :\\n\",predicted)\n#\n# #Accuracy\nDT = metrics.accuracy_score(Y_test, predicted) * 100\nprint(\"\\nThe accuracy score using the DecisionTreeClassifier : \",DT)\n#\n# #Precision\nprint('precision')\n# Precision = TP / (TP + FP) (Where TP = True Positive, TN = True Negative, FP = False Positive, FN = False Negative).\nprecision = precision_score(Y_test, predicted, pos_label=1)\nprint(precision_score(Y_test, predicted, pos_label=1))\n\n#Recall\nprint('recall')\n# Recall = TP / (TP + FN)\nrecall = recall_score(Y_test, predicted, pos_label=1)\nprint(recall_score(Y_test, predicted, pos_label=1))\n\n#f1-score\nprint('f-Score')\n# F - scores are a statistical method for determining accuracy accounting for both precision and recall.\nfscore = f1_score(Y_test, predicted, pos_label=1)\nprint(f1_score(Y_test, predicted, pos_label=1))"
},
{
"code": null,
"e": 10084,
"s": 10029,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 10236,
"s": 10084,
"text": "The accuracy score using the DecisionTreeClassifier : 99.9403110845827\nprecision\n0.810126582278481\nrecall\n0.7710843373493976\nf-Score\n0.7901234567901234"
}
] |
od command in Linux with example - GeeksforGeeks
|
24 May, 2019
od command in Linux is used to convert the content of input in different formats with octal format as the default format.This command is especially useful when debugging Linux scripts for unwanted changes or characters. If more than one file is specified, od command concatenates them in the listed order to form the input.It can display output in a variety of other formats, including hexadecimal, decimal, and ASCII. It is useful for visualizing data that is not in a human-readable format, like the executable code of a program.
Syntax :
od [OPTION]... [FILE]...
Options of od command
1. -b Option :It displays the contents of input in octal format.
SYNTAX :
$ od -b input.txt
EXAMPLE :
input :
100
101
102
103
104
105
OUTPUT :The first column in the output of od represents the byte offset in file.
2. -c Option :It displays the contents of input in character format.
SYNTAX :
$ od -c input.txt
EXAMPLE :
input :
100
101
102
103
104
105
OUTPUT :
3. -An Option :It displays the contents of input in character format but with no offset information.
SYNTAX :
$ od -An -c input.txt
EXAMPLE :
input :
100
101
102
103
104
105
OUTPUT :
4. -A Option :It displays the contents of input in different format by concatenation some special character with -A.For example:1. -Ax for Hexadecimal format(we concatenate x with -A)2. -Ao for Hexadecimal format(we concatenate o with -A)3. -Ad for Hexadecimal format(we concatenate d with -A)
SYNTAX :
$ od -Ax input.txt
$ od -Ao input.txt
$ od -Ad input.txt
EXAMPLE :
input :
100
101
102
103
104
105
OUTPUT :
5. – Option :Accept input from command line.
SYNTAX :
$ od -c -
EXAMPLE :
Here, we see that first the input was given and then after pressing the ctrl+d the od command output was displayed.
6. Display hidden character in a file :
Consider the following content of file :
Geek ^Mforgeeks
If a file containing the above string is printed using the cat command, following output is seen :
$ cat file
$ forgeekseek
so,in order to remove it we use,
OUTPUT :
$ od -c file
0000000 G e e k f o r \r g e e k s \n
0000020
7. -j Option :It displays the output after skipping some bytes.
SYNTAX :
$ od -j4 -c input.txt
EXAMPLE :
input :
100
101
102
103
104
105
OUTPUT :
Here,initial 4 bytes were skipped from output.
8. -N Option :It display limited bytes in output using -N option.
SYNTAX :
$ od -N4 -c input.txt
EXAMPLE :
input :
100
101
102
103
104
105
OUTPUT :
Here,initial 4 bytes were displayed from output.It is the opposite of -j option.
9. -w Option :It is used to customize the output width.
SYNTAX :
$ $ od -w1 -c -Ad input.txt
EXAMPLE :
input :
100
101
102
103
104
105
OUTPUT :
So we see that output width was reduced to 1
10. -v Option :It is used to output duplicate values.As can be observed in the output above, a * was printed. This is done to suppress the output of lines that are same or duplicates. But through -v option these lines can also be printed.
SYNTAX :
$ $ od -w1 -v -c -Ad input.txt
EXAMPLE :
input :
100
101
102
103
104
105
OUTPUT :
11. -i Option :It display output as decimal integer.
SYNTAX :
$ $ od -i input.txt
EXAMPLE :
input :
100
101
102
103
104
105
OUTPUT :
12. -o Option :It display output as octal 2 byte units.
SYNTAX :
$ $ od -o input.txt
EXAMPLE :
input :
100
101
102
103
104
105
OUTPUT :
13. -x Option :It display output as hexadecimal 2 byte units
SYNTAX :
$ $ od -x input.txt
EXAMPLE :
input :
100
101
102
103
104
105
OUTPUT :
14. -t Option : It select output format and display it.Traditional format specifications may be intermixed; they accumulate:-a same as -t a, select named characters, ignoring high-order bit-b same as -t o1, select octal bytes-c same as -t c, select printable characters or backslash escapes-d same as -t u2, select unsigned decimal 2-byte units-f same as -t fF, select floats-i same as -t dI, select decimal ints-l same as -t dL, select decimal longs-o same as -t o2, select octal 2-byte units-s same as -t d2, select decimal 2-byte units-x same as -t x2, select hexadecimal 2-byte units
SYNTAX :
$ $ od -ta input.txt
EXAMPLE :
input :
100
101
102
103
104
105
OUTPUT :
15. –help Option :It displays help information.
SYNTAX :
$ $ od --help
OUTPUT :
16. –version Option :It displays version information.
SYNTAX :
$ $ od --version
OUTPUT :
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
UDP Server-Client implementation in C
tar command in Linux with examples
Cat command in Linux with examples
Mutex lock for Linux Thread Synchronization
Named Pipe or FIFO with example C program
Conditional Statements | Shell Script
curl command in Linux with Examples
echo command in Linux with Examples
touch command in Linux with Examples
Thread functions in C/C++
|
[
{
"code": null,
"e": 23924,
"s": 23896,
"text": "\n24 May, 2019"
},
{
"code": null,
"e": 24456,
"s": 23924,
"text": "od command in Linux is used to convert the content of input in different formats with octal format as the default format.This command is especially useful when debugging Linux scripts for unwanted changes or characters. If more than one file is specified, od command concatenates them in the listed order to form the input.It can display output in a variety of other formats, including hexadecimal, decimal, and ASCII. It is useful for visualizing data that is not in a human-readable format, like the executable code of a program."
},
{
"code": null,
"e": 24465,
"s": 24456,
"text": "Syntax :"
},
{
"code": null,
"e": 24491,
"s": 24465,
"text": "od [OPTION]... [FILE]...\n"
},
{
"code": null,
"e": 24513,
"s": 24491,
"text": "Options of od command"
},
{
"code": null,
"e": 24578,
"s": 24513,
"text": "1. -b Option :It displays the contents of input in octal format."
},
{
"code": null,
"e": 24587,
"s": 24578,
"text": "SYNTAX :"
},
{
"code": null,
"e": 24606,
"s": 24587,
"text": "$ od -b input.txt\n"
},
{
"code": null,
"e": 24616,
"s": 24606,
"text": "EXAMPLE :"
},
{
"code": null,
"e": 24649,
"s": 24616,
"text": "input :\n100\n101\n102\n103\n104\n105\n"
},
{
"code": null,
"e": 24730,
"s": 24649,
"text": "OUTPUT :The first column in the output of od represents the byte offset in file."
},
{
"code": null,
"e": 24799,
"s": 24730,
"text": "2. -c Option :It displays the contents of input in character format."
},
{
"code": null,
"e": 24808,
"s": 24799,
"text": "SYNTAX :"
},
{
"code": null,
"e": 24827,
"s": 24808,
"text": "$ od -c input.txt\n"
},
{
"code": null,
"e": 24837,
"s": 24827,
"text": "EXAMPLE :"
},
{
"code": null,
"e": 24870,
"s": 24837,
"text": "input :\n100\n101\n102\n103\n104\n105\n"
},
{
"code": null,
"e": 24879,
"s": 24870,
"text": "OUTPUT :"
},
{
"code": null,
"e": 24980,
"s": 24879,
"text": "3. -An Option :It displays the contents of input in character format but with no offset information."
},
{
"code": null,
"e": 24989,
"s": 24980,
"text": "SYNTAX :"
},
{
"code": null,
"e": 25012,
"s": 24989,
"text": "$ od -An -c input.txt\n"
},
{
"code": null,
"e": 25022,
"s": 25012,
"text": "EXAMPLE :"
},
{
"code": null,
"e": 25055,
"s": 25022,
"text": "input :\n100\n101\n102\n103\n104\n105\n"
},
{
"code": null,
"e": 25064,
"s": 25055,
"text": "OUTPUT :"
},
{
"code": null,
"e": 25358,
"s": 25064,
"text": "4. -A Option :It displays the contents of input in different format by concatenation some special character with -A.For example:1. -Ax for Hexadecimal format(we concatenate x with -A)2. -Ao for Hexadecimal format(we concatenate o with -A)3. -Ad for Hexadecimal format(we concatenate d with -A)"
},
{
"code": null,
"e": 25367,
"s": 25358,
"text": "SYNTAX :"
},
{
"code": null,
"e": 25425,
"s": 25367,
"text": "$ od -Ax input.txt\n$ od -Ao input.txt\n$ od -Ad input.txt\n"
},
{
"code": null,
"e": 25435,
"s": 25425,
"text": "EXAMPLE :"
},
{
"code": null,
"e": 25468,
"s": 25435,
"text": "input :\n100\n101\n102\n103\n104\n105\n"
},
{
"code": null,
"e": 25477,
"s": 25468,
"text": "OUTPUT :"
},
{
"code": null,
"e": 25522,
"s": 25477,
"text": "5. – Option :Accept input from command line."
},
{
"code": null,
"e": 25531,
"s": 25522,
"text": "SYNTAX :"
},
{
"code": null,
"e": 25543,
"s": 25531,
"text": " $ od -c -\n"
},
{
"code": null,
"e": 25553,
"s": 25543,
"text": "EXAMPLE :"
},
{
"code": null,
"e": 25669,
"s": 25553,
"text": "Here, we see that first the input was given and then after pressing the ctrl+d the od command output was displayed."
},
{
"code": null,
"e": 25709,
"s": 25669,
"text": "6. Display hidden character in a file :"
},
{
"code": null,
"e": 25750,
"s": 25709,
"text": "Consider the following content of file :"
},
{
"code": null,
"e": 25766,
"s": 25750,
"text": "Geek ^Mforgeeks"
},
{
"code": null,
"e": 25865,
"s": 25766,
"text": "If a file containing the above string is printed using the cat command, following output is seen :"
},
{
"code": null,
"e": 25893,
"s": 25865,
"text": " \n$ cat file\n$ forgeekseek\n"
},
{
"code": null,
"e": 25926,
"s": 25893,
"text": "so,in order to remove it we use,"
},
{
"code": null,
"e": 25935,
"s": 25926,
"text": "OUTPUT :"
},
{
"code": null,
"e": 26039,
"s": 25935,
"text": "$ od -c file\n0000000 G e e k f o r \\r g e e k s \\n\n0000020\n"
},
{
"code": null,
"e": 26103,
"s": 26039,
"text": "7. -j Option :It displays the output after skipping some bytes."
},
{
"code": null,
"e": 26112,
"s": 26103,
"text": "SYNTAX :"
},
{
"code": null,
"e": 26135,
"s": 26112,
"text": "$ od -j4 -c input.txt\n"
},
{
"code": null,
"e": 26145,
"s": 26135,
"text": "EXAMPLE :"
},
{
"code": null,
"e": 26178,
"s": 26145,
"text": "input :\n100\n101\n102\n103\n104\n105\n"
},
{
"code": null,
"e": 26187,
"s": 26178,
"text": "OUTPUT :"
},
{
"code": null,
"e": 26234,
"s": 26187,
"text": "Here,initial 4 bytes were skipped from output."
},
{
"code": null,
"e": 26300,
"s": 26234,
"text": "8. -N Option :It display limited bytes in output using -N option."
},
{
"code": null,
"e": 26309,
"s": 26300,
"text": "SYNTAX :"
},
{
"code": null,
"e": 26332,
"s": 26309,
"text": "$ od -N4 -c input.txt\n"
},
{
"code": null,
"e": 26342,
"s": 26332,
"text": "EXAMPLE :"
},
{
"code": null,
"e": 26375,
"s": 26342,
"text": "input :\n100\n101\n102\n103\n104\n105\n"
},
{
"code": null,
"e": 26384,
"s": 26375,
"text": "OUTPUT :"
},
{
"code": null,
"e": 26465,
"s": 26384,
"text": "Here,initial 4 bytes were displayed from output.It is the opposite of -j option."
},
{
"code": null,
"e": 26521,
"s": 26465,
"text": "9. -w Option :It is used to customize the output width."
},
{
"code": null,
"e": 26530,
"s": 26521,
"text": "SYNTAX :"
},
{
"code": null,
"e": 26559,
"s": 26530,
"text": "$ $ od -w1 -c -Ad input.txt\n"
},
{
"code": null,
"e": 26569,
"s": 26559,
"text": "EXAMPLE :"
},
{
"code": null,
"e": 26602,
"s": 26569,
"text": "input :\n100\n101\n102\n103\n104\n105\n"
},
{
"code": null,
"e": 26611,
"s": 26602,
"text": "OUTPUT :"
},
{
"code": null,
"e": 26656,
"s": 26611,
"text": "So we see that output width was reduced to 1"
},
{
"code": null,
"e": 26895,
"s": 26656,
"text": "10. -v Option :It is used to output duplicate values.As can be observed in the output above, a * was printed. This is done to suppress the output of lines that are same or duplicates. But through -v option these lines can also be printed."
},
{
"code": null,
"e": 26904,
"s": 26895,
"text": "SYNTAX :"
},
{
"code": null,
"e": 26936,
"s": 26904,
"text": "$ $ od -w1 -v -c -Ad input.txt\n"
},
{
"code": null,
"e": 26946,
"s": 26936,
"text": "EXAMPLE :"
},
{
"code": null,
"e": 26979,
"s": 26946,
"text": "input :\n100\n101\n102\n103\n104\n105\n"
},
{
"code": null,
"e": 26988,
"s": 26979,
"text": "OUTPUT :"
},
{
"code": null,
"e": 27041,
"s": 26988,
"text": "11. -i Option :It display output as decimal integer."
},
{
"code": null,
"e": 27050,
"s": 27041,
"text": "SYNTAX :"
},
{
"code": null,
"e": 27071,
"s": 27050,
"text": "$ $ od -i input.txt\n"
},
{
"code": null,
"e": 27081,
"s": 27071,
"text": "EXAMPLE :"
},
{
"code": null,
"e": 27114,
"s": 27081,
"text": "input :\n100\n101\n102\n103\n104\n105\n"
},
{
"code": null,
"e": 27123,
"s": 27114,
"text": "OUTPUT :"
},
{
"code": null,
"e": 27179,
"s": 27123,
"text": "12. -o Option :It display output as octal 2 byte units."
},
{
"code": null,
"e": 27188,
"s": 27179,
"text": "SYNTAX :"
},
{
"code": null,
"e": 27209,
"s": 27188,
"text": "$ $ od -o input.txt\n"
},
{
"code": null,
"e": 27219,
"s": 27209,
"text": "EXAMPLE :"
},
{
"code": null,
"e": 27252,
"s": 27219,
"text": "input :\n100\n101\n102\n103\n104\n105\n"
},
{
"code": null,
"e": 27261,
"s": 27252,
"text": "OUTPUT :"
},
{
"code": null,
"e": 27322,
"s": 27261,
"text": "13. -x Option :It display output as hexadecimal 2 byte units"
},
{
"code": null,
"e": 27331,
"s": 27322,
"text": "SYNTAX :"
},
{
"code": null,
"e": 27352,
"s": 27331,
"text": "$ $ od -x input.txt\n"
},
{
"code": null,
"e": 27362,
"s": 27352,
"text": "EXAMPLE :"
},
{
"code": null,
"e": 27395,
"s": 27362,
"text": "input :\n100\n101\n102\n103\n104\n105\n"
},
{
"code": null,
"e": 27404,
"s": 27395,
"text": "OUTPUT :"
},
{
"code": null,
"e": 27992,
"s": 27404,
"text": "14. -t Option : It select output format and display it.Traditional format specifications may be intermixed; they accumulate:-a same as -t a, select named characters, ignoring high-order bit-b same as -t o1, select octal bytes-c same as -t c, select printable characters or backslash escapes-d same as -t u2, select unsigned decimal 2-byte units-f same as -t fF, select floats-i same as -t dI, select decimal ints-l same as -t dL, select decimal longs-o same as -t o2, select octal 2-byte units-s same as -t d2, select decimal 2-byte units-x same as -t x2, select hexadecimal 2-byte units"
},
{
"code": null,
"e": 28001,
"s": 27992,
"text": "SYNTAX :"
},
{
"code": null,
"e": 28023,
"s": 28001,
"text": "$ $ od -ta input.txt\n"
},
{
"code": null,
"e": 28033,
"s": 28023,
"text": "EXAMPLE :"
},
{
"code": null,
"e": 28066,
"s": 28033,
"text": "input :\n100\n101\n102\n103\n104\n105\n"
},
{
"code": null,
"e": 28075,
"s": 28066,
"text": "OUTPUT :"
},
{
"code": null,
"e": 28123,
"s": 28075,
"text": "15. –help Option :It displays help information."
},
{
"code": null,
"e": 28132,
"s": 28123,
"text": "SYNTAX :"
},
{
"code": null,
"e": 28147,
"s": 28132,
"text": "$ $ od --help\n"
},
{
"code": null,
"e": 28156,
"s": 28147,
"text": "OUTPUT :"
},
{
"code": null,
"e": 28210,
"s": 28156,
"text": "16. –version Option :It displays version information."
},
{
"code": null,
"e": 28219,
"s": 28210,
"text": "SYNTAX :"
},
{
"code": null,
"e": 28237,
"s": 28219,
"text": "$ $ od --version\n"
},
{
"code": null,
"e": 28246,
"s": 28237,
"text": "OUTPUT :"
},
{
"code": null,
"e": 28260,
"s": 28246,
"text": "linux-command"
},
{
"code": null,
"e": 28280,
"s": 28260,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 28291,
"s": 28280,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28389,
"s": 28291,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28398,
"s": 28389,
"text": "Comments"
},
{
"code": null,
"e": 28411,
"s": 28398,
"text": "Old Comments"
},
{
"code": null,
"e": 28449,
"s": 28411,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 28484,
"s": 28449,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 28519,
"s": 28484,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 28563,
"s": 28519,
"text": "Mutex lock for Linux Thread Synchronization"
},
{
"code": null,
"e": 28605,
"s": 28563,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 28643,
"s": 28605,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 28679,
"s": 28643,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 28715,
"s": 28679,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 28752,
"s": 28715,
"text": "touch command in Linux with Examples"
}
] |
How to Set the Padding of the Label in C#?
|
30 Jun, 2019
In Windows Forms, Label control is used to display text on the form and it does not take part in user input or in mouse or keyboard events. You are allowed to set the space between the content and the boundaries of the Label control using the Padding Property in the windows form. You can set this property using two different methods:
1. Design-Time: It is the easiest method to set the Padding property of the Label control using the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the Label control from the ToolBox and drop it on the windows form. You are allowed to place a Label control anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the Label control to set the Padding property of the Label.Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the padding between the text and the label boundaries in the windows forms programmatically with the help of given syntax:
public System.Windows.Forms.Padding Padding { get; set; }
Here, Padding indicates the Label control’s internal spacing characteristics. Following steps are used to set the Padding property of the Label:
Step 1: Create a label using the Label() constructor is provided by the Label class.// Creating label using Label class
Label mylab = new Label();
// Creating label using Label class
Label mylab = new Label();
Step 2: After creating Label, set the Padding property of the Label provided by the Label class.// Set Padding property of the label
mylab.Padding = new Padding(6);
// Set Padding property of the label
mylab.Padding = new Padding(6);
Step 3: And last add this Label control to form using Add() method.// Add this label to the form
this.Controls.Add(mylab);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = "GeeksforGeeks"; mylab.Location = new Point(222, 90); mylab.AutoSize = true; mylab.Font = new Font("Calibri", 18); mylab.BorderStyle = BorderStyle.Fixed3D; mylab.ForeColor = Color.Green; mylab.Padding = new Padding(6); // Adding this control to the form this.Controls.Add(mylab); // Creating and setting the label Label mylab1 = new Label(); mylab1.Text = "Welcome To GeeksforGeeks"; mylab1.Location = new Point(155, 170); mylab1.AutoSize = true; mylab1.BorderStyle = BorderStyle.Fixed3D; mylab1.Font = new Font("Calibri", 18); mylab1.Padding = new Padding(6); // Adding this control to the form this.Controls.Add(mylab1); }}}Output:Before setting padding:After setting padding:
// Add this label to the form
this.Controls.Add(mylab);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = "GeeksforGeeks"; mylab.Location = new Point(222, 90); mylab.AutoSize = true; mylab.Font = new Font("Calibri", 18); mylab.BorderStyle = BorderStyle.Fixed3D; mylab.ForeColor = Color.Green; mylab.Padding = new Padding(6); // Adding this control to the form this.Controls.Add(mylab); // Creating and setting the label Label mylab1 = new Label(); mylab1.Text = "Welcome To GeeksforGeeks"; mylab1.Location = new Point(155, 170); mylab1.AutoSize = true; mylab1.BorderStyle = BorderStyle.Fixed3D; mylab1.Font = new Font("Calibri", 18); mylab1.Padding = new Padding(6); // Adding this control to the form this.Controls.Add(mylab1); }}}
Output:
Before setting padding:
After setting padding:
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Multiple inheritance using interfaces
C# | Delegates
Introduction to .NET Framework
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
C# | Class and Object
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jun, 2019"
},
{
"code": null,
"e": 364,
"s": 28,
"text": "In Windows Forms, Label control is used to display text on the form and it does not take part in user input or in mouse or keyboard events. You are allowed to set the space between the content and the boundaries of the Label control using the Padding Property in the windows form. You can set this property using two different methods:"
},
{
"code": null,
"e": 481,
"s": 364,
"text": "1. Design-Time: It is the easiest method to set the Padding property of the Label control using the following steps:"
},
{
"code": null,
"e": 597,
"s": 481,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 772,
"s": 597,
"text": "Step 2: Drag the Label control from the ToolBox and drop it on the windows form. You are allowed to place a Label control anywhere on the windows form according to your need."
},
{
"code": null,
"e": 900,
"s": 772,
"text": "Step 3: After drag and drop you will go to the properties of the Label control to set the Padding property of the Label.Output:"
},
{
"code": null,
"e": 908,
"s": 900,
"text": "Output:"
},
{
"code": null,
"e": 1123,
"s": 908,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the padding between the text and the label boundaries in the windows forms programmatically with the help of given syntax:"
},
{
"code": null,
"e": 1181,
"s": 1123,
"text": "public System.Windows.Forms.Padding Padding { get; set; }"
},
{
"code": null,
"e": 1326,
"s": 1181,
"text": "Here, Padding indicates the Label control’s internal spacing characteristics. Following steps are used to set the Padding property of the Label:"
},
{
"code": null,
"e": 1474,
"s": 1326,
"text": "Step 1: Create a label using the Label() constructor is provided by the Label class.// Creating label using Label class\nLabel mylab = new Label();\n"
},
{
"code": null,
"e": 1538,
"s": 1474,
"text": "// Creating label using Label class\nLabel mylab = new Label();\n"
},
{
"code": null,
"e": 1704,
"s": 1538,
"text": "Step 2: After creating Label, set the Padding property of the Label provided by the Label class.// Set Padding property of the label\nmylab.Padding = new Padding(6);\n"
},
{
"code": null,
"e": 1774,
"s": 1704,
"text": "// Set Padding property of the label\nmylab.Padding = new Padding(6);\n"
},
{
"code": null,
"e": 3210,
"s": 1774,
"text": "Step 3: And last add this Label control to form using Add() method.// Add this label to the form\nthis.Controls.Add(mylab);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = \"GeeksforGeeks\"; mylab.Location = new Point(222, 90); mylab.AutoSize = true; mylab.Font = new Font(\"Calibri\", 18); mylab.BorderStyle = BorderStyle.Fixed3D; mylab.ForeColor = Color.Green; mylab.Padding = new Padding(6); // Adding this control to the form this.Controls.Add(mylab); // Creating and setting the label Label mylab1 = new Label(); mylab1.Text = \"Welcome To GeeksforGeeks\"; mylab1.Location = new Point(155, 170); mylab1.AutoSize = true; mylab1.BorderStyle = BorderStyle.Fixed3D; mylab1.Font = new Font(\"Calibri\", 18); mylab1.Padding = new Padding(6); // Adding this control to the form this.Controls.Add(mylab1); }}}Output:Before setting padding:After setting padding:"
},
{
"code": null,
"e": 3267,
"s": 3210,
"text": "// Add this label to the form\nthis.Controls.Add(mylab);\n"
},
{
"code": null,
"e": 3276,
"s": 3267,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = \"GeeksforGeeks\"; mylab.Location = new Point(222, 90); mylab.AutoSize = true; mylab.Font = new Font(\"Calibri\", 18); mylab.BorderStyle = BorderStyle.Fixed3D; mylab.ForeColor = Color.Green; mylab.Padding = new Padding(6); // Adding this control to the form this.Controls.Add(mylab); // Creating and setting the label Label mylab1 = new Label(); mylab1.Text = \"Welcome To GeeksforGeeks\"; mylab1.Location = new Point(155, 170); mylab1.AutoSize = true; mylab1.BorderStyle = BorderStyle.Fixed3D; mylab1.Font = new Font(\"Calibri\", 18); mylab1.Padding = new Padding(6); // Adding this control to the form this.Controls.Add(mylab1); }}}",
"e": 4529,
"s": 3276,
"text": null
},
{
"code": null,
"e": 4537,
"s": 4529,
"text": "Output:"
},
{
"code": null,
"e": 4561,
"s": 4537,
"text": "Before setting padding:"
},
{
"code": null,
"e": 4584,
"s": 4561,
"text": "After setting padding:"
},
{
"code": null,
"e": 4587,
"s": 4584,
"text": "C#"
},
{
"code": null,
"e": 4685,
"s": 4587,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4713,
"s": 4685,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 4756,
"s": 4713,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 4771,
"s": 4756,
"text": "C# | Delegates"
},
{
"code": null,
"e": 4802,
"s": 4771,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 4851,
"s": 4802,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 4867,
"s": 4851,
"text": "C# | Data Types"
},
{
"code": null,
"e": 4890,
"s": 4867,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 4930,
"s": 4890,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 4948,
"s": 4930,
"text": "C# | Constructors"
}
] |
How to Scrape Paragraphs using Python?
|
29 Dec, 2020
Prerequisite: Implementing Web Scraping in Python with BeautifulSoup
In this article, we are going to see how we extract all the paragraphs from the given HTML document or URL using python.
Module Needed:
bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.
pip install bs4
requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal.
pip install requests
Approach:
Import module
Create an HTML document and specify the ‘<p>’ tag into the code
Pass the HTML document into the Beautifulsoup() function
Use the ‘P’ tag to extract paragraphs from the Beautifulsoup object
Get text from the HTML document with get_text().
Code:
Python3
# import modulefrom bs4 import BeautifulSoup # Html dochtml_doc = """<html><head><title>Geeks</title></head><body><h2>paragraphs</h2> <p>Welcome geeks.</p> <p>Hello geeks.</p> </body></html>"""soup = BeautifulSoup(html_doc, 'html.parser') # traverse paragraphs from soupfor data in soup.find_all("p"): print(data.get_text())
Output:
Welcome geeks.
Hello geeks.
Now Lets Extract Paragraphs from the given URL.
Code:
Python3
# import moduleimport requestsimport pandas as pdfrom bs4 import BeautifulSoup # link for extract html datadef getdata(url): r = requests.get(url) return r.text htmldata = getdata("https://www.geeksforgeeks.org/")soup = BeautifulSoup(htmldata, 'html.parser')data = ''for data in soup.find_all("p"): print(data.get_text())
Output:
Python web-scraping-exercises
python-utility
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 122,
"s": 53,
"text": "Prerequisite: Implementing Web Scraping in Python with BeautifulSoup"
},
{
"code": null,
"e": 243,
"s": 122,
"text": "In this article, we are going to see how we extract all the paragraphs from the given HTML document or URL using python."
},
{
"code": null,
"e": 258,
"s": 243,
"text": "Module Needed:"
},
{
"code": null,
"e": 451,
"s": 258,
"text": "bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal."
},
{
"code": null,
"e": 468,
"s": 451,
"text": "pip install bs4\n"
},
{
"code": null,
"e": 653,
"s": 468,
"text": "requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal."
},
{
"code": null,
"e": 675,
"s": 653,
"text": "pip install requests\n"
},
{
"code": null,
"e": 685,
"s": 675,
"text": "Approach:"
},
{
"code": null,
"e": 699,
"s": 685,
"text": "Import module"
},
{
"code": null,
"e": 763,
"s": 699,
"text": "Create an HTML document and specify the ‘<p>’ tag into the code"
},
{
"code": null,
"e": 820,
"s": 763,
"text": "Pass the HTML document into the Beautifulsoup() function"
},
{
"code": null,
"e": 888,
"s": 820,
"text": "Use the ‘P’ tag to extract paragraphs from the Beautifulsoup object"
},
{
"code": null,
"e": 937,
"s": 888,
"text": "Get text from the HTML document with get_text()."
},
{
"code": null,
"e": 943,
"s": 937,
"text": "Code:"
},
{
"code": null,
"e": 951,
"s": 943,
"text": "Python3"
},
{
"code": "# import modulefrom bs4 import BeautifulSoup # Html dochtml_doc = \"\"\"<html><head><title>Geeks</title></head><body><h2>paragraphs</h2> <p>Welcome geeks.</p> <p>Hello geeks.</p> </body></html>\"\"\"soup = BeautifulSoup(html_doc, 'html.parser') # traverse paragraphs from soupfor data in soup.find_all(\"p\"): print(data.get_text())",
"e": 1286,
"s": 951,
"text": null
},
{
"code": null,
"e": 1294,
"s": 1286,
"text": "Output:"
},
{
"code": null,
"e": 1323,
"s": 1294,
"text": "Welcome geeks.\nHello geeks.\n"
},
{
"code": null,
"e": 1371,
"s": 1323,
"text": "Now Lets Extract Paragraphs from the given URL."
},
{
"code": null,
"e": 1377,
"s": 1371,
"text": "Code:"
},
{
"code": null,
"e": 1385,
"s": 1377,
"text": "Python3"
},
{
"code": "# import moduleimport requestsimport pandas as pdfrom bs4 import BeautifulSoup # link for extract html datadef getdata(url): r = requests.get(url) return r.text htmldata = getdata(\"https://www.geeksforgeeks.org/\")soup = BeautifulSoup(htmldata, 'html.parser')data = ''for data in soup.find_all(\"p\"): print(data.get_text())",
"e": 1718,
"s": 1385,
"text": null
},
{
"code": null,
"e": 1726,
"s": 1718,
"text": "Output:"
},
{
"code": null,
"e": 1756,
"s": 1726,
"text": "Python web-scraping-exercises"
},
{
"code": null,
"e": 1771,
"s": 1756,
"text": "python-utility"
},
{
"code": null,
"e": 1784,
"s": 1771,
"text": "Web-scraping"
},
{
"code": null,
"e": 1791,
"s": 1784,
"text": "Python"
},
{
"code": null,
"e": 1889,
"s": 1791,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1907,
"s": 1889,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1949,
"s": 1907,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1971,
"s": 1949,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1997,
"s": 1971,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2029,
"s": 1997,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2058,
"s": 2029,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2085,
"s": 2058,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2115,
"s": 2085,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2151,
"s": 2115,
"text": "Convert integer to string in Python"
}
] |
TypeScript | Array reverse() Method
|
03 Mar, 2021
The Array.reverse() is an inbuilt TypeScript function which is used to reverses the element of an array. Syntax:
array.reverse();
Parameter: This methods does not accept any parameter. Return Value: This method returns the reversed single value of the array. Below examples illustrate the Array reverse() Method in TypeScript.
Example 1:
TypeScript
// Driver codevar arr = [ 11, 89, 23, 7, 98 ]; // use of reverse() method var val = arr.reverse(); // printingconsole.log( val );
Output:
[ 98, 7, 23, 89, 11 ]
Example 2:
TypeScript
// Driver codevar arr = [2, 5, 6, 3, 8, 9]; var val; // use of reverse() method val = arr.reverse();val = val.reverse(); // printingconsole.log( val );
Output:
[ 2, 5, 6, 3, 8, 9 ]
pratikraut0000
TypeScript
JavaScript
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
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 142,
"s": 28,
"text": "The Array.reverse() is an inbuilt TypeScript function which is used to reverses the element of an array. Syntax:"
},
{
"code": null,
"e": 160,
"s": 142,
"text": "array.reverse(); "
},
{
"code": null,
"e": 357,
"s": 160,
"text": "Parameter: This methods does not accept any parameter. Return Value: This method returns the reversed single value of the array. Below examples illustrate the Array reverse() Method in TypeScript."
},
{
"code": null,
"e": 369,
"s": 357,
"text": "Example 1: "
},
{
"code": null,
"e": 380,
"s": 369,
"text": "TypeScript"
},
{
"code": "// Driver codevar arr = [ 11, 89, 23, 7, 98 ]; // use of reverse() method var val = arr.reverse(); // printingconsole.log( val );",
"e": 513,
"s": 380,
"text": null
},
{
"code": null,
"e": 522,
"s": 513,
"text": "Output: "
},
{
"code": null,
"e": 544,
"s": 522,
"text": "[ 98, 7, 23, 89, 11 ]"
},
{
"code": null,
"e": 556,
"s": 544,
"text": "Example 2: "
},
{
"code": null,
"e": 567,
"s": 556,
"text": "TypeScript"
},
{
"code": "// Driver codevar arr = [2, 5, 6, 3, 8, 9]; var val; // use of reverse() method val = arr.reverse();val = val.reverse(); // printingconsole.log( val );",
"e": 723,
"s": 567,
"text": null
},
{
"code": null,
"e": 732,
"s": 723,
"text": "Output: "
},
{
"code": null,
"e": 753,
"s": 732,
"text": "[ 2, 5, 6, 3, 8, 9 ]"
},
{
"code": null,
"e": 770,
"s": 755,
"text": "pratikraut0000"
},
{
"code": null,
"e": 781,
"s": 770,
"text": "TypeScript"
},
{
"code": null,
"e": 792,
"s": 781,
"text": "JavaScript"
},
{
"code": null,
"e": 809,
"s": 792,
"text": "Web Technologies"
},
{
"code": null,
"e": 907,
"s": 809,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 968,
"s": 907,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1040,
"s": 968,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1080,
"s": 1040,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1121,
"s": 1080,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1163,
"s": 1121,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 1196,
"s": 1163,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1258,
"s": 1196,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1319,
"s": 1258,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1369,
"s": 1319,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Software Engineering | Calculation of Function Point (FP)
|
28 Jun, 2020
Function Point (FP) is an element of software development which helps to approximate the cost of development early in the process. It may measures functionality from user’s point of view.
Counting Function Point (FP):
Step-1:F = 14 * scaleScale varies from 0 to 5 according to character of Complexity Adjustment Factor (CAF). Below table shows scale:0 - No Influence
1 - Incidental
2 - Moderate
3 - Average
4 - Significant
5 - Essential
F = 14 * scale
Scale varies from 0 to 5 according to character of Complexity Adjustment Factor (CAF). Below table shows scale:
0 - No Influence
1 - Incidental
2 - Moderate
3 - Average
4 - Significant
5 - Essential
Step-2: Calculate Complexity Adjustment Factor (CAF).CAF = 0.65 + ( 0.01 * F )
CAF = 0.65 + ( 0.01 * F )
Step-3: Calculate Unadjusted Function Point (UFP).TABLE (Required)Function UnitsLowAvgHighEI346EO457EQ346ILF71015EIF5710Multiply each individual function point to corresponding values in TABLE.
TABLE (Required)
Multiply each individual function point to corresponding values in TABLE.
Step-4: Calculate Function Point.FP = UFP * CAF
FP = UFP * CAF
Example:Given the following values, compute function point when all complexity adjustment factor (CAF) and weighting factors are average.
User Input = 50
User Output = 40
User Inquiries = 35
User Files = 6
External Interface = 4
Explanation:
Step-1: As complexity adjustment factor is average (given in question), hence,scale = 3.
F = 14 * 3 = 42
scale = 3.
F = 14 * 3 = 42
Step-2:CAF = 0.65 + ( 0.01 * 42 ) = 1.07
CAF = 0.65 + ( 0.01 * 42 ) = 1.07
Step-3: As weighting factors are also average (given in question) hence we will multiply each individual function point to corresponding values in TABLE.UFP = (50*4) + (40*5) + (35*4) + (6*10) + (4*7) = 628
UFP = (50*4) + (40*5) + (35*4) + (6*10) + (4*7) = 628
Step-4:Function Point = 628 * 1.07 = 671.96 This is the required answer.
Function Point = 628 * 1.07 = 671.96
This is the required answer.
Program to calculate Function Point is as follows :-
#include <bits/stdc++.h>using namespace std; // Function to calculate Function Pointvoid calfp(int frates[][3], int fac_rate){ // Function Units string funUnits[5] = { "External Inputs", "External Outputs", "External Inquiries", "Internal Logical Files", "External Interface Files" }; // Weight Rates string wtRates[3] = { "Low", "Average", "High" }; // Weight Factors int wtFactors[5][3] = { { 3, 4, 6 }, { 4, 5, 7 }, { 3, 4, 6 }, { 7, 10, 15 }, { 5, 7, 10 }, }; int UFP = 0; // Calculating UFP (Unadjusted Function Point) for (int i = 0; i < 5; i++) { for (int j = 0; j < 3; j++) { int freq = frates[i][j]; UFP += freq * wtFactors[i][j]; } } // 14 factors string aspects[14] = { "reliable backup and recovery required ?", "data communication required ?", "are there distributed processing functions ?", "is performance critical ?", "will the system run in an existing heavily utilized operational environment ?", "on line data entry required ?", "does the on line data entry require the input transaction to be built over multiple screens or operations ?", "are the master files updated on line ?", "is the inputs, outputs, files or inquiries complex ?", "is the internal processing complex ?", "is the code designed to be reusable ?", "are the conversion and installation included in the design ?", "is the system designed for multiple installations in different organizations ?", "is the application designed to facilitate change and ease of use by the user ?" }; /* Rate Scale of Factors Rate the following aspects on a scale of 0-5 :- 0 - No influence 1 - Incidental 2 - Moderate 3 - Average 4 - Significant 5 - Essential */ int sumF = 0; // Taking Input of factors rate for (int i = 0; i < 14; i++) { int rate = fac_rate; sumF += rate; } // Calculate CFP double CAF = 0.65 + 0.01 * sumF; // Calculate Function Point (FP) double FP = UFP * CAF; // Output Values cout << "Function Point Analysis :-" << endl; cout << "Unadjusted Function Points (UFP) : " << UFP << endl; cout << "Complexity Adjustment Factor (CAF) : " << CAF << endl; cout << "Function Points (FP) : " << FP << endl;} // driver functionint main(){ int frates[5][3] = { { 0, 50, 0 }, { 0, 40, 0 }, { 0, 35, 0 }, { 0, 6, 0 }, { 0, 4, 0 } }; int fac_rate = 3; calfp(frates, fac_rate); return 0;}
Function Point Analysis :-
Unadjusted Function Points (UFP) : 628
Complexity Adjustment Factor (CAF) : 1.07
Function Points (FP) : 671.96
chitrasingla2001
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Functional vs Non Functional Requirements
Differences between Verification and Validation
Unit Testing | Software Testing
Software Engineering | Classical Waterfall Model
Software Requirement Specification (SRS) Format
Difference between Spring and Spring Boot
Software Engineering | Requirements Engineering Process
Software Testing Life Cycle (STLC)
Difference between IAAS, PAAS and SAAS
Software Engineering | Architectural Design
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2020"
},
{
"code": null,
"e": 242,
"s": 54,
"text": "Function Point (FP) is an element of software development which helps to approximate the cost of development early in the process. It may measures functionality from user’s point of view."
},
{
"code": null,
"e": 272,
"s": 242,
"text": "Counting Function Point (FP):"
},
{
"code": null,
"e": 492,
"s": 272,
"text": "Step-1:F = 14 * scaleScale varies from 0 to 5 according to character of Complexity Adjustment Factor (CAF). Below table shows scale:0 - No Influence\n1 - Incidental\n2 - Moderate\n3 - Average\n4 - Significant\n5 - Essential "
},
{
"code": null,
"e": 507,
"s": 492,
"text": "F = 14 * scale"
},
{
"code": null,
"e": 619,
"s": 507,
"text": "Scale varies from 0 to 5 according to character of Complexity Adjustment Factor (CAF). Below table shows scale:"
},
{
"code": null,
"e": 707,
"s": 619,
"text": "0 - No Influence\n1 - Incidental\n2 - Moderate\n3 - Average\n4 - Significant\n5 - Essential "
},
{
"code": null,
"e": 786,
"s": 707,
"text": "Step-2: Calculate Complexity Adjustment Factor (CAF).CAF = 0.65 + ( 0.01 * F )"
},
{
"code": null,
"e": 812,
"s": 786,
"text": "CAF = 0.65 + ( 0.01 * F )"
},
{
"code": null,
"e": 1006,
"s": 812,
"text": "Step-3: Calculate Unadjusted Function Point (UFP).TABLE (Required)Function UnitsLowAvgHighEI346EO457EQ346ILF71015EIF5710Multiply each individual function point to corresponding values in TABLE."
},
{
"code": null,
"e": 1023,
"s": 1006,
"text": "TABLE (Required)"
},
{
"code": null,
"e": 1097,
"s": 1023,
"text": "Multiply each individual function point to corresponding values in TABLE."
},
{
"code": null,
"e": 1145,
"s": 1097,
"text": "Step-4: Calculate Function Point.FP = UFP * CAF"
},
{
"code": null,
"e": 1160,
"s": 1145,
"text": "FP = UFP * CAF"
},
{
"code": null,
"e": 1298,
"s": 1160,
"text": "Example:Given the following values, compute function point when all complexity adjustment factor (CAF) and weighting factors are average."
},
{
"code": null,
"e": 1390,
"s": 1298,
"text": "User Input = 50\nUser Output = 40\nUser Inquiries = 35\nUser Files = 6\nExternal Interface = 4 "
},
{
"code": null,
"e": 1403,
"s": 1390,
"text": "Explanation:"
},
{
"code": null,
"e": 1509,
"s": 1403,
"text": "Step-1: As complexity adjustment factor is average (given in question), hence,scale = 3.\nF = 14 * 3 = 42 "
},
{
"code": null,
"e": 1537,
"s": 1509,
"text": "scale = 3.\nF = 14 * 3 = 42 "
},
{
"code": null,
"e": 1579,
"s": 1537,
"text": "Step-2:CAF = 0.65 + ( 0.01 * 42 ) = 1.07 "
},
{
"code": null,
"e": 1614,
"s": 1579,
"text": "CAF = 0.65 + ( 0.01 * 42 ) = 1.07 "
},
{
"code": null,
"e": 1822,
"s": 1614,
"text": "Step-3: As weighting factors are also average (given in question) hence we will multiply each individual function point to corresponding values in TABLE.UFP = (50*4) + (40*5) + (35*4) + (6*10) + (4*7) = 628 "
},
{
"code": null,
"e": 1877,
"s": 1822,
"text": "UFP = (50*4) + (40*5) + (35*4) + (6*10) + (4*7) = 628 "
},
{
"code": null,
"e": 1950,
"s": 1877,
"text": "Step-4:Function Point = 628 * 1.07 = 671.96 This is the required answer."
},
{
"code": null,
"e": 1988,
"s": 1950,
"text": "Function Point = 628 * 1.07 = 671.96 "
},
{
"code": null,
"e": 2017,
"s": 1988,
"text": "This is the required answer."
},
{
"code": null,
"e": 2070,
"s": 2017,
"text": "Program to calculate Function Point is as follows :-"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // Function to calculate Function Pointvoid calfp(int frates[][3], int fac_rate){ // Function Units string funUnits[5] = { \"External Inputs\", \"External Outputs\", \"External Inquiries\", \"Internal Logical Files\", \"External Interface Files\" }; // Weight Rates string wtRates[3] = { \"Low\", \"Average\", \"High\" }; // Weight Factors int wtFactors[5][3] = { { 3, 4, 6 }, { 4, 5, 7 }, { 3, 4, 6 }, { 7, 10, 15 }, { 5, 7, 10 }, }; int UFP = 0; // Calculating UFP (Unadjusted Function Point) for (int i = 0; i < 5; i++) { for (int j = 0; j < 3; j++) { int freq = frates[i][j]; UFP += freq * wtFactors[i][j]; } } // 14 factors string aspects[14] = { \"reliable backup and recovery required ?\", \"data communication required ?\", \"are there distributed processing functions ?\", \"is performance critical ?\", \"will the system run in an existing heavily utilized operational environment ?\", \"on line data entry required ?\", \"does the on line data entry require the input transaction to be built over multiple screens or operations ?\", \"are the master files updated on line ?\", \"is the inputs, outputs, files or inquiries complex ?\", \"is the internal processing complex ?\", \"is the code designed to be reusable ?\", \"are the conversion and installation included in the design ?\", \"is the system designed for multiple installations in different organizations ?\", \"is the application designed to facilitate change and ease of use by the user ?\" }; /* Rate Scale of Factors Rate the following aspects on a scale of 0-5 :- 0 - No influence 1 - Incidental 2 - Moderate 3 - Average 4 - Significant 5 - Essential */ int sumF = 0; // Taking Input of factors rate for (int i = 0; i < 14; i++) { int rate = fac_rate; sumF += rate; } // Calculate CFP double CAF = 0.65 + 0.01 * sumF; // Calculate Function Point (FP) double FP = UFP * CAF; // Output Values cout << \"Function Point Analysis :-\" << endl; cout << \"Unadjusted Function Points (UFP) : \" << UFP << endl; cout << \"Complexity Adjustment Factor (CAF) : \" << CAF << endl; cout << \"Function Points (FP) : \" << FP << endl;} // driver functionint main(){ int frates[5][3] = { { 0, 50, 0 }, { 0, 40, 0 }, { 0, 35, 0 }, { 0, 6, 0 }, { 0, 4, 0 } }; int fac_rate = 3; calfp(frates, fac_rate); return 0;}",
"e": 4796,
"s": 2070,
"text": null
},
{
"code": null,
"e": 4935,
"s": 4796,
"text": "Function Point Analysis :-\nUnadjusted Function Points (UFP) : 628\nComplexity Adjustment Factor (CAF) : 1.07\nFunction Points (FP) : 671.96\n"
},
{
"code": null,
"e": 4952,
"s": 4935,
"text": "chitrasingla2001"
},
{
"code": null,
"e": 4973,
"s": 4952,
"text": "Software Engineering"
},
{
"code": null,
"e": 5071,
"s": 4973,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5113,
"s": 5071,
"text": "Functional vs Non Functional Requirements"
},
{
"code": null,
"e": 5161,
"s": 5113,
"text": "Differences between Verification and Validation"
},
{
"code": null,
"e": 5193,
"s": 5161,
"text": "Unit Testing | Software Testing"
},
{
"code": null,
"e": 5242,
"s": 5193,
"text": "Software Engineering | Classical Waterfall Model"
},
{
"code": null,
"e": 5290,
"s": 5242,
"text": "Software Requirement Specification (SRS) Format"
},
{
"code": null,
"e": 5332,
"s": 5290,
"text": "Difference between Spring and Spring Boot"
},
{
"code": null,
"e": 5388,
"s": 5332,
"text": "Software Engineering | Requirements Engineering Process"
},
{
"code": null,
"e": 5423,
"s": 5388,
"text": "Software Testing Life Cycle (STLC)"
},
{
"code": null,
"e": 5462,
"s": 5423,
"text": "Difference between IAAS, PAAS and SAAS"
}
] |
matplotlib.pyplot.phase_spectrum() in Python
|
22 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.
The phase_spectrum() function in pyplot module of matplotlib library is used to plot the phase_spectrum. Generally, it compute the phase_spectrum of sequence and plotting is done.
Syntax: phase_spectrum(x, Fs=2, Fc=0, window=mlab.window_hanning, pad_to=None, sides=’default’, **kwargs)
Parameters: This method accept the following parameters that are described below:
x: This parameter is a sequence of data.
Fs : This parameter is a scalar. Its default value is 2.
window: This parameter take a data segment as an argument and return the windowed version of the segment. Its default value is window_hanning()
sides: This parameter specifies which sides of the spectrum to return. This can have following values : ‘default’, ‘onesided’ and ‘twosided’.
pad_to : This parameter contains the integer value to which the data segment is padded.
Fc: This parameter is also contains the integer value to offsets the x extents of the plot to reflect the frequency range. Its default value is 0
Returns: This returns the following:
spectrum :This returns the angle spectrum in radians.
freqs :This returns the frequencies corresponding to the elements in spectrum.
line : This returns the line created by this function.
The resultant is (spectrum, freqs, line)
Below examples illustrate the matplotlib.pyplot.phase_spectrum() function in matplotlib.pyplot:
Example-1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(10**5) dt = 0.0001Fs = 1 / dt geeks = np.array([24.40, 110.25, 20.05, 22.00, 61.90, 7.80, 15.00, 22.80, 34.90, 57.30]) nse = np.random.randn(len(geeks))r = np.exp(-geeks / 0.05) s = 0.1 * np.sin(2 * np.pi * geeks) + nse # plot phase_spectrumplt.phase_spectrum(s, Fs = Fs)plt.title('matplotlib.pyplot.phase_spectrum() function Example', fontweight ="bold") plt.show()
Output:
Example-2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(0) dt = 0.01Fs = 1 / dtt = np.arange(0, 10, dt)nse = np.random.randn(len(t))r = np.exp(-t / 0.05) cnse = np.convolve(nse, r)*dtcnse = cnse[:len(t)]s = 0.1 * np.sin(2 * np.pi * t) + cnse # plot simple spectrumplt.subplot(2, 1, 1)plt.plot(t, s)plt.title('matplotlib.pyplot.phase_spectrum() function Example', fontweight ="bold") plt.subplot(2, 1, 2)plt.phase_spectrum(s, Fs = Fs) plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 333,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc."
},
{
"code": null,
"e": 513,
"s": 333,
"text": "The phase_spectrum() function in pyplot module of matplotlib library is used to plot the phase_spectrum. Generally, it compute the phase_spectrum of sequence and plotting is done."
},
{
"code": null,
"e": 619,
"s": 513,
"text": "Syntax: phase_spectrum(x, Fs=2, Fc=0, window=mlab.window_hanning, pad_to=None, sides=’default’, **kwargs)"
},
{
"code": null,
"e": 701,
"s": 619,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 742,
"s": 701,
"text": "x: This parameter is a sequence of data."
},
{
"code": null,
"e": 799,
"s": 742,
"text": "Fs : This parameter is a scalar. Its default value is 2."
},
{
"code": null,
"e": 943,
"s": 799,
"text": "window: This parameter take a data segment as an argument and return the windowed version of the segment. Its default value is window_hanning()"
},
{
"code": null,
"e": 1085,
"s": 943,
"text": "sides: This parameter specifies which sides of the spectrum to return. This can have following values : ‘default’, ‘onesided’ and ‘twosided’."
},
{
"code": null,
"e": 1173,
"s": 1085,
"text": "pad_to : This parameter contains the integer value to which the data segment is padded."
},
{
"code": null,
"e": 1319,
"s": 1173,
"text": "Fc: This parameter is also contains the integer value to offsets the x extents of the plot to reflect the frequency range. Its default value is 0"
},
{
"code": null,
"e": 1356,
"s": 1319,
"text": "Returns: This returns the following:"
},
{
"code": null,
"e": 1410,
"s": 1356,
"text": "spectrum :This returns the angle spectrum in radians."
},
{
"code": null,
"e": 1489,
"s": 1410,
"text": "freqs :This returns the frequencies corresponding to the elements in spectrum."
},
{
"code": null,
"e": 1544,
"s": 1489,
"text": "line : This returns the line created by this function."
},
{
"code": null,
"e": 1585,
"s": 1544,
"text": "The resultant is (spectrum, freqs, line)"
},
{
"code": null,
"e": 1681,
"s": 1585,
"text": "Below examples illustrate the matplotlib.pyplot.phase_spectrum() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 1692,
"s": 1681,
"text": "Example-1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(10**5) dt = 0.0001Fs = 1 / dt geeks = np.array([24.40, 110.25, 20.05, 22.00, 61.90, 7.80, 15.00, 22.80, 34.90, 57.30]) nse = np.random.randn(len(geeks))r = np.exp(-geeks / 0.05) s = 0.1 * np.sin(2 * np.pi * geeks) + nse # plot phase_spectrumplt.phase_spectrum(s, Fs = Fs)plt.title('matplotlib.pyplot.phase_spectrum() function Example', fontweight =\"bold\") plt.show()",
"e": 2236,
"s": 1692,
"text": null
},
{
"code": null,
"e": 2244,
"s": 2236,
"text": "Output:"
},
{
"code": null,
"e": 2255,
"s": 2244,
"text": "Example-2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(0) dt = 0.01Fs = 1 / dtt = np.arange(0, 10, dt)nse = np.random.randn(len(t))r = np.exp(-t / 0.05) cnse = np.convolve(nse, r)*dtcnse = cnse[:len(t)]s = 0.1 * np.sin(2 * np.pi * t) + cnse # plot simple spectrumplt.subplot(2, 1, 1)plt.plot(t, s)plt.title('matplotlib.pyplot.phase_spectrum() function Example', fontweight =\"bold\") plt.subplot(2, 1, 2)plt.phase_spectrum(s, Fs = Fs) plt.show()",
"e": 2803,
"s": 2255,
"text": null
},
{
"code": null,
"e": 2811,
"s": 2803,
"text": "Output:"
},
{
"code": null,
"e": 2829,
"s": 2811,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2836,
"s": 2829,
"text": "Python"
},
{
"code": null,
"e": 2934,
"s": 2836,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2966,
"s": 2934,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2993,
"s": 2966,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3014,
"s": 2993,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3037,
"s": 3014,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3093,
"s": 3037,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3124,
"s": 3093,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3166,
"s": 3124,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3208,
"s": 3166,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3247,
"s": 3208,
"text": "Python | Get unique values from a list"
}
] |
GOCG13: Google’s Online Challenge Experience for Business Intern | Singapore
|
25 Oct, 2020
Google’s Business Internship is open to students from all academic disciplines. Many intern roles within this program don’t require technical skills and could include working with advertiser or publisher accounts to develop compelling advertising solutions for brand advertisers, improving access to relevant information for millions of internet users, analyzing large sets of data, or developing scalable support solutions for rapid-growth internally or externally.
As an intern, you will be working on projects with high impact during a 10-12 week paid, full-time internship. You will be assigned an intern manager who will help to identify project goals, inspire and mentor you, and support your professional development.
Format:
There was 12 Multiple Choice Question(MCQs) type questions.
These questions had to be solved within a duration of 30 minutes.
Topics involved: The topics revolved around General Cognitive Ability and Role Related Knowledge. Questions were given to test the problem-solving skills of a potential candidate. These questions involved Flow-Chart representations, Linear Algebra, Letter Coding, Logical Deductions, and Relationships.
Questions asked: Some of the questions asked revolved around the following scenarios:
Question on a Flow-Chart representation: The flowchart depicted the Ticket Management System of a customer. This question was to assess a candidate’s understanding of a given flowchart and to draw deductions from the same.Question-based on simple Linear Algebra: If P+ Q = 154 and P – Q = 62. Find the corresponding value of Q.Question on Letter Coding was there: If PENGUIN is written as PIUGNEN then what will ALBATROSS be written as?Question on work to be completed: If X(name) and Y(name) take N days to complete a given task and it is also noticed that Y is thrice as fast as X. How long will X take to finish the task alone?Questions on Assumptions were asked: If x were greater than 0, draw conclusions from the below statements:Statement 1: x5 - 32 = 0
Statement 2: x4 - 16 = 0
Options:Are both Statements required to prove the theory?Only statement 1 is enoughOnly statement 2 is enoughBoth statements are falseQuestion on Relationships: There are 7 people; Charlie, Robin, Alex, Taylor, Jamie, Joe, Bobby who visit parks around their area; Locust Park, Avenham Park, Grandlin Park, 32 Avenue Park, and Franklin Park not necessarily in the same order.Charlie visits Locust Park on Thursday, Bobby visits parks except on Sundays. Alex and Joe visit parks on Saturday and Tuesday respectively. Taylor visits the Avenham Park while Franklin Park is open on Mondays and Jamie does not visit Grandlin Park on Wednesday. Who visits Franklin Park?
Question on a Flow-Chart representation: The flowchart depicted the Ticket Management System of a customer. This question was to assess a candidate’s understanding of a given flowchart and to draw deductions from the same.
Question on a Flow-Chart representation: The flowchart depicted the Ticket Management System of a customer. This question was to assess a candidate’s understanding of a given flowchart and to draw deductions from the same.
Question-based on simple Linear Algebra: If P+ Q = 154 and P – Q = 62. Find the corresponding value of Q.
Question-based on simple Linear Algebra: If P+ Q = 154 and P – Q = 62. Find the corresponding value of Q.
Question on Letter Coding was there: If PENGUIN is written as PIUGNEN then what will ALBATROSS be written as?
Question on Letter Coding was there: If PENGUIN is written as PIUGNEN then what will ALBATROSS be written as?
Question on work to be completed: If X(name) and Y(name) take N days to complete a given task and it is also noticed that Y is thrice as fast as X. How long will X take to finish the task alone?
Question on work to be completed: If X(name) and Y(name) take N days to complete a given task and it is also noticed that Y is thrice as fast as X. How long will X take to finish the task alone?
Questions on Assumptions were asked: If x were greater than 0, draw conclusions from the below statements:Statement 1: x5 - 32 = 0
Statement 2: x4 - 16 = 0
Options:Are both Statements required to prove the theory?Only statement 1 is enoughOnly statement 2 is enoughBoth statements are false
Questions on Assumptions were asked: If x were greater than 0, draw conclusions from the below statements:
Statement 1: x5 - 32 = 0
Statement 2: x4 - 16 = 0
Options:
Are both Statements required to prove the theory?
Only statement 1 is enough
Only statement 2 is enough
Both statements are false
Question on Relationships: There are 7 people; Charlie, Robin, Alex, Taylor, Jamie, Joe, Bobby who visit parks around their area; Locust Park, Avenham Park, Grandlin Park, 32 Avenue Park, and Franklin Park not necessarily in the same order.Charlie visits Locust Park on Thursday, Bobby visits parks except on Sundays. Alex and Joe visit parks on Saturday and Tuesday respectively. Taylor visits the Avenham Park while Franklin Park is open on Mondays and Jamie does not visit Grandlin Park on Wednesday. Who visits Franklin Park?
Question on Relationships: There are 7 people; Charlie, Robin, Alex, Taylor, Jamie, Joe, Bobby who visit parks around their area; Locust Park, Avenham Park, Grandlin Park, 32 Avenue Park, and Franklin Park not necessarily in the same order.
Charlie visits Locust Park on Thursday, Bobby visits parks except on Sundays. Alex and Joe visit parks on Saturday and Tuesday respectively. Taylor visits the Avenham Park while Franklin Park is open on Mondays and Jamie does not visit Grandlin Park on Wednesday. Who visits Franklin Park?
And many more...
Note: The above-mentioned questions are not exactly similar to the ones asked in the test, these questions are to provide an idea as to what kind of questions might appear in the test.
Experience: I personally found the questions fairly simple and easy to understand and can easily be solved within the stipulated time duration.
Tips:
Prepare well for Logical Reasoning type of Questions. This includes Letter coding, Number patterns, Assumptions, Logical Deductions, and Relationships among various entities.
Keep a track of time and do not spend too much time on a question you are unsure about.
If you have a doubt in a particular question, visit the question once you have completed the remaining questions.
Google
Marketing
Interview Experiences
Google
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE 1
Amazon Interview Experience SDE-2 (3 Years Experienced)
Write It Up: Share Your Interview Experiences
Google SWE Interview Experience (Google Online Coding Challenge) 2022
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Nagarro Interview Experience | On-Campus 2021
Amazon Interview Experience for SDE-1
Nagarro Interview Experience
Tiger Analytics Interview Experience for Data Analyst (On-Campus)
Goldman Sachs Interview Experience for FTE ( On-Campus) Virtual 2021-22
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Oct, 2020"
},
{
"code": null,
"e": 495,
"s": 28,
"text": "Google’s Business Internship is open to students from all academic disciplines. Many intern roles within this program don’t require technical skills and could include working with advertiser or publisher accounts to develop compelling advertising solutions for brand advertisers, improving access to relevant information for millions of internet users, analyzing large sets of data, or developing scalable support solutions for rapid-growth internally or externally."
},
{
"code": null,
"e": 753,
"s": 495,
"text": "As an intern, you will be working on projects with high impact during a 10-12 week paid, full-time internship. You will be assigned an intern manager who will help to identify project goals, inspire and mentor you, and support your professional development."
},
{
"code": null,
"e": 761,
"s": 753,
"text": "Format:"
},
{
"code": null,
"e": 821,
"s": 761,
"text": "There was 12 Multiple Choice Question(MCQs) type questions."
},
{
"code": null,
"e": 887,
"s": 821,
"text": "These questions had to be solved within a duration of 30 minutes."
},
{
"code": null,
"e": 1191,
"s": 887,
"text": "Topics involved: The topics revolved around General Cognitive Ability and Role Related Knowledge. Questions were given to test the problem-solving skills of a potential candidate. These questions involved Flow-Chart representations, Linear Algebra, Letter Coding, Logical Deductions, and Relationships."
},
{
"code": null,
"e": 1277,
"s": 1191,
"text": "Questions asked: Some of the questions asked revolved around the following scenarios:"
},
{
"code": null,
"e": 2728,
"s": 1277,
"text": "Question on a Flow-Chart representation: The flowchart depicted the Ticket Management System of a customer. This question was to assess a candidate’s understanding of a given flowchart and to draw deductions from the same.Question-based on simple Linear Algebra: If P+ Q = 154 and P – Q = 62. Find the corresponding value of Q.Question on Letter Coding was there: If PENGUIN is written as PIUGNEN then what will ALBATROSS be written as?Question on work to be completed: If X(name) and Y(name) take N days to complete a given task and it is also noticed that Y is thrice as fast as X. How long will X take to finish the task alone?Questions on Assumptions were asked: If x were greater than 0, draw conclusions from the below statements:Statement 1: x5 - 32 = 0\nStatement 2: x4 - 16 = 0\nOptions:Are both Statements required to prove the theory?Only statement 1 is enoughOnly statement 2 is enoughBoth statements are falseQuestion on Relationships: There are 7 people; Charlie, Robin, Alex, Taylor, Jamie, Joe, Bobby who visit parks around their area; Locust Park, Avenham Park, Grandlin Park, 32 Avenue Park, and Franklin Park not necessarily in the same order.Charlie visits Locust Park on Thursday, Bobby visits parks except on Sundays. Alex and Joe visit parks on Saturday and Tuesday respectively. Taylor visits the Avenham Park while Franklin Park is open on Mondays and Jamie does not visit Grandlin Park on Wednesday. Who visits Franklin Park?"
},
{
"code": null,
"e": 2951,
"s": 2728,
"text": "Question on a Flow-Chart representation: The flowchart depicted the Ticket Management System of a customer. This question was to assess a candidate’s understanding of a given flowchart and to draw deductions from the same."
},
{
"code": null,
"e": 3174,
"s": 2951,
"text": "Question on a Flow-Chart representation: The flowchart depicted the Ticket Management System of a customer. This question was to assess a candidate’s understanding of a given flowchart and to draw deductions from the same."
},
{
"code": null,
"e": 3281,
"s": 3174,
"text": "Question-based on simple Linear Algebra: If P+ Q = 154 and P – Q = 62. Find the corresponding value of Q."
},
{
"code": null,
"e": 3388,
"s": 3281,
"text": "Question-based on simple Linear Algebra: If P+ Q = 154 and P – Q = 62. Find the corresponding value of Q."
},
{
"code": null,
"e": 3498,
"s": 3388,
"text": "Question on Letter Coding was there: If PENGUIN is written as PIUGNEN then what will ALBATROSS be written as?"
},
{
"code": null,
"e": 3608,
"s": 3498,
"text": "Question on Letter Coding was there: If PENGUIN is written as PIUGNEN then what will ALBATROSS be written as?"
},
{
"code": null,
"e": 3803,
"s": 3608,
"text": "Question on work to be completed: If X(name) and Y(name) take N days to complete a given task and it is also noticed that Y is thrice as fast as X. How long will X take to finish the task alone?"
},
{
"code": null,
"e": 3998,
"s": 3803,
"text": "Question on work to be completed: If X(name) and Y(name) take N days to complete a given task and it is also noticed that Y is thrice as fast as X. How long will X take to finish the task alone?"
},
{
"code": null,
"e": 4289,
"s": 3998,
"text": "Questions on Assumptions were asked: If x were greater than 0, draw conclusions from the below statements:Statement 1: x5 - 32 = 0\nStatement 2: x4 - 16 = 0\nOptions:Are both Statements required to prove the theory?Only statement 1 is enoughOnly statement 2 is enoughBoth statements are false"
},
{
"code": null,
"e": 4396,
"s": 4289,
"text": "Questions on Assumptions were asked: If x were greater than 0, draw conclusions from the below statements:"
},
{
"code": null,
"e": 4447,
"s": 4396,
"text": "Statement 1: x5 - 32 = 0\nStatement 2: x4 - 16 = 0\n"
},
{
"code": null,
"e": 4456,
"s": 4447,
"text": "Options:"
},
{
"code": null,
"e": 4506,
"s": 4456,
"text": "Are both Statements required to prove the theory?"
},
{
"code": null,
"e": 4533,
"s": 4506,
"text": "Only statement 1 is enough"
},
{
"code": null,
"e": 4560,
"s": 4533,
"text": "Only statement 2 is enough"
},
{
"code": null,
"e": 4586,
"s": 4560,
"text": "Both statements are false"
},
{
"code": null,
"e": 5116,
"s": 4586,
"text": "Question on Relationships: There are 7 people; Charlie, Robin, Alex, Taylor, Jamie, Joe, Bobby who visit parks around their area; Locust Park, Avenham Park, Grandlin Park, 32 Avenue Park, and Franklin Park not necessarily in the same order.Charlie visits Locust Park on Thursday, Bobby visits parks except on Sundays. Alex and Joe visit parks on Saturday and Tuesday respectively. Taylor visits the Avenham Park while Franklin Park is open on Mondays and Jamie does not visit Grandlin Park on Wednesday. Who visits Franklin Park?"
},
{
"code": null,
"e": 5357,
"s": 5116,
"text": "Question on Relationships: There are 7 people; Charlie, Robin, Alex, Taylor, Jamie, Joe, Bobby who visit parks around their area; Locust Park, Avenham Park, Grandlin Park, 32 Avenue Park, and Franklin Park not necessarily in the same order."
},
{
"code": null,
"e": 5647,
"s": 5357,
"text": "Charlie visits Locust Park on Thursday, Bobby visits parks except on Sundays. Alex and Joe visit parks on Saturday and Tuesday respectively. Taylor visits the Avenham Park while Franklin Park is open on Mondays and Jamie does not visit Grandlin Park on Wednesday. Who visits Franklin Park?"
},
{
"code": null,
"e": 5664,
"s": 5647,
"text": "And many more..."
},
{
"code": null,
"e": 5849,
"s": 5664,
"text": "Note: The above-mentioned questions are not exactly similar to the ones asked in the test, these questions are to provide an idea as to what kind of questions might appear in the test."
},
{
"code": null,
"e": 5993,
"s": 5849,
"text": "Experience: I personally found the questions fairly simple and easy to understand and can easily be solved within the stipulated time duration."
},
{
"code": null,
"e": 5999,
"s": 5993,
"text": "Tips:"
},
{
"code": null,
"e": 6174,
"s": 5999,
"text": "Prepare well for Logical Reasoning type of Questions. This includes Letter coding, Number patterns, Assumptions, Logical Deductions, and Relationships among various entities."
},
{
"code": null,
"e": 6262,
"s": 6174,
"text": "Keep a track of time and do not spend too much time on a question you are unsure about."
},
{
"code": null,
"e": 6376,
"s": 6262,
"text": "If you have a doubt in a particular question, visit the question once you have completed the remaining questions."
},
{
"code": null,
"e": 6383,
"s": 6376,
"text": "Google"
},
{
"code": null,
"e": 6393,
"s": 6383,
"text": "Marketing"
},
{
"code": null,
"e": 6415,
"s": 6393,
"text": "Interview Experiences"
},
{
"code": null,
"e": 6422,
"s": 6415,
"text": "Google"
},
{
"code": null,
"e": 6520,
"s": 6422,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6558,
"s": 6520,
"text": "Amazon Interview Experience for SDE 1"
},
{
"code": null,
"e": 6614,
"s": 6558,
"text": "Amazon Interview Experience SDE-2 (3 Years Experienced)"
},
{
"code": null,
"e": 6660,
"s": 6614,
"text": "Write It Up: Share Your Interview Experiences"
},
{
"code": null,
"e": 6730,
"s": 6660,
"text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022"
},
{
"code": null,
"e": 6803,
"s": 6730,
"text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022"
},
{
"code": null,
"e": 6849,
"s": 6803,
"text": "Nagarro Interview Experience | On-Campus 2021"
},
{
"code": null,
"e": 6887,
"s": 6849,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 6916,
"s": 6887,
"text": "Nagarro Interview Experience"
},
{
"code": null,
"e": 6982,
"s": 6916,
"text": "Tiger Analytics Interview Experience for Data Analyst (On-Campus)"
}
] |
How to check a variable is of function type using JavaScript ?
|
15 Apr, 2019
A function in JavaScript is the set of statements used to perform a specific task. A function can be either a named one or an anonymous one. The set of statements inside a function is executed when the function is invoked or called. A function can be assigned to a variable or passed to a method.
var gfg = function(){/* A set of statements */};
Here, an anonymous function is assigned to the variable named as ‘gfg’. There are various methods to check the variable is of function type or not. Some of them are discussed below:
Using instanceof operator: The instanceof operator checks the type of an object at run time. It return a corresponding boolean value, i.e, either true or false to indicate if the object is of a particular type or not.Example: This example uses instanceof operator to check a variable is of function type or not.<script> // Declare a variable and initialize it// with anonymous functionvar gfg = function(){/* A set of statements */}; // Function to check a variable is of// function type or notfunction testing(x) { if(x instanceof Function) { document.write("Variable is of function type"); } else { document.write("Variable is not of function type"); }} // Function calltesting(gfg); </script> Output:Variable is of function typeUsing Strict Equal (===) operator: In JavaScript, ‘===’ Operator is used to check whether two entities are of equal values as well as of equal type provides a boolean result. In this example, we use the ‘===’ operator. This operator, called the Strict Equal operator, checks if the operands are of the same type.Example: This example uses === operator to check a variable is of function type or not.<script> // Declare a variable and initialize it// with anonymous functionvar gfg = function(){/* A set of statements */}; // Function to check a variable is of// function type or notfunction testing(x){ if (typeof x === "function") { document.write("Variable is of function type"); } else { document.write("Variable is not of function type"); }} // Function calltesting(gfg); </script> Output:Variable is of function typeUsing object.prototype.toString: This method uses object.prototype.toString. Every object has a toString() method, which is called implicitly when a value of String type is expected. If the toString() method is not overridden, by default it returns ‘[object type]’ where ‘type’ is the object type.Example: This example uses object.prototype.toString operator to check a variable is of function type or not.<script> // Declare a variable and initialize it// with anonymous functionvar gfg = function(){/* A set of statements */}; // Function to check a variable is of// function type or notfunction testing(x){ if (Object.prototype.toString.call(x) == '[object Function]') { document.write("Variable is of function type"); } else { document.write("Variable is not of function type"); }} // Function calltesting(gfg); </script> Output:Variable is of function type
Using instanceof operator: The instanceof operator checks the type of an object at run time. It return a corresponding boolean value, i.e, either true or false to indicate if the object is of a particular type or not.Example: This example uses instanceof operator to check a variable is of function type or not.<script> // Declare a variable and initialize it// with anonymous functionvar gfg = function(){/* A set of statements */}; // Function to check a variable is of// function type or notfunction testing(x) { if(x instanceof Function) { document.write("Variable is of function type"); } else { document.write("Variable is not of function type"); }} // Function calltesting(gfg); </script> Output:Variable is of function type
Example: This example uses instanceof operator to check a variable is of function type or not.
<script> // Declare a variable and initialize it// with anonymous functionvar gfg = function(){/* A set of statements */}; // Function to check a variable is of// function type or notfunction testing(x) { if(x instanceof Function) { document.write("Variable is of function type"); } else { document.write("Variable is not of function type"); }} // Function calltesting(gfg); </script>
Output:
Variable is of function type
Using Strict Equal (===) operator: In JavaScript, ‘===’ Operator is used to check whether two entities are of equal values as well as of equal type provides a boolean result. In this example, we use the ‘===’ operator. This operator, called the Strict Equal operator, checks if the operands are of the same type.Example: This example uses === operator to check a variable is of function type or not.<script> // Declare a variable and initialize it// with anonymous functionvar gfg = function(){/* A set of statements */}; // Function to check a variable is of// function type or notfunction testing(x){ if (typeof x === "function") { document.write("Variable is of function type"); } else { document.write("Variable is not of function type"); }} // Function calltesting(gfg); </script> Output:Variable is of function type
Example: This example uses === operator to check a variable is of function type or not.
<script> // Declare a variable and initialize it// with anonymous functionvar gfg = function(){/* A set of statements */}; // Function to check a variable is of// function type or notfunction testing(x){ if (typeof x === "function") { document.write("Variable is of function type"); } else { document.write("Variable is not of function type"); }} // Function calltesting(gfg); </script>
Output:
Variable is of function type
Using object.prototype.toString: This method uses object.prototype.toString. Every object has a toString() method, which is called implicitly when a value of String type is expected. If the toString() method is not overridden, by default it returns ‘[object type]’ where ‘type’ is the object type.Example: This example uses object.prototype.toString operator to check a variable is of function type or not.<script> // Declare a variable and initialize it// with anonymous functionvar gfg = function(){/* A set of statements */}; // Function to check a variable is of// function type or notfunction testing(x){ if (Object.prototype.toString.call(x) == '[object Function]') { document.write("Variable is of function type"); } else { document.write("Variable is not of function type"); }} // Function calltesting(gfg); </script> Output:Variable is of function type
Example: This example uses object.prototype.toString operator to check a variable is of function type or not.
<script> // Declare a variable and initialize it// with anonymous functionvar gfg = function(){/* A set of statements */}; // Function to check a variable is of// function type or notfunction testing(x){ if (Object.prototype.toString.call(x) == '[object Function]') { document.write("Variable is of function type"); } else { document.write("Variable is not of function type"); }} // Function calltesting(gfg); </script>
Output:
Variable is of function type
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Apr, 2019"
},
{
"code": null,
"e": 325,
"s": 28,
"text": "A function in JavaScript is the set of statements used to perform a specific task. A function can be either a named one or an anonymous one. The set of statements inside a function is executed when the function is invoked or called. A function can be assigned to a variable or passed to a method."
},
{
"code": "var gfg = function(){/* A set of statements */};",
"e": 374,
"s": 325,
"text": null
},
{
"code": null,
"e": 556,
"s": 374,
"text": "Here, an anonymous function is assigned to the variable named as ‘gfg’. There are various methods to check the variable is of function type or not. Some of them are discussed below:"
},
{
"code": null,
"e": 3133,
"s": 556,
"text": "Using instanceof operator: The instanceof operator checks the type of an object at run time. It return a corresponding boolean value, i.e, either true or false to indicate if the object is of a particular type or not.Example: This example uses instanceof operator to check a variable is of function type or not.<script> // Declare a variable and initialize it// with anonymous functionvar gfg = function(){/* A set of statements */}; // Function to check a variable is of// function type or notfunction testing(x) { if(x instanceof Function) { document.write(\"Variable is of function type\"); } else { document.write(\"Variable is not of function type\"); }} // Function calltesting(gfg); </script> Output:Variable is of function typeUsing Strict Equal (===) operator: In JavaScript, ‘===’ Operator is used to check whether two entities are of equal values as well as of equal type provides a boolean result. In this example, we use the ‘===’ operator. This operator, called the Strict Equal operator, checks if the operands are of the same type.Example: This example uses === operator to check a variable is of function type or not.<script> // Declare a variable and initialize it// with anonymous functionvar gfg = function(){/* A set of statements */}; // Function to check a variable is of// function type or notfunction testing(x){ if (typeof x === \"function\") { document.write(\"Variable is of function type\"); } else { document.write(\"Variable is not of function type\"); }} // Function calltesting(gfg); </script> Output:Variable is of function typeUsing object.prototype.toString: This method uses object.prototype.toString. Every object has a toString() method, which is called implicitly when a value of String type is expected. If the toString() method is not overridden, by default it returns ‘[object type]’ where ‘type’ is the object type.Example: This example uses object.prototype.toString operator to check a variable is of function type or not.<script> // Declare a variable and initialize it// with anonymous functionvar gfg = function(){/* A set of statements */}; // Function to check a variable is of// function type or notfunction testing(x){ if (Object.prototype.toString.call(x) == '[object Function]') { document.write(\"Variable is of function type\"); } else { document.write(\"Variable is not of function type\"); }} // Function calltesting(gfg); </script> Output:Variable is of function type"
},
{
"code": null,
"e": 3922,
"s": 3133,
"text": "Using instanceof operator: The instanceof operator checks the type of an object at run time. It return a corresponding boolean value, i.e, either true or false to indicate if the object is of a particular type or not.Example: This example uses instanceof operator to check a variable is of function type or not.<script> // Declare a variable and initialize it// with anonymous functionvar gfg = function(){/* A set of statements */}; // Function to check a variable is of// function type or notfunction testing(x) { if(x instanceof Function) { document.write(\"Variable is of function type\"); } else { document.write(\"Variable is not of function type\"); }} // Function calltesting(gfg); </script> Output:Variable is of function type"
},
{
"code": null,
"e": 4017,
"s": 3922,
"text": "Example: This example uses instanceof operator to check a variable is of function type or not."
},
{
"code": "<script> // Declare a variable and initialize it// with anonymous functionvar gfg = function(){/* A set of statements */}; // Function to check a variable is of// function type or notfunction testing(x) { if(x instanceof Function) { document.write(\"Variable is of function type\"); } else { document.write(\"Variable is not of function type\"); }} // Function calltesting(gfg); </script> ",
"e": 4460,
"s": 4017,
"text": null
},
{
"code": null,
"e": 4468,
"s": 4460,
"text": "Output:"
},
{
"code": null,
"e": 4497,
"s": 4468,
"text": "Variable is of function type"
},
{
"code": null,
"e": 5374,
"s": 4497,
"text": "Using Strict Equal (===) operator: In JavaScript, ‘===’ Operator is used to check whether two entities are of equal values as well as of equal type provides a boolean result. In this example, we use the ‘===’ operator. This operator, called the Strict Equal operator, checks if the operands are of the same type.Example: This example uses === operator to check a variable is of function type or not.<script> // Declare a variable and initialize it// with anonymous functionvar gfg = function(){/* A set of statements */}; // Function to check a variable is of// function type or notfunction testing(x){ if (typeof x === \"function\") { document.write(\"Variable is of function type\"); } else { document.write(\"Variable is not of function type\"); }} // Function calltesting(gfg); </script> Output:Variable is of function type"
},
{
"code": null,
"e": 5462,
"s": 5374,
"text": "Example: This example uses === operator to check a variable is of function type or not."
},
{
"code": "<script> // Declare a variable and initialize it// with anonymous functionvar gfg = function(){/* A set of statements */}; // Function to check a variable is of// function type or notfunction testing(x){ if (typeof x === \"function\") { document.write(\"Variable is of function type\"); } else { document.write(\"Variable is not of function type\"); }} // Function calltesting(gfg); </script> ",
"e": 5905,
"s": 5462,
"text": null
},
{
"code": null,
"e": 5913,
"s": 5905,
"text": "Output:"
},
{
"code": null,
"e": 5942,
"s": 5913,
"text": "Variable is of function type"
},
{
"code": null,
"e": 6855,
"s": 5942,
"text": "Using object.prototype.toString: This method uses object.prototype.toString. Every object has a toString() method, which is called implicitly when a value of String type is expected. If the toString() method is not overridden, by default it returns ‘[object type]’ where ‘type’ is the object type.Example: This example uses object.prototype.toString operator to check a variable is of function type or not.<script> // Declare a variable and initialize it// with anonymous functionvar gfg = function(){/* A set of statements */}; // Function to check a variable is of// function type or notfunction testing(x){ if (Object.prototype.toString.call(x) == '[object Function]') { document.write(\"Variable is of function type\"); } else { document.write(\"Variable is not of function type\"); }} // Function calltesting(gfg); </script> Output:Variable is of function type"
},
{
"code": null,
"e": 6965,
"s": 6855,
"text": "Example: This example uses object.prototype.toString operator to check a variable is of function type or not."
},
{
"code": "<script> // Declare a variable and initialize it// with anonymous functionvar gfg = function(){/* A set of statements */}; // Function to check a variable is of// function type or notfunction testing(x){ if (Object.prototype.toString.call(x) == '[object Function]') { document.write(\"Variable is of function type\"); } else { document.write(\"Variable is not of function type\"); }} // Function calltesting(gfg); </script> ",
"e": 7437,
"s": 6965,
"text": null
},
{
"code": null,
"e": 7445,
"s": 7437,
"text": "Output:"
},
{
"code": null,
"e": 7474,
"s": 7445,
"text": "Variable is of function type"
},
{
"code": null,
"e": 7481,
"s": 7474,
"text": "Picked"
},
{
"code": null,
"e": 7492,
"s": 7481,
"text": "JavaScript"
},
{
"code": null,
"e": 7509,
"s": 7492,
"text": "Web Technologies"
},
{
"code": null,
"e": 7536,
"s": 7509,
"text": "Web technologies Questions"
}
] |
C Program for Identity Matrix
|
08 Jul, 2022
Introduction to Identity Matrix :
The dictionary definition of an Identity Matrix is a square matrix in which all the elements of the principal or main diagonal are 1’s and all other elements are zeros. In the below image, every matrix is an Identity Matrix.
In linear algebra, this is sometimes called as a Unit Matrix, of a square matrix (size = n x n) with ones on the main diagonal and zeros elsewhere. The identity matrix is denoted by “ I “. Sometimes U or E is also used to denote an Identity Matrix. A property of the identity matrix is that it leaves a matrix unchanged if it is multiplied by an Identity Matrix.
Examples:
Input : 2
Output : 1 0
0 1
Input : 4
Output : 1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
The explanation is simple. We need to make all
the elements of principal or main diagonal as
1 and everything else as 0.
Program to print Identity Matrix : The logic is simple. You need to the print 1 in those positions where row is equal to column of a matrix and make all other positions as 0.
C
// C program to print Identity Matrix#include<stdio.h> int Identity(int num){ int row, col; for (row = 0; row < num; row++) { for (col = 0; col < num; col++) { // Checking if row is equal to column if (row == col) printf("%d ", 1); else printf("%d ", 0); } printf("\n"); } return 0;} // Driver Codeint main(){ int size = 5; identity(size); return 0;}
Output:
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
Time complexity: O(n2) where n is number of rows and columns of matrix
Auxiliary Space: O(1)
kumargaurav97520
C Language
C Programs
Mathematical
Matrix
School Programming
Mathematical
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Operators in C / C++
Exception Handling in C++
Smart Pointers in C++ and How to Use Them
Strings in C
Arrow operator -> in C/C++ with Examples
Basics of File Handling in C
UDP Server-Client implementation in C
Header files in C/C++ and its uses
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 86,
"s": 52,
"text": "Introduction to Identity Matrix :"
},
{
"code": null,
"e": 314,
"s": 86,
"text": " The dictionary definition of an Identity Matrix is a square matrix in which all the elements of the principal or main diagonal are 1’s and all other elements are zeros. In the below image, every matrix is an Identity Matrix. "
},
{
"code": null,
"e": 677,
"s": 314,
"text": "In linear algebra, this is sometimes called as a Unit Matrix, of a square matrix (size = n x n) with ones on the main diagonal and zeros elsewhere. The identity matrix is denoted by “ I “. Sometimes U or E is also used to denote an Identity Matrix. A property of the identity matrix is that it leaves a matrix unchanged if it is multiplied by an Identity Matrix."
},
{
"code": null,
"e": 689,
"s": 677,
"text": "Examples: "
},
{
"code": null,
"e": 928,
"s": 689,
"text": "Input : 2\nOutput : 1 0\n 0 1\n\nInput : 4\nOutput : 1 0 0 0\n 0 1 0 0\n 0 0 1 0\n 0 0 0 1\nThe explanation is simple. We need to make all\nthe elements of principal or main diagonal as \n1 and everything else as 0."
},
{
"code": null,
"e": 1104,
"s": 928,
"text": "Program to print Identity Matrix : The logic is simple. You need to the print 1 in those positions where row is equal to column of a matrix and make all other positions as 0. "
},
{
"code": null,
"e": 1106,
"s": 1104,
"text": "C"
},
{
"code": "// C program to print Identity Matrix#include<stdio.h> int Identity(int num){ int row, col; for (row = 0; row < num; row++) { for (col = 0; col < num; col++) { // Checking if row is equal to column if (row == col) printf(\"%d \", 1); else printf(\"%d \", 0); } printf(\"\\n\"); } return 0;} // Driver Codeint main(){ int size = 5; identity(size); return 0;}",
"e": 1577,
"s": 1106,
"text": null
},
{
"code": null,
"e": 1586,
"s": 1577,
"text": "Output: "
},
{
"code": null,
"e": 1666,
"s": 1586,
"text": "1 0 0 0 0 \n0 1 0 0 0 \n0 0 1 0 0 \n0 0 0 1 0 \n0 0 0 0 1 "
},
{
"code": null,
"e": 1737,
"s": 1666,
"text": "Time complexity: O(n2) where n is number of rows and columns of matrix"
},
{
"code": null,
"e": 1759,
"s": 1737,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1776,
"s": 1759,
"text": "kumargaurav97520"
},
{
"code": null,
"e": 1787,
"s": 1776,
"text": "C Language"
},
{
"code": null,
"e": 1798,
"s": 1787,
"text": "C Programs"
},
{
"code": null,
"e": 1811,
"s": 1798,
"text": "Mathematical"
},
{
"code": null,
"e": 1818,
"s": 1811,
"text": "Matrix"
},
{
"code": null,
"e": 1837,
"s": 1818,
"text": "School Programming"
},
{
"code": null,
"e": 1850,
"s": 1837,
"text": "Mathematical"
},
{
"code": null,
"e": 1857,
"s": 1850,
"text": "Matrix"
},
{
"code": null,
"e": 1955,
"s": 1857,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2003,
"s": 1955,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2048,
"s": 2003,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 2069,
"s": 2048,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 2095,
"s": 2069,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 2137,
"s": 2095,
"text": "Smart Pointers in C++ and How to Use Them"
},
{
"code": null,
"e": 2150,
"s": 2137,
"text": "Strings in C"
},
{
"code": null,
"e": 2191,
"s": 2150,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 2220,
"s": 2191,
"text": "Basics of File Handling in C"
},
{
"code": null,
"e": 2258,
"s": 2220,
"text": "UDP Server-Client implementation in C"
}
] |
How to find the type of Struct in Golang?
|
05 May, 2020
A structure or struct in Golang is a user-defined data type which is a composition of various data fields. Each data field has its own data type, which can be a built-in or another user-defined type. Struct represents any real-world entity that has some set of properties/fields. Go does not support the concept of classes, structs are the only way to create a user-defined type in this language. There are various ways by which we can identify the type of struct in Go:
Method 1: Using reflect package
You can use the reflect package to find the given type of a struct. Reflection package allows determining the variables’ type at runtime.
Syntax:
func typeofstruct(x interface{}){
fmt.Println(reflect.TypeOf(x))
}
or
func typeofstruct(x interface{}){
fmt.Println(reflect.ValueOf(x).Kind())
}
Example:
package main // importing required modulesimport ( "fmt" "reflect") //struct Student definitiontype Student struct { name string rollno int phone int64 city string} func main() { // making a struct instance // note: data fields should be entered in the order // they are declared in the struct definition var st1 = Student{"Raman", 01, 88888888888, "Mumbai"} fmt.Println(reflect.TypeOf(st1)) fmt.Println(reflect.ValueOf(st1).Kind()) // Naming fields while // initializing a struct st2 := Student{name: "Naman", rollno: 02, phone: 1010101010, city: "Delhi"} fmt.Println(reflect.TypeOf(st2)) fmt.Println(reflect.ValueOf(st2).Kind())}
Output:
main.Student
struct
main.Student
struct
Method reflect.TypeOf returns main.Student type while the reflect.Kind returns a struct. It is because the method reflect.TypeOf returns a variable of type reflect.Type. reflect.Type contains all the information about the type that defines the variable that was passed, in this case, Student. The kind tells what this type is made initially of- a pointer, an int, a string, a struct, an interface, or another built-in data type. In our case, the type is a Student, and the kind is a struct.
Method 2: Using type assertions
Another way to check a struct’s type can be by using a type switch and doing several type assertions. A type switch uses several type assertions in series and runs the first matching type. In this switch, the case contains the type which is going to compare with the type present in the switch expression, and if none of the cases matches, then the default case is evaluated.
Syntax:
switch optstatement; typeswitchexpression{
case typelist 1: Statement..
case typelist 2: Statement..
...
default: Statement..
}
Example:
// Golang program to find a struct type// using type assertionspackage main import "fmt" // struct Employee definitiontype Employee struct { name string employee_id int} func Teststruct(x interface{}) { // type switch switch x.(type) { case Employee: fmt.Println("Employee type") case int: fmt.Println("int type") default: fmt.Println("Error") }} func main() { // Declaring and initializing a // struct using a struct literal t := Employee{"Ram", 1234} Teststruct(t)}
Output:
Employee type
Picked
Go Language
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 May, 2020"
},
{
"code": null,
"e": 499,
"s": 28,
"text": "A structure or struct in Golang is a user-defined data type which is a composition of various data fields. Each data field has its own data type, which can be a built-in or another user-defined type. Struct represents any real-world entity that has some set of properties/fields. Go does not support the concept of classes, structs are the only way to create a user-defined type in this language. There are various ways by which we can identify the type of struct in Go:"
},
{
"code": null,
"e": 531,
"s": 499,
"text": "Method 1: Using reflect package"
},
{
"code": null,
"e": 669,
"s": 531,
"text": "You can use the reflect package to find the given type of a struct. Reflection package allows determining the variables’ type at runtime."
},
{
"code": null,
"e": 677,
"s": 669,
"text": "Syntax:"
},
{
"code": null,
"e": 749,
"s": 677,
"text": "func typeofstruct(x interface{}){\n fmt.Println(reflect.TypeOf(x))\n}\n"
},
{
"code": null,
"e": 752,
"s": 749,
"text": "or"
},
{
"code": null,
"e": 832,
"s": 752,
"text": "func typeofstruct(x interface{}){\n fmt.Println(reflect.ValueOf(x).Kind())\n}\n"
},
{
"code": null,
"e": 841,
"s": 832,
"text": "Example:"
},
{
"code": "package main // importing required modulesimport ( \"fmt\" \"reflect\") //struct Student definitiontype Student struct { name string rollno int phone int64 city string} func main() { // making a struct instance // note: data fields should be entered in the order // they are declared in the struct definition var st1 = Student{\"Raman\", 01, 88888888888, \"Mumbai\"} fmt.Println(reflect.TypeOf(st1)) fmt.Println(reflect.ValueOf(st1).Kind()) // Naming fields while // initializing a struct st2 := Student{name: \"Naman\", rollno: 02, phone: 1010101010, city: \"Delhi\"} fmt.Println(reflect.TypeOf(st2)) fmt.Println(reflect.ValueOf(st2).Kind())}",
"e": 1548,
"s": 841,
"text": null
},
{
"code": null,
"e": 1556,
"s": 1548,
"text": "Output:"
},
{
"code": null,
"e": 1597,
"s": 1556,
"text": "main.Student\nstruct\nmain.Student\nstruct\n"
},
{
"code": null,
"e": 2088,
"s": 1597,
"text": "Method reflect.TypeOf returns main.Student type while the reflect.Kind returns a struct. It is because the method reflect.TypeOf returns a variable of type reflect.Type. reflect.Type contains all the information about the type that defines the variable that was passed, in this case, Student. The kind tells what this type is made initially of- a pointer, an int, a string, a struct, an interface, or another built-in data type. In our case, the type is a Student, and the kind is a struct."
},
{
"code": null,
"e": 2120,
"s": 2088,
"text": "Method 2: Using type assertions"
},
{
"code": null,
"e": 2496,
"s": 2120,
"text": "Another way to check a struct’s type can be by using a type switch and doing several type assertions. A type switch uses several type assertions in series and runs the first matching type. In this switch, the case contains the type which is going to compare with the type present in the switch expression, and if none of the cases matches, then the default case is evaluated."
},
{
"code": null,
"e": 2504,
"s": 2496,
"text": "Syntax:"
},
{
"code": null,
"e": 2633,
"s": 2504,
"text": "switch optstatement; typeswitchexpression{\ncase typelist 1: Statement..\ncase typelist 2: Statement..\n...\ndefault: Statement..\n}\n"
},
{
"code": null,
"e": 2642,
"s": 2633,
"text": "Example:"
},
{
"code": "// Golang program to find a struct type// using type assertionspackage main import \"fmt\" // struct Employee definitiontype Employee struct { name string employee_id int} func Teststruct(x interface{}) { // type switch switch x.(type) { case Employee: fmt.Println(\"Employee type\") case int: fmt.Println(\"int type\") default: fmt.Println(\"Error\") }} func main() { // Declaring and initializing a // struct using a struct literal t := Employee{\"Ram\", 1234} Teststruct(t)}",
"e": 3178,
"s": 2642,
"text": null
},
{
"code": null,
"e": 3186,
"s": 3178,
"text": "Output:"
},
{
"code": null,
"e": 3201,
"s": 3186,
"text": "Employee type\n"
},
{
"code": null,
"e": 3208,
"s": 3201,
"text": "Picked"
},
{
"code": null,
"e": 3220,
"s": 3208,
"text": "Go Language"
},
{
"code": null,
"e": 3236,
"s": 3220,
"text": "Write From Home"
}
] |
How to count number of distinct values per field/ key in MongoDB?
|
You can use the distinct command for this. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.distinctCountValuesDemo.insertOne({"StudentFirstName":"John","StudentFavouriteSubject":["C","C++","Java","MySQL","C","C++"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a39f193b406bd3df60e07")
}
> db.distinctCountValuesDemo.insertOne({"StudentFirstName":"Larry","StudentFavouriteSubject":["MongoDB","SQL Server"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a3a1193b406bd3df60e08")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.distinctCountValuesDemo.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c8a39f193b406bd3df60e07"),
"StudentFirstName" : "John",
"StudentFavouriteSubject" : [
"C",
"C++",
"Java",
"MySQL",
"C",
"C++"
]
}
{
"_id" : ObjectId("5c8a3a1193b406bd3df60e08"),
"StudentFirstName" : "Larry",
"StudentFavouriteSubject" : [
"MongoDB",
"SQL Server"
]
}
Here is the query to find a number of distinct values per field/key −
> db.distinctCountValuesDemo.distinct('StudentFavouriteSubject');
The following is the output −
[ "C", "C++", "Java", "MySQL", "MongoDB", "SQL Server" ]
Here is the query to find the length of the distinct value in the array −
> db.distinctCountValuesDemo.distinct('StudentFavouriteSubject').length;
The following is the output −
6
|
[
{
"code": null,
"e": 1368,
"s": 1187,
"text": "You can use the distinct command for this. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −"
},
{
"code": null,
"e": 1791,
"s": 1368,
"text": "> db.distinctCountValuesDemo.insertOne({\"StudentFirstName\":\"John\",\"StudentFavouriteSubject\":[\"C\",\"C++\",\"Java\",\"MySQL\",\"C\",\"C++\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8a39f193b406bd3df60e07\")\n}\n> db.distinctCountValuesDemo.insertOne({\"StudentFirstName\":\"Larry\",\"StudentFavouriteSubject\":[\"MongoDB\",\"SQL Server\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8a3a1193b406bd3df60e08\")\n}"
},
{
"code": null,
"e": 1889,
"s": 1791,
"text": "Display all documents from a collection with the help of find() method. The query is as follows −"
},
{
"code": null,
"e": 1935,
"s": 1889,
"text": "> db.distinctCountValuesDemo.find().pretty();"
},
{
"code": null,
"e": 1965,
"s": 1935,
"text": "The following is the output −"
},
{
"code": null,
"e": 2324,
"s": 1965,
"text": "{\n \"_id\" : ObjectId(\"5c8a39f193b406bd3df60e07\"),\n \"StudentFirstName\" : \"John\",\n \"StudentFavouriteSubject\" : [\n \"C\",\n \"C++\",\n \"Java\",\n \"MySQL\",\n \"C\",\n \"C++\"\n ]\n}\n{\n \"_id\" : ObjectId(\"5c8a3a1193b406bd3df60e08\"),\n \"StudentFirstName\" : \"Larry\",\n \"StudentFavouriteSubject\" : [\n \"MongoDB\",\n \"SQL Server\"\n ]\n}"
},
{
"code": null,
"e": 2394,
"s": 2324,
"text": "Here is the query to find a number of distinct values per field/key −"
},
{
"code": null,
"e": 2460,
"s": 2394,
"text": "> db.distinctCountValuesDemo.distinct('StudentFavouriteSubject');"
},
{
"code": null,
"e": 2490,
"s": 2460,
"text": "The following is the output −"
},
{
"code": null,
"e": 2547,
"s": 2490,
"text": "[ \"C\", \"C++\", \"Java\", \"MySQL\", \"MongoDB\", \"SQL Server\" ]"
},
{
"code": null,
"e": 2621,
"s": 2547,
"text": "Here is the query to find the length of the distinct value in the array −"
},
{
"code": null,
"e": 2694,
"s": 2621,
"text": "> db.distinctCountValuesDemo.distinct('StudentFavouriteSubject').length;"
},
{
"code": null,
"e": 2724,
"s": 2694,
"text": "The following is the output −"
},
{
"code": null,
"e": 2726,
"s": 2724,
"text": "6"
}
] |
List add(int index, E element) method in Java
|
11 Dec, 2018
The add(int index, E ele) method of List interface in Java is used to insert the specified element at the given index in the current list.
Syntax:
public void add(int index, E element)
Parameter: This method accepts two parameters as shown in the above syntax:
index: This parameter specifies the index at which we the given element is to be inserted.
element: This parameter specifies the element to insert in the list.
Return Value: The return type of the function is void and it does not returns anything.
Exceptions:
UnsupportedOperationException – It throws this exception if the add() operation is not supported by this list.
ClassCastException – It throws this exception if the class of the specified element prevents it from being added to this list.
NullPointerException – It throws this exception if the specified element is null and this list does not permit null elements.
IllegalArgumentException – It throws this exception if some property of this element prevents it from being added to this list.
Below programs illustrate the List.add(int index, E element) method:
Program 1:
// Java code to illustrate add(int index, E elements)import java.io.*;import java.util.*; public class ArrayListDemo { public static void main(String[] args) { // create an empty list with an initial capacity List<String> list = new ArrayList<String>(5); // use add() method to initially // add elements in the list list.add("Geeks"); list.add("For"); list.add("Geeks"); // Add a new element at index 0 list.add(0, "Hello"); // prints all the elements available in list for (String str : list) { System.out.print(str + " "); } }}
Hello Geeks For Geeks
Program 2:
// Java code to illustrate add(int index, E elements)import java.io.*;import java.util.*; public class ArrayListDemo { public static void main(String[] args) { // create an empty list with an initial capacity List<Integer> list = new ArrayList<Integer>(5); // use add() method to initially // add elements in the list list.add(10); list.add(20); list.add(30); // Add a new 25 at index 2 list.add(2, 25); // prints all the elements available in list for (Integer num : list) { System.out.print(num + " "); } }}
10 20 25 30
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#add(int, %20E)
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
HashMap in Java with Examples
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Stack Class in Java
Initialize an ArrayList in Java
Initializing a List in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "The add(int index, E ele) method of List interface in Java is used to insert the specified element at the given index in the current list."
},
{
"code": null,
"e": 175,
"s": 167,
"text": "Syntax:"
},
{
"code": null,
"e": 213,
"s": 175,
"text": "public void add(int index, E element)"
},
{
"code": null,
"e": 289,
"s": 213,
"text": "Parameter: This method accepts two parameters as shown in the above syntax:"
},
{
"code": null,
"e": 380,
"s": 289,
"text": "index: This parameter specifies the index at which we the given element is to be inserted."
},
{
"code": null,
"e": 449,
"s": 380,
"text": "element: This parameter specifies the element to insert in the list."
},
{
"code": null,
"e": 537,
"s": 449,
"text": "Return Value: The return type of the function is void and it does not returns anything."
},
{
"code": null,
"e": 549,
"s": 537,
"text": "Exceptions:"
},
{
"code": null,
"e": 660,
"s": 549,
"text": "UnsupportedOperationException – It throws this exception if the add() operation is not supported by this list."
},
{
"code": null,
"e": 787,
"s": 660,
"text": "ClassCastException – It throws this exception if the class of the specified element prevents it from being added to this list."
},
{
"code": null,
"e": 913,
"s": 787,
"text": "NullPointerException – It throws this exception if the specified element is null and this list does not permit null elements."
},
{
"code": null,
"e": 1041,
"s": 913,
"text": "IllegalArgumentException – It throws this exception if some property of this element prevents it from being added to this list."
},
{
"code": null,
"e": 1110,
"s": 1041,
"text": "Below programs illustrate the List.add(int index, E element) method:"
},
{
"code": null,
"e": 1121,
"s": 1110,
"text": "Program 1:"
},
{
"code": "// Java code to illustrate add(int index, E elements)import java.io.*;import java.util.*; public class ArrayListDemo { public static void main(String[] args) { // create an empty list with an initial capacity List<String> list = new ArrayList<String>(5); // use add() method to initially // add elements in the list list.add(\"Geeks\"); list.add(\"For\"); list.add(\"Geeks\"); // Add a new element at index 0 list.add(0, \"Hello\"); // prints all the elements available in list for (String str : list) { System.out.print(str + \" \"); } }}",
"e": 1764,
"s": 1121,
"text": null
},
{
"code": null,
"e": 1787,
"s": 1764,
"text": "Hello Geeks For Geeks\n"
},
{
"code": null,
"e": 1798,
"s": 1787,
"text": "Program 2:"
},
{
"code": "// Java code to illustrate add(int index, E elements)import java.io.*;import java.util.*; public class ArrayListDemo { public static void main(String[] args) { // create an empty list with an initial capacity List<Integer> list = new ArrayList<Integer>(5); // use add() method to initially // add elements in the list list.add(10); list.add(20); list.add(30); // Add a new 25 at index 2 list.add(2, 25); // prints all the elements available in list for (Integer num : list) { System.out.print(num + \" \"); } }}",
"e": 2422,
"s": 1798,
"text": null
},
{
"code": null,
"e": 2435,
"s": 2422,
"text": "10 20 25 30\n"
},
{
"code": null,
"e": 2523,
"s": 2435,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#add(int, %20E)"
},
{
"code": null,
"e": 2540,
"s": 2523,
"text": "Java-Collections"
},
{
"code": null,
"e": 2555,
"s": 2540,
"text": "Java-Functions"
},
{
"code": null,
"e": 2565,
"s": 2555,
"text": "java-list"
},
{
"code": null,
"e": 2570,
"s": 2565,
"text": "Java"
},
{
"code": null,
"e": 2575,
"s": 2570,
"text": "Java"
},
{
"code": null,
"e": 2592,
"s": 2575,
"text": "Java-Collections"
},
{
"code": null,
"e": 2690,
"s": 2592,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2709,
"s": 2690,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2739,
"s": 2709,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 2759,
"s": 2739,
"text": "Collections in Java"
},
{
"code": null,
"e": 2774,
"s": 2759,
"text": "Stream In Java"
},
{
"code": null,
"e": 2806,
"s": 2774,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 2830,
"s": 2806,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 2842,
"s": 2830,
"text": "Set in Java"
},
{
"code": null,
"e": 2862,
"s": 2842,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 2894,
"s": 2862,
"text": "Initialize an ArrayList in Java"
}
] |
GCD of two numbers when one of them can be very large
|
23 Jun, 2022
Given two numbers ‘a’ and ‘b’ such that (0 <= a <= 10^12 and b <= b < 10^250). Find the GCD of two given numbers.Examples :
Input: a = 978
b = 89798763754892653453379597352537489494736
Output: 6
Input: a = 1221
b = 1234567891011121314151617181920212223242526272829
Output: 3
Solution : In the given problem, we can see that first number ‘a’ can be handled by long long int data type but second number ‘b’ can not be handled by any int data type. Here we read second number as a string and we will try to make it less than and equal to ‘a’ by taking it’s modulo with ‘a’.Below is implementation of the above idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find GCD of two numbers such that// the second number can be very large.#include<bits/stdc++.h>using namespace std;typedef long long int ll; // function to find gcd of two integer numbersll gcd(ll a, ll b){ if (!a) return b; return gcd(b % a, a);} // Here 'a' is integer and 'b' is string.// The idea is to make the second number (represented// as b) less than and equal to first number by// calculating its mod with first integer number// using basic mathematicsll reduceB(ll a, char b[]){ // Initialize result ll mod = 0; // calculating mod of b with a to make // b like 0 <= b < a for (int i = 0; i < strlen(b); i++) mod = (mod * 10 + b[i] - '0') % a; return mod; // return modulo} // This function returns GCD of 'a' and 'b'// where b can be very large and is represented// as a character array or stringll gcdLarge(ll a, char b[]){ // Reduce 'b' (second number) after modulo with a ll num = reduceB(a, b); // gcd of two numbers return gcd(a, num);} // Driver programint main(){ // first number which is integer ll a = 1221; // second number is represented as string because // it can not be handled by integer data type char b[] = "1234567891011121314151617181920212223242526272829"; if (a == 0) cout << b << endl; else cout << gcdLarge(a, b) << endl; return 0;}
// Java program to find// GCD of two numbers// such that the second// number can be very large. class GFG{ // This function computes // the gcd of 2 numbers private static int gcd(int reduceNum, int b) { return b == 0 ? reduceNum : gcd(b, reduceNum % b); } // Here 'a' is integer and 'b' // is string. The idea is to make // the second number (represented // as b) less than and equal to // first number by calculating its // modulus with first integer // number using basic mathematics private static int reduceB(int a, String b) { int result = 0; for (int i = 0; i < b.length(); i++) { result = (result * 10 + b.charAt(i) - '0') % a; } return result; } private static int gcdLarge(int a, String b) { // Reduce 'b' i.e the second // number after modulo with a int num = reduceB(a, b); // Now,use the euclid's algorithm // to find the gcd of the 2 numbers return gcd(num, a); } // Driver code public static void main(String[] args) { // First Number which // is the integer int a = 1221; // Second Number is represented // as a string because it cannot // be represented as an integer // data type String b = "19837658191095787329"; if (a == 0) System.out.println(b); else System.out.println(gcdLarge(a, b)); } // This code is contributed// by Tanishq Saluja.}
# Python3 program to find GCD of# two numbers such that the second# number can be very large. # Function to find gcd# of two integer numbersdef gcd(a, b) : if (a == 0) : return b return gcd(b % a, a) # Here 'a' is integer and 'b' is string.# The idea is to make the second number# (represented as b) less than and equal# to first number by calculating its mod# with first integer number using basic# mathematicsdef reduceB(a, b) : # Initialize result mod = 0 # Calculating mod of b with a # to make b like 0 <= b < a for i in range(0, len(b)) : mod = (mod * 10 + ord(b[i])) % a return mod # return modulo # This function returns GCD of# 'a' and 'b' where b can be# very large and is represented# as a character array or stringdef gcdLarge(a, b) : # Reduce 'b' (second number) # after modulo with a num = reduceB(a, b) # gcd of two numbers return gcd(a, num) # Driver program # First number which is integera = 1221 # Second number is represented# as string because it can not# be handled by integer data typeb = "1234567891011121314151617181920212223242526272829"if a == 0: print(b)else: print(gcdLarge(a, b)) # This code is contributed by Nikita Tiwari.
// C# program to find GCD of// two numbers such that the// second number can be very large.using System; class GFG{// function to find gcd// of two integer numberspublic long gcd(long a, long b){ if (a == 0) return b; return gcd(b % a, a);} // Here 'a' is integer and// 'b' is string. The idea// is to make the second// number (represented as b)// less than and equal to// first number by calculating// its mod with first integer// number using basic mathematicspublic long reduceB(long a, string b){ // Initialize result long mod = 0; // calculating mod of // b with a to make // b like 0 <= b < a for (int i = 0; i < b.Length; i++) mod = (mod * 10 + (b[i] - '0')) % a; return mod;} // This function returns GCD// of 'a' and 'b' where b can// be very large and is// represented as a character// array or stringpublic long gcdLarge(long a, string b){ // Reduce 'b' (second number) // after modulo with a long num = reduceB(a, b); // gcd of two numbers return gcd(a, num);} // Driver Codestatic void Main(){ // first number // which is integer long a = 1221; // second number is represented // as string because it can not // be handled by integer data type string b = "1234567891011121314151617181920212223242526272829"; GFG p = new GFG(); if (a == 0) Console.WriteLine(b); else Console.WriteLine(p.gcdLarge(a, b)); }} // This code is contributed by mits.
<?php// PHP program to find GCD of// two numbers such that the// second number can be very large. // function to find gcd of// two integer numbersfunction gcd($a, $b){ if (!$a) return $b; return gcd($b % $a, $a);} // Here 'a' is integer and 'b'// is string. The idea is to// make the second number// (represented as b) less than// and equal to first number by// calculating its mod with first// integer number using basic mathematicsfunction reduceB($a, $b){ // Initialize result $mod = 0; // calculating mod of b with // a to make b like 0 <= b < a for ($i = 0; $i < strlen($b); $i++) $mod = ($mod * 10 + $b[$i] - '0') % $a; // return modulo return $mod;} // This function returns GCD of// 'a' and 'b' where b can be// very large and is represented// as a character array or stringfunction gcdLarge($a, $b){ // Reduce 'b' (second number) // after modulo with a $num = reduceB($a, $b); // gcd of two numbers return gcd($a, $num);} // Driver Code // first number which is integer$a = 1221; // second number is represented// as string because it can not// be handled by integer data type$b = "1234567891011121314151617181920212223242526272829"; if ($a == 0) { echo($b);}else { echo gcdLarge($a, $b);} // This code is contributed by nitin mittal.?>
<script> // JavaScript program to find GCD of two numbers such that// the second number can be very large. // function to find gcd of two integer numbersfunction gcd( a, b){ if (!a) return b; return gcd(b%a,a);} // Here 'a' is integer and 'b' is string.// The idea is to make the second number (represented// as b) less than and equal to first number by// calculating its mod with first integer number// using basic mathematicsfunction reduceB( a, b){ // Initialize result let mod = 0; // calculating mod of b with a to make // b like 0 <= b < a for (let i=0; i<b.length-1; i++) mod = (mod*10 + b[i] - '0')%a; return mod; // return modulo} // This function returns GCD of 'a' and 'b'// where b can be very large and is represented// as a character array or stringfunction gcdLarge( a, b){ // Reduce 'b' (second number) after modulo with a let num = reduceB(a, b); // gcd of two numbers return gcd(a, num);} // Driver program // first number which is integer let a = 1221; // second number is represented as string because // it can not be handled by integer data type let b = "1234567891011121314151617181920212223242526272829"; if (a == 0) document.write( b); else document.write(gcdLarge(a, b)); // This code contributed by aashish1995 </script>
3
Time Complexity: O(log (min(a,b))) Auxiliary Space: O(log (min(a,b)))
This article is contributed by Aarti_Rathi and Shashank Mishra (Gullu).This article is reviewed by team GeeksforGeeks . Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
Mithun Kumar
TanishqSaluja
urcoder4u
aashish1995
rushal06
codewithrathi
large-numbers
Modular Arithmetic
Mathematical
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Sieve of Eratosthenes
Prime Numbers
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
The Knight's tour problem | Backtracking-1
Algorithm to solve Rubik's Cube
Program for Decimal to Binary Conversion
Modulo 10^9+7 (1000000007)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 180,
"s": 54,
"text": "Given two numbers ‘a’ and ‘b’ such that (0 <= a <= 10^12 and b <= b < 10^250). Find the GCD of two given numbers.Examples : "
},
{
"code": null,
"e": 348,
"s": 180,
"text": "Input: a = 978 \n b = 89798763754892653453379597352537489494736\nOutput: 6\n\nInput: a = 1221 \n b = 1234567891011121314151617181920212223242526272829\nOutput: 3"
},
{
"code": null,
"e": 690,
"s": 350,
"text": "Solution : In the given problem, we can see that first number ‘a’ can be handled by long long int data type but second number ‘b’ can not be handled by any int data type. Here we read second number as a string and we will try to make it less than and equal to ‘a’ by taking it’s modulo with ‘a’.Below is implementation of the above idea. "
},
{
"code": null,
"e": 694,
"s": 690,
"text": "C++"
},
{
"code": null,
"e": 699,
"s": 694,
"text": "Java"
},
{
"code": null,
"e": 707,
"s": 699,
"text": "Python3"
},
{
"code": null,
"e": 710,
"s": 707,
"text": "C#"
},
{
"code": null,
"e": 714,
"s": 710,
"text": "PHP"
},
{
"code": null,
"e": 725,
"s": 714,
"text": "Javascript"
},
{
"code": "// C++ program to find GCD of two numbers such that// the second number can be very large.#include<bits/stdc++.h>using namespace std;typedef long long int ll; // function to find gcd of two integer numbersll gcd(ll a, ll b){ if (!a) return b; return gcd(b % a, a);} // Here 'a' is integer and 'b' is string.// The idea is to make the second number (represented// as b) less than and equal to first number by// calculating its mod with first integer number// using basic mathematicsll reduceB(ll a, char b[]){ // Initialize result ll mod = 0; // calculating mod of b with a to make // b like 0 <= b < a for (int i = 0; i < strlen(b); i++) mod = (mod * 10 + b[i] - '0') % a; return mod; // return modulo} // This function returns GCD of 'a' and 'b'// where b can be very large and is represented// as a character array or stringll gcdLarge(ll a, char b[]){ // Reduce 'b' (second number) after modulo with a ll num = reduceB(a, b); // gcd of two numbers return gcd(a, num);} // Driver programint main(){ // first number which is integer ll a = 1221; // second number is represented as string because // it can not be handled by integer data type char b[] = \"1234567891011121314151617181920212223242526272829\"; if (a == 0) cout << b << endl; else cout << gcdLarge(a, b) << endl; return 0;}",
"e": 2104,
"s": 725,
"text": null
},
{
"code": "// Java program to find// GCD of two numbers// such that the second// number can be very large. class GFG{ // This function computes // the gcd of 2 numbers private static int gcd(int reduceNum, int b) { return b == 0 ? reduceNum : gcd(b, reduceNum % b); } // Here 'a' is integer and 'b' // is string. The idea is to make // the second number (represented // as b) less than and equal to // first number by calculating its // modulus with first integer // number using basic mathematics private static int reduceB(int a, String b) { int result = 0; for (int i = 0; i < b.length(); i++) { result = (result * 10 + b.charAt(i) - '0') % a; } return result; } private static int gcdLarge(int a, String b) { // Reduce 'b' i.e the second // number after modulo with a int num = reduceB(a, b); // Now,use the euclid's algorithm // to find the gcd of the 2 numbers return gcd(num, a); } // Driver code public static void main(String[] args) { // First Number which // is the integer int a = 1221; // Second Number is represented // as a string because it cannot // be represented as an integer // data type String b = \"19837658191095787329\"; if (a == 0) System.out.println(b); else System.out.println(gcdLarge(a, b)); } // This code is contributed// by Tanishq Saluja.}",
"e": 3672,
"s": 2104,
"text": null
},
{
"code": "# Python3 program to find GCD of# two numbers such that the second# number can be very large. # Function to find gcd# of two integer numbersdef gcd(a, b) : if (a == 0) : return b return gcd(b % a, a) # Here 'a' is integer and 'b' is string.# The idea is to make the second number# (represented as b) less than and equal# to first number by calculating its mod# with first integer number using basic# mathematicsdef reduceB(a, b) : # Initialize result mod = 0 # Calculating mod of b with a # to make b like 0 <= b < a for i in range(0, len(b)) : mod = (mod * 10 + ord(b[i])) % a return mod # return modulo # This function returns GCD of# 'a' and 'b' where b can be# very large and is represented# as a character array or stringdef gcdLarge(a, b) : # Reduce 'b' (second number) # after modulo with a num = reduceB(a, b) # gcd of two numbers return gcd(a, num) # Driver program # First number which is integera = 1221 # Second number is represented# as string because it can not# be handled by integer data typeb = \"1234567891011121314151617181920212223242526272829\"if a == 0: print(b)else: print(gcdLarge(a, b)) # This code is contributed by Nikita Tiwari.",
"e": 4931,
"s": 3672,
"text": null
},
{
"code": "// C# program to find GCD of// two numbers such that the// second number can be very large.using System; class GFG{// function to find gcd// of two integer numberspublic long gcd(long a, long b){ if (a == 0) return b; return gcd(b % a, a);} // Here 'a' is integer and// 'b' is string. The idea// is to make the second// number (represented as b)// less than and equal to// first number by calculating// its mod with first integer// number using basic mathematicspublic long reduceB(long a, string b){ // Initialize result long mod = 0; // calculating mod of // b with a to make // b like 0 <= b < a for (int i = 0; i < b.Length; i++) mod = (mod * 10 + (b[i] - '0')) % a; return mod;} // This function returns GCD// of 'a' and 'b' where b can// be very large and is// represented as a character// array or stringpublic long gcdLarge(long a, string b){ // Reduce 'b' (second number) // after modulo with a long num = reduceB(a, b); // gcd of two numbers return gcd(a, num);} // Driver Codestatic void Main(){ // first number // which is integer long a = 1221; // second number is represented // as string because it can not // be handled by integer data type string b = \"1234567891011121314151617181920212223242526272829\"; GFG p = new GFG(); if (a == 0) Console.WriteLine(b); else Console.WriteLine(p.gcdLarge(a, b)); }} // This code is contributed by mits.",
"e": 6400,
"s": 4931,
"text": null
},
{
"code": "<?php// PHP program to find GCD of// two numbers such that the// second number can be very large. // function to find gcd of// two integer numbersfunction gcd($a, $b){ if (!$a) return $b; return gcd($b % $a, $a);} // Here 'a' is integer and 'b'// is string. The idea is to// make the second number// (represented as b) less than// and equal to first number by// calculating its mod with first// integer number using basic mathematicsfunction reduceB($a, $b){ // Initialize result $mod = 0; // calculating mod of b with // a to make b like 0 <= b < a for ($i = 0; $i < strlen($b); $i++) $mod = ($mod * 10 + $b[$i] - '0') % $a; // return modulo return $mod;} // This function returns GCD of// 'a' and 'b' where b can be// very large and is represented// as a character array or stringfunction gcdLarge($a, $b){ // Reduce 'b' (second number) // after modulo with a $num = reduceB($a, $b); // gcd of two numbers return gcd($a, $num);} // Driver Code // first number which is integer$a = 1221; // second number is represented// as string because it can not// be handled by integer data type$b = \"1234567891011121314151617181920212223242526272829\"; if ($a == 0) { echo($b);}else { echo gcdLarge($a, $b);} // This code is contributed by nitin mittal.?>",
"e": 7722,
"s": 6400,
"text": null
},
{
"code": "<script> // JavaScript program to find GCD of two numbers such that// the second number can be very large. // function to find gcd of two integer numbersfunction gcd( a, b){ if (!a) return b; return gcd(b%a,a);} // Here 'a' is integer and 'b' is string.// The idea is to make the second number (represented// as b) less than and equal to first number by// calculating its mod with first integer number// using basic mathematicsfunction reduceB( a, b){ // Initialize result let mod = 0; // calculating mod of b with a to make // b like 0 <= b < a for (let i=0; i<b.length-1; i++) mod = (mod*10 + b[i] - '0')%a; return mod; // return modulo} // This function returns GCD of 'a' and 'b'// where b can be very large and is represented// as a character array or stringfunction gcdLarge( a, b){ // Reduce 'b' (second number) after modulo with a let num = reduceB(a, b); // gcd of two numbers return gcd(a, num);} // Driver program // first number which is integer let a = 1221; // second number is represented as string because // it can not be handled by integer data type let b = \"1234567891011121314151617181920212223242526272829\"; if (a == 0) document.write( b); else document.write(gcdLarge(a, b)); // This code contributed by aashish1995 </script>",
"e": 9057,
"s": 7722,
"text": null
},
{
"code": null,
"e": 9059,
"s": 9057,
"text": "3"
},
{
"code": null,
"e": 9130,
"s": 9059,
"text": "Time Complexity: O(log (min(a,b))) Auxiliary Space: O(log (min(a,b))) "
},
{
"code": null,
"e": 9376,
"s": 9130,
"text": "This article is contributed by Aarti_Rathi and Shashank Mishra (Gullu).This article is reviewed by team GeeksforGeeks . Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 9389,
"s": 9376,
"text": "nitin mittal"
},
{
"code": null,
"e": 9402,
"s": 9389,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 9416,
"s": 9402,
"text": "TanishqSaluja"
},
{
"code": null,
"e": 9426,
"s": 9416,
"text": "urcoder4u"
},
{
"code": null,
"e": 9438,
"s": 9426,
"text": "aashish1995"
},
{
"code": null,
"e": 9447,
"s": 9438,
"text": "rushal06"
},
{
"code": null,
"e": 9461,
"s": 9447,
"text": "codewithrathi"
},
{
"code": null,
"e": 9475,
"s": 9461,
"text": "large-numbers"
},
{
"code": null,
"e": 9494,
"s": 9475,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 9507,
"s": 9494,
"text": "Mathematical"
},
{
"code": null,
"e": 9520,
"s": 9507,
"text": "Mathematical"
},
{
"code": null,
"e": 9539,
"s": 9520,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 9637,
"s": 9539,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9661,
"s": 9637,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 9682,
"s": 9661,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 9704,
"s": 9682,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 9718,
"s": 9704,
"text": "Prime Numbers"
},
{
"code": null,
"e": 9771,
"s": 9718,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 9808,
"s": 9771,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 9851,
"s": 9808,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 9883,
"s": 9851,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 9924,
"s": 9883,
"text": "Program for Decimal to Binary Conversion"
}
] |
Variational AutoEncoders
|
27 Jan, 2022
Variational autoencoder was proposed in 2013 by Knigma and Welling at Google and Qualcomm. A variational autoencoder (VAE) provides a probabilistic manner for describing an observation in latent space. Thus, rather than building an encoder that outputs a single value to describe each latent state attribute, we’ll formulate our encoder to describe a probability distribution for each latent attribute.
It has many applications such as data compression, synthetic data creation etc.
Architecture:
Autoencoders are a type of neural network that learns the data encodings from the dataset in an unsupervised way. It basically contains two parts: the first one is an encoder which is similar to the convolution neural network except for the last layer. The aim of the encoder to learn efficient data encoding from the dataset and pass it into a bottleneck architecture. The other part of the autoencoder is a decoder that uses latent space in the bottleneck layer to regenerate the images similar to the dataset. These results backpropagate from the neural network in the form of the loss function.
Variational autoencoder is different from autoencoder in a way such that it provides a statistic manner for describing the samples of the dataset in latent space. Therefore, in variational autoencoder, the encoder outputs a probability distribution in the bottleneck layer instead of a single output value.
Mathematics behind variational autoencoder:
Variational autoencoder uses KL-divergence as its loss function, the goal of this is to minimize the difference between a supposed distribution and original distribution of dataset.
Suppose we have a distribution z and we want to generate the observation x from it. In other words, we want to calculate
We can do it by following way:
But, the calculation of p(x) can be quite difficult
This usually makes it an intractable distribution. Hence, we need to approximate p(z|x) to q(z|x) to make it a tractable distribution. To better approximate p(z|x) to q(z|x), we will minimize the KL-divergence loss which calculates how similar two distributions are:
By simplifying, the above minimization problem is equivalent to the following maximization problem :
The first term represents the reconstruction likelihood and the other term ensures that our learned distribution q is similar to the true prior distribution p.
Thus our total loss consists of two terms, one is reconstruction error and other is KL-divergence loss:
Implementation:
In this implementation, we will be using the Fashion-MNIST dataset, this dataset is already available in keras.datasets API, so we don’t need to add or upload manually.
First, we need to import the necessary packages to our python environment. we will be using Keras package with tensorflow as a backend.
Code:
python3
# codeimport numpy as npimport tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras import Input, Modelfrom tensorflow.keras.layers import Layer, Conv2D, Flatten, Dense, Reshape, Conv2DTransposeimport matplotlib.pyplot as plt
For variational autoencoders, we need to define the architecture of two parts encoder and decoder but first, we will define the bottleneck layer of architecture, the sampling layer.
Code:
python3
# this sampling layer is the bottleneck layer of variational autoencoder,# it uses the output from two dense layers z_mean and z_log_var as input,# convert them into normal distribution and pass them to the decoder layerclass Sampling(Layer): def call(self, inputs): z_mean, z_log_var = inputs batch = tf.shape(z_mean)[0] dim = tf.shape(z_mean)[1] epsilon = tf.keras.backend.random_normal(shape =(batch, dim)) return z_mean + tf.exp(0.5 * z_log_var) * epsilon
Now, we define the architecture of encoder part of our autoencoder, this part takes images as input and encodes their representation in the Sampling layer.
Code:
python3
# Define Encoder Modellatent_dim = 2 encoder_inputs = Input(shape =(28, 28, 1))x = Conv2D(32, 3, activation ="relu", strides = 2, padding ="same")(encoder_inputs)x = Conv2D(64, 3, activation ="relu", strides = 2, padding ="same")(x)x = Flatten()(x)x = Dense(16, activation ="relu")(x)z_mean = Dense(latent_dim, name ="z_mean")(x)z_log_var = Dense(latent_dim, name ="z_log_var")(x)z = Sampling()([z_mean, z_log_var])encoder = Model(encoder_inputs, [z_mean, z_log_var, z], name ="encoder")encoder.summary()
Model: "encoder"
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
input_3 (InputLayer) [(None, 28, 28, 1)] 0
__________________________________________________________________________________________________
conv2d_2 (Conv2D) (None, 14, 14, 32) 320 input_3[0][0]
__________________________________________________________________________________________________
conv2d_3 (Conv2D) (None, 7, 7, 64) 18496 conv2d_2[0][0]
__________________________________________________________________________________________________
flatten_1 (Flatten) (None, 3136) 0 conv2d_3[0][0]
__________________________________________________________________________________________________
dense_2 (Dense) (None, 16) 50192 flatten_1[0][0]
__________________________________________________________________________________________________
z_mean (Dense) (None, 2) 34 dense_2[0][0]
__________________________________________________________________________________________________
z_log_var (Dense) (None, 2) 34 dense_2[0][0]
__________________________________________________________________________________________________
sampling_1 (Sampling) (None, 2) 0 z_mean[0][0]
z_log_var[0][0]
==================================================================================================
Total params: 69, 076
Trainable params: 69, 076
Non-trainable params: 0
__________________________________________________________________________________________________
Now, we define the architecture of decoder part of our autoencoder, this part takes the output of the sampling layer as input and output an image of size (28, 28, 1) .
Code:
python3
# Define Decoder Architecturelatent_inputs = keras.Input(shape =(latent_dim, ))x = Dense(7 * 7 * 64, activation ="relu")(latent_inputs)x = Reshape((7, 7, 64))(x)x = Conv2DTranspose(64, 3, activation ="relu", strides = 2, padding ="same")(x)x = Conv2DTranspose(32, 3, activation ="relu", strides = 2, padding ="same")(x)decoder_outputs = Conv2DTranspose(1, 3, activation ="sigmoid", padding ="same")(x)decoder = Model(latent_inputs, decoder_outputs, name ="decoder")decoder.summary()
Model: "decoder"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_4 (InputLayer) [(None, 2)] 0
_________________________________________________________________
dense_3 (Dense) (None, 3136) 9408
_________________________________________________________________
reshape_1 (Reshape) (None, 7, 7, 64) 0
_________________________________________________________________
conv2d_transpose_3 (Conv2DTr (None, 14, 14, 64) 36928
_________________________________________________________________
conv2d_transpose_4 (Conv2DTr (None, 28, 28, 32) 18464
_________________________________________________________________
conv2d_transpose_5 (Conv2DTr (None, 28, 28, 1) 289
=================================================================
Total params: 65, 089
Trainable params: 65, 089
Non-trainable params: 0
_________________________________________________________________
In this step, we combine the model and define the training procedure with loss functions.
Code:
python3
# this class takes encoder and decoder models and# define the complete variational autoencoder architectureclass VAE(keras.Model): def __init__(self, encoder, decoder, **kwargs): super(VAE, self).__init__(**kwargs) self.encoder = encoder self.decoder = decoder def train_step(self, data): if isinstance(data, tuple): data = data[0] with tf.GradientTape() as tape: z_mean, z_log_var, z = encoder(data) reconstruction = decoder(z) reconstruction_loss = tf.reduce_mean( keras.losses.binary_crossentropy(data, reconstruction) ) reconstruction_loss *= 28 * 28 kl_loss = 1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var) kl_loss = tf.reduce_mean(kl_loss) kl_loss *= -0.5 total_loss = reconstruction_loss + kl_loss grads = tape.gradient(total_loss, self.trainable_weights) self.optimizer.apply_gradients(zip(grads, self.trainable_weights)) return { "loss": total_loss, "reconstruction_loss": reconstruction_loss, "kl_loss": kl_loss, }
Now it’s the right time to train our variational autoencoder model, we will train it for 100 epochs. But first we need to import the fashion MNIST dataset.
Code:
python3
# load fashion mnist dataset from keras.dataset API(x_train, _), (x_test, _) = keras.datasets.fashion_mnist.load_data()fmnist_images = np.concatenate([x_train, x_test], axis = 0)# expand dimension to add a color map dimensionfmnist_images = np.expand_dims(fmnist_images, -1).astype("float32") / 255 # compile and train the modelvae = VAE(encoder, decoder)vae.compile(optimizer ='rmsprop')vae.fit(fmnist_images, epochs = 100, batch_size = 64)
Epoch 1/100
1094/1094 [==============================] - 7s 6ms/step - loss: 301.9441 - reconstruction_loss: 298.3138 - kl_loss: 3.6303
Epoch 2/100
1094/1094 [==============================] - 7s 6ms/step - loss: 273.5940 - reconstruction_loss: 270.0484 - kl_loss: 3.5456
Epoch 3/100
1094/1094 [==============================] - 7s 6ms/step - loss: 269.3337 - reconstruction_loss: 265.9077 - kl_loss: 3.4260
Epoch 4/100
1094/1094 [==============================] - 7s 6ms/step - loss: 266.8168 - reconstruction_loss: 263.4100 - kl_loss: 3.4068
Epoch 5/100
1094/1094 [==============================] - 7s 6ms/step - loss: 264.9917 - reconstruction_loss: 261.5603 - kl_loss: 3.4314
Epoch 6/100
1094/1094 [==============================] - 7s 6ms/step - loss: 263.5237 - reconstruction_loss: 260.0712 - kl_loss: 3.4525
Epoch 7/100
1094/1094 [==============================] - 7s 6ms/step - loss: 262.3414 - reconstruction_loss: 258.8548 - kl_loss: 3.4865
Epoch 8/100
1094/1094 [==============================] - 7s 6ms/step - loss: 261.4241 - reconstruction_loss: 257.9104 - kl_loss: 3.5137
Epoch 9/100
1094/1094 [==============================] - 7s 6ms/step - loss: 260.6090 - reconstruction_loss: 257.0662 - kl_loss: 3.5428
Epoch 10/100
1094/1094 [==============================] - 7s 6ms/step - loss: 259.9735 - reconstruction_loss: 256.4075 - kl_loss: 3.5660
Epoch 11/100
1094/1094 [==============================] - 7s 6ms/step - loss: 259.4184 - reconstruction_loss: 255.8348 - kl_loss: 3.5836
Epoch 12/100
1094/1094 [==============================] - 7s 6ms/step - loss: 258.9688 - reconstruction_loss: 255.3724 - kl_loss: 3.5964
Epoch 13/100
1094/1094 [==============================] - 7s 6ms/step - loss: 258.5413 - reconstruction_loss: 254.9356 - kl_loss: 3.6057
Epoch 14/100
1094/1094 [==============================] - 7s 6ms/step - loss: 258.2400 - reconstruction_loss: 254.6236 - kl_loss: 3.6163
Epoch 15/100
1094/1094 [==============================] - 7s 6ms/step - loss: 257.9335 - reconstruction_loss: 254.3038 - kl_loss: 3.6298
Epoch 16/100
1094/1094 [==============================] - 7s 6ms/step - loss: 257.6331 - reconstruction_loss: 253.9993 - kl_loss: 3.6339
Epoch 17/100
1094/1094 [==============================] - 7s 6ms/step - loss: 257.4199 - reconstruction_loss: 253.7707 - kl_loss: 3.6492
Epoch 18/100
1094/1094 [==============================] - 6s 6ms/step - loss: 257.1951 - reconstruction_loss: 253.5309 - kl_loss: 3.6643
Epoch 19/100
1094/1094 [==============================] - 7s 6ms/step - loss: 256.9326 - reconstruction_loss: 253.2723 - kl_loss: 3.6604
Epoch 20/100
1094/1094 [==============================] - 7s 6ms/step - loss: 256.7551 - reconstruction_loss: 253.0836 - kl_loss: 3.6715
Epoch 21/100
1094/1094 [==============================] - 7s 6ms/step - loss: 256.5663 - reconstruction_loss: 252.8877 - kl_loss: 3.6786
Epoch 22/100
1094/1094 [==============================] - 7s 6ms/step - loss: 256.4068 - reconstruction_loss: 252.7112 - kl_loss: 3.6956
Epoch 23/100
1094/1094 [==============================] - 7s 6ms/step - loss: 256.2588 - reconstruction_loss: 252.5588 - kl_loss: 3.7000
Epoch 24/100
1094/1094 [==============================] - 7s 6ms/step - loss: 256.0853 - reconstruction_loss: 252.3794 - kl_loss: 3.7059
Epoch 25/100
1094/1094 [==============================] - 7s 6ms/step - loss: 255.9321 - reconstruction_loss: 252.2201 - kl_loss: 3.7120
Epoch 26/100
1094/1094 [==============================] - 7s 6ms/step - loss: 255.7962 - reconstruction_loss: 252.0814 - kl_loss: 3.7148
Epoch 27/100
1094/1094 [==============================] - 7s 6ms/step - loss: 255.6953 - reconstruction_loss: 251.9673 - kl_loss: 3.7280
Epoch 28/100
1094/1094 [==============================] - 7s 6ms/step - loss: 255.5534 - reconstruction_loss: 251.8248 - kl_loss: 3.7287
Epoch 29/100
1094/1094 [==============================] - 7s 6ms/step - loss: 255.4437 - reconstruction_loss: 251.7134 - kl_loss: 3.7303
Epoch 30/100
1094/1094 [==============================] - 7s 6ms/step - loss: 255.3439 - reconstruction_loss: 251.6064 - kl_loss: 3.7375
Epoch 31/100
1094/1094 [==============================] - 7s 6ms/step - loss: 255.2326 - reconstruction_loss: 251.5018 - kl_loss: 3.7308
Epoch 32/100
1094/1094 [==============================] - 7s 6ms/step - loss: 255.1356 - reconstruction_loss: 251.3933 - kl_loss: 3.7423
Epoch 33/100
1094/1094 [==============================] - 7s 6ms/step - loss: 255.0660 - reconstruction_loss: 251.3224 - kl_loss: 3.7436
Epoch 34/100
1094/1094 [==============================] - 7s 6ms/step - loss: 254.9977 - reconstruction_loss: 251.2449 - kl_loss: 3.7528
Epoch 35/100
1094/1094 [==============================] - 7s 6ms/step - loss: 254.8857 - reconstruction_loss: 251.1363 - kl_loss: 3.7494
Epoch 36/100
1094/1094 [==============================] - 7s 6ms/step - loss: 254.7980 - reconstruction_loss: 251.0481 - kl_loss: 3.7499
Epoch 37/100
1094/1094 [==============================] - 7s 6ms/step - loss: 254.7485 - reconstruction_loss: 250.9851 - kl_loss: 3.7634
Epoch 38/100
1094/1094 [==============================] - 7s 6ms/step - loss: 254.6701 - reconstruction_loss: 250.9049 - kl_loss: 3.7652
Epoch 39/100
1094/1094 [==============================] - 6s 6ms/step - loss: 254.6105 - reconstruction_loss: 250.8389 - kl_loss: 3.7716
Epoch 40/100
1094/1094 [==============================] - 7s 6ms/step - loss: 254.4979 - reconstruction_loss: 250.7333 - kl_loss: 3.7646
Epoch 41/100
1094/1094 [==============================] - 7s 6ms/step - loss: 254.4734 - reconstruction_loss: 250.7037 - kl_loss: 3.7697
Epoch 42/100
1094/1094 [==============================] - 7s 6ms/step - loss: 254.4408 - reconstruction_loss: 250.6576 - kl_loss: 3.7831
Epoch 43/100
1094/1094 [==============================] - 7s 6ms/step - loss: 254.3272 - reconstruction_loss: 250.5562 - kl_loss: 3.7711
Epoch 44/100
1094/1094 [==============================] - 7s 6ms/step - loss: 254.3110 - reconstruction_loss: 250.5354 - kl_loss: 3.7755
Epoch 45/100
1094/1094 [==============================] - 7s 6ms/step - loss: 254.1982 - reconstruction_loss: 250.4256 - kl_loss: 3.7726
Epoch 46/100
1094/1094 [==============================] - 7s 6ms/step - loss: 254.1655 - reconstruction_loss: 250.3795 - kl_loss: 3.7860
Epoch 47/100
1094/1094 [==============================] - 7s 6ms/step - loss: 254.0979 - reconstruction_loss: 250.3105 - kl_loss: 3.7875
Epoch 48/100
1094/1094 [==============================] - 7s 6ms/step - loss: 254.0801 - reconstruction_loss: 250.2973 - kl_loss: 3.7828
Epoch 49/100
1094/1094 [==============================] - 7s 6ms/step - loss: 254.0101 - reconstruction_loss: 250.2270 - kl_loss: 3.7831
Epoch 50/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.9512 - reconstruction_loss: 250.1681 - kl_loss: 3.7831
Epoch 51/100
1094/1094 [==============================] - 7s 7ms/step - loss: 253.9307 - reconstruction_loss: 250.1408 - kl_loss: 3.7899
Epoch 52/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.8858 - reconstruction_loss: 250.1059 - kl_loss: 3.7800
Epoch 53/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.8118 - reconstruction_loss: 250.0236 - kl_loss: 3.7882
Epoch 54/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.8171 - reconstruction_loss: 250.0325 - kl_loss: 3.7845
Epoch 55/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.7622 - reconstruction_loss: 249.9735 - kl_loss: 3.7887
Epoch 56/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.7338 - reconstruction_loss: 249.9380 - kl_loss: 3.7959
Epoch 57/100
1094/1094 [==============================] - 6s 6ms/step - loss: 253.6761 - reconstruction_loss: 249.8792 - kl_loss: 3.7969
Epoch 58/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.6236 - reconstruction_loss: 249.8283 - kl_loss: 3.7954
Epoch 59/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.6181 - reconstruction_loss: 249.8236 - kl_loss: 3.7945
Epoch 60/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.5509 - reconstruction_loss: 249.7587 - kl_loss: 3.7921
Epoch 61/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.5124 - reconstruction_loss: 249.7126 - kl_loss: 3.7998
Epoch 62/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.4739 - reconstruction_loss: 249.6683 - kl_loss: 3.8056
Epoch 63/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.4609 - reconstruction_loss: 249.6567 - kl_loss: 3.8042
Epoch 64/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.4066 - reconstruction_loss: 249.6020 - kl_loss: 3.8045
Epoch 65/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.3578 - reconstruction_loss: 249.5580 - kl_loss: 3.7998
Epoch 66/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.3728 - reconstruction_loss: 249.5609 - kl_loss: 3.8118
Epoch 67/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.3523 - reconstruction_loss: 249.5351 - kl_loss: 3.8171
Epoch 68/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.2646 - reconstruction_loss: 249.4452 - kl_loss: 3.8194
Epoch 69/100
1094/1094 [==============================] - 6s 6ms/step - loss: 253.2642 - reconstruction_loss: 249.4603 - kl_loss: 3.8040
Epoch 70/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.2227 - reconstruction_loss: 249.4159 - kl_loss: 3.8068
Epoch 71/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.1848 - reconstruction_loss: 249.3755 - kl_loss: 3.8094
Epoch 72/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.1812 - reconstruction_loss: 249.3737 - kl_loss: 3.8074
Epoch 73/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.1803 - reconstruction_loss: 249.3743 - kl_loss: 3.8059
Epoch 74/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.1295 - reconstruction_loss: 249.3114 - kl_loss: 3.8181
Epoch 75/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.0516 - reconstruction_loss: 249.2391 - kl_loss: 3.8125
Epoch 76/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.0736 - reconstruction_loss: 249.2582 - kl_loss: 3.8154
Epoch 77/100
1094/1094 [==============================] - 6s 6ms/step - loss: 253.0331 - reconstruction_loss: 249.2200 - kl_loss: 3.8131
Epoch 78/100
1094/1094 [==============================] - 7s 6ms/step - loss: 253.0479 - reconstruction_loss: 249.2272 - kl_loss: 3.8207
Epoch 79/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.9317 - reconstruction_loss: 249.1137 - kl_loss: 3.8179
Epoch 80/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.9578 - reconstruction_loss: 249.1483 - kl_loss: 3.8095
Epoch 81/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.9072 - reconstruction_loss: 249.0963 - kl_loss: 3.8109
Epoch 82/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.8793 - reconstruction_loss: 249.0646 - kl_loss: 3.8147
Epoch 83/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.8914 - reconstruction_loss: 249.0676 - kl_loss: 3.8238
Epoch 84/100
1094/1094 [==============================] - 6s 6ms/step - loss: 252.8365 - reconstruction_loss: 249.0121 - kl_loss: 3.8244
Epoch 85/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.8063 - reconstruction_loss: 248.9844 - kl_loss: 3.8218
Epoch 86/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.7960 - reconstruction_loss: 248.9777 - kl_loss: 3.8183
Epoch 87/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.7733 - reconstruction_loss: 248.9529 - kl_loss: 3.8204
Epoch 88/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.7303 - reconstruction_loss: 248.9055 - kl_loss: 3.8248
Epoch 89/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.7225 - reconstruction_loss: 248.8902 - kl_loss: 3.8323
Epoch 90/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.6822 - reconstruction_loss: 248.8549 - kl_loss: 3.8273
Epoch 91/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.6540 - reconstruction_loss: 248.8314 - kl_loss: 3.8227
Epoch 92/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.6540 - reconstruction_loss: 248.8239 - kl_loss: 3.8300
Epoch 93/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.6213 - reconstruction_loss: 248.7778 - kl_loss: 3.8435
Epoch 94/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.5990 - reconstruction_loss: 248.7594 - kl_loss: 3.8397
Epoch 95/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.5786 - reconstruction_loss: 248.7413 - kl_loss: 3.8373
Epoch 96/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.5839 - reconstruction_loss: 248.7411 - kl_loss: 3.8427
Epoch 97/100
1094/1094 [==============================] - 7s 7ms/step - loss: 252.5364 - reconstruction_loss: 248.6960 - kl_loss: 3.8404
Epoch 98/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.5347 - reconstruction_loss: 248.6915 - kl_loss: 3.8431
Epoch 99/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.4996 - reconstruction_loss: 248.6569 - kl_loss: 3.8428
Epoch 100/100
1094/1094 [==============================] - 7s 6ms/step - loss: 252.4938 - reconstruction_loss: 248.6405 - kl_loss: 3.8533
<tensorflow.python.keras.callbacks.History at 0x7f5467c56be0>
In this step, we display training results, we will be displaying these results according to their values in latent space vectors.
Code:
python3
def plot_latent(encoder, decoder): # display a n * n 2D manifold of images n = 10 img_dim = 28 scale = 2.0 figsize = 15 figure = np.zeros((img_dim * n, img_dim * n)) # linearly spaced coordinates corresponding to the 2D plot # of images classes in the latent space grid_x = np.linspace(-scale, scale, n) grid_y = np.linspace(-scale, scale, n)[::-1] for i, yi in enumerate(grid_y): for j, xi in enumerate(grid_x): z_sample = np.array([[xi, yi]]) x_decoded = decoder.predict(z_sample) images = x_decoded[0].reshape(img_dim, img_dim) figure[ i * img_dim : (i + 1) * img_dim, j * img_dim : (j + 1) * img_dim, ] = images plt.figure(figsize =(figsize, figsize)) start_range = img_dim // 2 end_range = n * img_dim + start_range + 1 pixel_range = np.arange(start_range, end_range, img_dim) sample_range_x = np.round(grid_x, 1) sample_range_y = np.round(grid_y, 1) plt.xticks(pixel_range, sample_range_x) plt.yticks(pixel_range, sample_range_y) plt.xlabel("z[0]") plt.ylabel("z[1]") plt.imshow(figure, cmap ="Greys_r") plt.show() plot_latent(encoder, decoder)
To get a more clear view of our representational latent vectors values, we will be plotting the scatter plot of training data on the basis of their values of corresponding latent dimensions generated from the encoder .
Code:
python3
def plot_label_clusters(encoder, decoder, data, test_lab): z_mean, _, _ = encoder.predict(data) plt.figure(figsize =(12, 10)) sc = plt.scatter(z_mean[:, 0], z_mean[:, 1], c = test_lab) cbar = plt.colorbar(sc, ticks = range(10)) cbar.ax.set_yticklabels([labels.get(i) for i in range(10)]) plt.xlabel("z[0]") plt.ylabel("z[1]") plt.show() labels = {0 :"T-shirt / top",1: "Trouser",2: "Pullover",3: "Dress",4: "Coat",5: "Sandal",6: "Shirt",7: "Sneaker",8: "Bag",9: "Ankle boot"} (x_train, y_train), _ = keras.datasets.fashion_mnist.load_data()x_train = np.expand_dims(x_train, -1).astype("float32") / 255plot_label_clusters(encoder, decoder, x_train, y_train)
References:
Variational Autoencoder Paper
Keras Variational Autoencoder
simmytarika5
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 431,
"s": 28,
"text": "Variational autoencoder was proposed in 2013 by Knigma and Welling at Google and Qualcomm. A variational autoencoder (VAE) provides a probabilistic manner for describing an observation in latent space. Thus, rather than building an encoder that outputs a single value to describe each latent state attribute, we’ll formulate our encoder to describe a probability distribution for each latent attribute."
},
{
"code": null,
"e": 511,
"s": 431,
"text": "It has many applications such as data compression, synthetic data creation etc."
},
{
"code": null,
"e": 525,
"s": 511,
"text": "Architecture:"
},
{
"code": null,
"e": 1124,
"s": 525,
"text": "Autoencoders are a type of neural network that learns the data encodings from the dataset in an unsupervised way. It basically contains two parts: the first one is an encoder which is similar to the convolution neural network except for the last layer. The aim of the encoder to learn efficient data encoding from the dataset and pass it into a bottleneck architecture. The other part of the autoencoder is a decoder that uses latent space in the bottleneck layer to regenerate the images similar to the dataset. These results backpropagate from the neural network in the form of the loss function."
},
{
"code": null,
"e": 1431,
"s": 1124,
"text": "Variational autoencoder is different from autoencoder in a way such that it provides a statistic manner for describing the samples of the dataset in latent space. Therefore, in variational autoencoder, the encoder outputs a probability distribution in the bottleneck layer instead of a single output value."
},
{
"code": null,
"e": 1475,
"s": 1431,
"text": "Mathematics behind variational autoencoder:"
},
{
"code": null,
"e": 1657,
"s": 1475,
"text": "Variational autoencoder uses KL-divergence as its loss function, the goal of this is to minimize the difference between a supposed distribution and original distribution of dataset."
},
{
"code": null,
"e": 1780,
"s": 1657,
"text": "Suppose we have a distribution z and we want to generate the observation x from it. In other words, we want to calculate "
},
{
"code": null,
"e": 1813,
"s": 1782,
"text": "We can do it by following way:"
},
{
"code": null,
"e": 1867,
"s": 1815,
"text": "But, the calculation of p(x) can be quite difficult"
},
{
"code": null,
"e": 2136,
"s": 1869,
"text": "This usually makes it an intractable distribution. Hence, we need to approximate p(z|x) to q(z|x) to make it a tractable distribution. To better approximate p(z|x) to q(z|x), we will minimize the KL-divergence loss which calculates how similar two distributions are:"
},
{
"code": null,
"e": 2239,
"s": 2138,
"text": "By simplifying, the above minimization problem is equivalent to the following maximization problem :"
},
{
"code": null,
"e": 2401,
"s": 2241,
"text": "The first term represents the reconstruction likelihood and the other term ensures that our learned distribution q is similar to the true prior distribution p."
},
{
"code": null,
"e": 2507,
"s": 2403,
"text": "Thus our total loss consists of two terms, one is reconstruction error and other is KL-divergence loss:"
},
{
"code": null,
"e": 2525,
"s": 2509,
"text": "Implementation:"
},
{
"code": null,
"e": 2696,
"s": 2527,
"text": "In this implementation, we will be using the Fashion-MNIST dataset, this dataset is already available in keras.datasets API, so we don’t need to add or upload manually."
},
{
"code": null,
"e": 2834,
"s": 2698,
"text": "First, we need to import the necessary packages to our python environment. we will be using Keras package with tensorflow as a backend."
},
{
"code": null,
"e": 2841,
"s": 2834,
"text": "Code: "
},
{
"code": null,
"e": 2849,
"s": 2841,
"text": "python3"
},
{
"code": "# codeimport numpy as npimport tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras import Input, Modelfrom tensorflow.keras.layers import Layer, Conv2D, Flatten, Dense, Reshape, Conv2DTransposeimport matplotlib.pyplot as plt",
"e": 3088,
"s": 2849,
"text": null
},
{
"code": null,
"e": 3270,
"s": 3088,
"text": "For variational autoencoders, we need to define the architecture of two parts encoder and decoder but first, we will define the bottleneck layer of architecture, the sampling layer."
},
{
"code": null,
"e": 3277,
"s": 3270,
"text": "Code: "
},
{
"code": null,
"e": 3285,
"s": 3277,
"text": "python3"
},
{
"code": "# this sampling layer is the bottleneck layer of variational autoencoder,# it uses the output from two dense layers z_mean and z_log_var as input,# convert them into normal distribution and pass them to the decoder layerclass Sampling(Layer): def call(self, inputs): z_mean, z_log_var = inputs batch = tf.shape(z_mean)[0] dim = tf.shape(z_mean)[1] epsilon = tf.keras.backend.random_normal(shape =(batch, dim)) return z_mean + tf.exp(0.5 * z_log_var) * epsilon",
"e": 3784,
"s": 3285,
"text": null
},
{
"code": null,
"e": 3940,
"s": 3784,
"text": "Now, we define the architecture of encoder part of our autoencoder, this part takes images as input and encodes their representation in the Sampling layer."
},
{
"code": null,
"e": 3947,
"s": 3940,
"text": "Code: "
},
{
"code": null,
"e": 3955,
"s": 3947,
"text": "python3"
},
{
"code": "# Define Encoder Modellatent_dim = 2 encoder_inputs = Input(shape =(28, 28, 1))x = Conv2D(32, 3, activation =\"relu\", strides = 2, padding =\"same\")(encoder_inputs)x = Conv2D(64, 3, activation =\"relu\", strides = 2, padding =\"same\")(x)x = Flatten()(x)x = Dense(16, activation =\"relu\")(x)z_mean = Dense(latent_dim, name =\"z_mean\")(x)z_log_var = Dense(latent_dim, name =\"z_log_var\")(x)z = Sampling()([z_mean, z_log_var])encoder = Model(encoder_inputs, [z_mean, z_log_var, z], name =\"encoder\")encoder.summary()",
"e": 4460,
"s": 3955,
"text": null
},
{
"code": null,
"e": 6628,
"s": 4460,
"text": "Model: \"encoder\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_3 (InputLayer) [(None, 28, 28, 1)] 0 \n__________________________________________________________________________________________________\nconv2d_2 (Conv2D) (None, 14, 14, 32) 320 input_3[0][0] \n__________________________________________________________________________________________________\nconv2d_3 (Conv2D) (None, 7, 7, 64) 18496 conv2d_2[0][0] \n__________________________________________________________________________________________________\nflatten_1 (Flatten) (None, 3136) 0 conv2d_3[0][0] \n__________________________________________________________________________________________________\ndense_2 (Dense) (None, 16) 50192 flatten_1[0][0] \n__________________________________________________________________________________________________\nz_mean (Dense) (None, 2) 34 dense_2[0][0] \n__________________________________________________________________________________________________\nz_log_var (Dense) (None, 2) 34 dense_2[0][0] \n__________________________________________________________________________________________________\nsampling_1 (Sampling) (None, 2) 0 z_mean[0][0] \n z_log_var[0][0] \n==================================================================================================\nTotal params: 69, 076\nTrainable params: 69, 076\nNon-trainable params: 0\n__________________________________________________________________________________________________"
},
{
"code": null,
"e": 6796,
"s": 6628,
"text": "Now, we define the architecture of decoder part of our autoencoder, this part takes the output of the sampling layer as input and output an image of size (28, 28, 1) ."
},
{
"code": null,
"e": 6803,
"s": 6796,
"text": "Code: "
},
{
"code": null,
"e": 6811,
"s": 6803,
"text": "python3"
},
{
"code": "# Define Decoder Architecturelatent_inputs = keras.Input(shape =(latent_dim, ))x = Dense(7 * 7 * 64, activation =\"relu\")(latent_inputs)x = Reshape((7, 7, 64))(x)x = Conv2DTranspose(64, 3, activation =\"relu\", strides = 2, padding =\"same\")(x)x = Conv2DTranspose(32, 3, activation =\"relu\", strides = 2, padding =\"same\")(x)decoder_outputs = Conv2DTranspose(1, 3, activation =\"sigmoid\", padding =\"same\")(x)decoder = Model(latent_inputs, decoder_outputs, name =\"decoder\")decoder.summary()",
"e": 7294,
"s": 6811,
"text": null
},
{
"code": null,
"e": 8439,
"s": 7294,
"text": "Model: \"decoder\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_4 (InputLayer) [(None, 2)] 0 \n_________________________________________________________________\ndense_3 (Dense) (None, 3136) 9408 \n_________________________________________________________________\nreshape_1 (Reshape) (None, 7, 7, 64) 0 \n_________________________________________________________________\nconv2d_transpose_3 (Conv2DTr (None, 14, 14, 64) 36928 \n_________________________________________________________________\nconv2d_transpose_4 (Conv2DTr (None, 28, 28, 32) 18464 \n_________________________________________________________________\nconv2d_transpose_5 (Conv2DTr (None, 28, 28, 1) 289 \n=================================================================\nTotal params: 65, 089\nTrainable params: 65, 089\nNon-trainable params: 0\n_________________________________________________________________"
},
{
"code": null,
"e": 8529,
"s": 8439,
"text": "In this step, we combine the model and define the training procedure with loss functions."
},
{
"code": null,
"e": 8536,
"s": 8529,
"text": "Code: "
},
{
"code": null,
"e": 8544,
"s": 8536,
"text": "python3"
},
{
"code": "# this class takes encoder and decoder models and# define the complete variational autoencoder architectureclass VAE(keras.Model): def __init__(self, encoder, decoder, **kwargs): super(VAE, self).__init__(**kwargs) self.encoder = encoder self.decoder = decoder def train_step(self, data): if isinstance(data, tuple): data = data[0] with tf.GradientTape() as tape: z_mean, z_log_var, z = encoder(data) reconstruction = decoder(z) reconstruction_loss = tf.reduce_mean( keras.losses.binary_crossentropy(data, reconstruction) ) reconstruction_loss *= 28 * 28 kl_loss = 1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var) kl_loss = tf.reduce_mean(kl_loss) kl_loss *= -0.5 total_loss = reconstruction_loss + kl_loss grads = tape.gradient(total_loss, self.trainable_weights) self.optimizer.apply_gradients(zip(grads, self.trainable_weights)) return { \"loss\": total_loss, \"reconstruction_loss\": reconstruction_loss, \"kl_loss\": kl_loss, }",
"e": 9704,
"s": 8544,
"text": null
},
{
"code": null,
"e": 9861,
"s": 9704,
"text": "Now it’s the right time to train our variational autoencoder model, we will train it for 100 epochs. But first we need to import the fashion MNIST dataset."
},
{
"code": null,
"e": 9868,
"s": 9861,
"text": "Code: "
},
{
"code": null,
"e": 9876,
"s": 9868,
"text": "python3"
},
{
"code": "# load fashion mnist dataset from keras.dataset API(x_train, _), (x_test, _) = keras.datasets.fashion_mnist.load_data()fmnist_images = np.concatenate([x_train, x_test], axis = 0)# expand dimension to add a color map dimensionfmnist_images = np.expand_dims(fmnist_images, -1).astype(\"float32\") / 255 # compile and train the modelvae = VAE(encoder, decoder)vae.compile(optimizer ='rmsprop')vae.fit(fmnist_images, epochs = 100, batch_size = 64)",
"e": 10321,
"s": 9876,
"text": null
},
{
"code": null,
"e": 24075,
"s": 10321,
"text": "Epoch 1/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 301.9441 - reconstruction_loss: 298.3138 - kl_loss: 3.6303\nEpoch 2/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 273.5940 - reconstruction_loss: 270.0484 - kl_loss: 3.5456\nEpoch 3/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 269.3337 - reconstruction_loss: 265.9077 - kl_loss: 3.4260\nEpoch 4/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 266.8168 - reconstruction_loss: 263.4100 - kl_loss: 3.4068\nEpoch 5/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 264.9917 - reconstruction_loss: 261.5603 - kl_loss: 3.4314\nEpoch 6/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 263.5237 - reconstruction_loss: 260.0712 - kl_loss: 3.4525\nEpoch 7/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 262.3414 - reconstruction_loss: 258.8548 - kl_loss: 3.4865\nEpoch 8/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 261.4241 - reconstruction_loss: 257.9104 - kl_loss: 3.5137\nEpoch 9/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 260.6090 - reconstruction_loss: 257.0662 - kl_loss: 3.5428\nEpoch 10/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 259.9735 - reconstruction_loss: 256.4075 - kl_loss: 3.5660\nEpoch 11/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 259.4184 - reconstruction_loss: 255.8348 - kl_loss: 3.5836\nEpoch 12/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 258.9688 - reconstruction_loss: 255.3724 - kl_loss: 3.5964\nEpoch 13/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 258.5413 - reconstruction_loss: 254.9356 - kl_loss: 3.6057\nEpoch 14/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 258.2400 - reconstruction_loss: 254.6236 - kl_loss: 3.6163\nEpoch 15/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 257.9335 - reconstruction_loss: 254.3038 - kl_loss: 3.6298\nEpoch 16/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 257.6331 - reconstruction_loss: 253.9993 - kl_loss: 3.6339\nEpoch 17/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 257.4199 - reconstruction_loss: 253.7707 - kl_loss: 3.6492\nEpoch 18/100\n1094/1094 [==============================] - 6s 6ms/step - loss: 257.1951 - reconstruction_loss: 253.5309 - kl_loss: 3.6643\nEpoch 19/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 256.9326 - reconstruction_loss: 253.2723 - kl_loss: 3.6604\nEpoch 20/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 256.7551 - reconstruction_loss: 253.0836 - kl_loss: 3.6715\nEpoch 21/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 256.5663 - reconstruction_loss: 252.8877 - kl_loss: 3.6786\nEpoch 22/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 256.4068 - reconstruction_loss: 252.7112 - kl_loss: 3.6956\nEpoch 23/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 256.2588 - reconstruction_loss: 252.5588 - kl_loss: 3.7000\nEpoch 24/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 256.0853 - reconstruction_loss: 252.3794 - kl_loss: 3.7059\nEpoch 25/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 255.9321 - reconstruction_loss: 252.2201 - kl_loss: 3.7120\nEpoch 26/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 255.7962 - reconstruction_loss: 252.0814 - kl_loss: 3.7148\nEpoch 27/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 255.6953 - reconstruction_loss: 251.9673 - kl_loss: 3.7280\nEpoch 28/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 255.5534 - reconstruction_loss: 251.8248 - kl_loss: 3.7287\nEpoch 29/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 255.4437 - reconstruction_loss: 251.7134 - kl_loss: 3.7303\nEpoch 30/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 255.3439 - reconstruction_loss: 251.6064 - kl_loss: 3.7375\nEpoch 31/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 255.2326 - reconstruction_loss: 251.5018 - kl_loss: 3.7308\nEpoch 32/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 255.1356 - reconstruction_loss: 251.3933 - kl_loss: 3.7423\nEpoch 33/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 255.0660 - reconstruction_loss: 251.3224 - kl_loss: 3.7436\nEpoch 34/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 254.9977 - reconstruction_loss: 251.2449 - kl_loss: 3.7528\nEpoch 35/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 254.8857 - reconstruction_loss: 251.1363 - kl_loss: 3.7494\nEpoch 36/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 254.7980 - reconstruction_loss: 251.0481 - kl_loss: 3.7499\nEpoch 37/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 254.7485 - reconstruction_loss: 250.9851 - kl_loss: 3.7634\nEpoch 38/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 254.6701 - reconstruction_loss: 250.9049 - kl_loss: 3.7652\nEpoch 39/100\n1094/1094 [==============================] - 6s 6ms/step - loss: 254.6105 - reconstruction_loss: 250.8389 - kl_loss: 3.7716\nEpoch 40/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 254.4979 - reconstruction_loss: 250.7333 - kl_loss: 3.7646\nEpoch 41/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 254.4734 - reconstruction_loss: 250.7037 - kl_loss: 3.7697\nEpoch 42/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 254.4408 - reconstruction_loss: 250.6576 - kl_loss: 3.7831\nEpoch 43/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 254.3272 - reconstruction_loss: 250.5562 - kl_loss: 3.7711\nEpoch 44/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 254.3110 - reconstruction_loss: 250.5354 - kl_loss: 3.7755\nEpoch 45/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 254.1982 - reconstruction_loss: 250.4256 - kl_loss: 3.7726\nEpoch 46/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 254.1655 - reconstruction_loss: 250.3795 - kl_loss: 3.7860\nEpoch 47/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 254.0979 - reconstruction_loss: 250.3105 - kl_loss: 3.7875\nEpoch 48/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 254.0801 - reconstruction_loss: 250.2973 - kl_loss: 3.7828\nEpoch 49/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 254.0101 - reconstruction_loss: 250.2270 - kl_loss: 3.7831\nEpoch 50/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.9512 - reconstruction_loss: 250.1681 - kl_loss: 3.7831\nEpoch 51/100\n1094/1094 [==============================] - 7s 7ms/step - loss: 253.9307 - reconstruction_loss: 250.1408 - kl_loss: 3.7899\nEpoch 52/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.8858 - reconstruction_loss: 250.1059 - kl_loss: 3.7800\nEpoch 53/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.8118 - reconstruction_loss: 250.0236 - kl_loss: 3.7882\nEpoch 54/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.8171 - reconstruction_loss: 250.0325 - kl_loss: 3.7845\nEpoch 55/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.7622 - reconstruction_loss: 249.9735 - kl_loss: 3.7887\nEpoch 56/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.7338 - reconstruction_loss: 249.9380 - kl_loss: 3.7959\nEpoch 57/100\n1094/1094 [==============================] - 6s 6ms/step - loss: 253.6761 - reconstruction_loss: 249.8792 - kl_loss: 3.7969\nEpoch 58/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.6236 - reconstruction_loss: 249.8283 - kl_loss: 3.7954\nEpoch 59/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.6181 - reconstruction_loss: 249.8236 - kl_loss: 3.7945\nEpoch 60/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.5509 - reconstruction_loss: 249.7587 - kl_loss: 3.7921\nEpoch 61/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.5124 - reconstruction_loss: 249.7126 - kl_loss: 3.7998\nEpoch 62/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.4739 - reconstruction_loss: 249.6683 - kl_loss: 3.8056\nEpoch 63/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.4609 - reconstruction_loss: 249.6567 - kl_loss: 3.8042\nEpoch 64/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.4066 - reconstruction_loss: 249.6020 - kl_loss: 3.8045\nEpoch 65/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.3578 - reconstruction_loss: 249.5580 - kl_loss: 3.7998\nEpoch 66/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.3728 - reconstruction_loss: 249.5609 - kl_loss: 3.8118\nEpoch 67/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.3523 - reconstruction_loss: 249.5351 - kl_loss: 3.8171\nEpoch 68/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.2646 - reconstruction_loss: 249.4452 - kl_loss: 3.8194\nEpoch 69/100\n1094/1094 [==============================] - 6s 6ms/step - loss: 253.2642 - reconstruction_loss: 249.4603 - kl_loss: 3.8040\nEpoch 70/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.2227 - reconstruction_loss: 249.4159 - kl_loss: 3.8068\nEpoch 71/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.1848 - reconstruction_loss: 249.3755 - kl_loss: 3.8094\nEpoch 72/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.1812 - reconstruction_loss: 249.3737 - kl_loss: 3.8074\nEpoch 73/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.1803 - reconstruction_loss: 249.3743 - kl_loss: 3.8059\nEpoch 74/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.1295 - reconstruction_loss: 249.3114 - kl_loss: 3.8181\nEpoch 75/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.0516 - reconstruction_loss: 249.2391 - kl_loss: 3.8125\nEpoch 76/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.0736 - reconstruction_loss: 249.2582 - kl_loss: 3.8154\nEpoch 77/100\n1094/1094 [==============================] - 6s 6ms/step - loss: 253.0331 - reconstruction_loss: 249.2200 - kl_loss: 3.8131\nEpoch 78/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 253.0479 - reconstruction_loss: 249.2272 - kl_loss: 3.8207\nEpoch 79/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.9317 - reconstruction_loss: 249.1137 - kl_loss: 3.8179\nEpoch 80/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.9578 - reconstruction_loss: 249.1483 - kl_loss: 3.8095\nEpoch 81/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.9072 - reconstruction_loss: 249.0963 - kl_loss: 3.8109\nEpoch 82/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.8793 - reconstruction_loss: 249.0646 - kl_loss: 3.8147\nEpoch 83/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.8914 - reconstruction_loss: 249.0676 - kl_loss: 3.8238\nEpoch 84/100\n1094/1094 [==============================] - 6s 6ms/step - loss: 252.8365 - reconstruction_loss: 249.0121 - kl_loss: 3.8244\nEpoch 85/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.8063 - reconstruction_loss: 248.9844 - kl_loss: 3.8218\nEpoch 86/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.7960 - reconstruction_loss: 248.9777 - kl_loss: 3.8183\nEpoch 87/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.7733 - reconstruction_loss: 248.9529 - kl_loss: 3.8204\nEpoch 88/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.7303 - reconstruction_loss: 248.9055 - kl_loss: 3.8248\nEpoch 89/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.7225 - reconstruction_loss: 248.8902 - kl_loss: 3.8323\nEpoch 90/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.6822 - reconstruction_loss: 248.8549 - kl_loss: 3.8273\nEpoch 91/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.6540 - reconstruction_loss: 248.8314 - kl_loss: 3.8227\nEpoch 92/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.6540 - reconstruction_loss: 248.8239 - kl_loss: 3.8300\nEpoch 93/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.6213 - reconstruction_loss: 248.7778 - kl_loss: 3.8435\nEpoch 94/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.5990 - reconstruction_loss: 248.7594 - kl_loss: 3.8397\nEpoch 95/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.5786 - reconstruction_loss: 248.7413 - kl_loss: 3.8373\nEpoch 96/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.5839 - reconstruction_loss: 248.7411 - kl_loss: 3.8427\nEpoch 97/100\n1094/1094 [==============================] - 7s 7ms/step - loss: 252.5364 - reconstruction_loss: 248.6960 - kl_loss: 3.8404\nEpoch 98/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.5347 - reconstruction_loss: 248.6915 - kl_loss: 3.8431\nEpoch 99/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.4996 - reconstruction_loss: 248.6569 - kl_loss: 3.8428\nEpoch 100/100\n1094/1094 [==============================] - 7s 6ms/step - loss: 252.4938 - reconstruction_loss: 248.6405 - kl_loss: 3.8533\n<tensorflow.python.keras.callbacks.History at 0x7f5467c56be0>"
},
{
"code": null,
"e": 24205,
"s": 24075,
"text": "In this step, we display training results, we will be displaying these results according to their values in latent space vectors."
},
{
"code": null,
"e": 24212,
"s": 24205,
"text": "Code: "
},
{
"code": null,
"e": 24220,
"s": 24212,
"text": "python3"
},
{
"code": "def plot_latent(encoder, decoder): # display a n * n 2D manifold of images n = 10 img_dim = 28 scale = 2.0 figsize = 15 figure = np.zeros((img_dim * n, img_dim * n)) # linearly spaced coordinates corresponding to the 2D plot # of images classes in the latent space grid_x = np.linspace(-scale, scale, n) grid_y = np.linspace(-scale, scale, n)[::-1] for i, yi in enumerate(grid_y): for j, xi in enumerate(grid_x): z_sample = np.array([[xi, yi]]) x_decoded = decoder.predict(z_sample) images = x_decoded[0].reshape(img_dim, img_dim) figure[ i * img_dim : (i + 1) * img_dim, j * img_dim : (j + 1) * img_dim, ] = images plt.figure(figsize =(figsize, figsize)) start_range = img_dim // 2 end_range = n * img_dim + start_range + 1 pixel_range = np.arange(start_range, end_range, img_dim) sample_range_x = np.round(grid_x, 1) sample_range_y = np.round(grid_y, 1) plt.xticks(pixel_range, sample_range_x) plt.yticks(pixel_range, sample_range_y) plt.xlabel(\"z[0]\") plt.ylabel(\"z[1]\") plt.imshow(figure, cmap =\"Greys_r\") plt.show() plot_latent(encoder, decoder)",
"e": 25435,
"s": 24220,
"text": null
},
{
"code": null,
"e": 25654,
"s": 25435,
"text": "To get a more clear view of our representational latent vectors values, we will be plotting the scatter plot of training data on the basis of their values of corresponding latent dimensions generated from the encoder ."
},
{
"code": null,
"e": 25661,
"s": 25654,
"text": "Code: "
},
{
"code": null,
"e": 25669,
"s": 25661,
"text": "python3"
},
{
"code": "def plot_label_clusters(encoder, decoder, data, test_lab): z_mean, _, _ = encoder.predict(data) plt.figure(figsize =(12, 10)) sc = plt.scatter(z_mean[:, 0], z_mean[:, 1], c = test_lab) cbar = plt.colorbar(sc, ticks = range(10)) cbar.ax.set_yticklabels([labels.get(i) for i in range(10)]) plt.xlabel(\"z[0]\") plt.ylabel(\"z[1]\") plt.show() labels = {0 :\"T-shirt / top\",1: \"Trouser\",2: \"Pullover\",3: \"Dress\",4: \"Coat\",5: \"Sandal\",6: \"Shirt\",7: \"Sneaker\",8: \"Bag\",9: \"Ankle boot\"} (x_train, y_train), _ = keras.datasets.fashion_mnist.load_data()x_train = np.expand_dims(x_train, -1).astype(\"float32\") / 255plot_label_clusters(encoder, decoder, x_train, y_train)",
"e": 26381,
"s": 25669,
"text": null
},
{
"code": null,
"e": 26393,
"s": 26381,
"text": "References:"
},
{
"code": null,
"e": 26423,
"s": 26393,
"text": "Variational Autoencoder Paper"
},
{
"code": null,
"e": 26453,
"s": 26423,
"text": "Keras Variational Autoencoder"
},
{
"code": null,
"e": 26466,
"s": 26453,
"text": "simmytarika5"
},
{
"code": null,
"e": 26483,
"s": 26466,
"text": "Machine Learning"
},
{
"code": null,
"e": 26500,
"s": 26483,
"text": "Machine Learning"
}
] |
Make all combinations of size k
|
11 Jul, 2022
Given two numbers n and k and you have to find all possible combination of k numbers from 1...n.Examples:
Input : n = 4
k = 2
Output : 1 2
1 3
1 4
2 3
2 4
3 4
Input : n = 5
k = 3
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
We have discussed one approach in the below post.Print all possible combinations of r elements in a given array of size nIn this, we use DFS based approach. We want all numbers from 1 to n. We first push all numbers from 1 to k in tmp_vector and as soon as k is equal to 0, we push all numbers from tmp_vector to ans_vector. After this, we remove the last element from tmp_vector and make all remaining combination.
C++
Java
Python3
C#
Javascript
// C++ program to print all combinations of size// k of elements in set 1..n#include <bits/stdc++.h>using namespace std; void makeCombiUtil(vector<vector<int> >& ans, vector<int>& tmp, int n, int left, int k){ // Pushing this vector to a vector of vector if (k == 0) { ans.push_back(tmp); return; } // i iterates from left to n. First time // left will be 1 for (int i = left; i <= n; ++i) { tmp.push_back(i); makeCombiUtil(ans, tmp, n, i + 1, k - 1); // Popping out last inserted element // from the vector tmp.pop_back(); }} // Prints all combinations of size k of numbers// from 1 to n.vector<vector<int> > makeCombi(int n, int k){ vector<vector<int> > ans; vector<int> tmp; makeCombiUtil(ans, tmp, n, 1, k); return ans;} // Driver codeint main(){ // given number int n = 5; int k = 3; vector<vector<int> > ans = makeCombi(n, k); for (int i = 0; i < ans.size(); i++) { for (int j = 0; j < ans[i].size(); j++) { cout << ans.at(i).at(j) << " "; } cout << endl; } return 0;}
// Java program to print all combinations of size// k of elements in set 1..nimport java.util.*;public class Main{ static Vector<Vector<Integer>> ans = new Vector<Vector<Integer>>(); static Vector<Integer> tmp = new Vector<Integer>(); static void makeCombiUtil(int n, int left, int k) { // Pushing this vector to a vector of vector if (k == 0) { ans.add(tmp); for(int i = 0; i < tmp.size(); i++) { System.out.print(tmp.get(i) + " "); } System.out.println(); return; } // i iterates from left to n. First time // left will be 1 for (int i = left; i <= n; ++i) { tmp.add(i); makeCombiUtil(n, i + 1, k - 1); // Popping out last inserted element // from the vector tmp.remove(tmp.size() - 1); } } // Prints all combinations of size k of numbers // from 1 to n. static Vector<Vector<Integer>> makeCombi(int n, int k) { makeCombiUtil(n, 1, k); return ans; } public static void main(String[] args) { // given number int n = 5; int k = 3; ans = makeCombi(n, k); }} // This code is contributed by suresh07.
# Python3 program to print all combinations of size# k of elements in set 1..nans = []tmp = [] def makeCombiUtil(n, left, k): # Pushing this vector to a vector of vector if (k == 0): ans.append(tmp) for i in range(len(tmp)): print(tmp[i], end = " ") print() return # i iterates from left to n. First time # left will be 1 for i in range(left, n + 1): tmp.append(i) makeCombiUtil(n, i + 1, k - 1) # Popping out last inserted element # from the vector tmp.pop() # Prints all combinations of size k of numbers# from 1 to n.def makeCombi(n, k): makeCombiUtil(n, 1, k) return ans # given numbern = 5k = 3ans = makeCombi(n, k) # This code is contributed by divyeshrabadiya07.
// C# program to print all combinations of size// k of elements in set 1..nusing System;using System.Collections.Generic;class GFG { static List<List<int>> ans = new List<List<int>>(); static List<int> tmp = new List<int>(); static void makeCombiUtil(int n, int left, int k) { // Pushing this vector to a vector of vector if (k == 0) { ans.Add(tmp); for(int i = 0; i < tmp.Count; i++) { Console.Write(tmp[i] + " "); } Console.WriteLine(); return; } // i iterates from left to n. First time // left will be 1 for (int i = left; i <= n; ++i) { tmp.Add(i); makeCombiUtil(n, i + 1, k - 1); // Popping out last inserted element // from the vector tmp.RemoveAt(tmp.Count - 1); } } // Prints all combinations of size k of numbers // from 1 to n. static List<List<int>> makeCombi(int n, int k) { makeCombiUtil(n, 1, k); return ans; } static void Main() { // given number int n = 5; int k = 3; ans = makeCombi(n, k); }} // This code is contributed by rameshtravel07.
<script> // Javascript program to print all combinations of size // k of elements in set 1..n let ans = []; let tmp = []; function makeCombiUtil(n, left, k) { // Pushing this vector to a vector of vector if (k == 0) { ans.push(tmp); for(let i = 0; i < tmp.length; i++) { document.write(tmp[i] + " "); } document.write("</br>"); return; } // i iterates from left to n. First time // left will be 1 for (let i = left; i <= n; ++i) { tmp.push(i); makeCombiUtil(n, i + 1, k - 1); // Popping out last inserted element // from the vector tmp.pop(); } } // Prints all combinations of size k of numbers // from 1 to n. function makeCombi(n, k) { makeCombiUtil(n, 1, k); return ans; } // given number let n = 5; let k = 3; ans = makeCombi(n, k); // This code is contributed by divyesh072019.</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((nCk)*k), where nCk is all possible subsets and k to copy subsets into ans vector.
Space Complexity: O((nCk)*k), to store all n C k subset in the ans vector of size k.
This article is contributed by Roshni Agarwal. 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.
kunal6203
divyesh072019
divyeshrabadiya07
rameshtravel07
suresh07
isha307
DFS
Combinatorial
DFS
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 162,
"s": 54,
"text": "Given two numbers n and k and you have to find all possible combination of k numbers from 1...n.Examples: "
},
{
"code": null,
"e": 465,
"s": 162,
"text": "Input : n = 4 \n k = 2\nOutput : 1 2 \n 1 3 \n 1 4 \n 2 3 \n 2 4 \n 3 4 \n\nInput : n = 5 \n k = 3\nOutput : 1 2 3 \n 1 2 4 \n 1 2 5 \n 1 3 4 \n 1 3 5 \n 1 4 5 \n 2 3 4 \n 2 3 5 \n 2 4 5 \n 3 4 5 "
},
{
"code": null,
"e": 884,
"s": 467,
"text": "We have discussed one approach in the below post.Print all possible combinations of r elements in a given array of size nIn this, we use DFS based approach. We want all numbers from 1 to n. We first push all numbers from 1 to k in tmp_vector and as soon as k is equal to 0, we push all numbers from tmp_vector to ans_vector. After this, we remove the last element from tmp_vector and make all remaining combination. "
},
{
"code": null,
"e": 888,
"s": 884,
"text": "C++"
},
{
"code": null,
"e": 893,
"s": 888,
"text": "Java"
},
{
"code": null,
"e": 901,
"s": 893,
"text": "Python3"
},
{
"code": null,
"e": 904,
"s": 901,
"text": "C#"
},
{
"code": null,
"e": 915,
"s": 904,
"text": "Javascript"
},
{
"code": "// C++ program to print all combinations of size// k of elements in set 1..n#include <bits/stdc++.h>using namespace std; void makeCombiUtil(vector<vector<int> >& ans, vector<int>& tmp, int n, int left, int k){ // Pushing this vector to a vector of vector if (k == 0) { ans.push_back(tmp); return; } // i iterates from left to n. First time // left will be 1 for (int i = left; i <= n; ++i) { tmp.push_back(i); makeCombiUtil(ans, tmp, n, i + 1, k - 1); // Popping out last inserted element // from the vector tmp.pop_back(); }} // Prints all combinations of size k of numbers// from 1 to n.vector<vector<int> > makeCombi(int n, int k){ vector<vector<int> > ans; vector<int> tmp; makeCombiUtil(ans, tmp, n, 1, k); return ans;} // Driver codeint main(){ // given number int n = 5; int k = 3; vector<vector<int> > ans = makeCombi(n, k); for (int i = 0; i < ans.size(); i++) { for (int j = 0; j < ans[i].size(); j++) { cout << ans.at(i).at(j) << \" \"; } cout << endl; } return 0;}",
"e": 2033,
"s": 915,
"text": null
},
{
"code": "// Java program to print all combinations of size// k of elements in set 1..nimport java.util.*;public class Main{ static Vector<Vector<Integer>> ans = new Vector<Vector<Integer>>(); static Vector<Integer> tmp = new Vector<Integer>(); static void makeCombiUtil(int n, int left, int k) { // Pushing this vector to a vector of vector if (k == 0) { ans.add(tmp); for(int i = 0; i < tmp.size(); i++) { System.out.print(tmp.get(i) + \" \"); } System.out.println(); return; } // i iterates from left to n. First time // left will be 1 for (int i = left; i <= n; ++i) { tmp.add(i); makeCombiUtil(n, i + 1, k - 1); // Popping out last inserted element // from the vector tmp.remove(tmp.size() - 1); } } // Prints all combinations of size k of numbers // from 1 to n. static Vector<Vector<Integer>> makeCombi(int n, int k) { makeCombiUtil(n, 1, k); return ans; } public static void main(String[] args) { // given number int n = 5; int k = 3; ans = makeCombi(n, k); }} // This code is contributed by suresh07.",
"e": 3336,
"s": 2033,
"text": null
},
{
"code": "# Python3 program to print all combinations of size# k of elements in set 1..nans = []tmp = [] def makeCombiUtil(n, left, k): # Pushing this vector to a vector of vector if (k == 0): ans.append(tmp) for i in range(len(tmp)): print(tmp[i], end = \" \") print() return # i iterates from left to n. First time # left will be 1 for i in range(left, n + 1): tmp.append(i) makeCombiUtil(n, i + 1, k - 1) # Popping out last inserted element # from the vector tmp.pop() # Prints all combinations of size k of numbers# from 1 to n.def makeCombi(n, k): makeCombiUtil(n, 1, k) return ans # given numbern = 5k = 3ans = makeCombi(n, k) # This code is contributed by divyeshrabadiya07.",
"e": 4104,
"s": 3336,
"text": null
},
{
"code": "// C# program to print all combinations of size// k of elements in set 1..nusing System;using System.Collections.Generic;class GFG { static List<List<int>> ans = new List<List<int>>(); static List<int> tmp = new List<int>(); static void makeCombiUtil(int n, int left, int k) { // Pushing this vector to a vector of vector if (k == 0) { ans.Add(tmp); for(int i = 0; i < tmp.Count; i++) { Console.Write(tmp[i] + \" \"); } Console.WriteLine(); return; } // i iterates from left to n. First time // left will be 1 for (int i = left; i <= n; ++i) { tmp.Add(i); makeCombiUtil(n, i + 1, k - 1); // Popping out last inserted element // from the vector tmp.RemoveAt(tmp.Count - 1); } } // Prints all combinations of size k of numbers // from 1 to n. static List<List<int>> makeCombi(int n, int k) { makeCombiUtil(n, 1, k); return ans; } static void Main() { // given number int n = 5; int k = 3; ans = makeCombi(n, k); }} // This code is contributed by rameshtravel07.",
"e": 5344,
"s": 4104,
"text": null
},
{
"code": "<script> // Javascript program to print all combinations of size // k of elements in set 1..n let ans = []; let tmp = []; function makeCombiUtil(n, left, k) { // Pushing this vector to a vector of vector if (k == 0) { ans.push(tmp); for(let i = 0; i < tmp.length; i++) { document.write(tmp[i] + \" \"); } document.write(\"</br>\"); return; } // i iterates from left to n. First time // left will be 1 for (let i = left; i <= n; ++i) { tmp.push(i); makeCombiUtil(n, i + 1, k - 1); // Popping out last inserted element // from the vector tmp.pop(); } } // Prints all combinations of size k of numbers // from 1 to n. function makeCombi(n, k) { makeCombiUtil(n, 1, k); return ans; } // given number let n = 5; let k = 3; ans = makeCombi(n, k); // This code is contributed by divyesh072019.</script>",
"e": 6409,
"s": 5344,
"text": null
},
{
"code": null,
"e": 6419,
"s": 6409,
"text": "Output: "
},
{
"code": null,
"e": 6489,
"s": 6419,
"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": 6592,
"s": 6489,
"text": "Time Complexity: O((nCk)*k), where nCk is all possible subsets and k to copy subsets into ans vector."
},
{
"code": null,
"e": 6677,
"s": 6592,
"text": "Space Complexity: O((nCk)*k), to store all n C k subset in the ans vector of size k."
},
{
"code": null,
"e": 7100,
"s": 6677,
"text": "This article is contributed by Roshni Agarwal. 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": 7110,
"s": 7100,
"text": "kunal6203"
},
{
"code": null,
"e": 7124,
"s": 7110,
"text": "divyesh072019"
},
{
"code": null,
"e": 7142,
"s": 7124,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 7157,
"s": 7142,
"text": "rameshtravel07"
},
{
"code": null,
"e": 7166,
"s": 7157,
"text": "suresh07"
},
{
"code": null,
"e": 7174,
"s": 7166,
"text": "isha307"
},
{
"code": null,
"e": 7178,
"s": 7174,
"text": "DFS"
},
{
"code": null,
"e": 7192,
"s": 7178,
"text": "Combinatorial"
},
{
"code": null,
"e": 7196,
"s": 7192,
"text": "DFS"
},
{
"code": null,
"e": 7210,
"s": 7196,
"text": "Combinatorial"
}
] |
C - Command Line Arguments
|
It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments and many times they are important for your program especially when you want to control your program from outside instead of hard coding those values inside the code.
The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program. Following is a simple example which checks if there is any argument supplied from the command line and take action accordingly −
#include <stdio.h>
int main( int argc, char *argv[] ) {
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with single argument, it produces the following result.
$./a.out testing
The argument supplied is testing
When the above code is compiled and executed with a two arguments, it produces the following result.
$./a.out testing1 testing2
Too many arguments supplied.
When the above code is compiled and executed without passing any argument, it produces the following result.
$./a.out
One argument expected
It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one, and if you pass one argument then argc is set at 2.
You pass all the command line arguments separated by a space, but if argument itself has a space then you can pass such arguments by putting them inside double quotes "" or single quotes ''. Let us re-write above example once again where we will print program name and we also pass a command line argument by putting inside double quotes −
#include <stdio.h>
int main( int argc, char *argv[] ) {
printf("Program name %s\n", argv[0]);
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with a single argument separated by space but inside double quotes, it produces the following result.
$./a.out "testing1 testing2"
Program name ./a.out
The argument supplied is testing1 testing2
|
[
{
"code": null,
"e": 2531,
"s": 2218,
"text": "It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments and many times they are important for your program especially when you want to control your program from outside instead of hard coding those values inside the code."
},
{
"code": null,
"e": 2867,
"s": 2531,
"text": "The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program. Following is a simple example which checks if there is any argument supplied from the command line and take action accordingly −"
},
{
"code": null,
"e": 3145,
"s": 2867,
"text": "#include <stdio.h>\n\nint main( int argc, char *argv[] ) {\n\n if( argc == 2 ) {\n printf(\"The argument supplied is %s\\n\", argv[1]);\n }\n else if( argc > 2 ) {\n printf(\"Too many arguments supplied.\\n\");\n }\n else {\n printf(\"One argument expected.\\n\");\n }\n}"
},
{
"code": null,
"e": 3246,
"s": 3145,
"text": "When the above code is compiled and executed with single argument, it produces the following result."
},
{
"code": null,
"e": 3296,
"s": 3246,
"text": "$./a.out testing\nThe argument supplied is testing"
},
{
"code": null,
"e": 3397,
"s": 3296,
"text": "When the above code is compiled and executed with a two arguments, it produces the following result."
},
{
"code": null,
"e": 3453,
"s": 3397,
"text": "$./a.out testing1 testing2\nToo many arguments supplied."
},
{
"code": null,
"e": 3562,
"s": 3453,
"text": "When the above code is compiled and executed without passing any argument, it produces the following result."
},
{
"code": null,
"e": 3593,
"s": 3562,
"text": "$./a.out\nOne argument expected"
},
{
"code": null,
"e": 3867,
"s": 3593,
"text": "It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one, and if you pass one argument then argc is set at 2."
},
{
"code": null,
"e": 4207,
"s": 3867,
"text": "You pass all the command line arguments separated by a space, but if argument itself has a space then you can pass such arguments by putting them inside double quotes \"\" or single quotes ''. Let us re-write above example once again where we will print program name and we also pass a command line argument by putting inside double quotes −"
},
{
"code": null,
"e": 4528,
"s": 4207,
"text": "#include <stdio.h>\n\nint main( int argc, char *argv[] ) {\n\n printf(\"Program name %s\\n\", argv[0]);\n \n if( argc == 2 ) {\n printf(\"The argument supplied is %s\\n\", argv[1]);\n }\n else if( argc > 2 ) {\n printf(\"Too many arguments supplied.\\n\");\n }\n else {\n printf(\"One argument expected.\\n\");\n }\n}"
},
{
"code": null,
"e": 4675,
"s": 4528,
"text": "When the above code is compiled and executed with a single argument separated by space but inside double quotes, it produces the following result."
}
] |
How to animate scrollLeft using jQuery?
|
To animate scrollLeft using jQuery, use the animate() method with scrollLeft.
You can try to run the following code to learn how to animate scrollLeft using jQuery:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#scrollme').click(function() {
$('html,body').animate({
scrollLeft: $('#demo').css('left')
}, 500, function() {
$('html, body').animate({
scrollLeft: 0
}, 500);
});
});
});
</script>
<style>
#demo {
width: 100px;
height: 100px;
background: green;
position: relative;
left: 800px;
}
</style>
</head>
<body>
<p><button id="scrollme">Click to scroll left</button></p>
<div id="demo"></div>
</body>
</html>
|
[
{
"code": null,
"e": 1265,
"s": 1187,
"text": "To animate scrollLeft using jQuery, use the animate() method with scrollLeft."
},
{
"code": null,
"e": 1352,
"s": 1265,
"text": "You can try to run the following code to learn how to animate scrollLeft using jQuery:"
},
{
"code": null,
"e": 1362,
"s": 1352,
"text": "Live Demo"
},
{
"code": null,
"e": 2002,
"s": 1362,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $('#scrollme').click(function() {\n $('html,body').animate({\n scrollLeft: $('#demo').css('left')\n }, 500, function() {\n\n $('html, body').animate({\n scrollLeft: 0\n }, 500);\n\n });\n});\n});\n</script>\n<style>\n#demo {\n width: 100px;\n height: 100px;\n background: green;\n position: relative;\n left: 800px;\n}\n</style>\n</head>\n<body>\n<p><button id=\"scrollme\">Click to scroll left</button></p>\n\n<div id=\"demo\"></div>\n\n</body>\n</html>"
}
] |
StringTokenizer Class in Java
|
15 Jun, 2022
StringTokenizer class in Java is used to break a string into tokens. A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed. A token is returned by taking a substring of the string that was used to create the StringTokenizer object. It provides the first step in the parsing process often called lexer or scanner. The String Tokenizer class allows an application to break strings into tokens. It implements the Enumeration interface. This class is used for parsing data. To use String Tokenizer class we have to specify an input string and a string that contains delimiters. Delimiters are the characters that separate tokens. Each character in the delimiter string is considered a valid delimiter. Default delimiters are whitespaces, new line, space, and tab.
Illustration:
Constructors of StringToken: Let us consider ‘str’ as the string to be tokenized
StringTokenizer(String str): default delimiters like newline, space, tab, carriage return, and form feed.StringTokenizer(String str, String delim): delim is a set of delimiters that are used to tokenize the given string.StringTokenizer(String str, String delim, boolean flag): The first two parameters have the same meaning wherein The flag serves the following purpose.
StringTokenizer(String str): default delimiters like newline, space, tab, carriage return, and form feed.
StringTokenizer(String str, String delim): delim is a set of delimiters that are used to tokenize the given string.
StringTokenizer(String str, String delim, boolean flag): The first two parameters have the same meaning wherein The flag serves the following purpose.
3.1: If the flag is false, delimiter characters serve to separate tokens
Example:
Input : if string --> "hello geeks" and Delimiter is " ", then
Output: tokens are "hello" and "geeks".
3.2: If the flag is true, delimiter characters are considered to be tokens.
Example:
Input : String --> is "hello geeks"and Delimiter is " ", then
Output: Tokens --> "hello", " " and "geeks".
Implementation:
Java
// Java Program to Illustrate StringTokenizer Class // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Constructor 1 System.out.println("Using Constructor 1 - "); // Creating object of class inside main() method StringTokenizer st1 = new StringTokenizer( "Hello Geeks How are you", " "); // Condition holds true till there is single token // remaining using hasMoreTokens() method while (st1.hasMoreTokens()) // Getting next tokens System.out.println(st1.nextToken()); // Constructor 2 System.out.println("Using Constructor 2 - "); // Again creating object of class inside main() // method StringTokenizer st2 = new StringTokenizer( "JAVA : Code : String", " :"); // If tokens are present while (st2.hasMoreTokens()) // Print all tokens System.out.println(st2.nextToken()); // Constructor 3 System.out.println("Using Constructor 3 - "); // Again creating object of class inside main() // method StringTokenizer st3 = new StringTokenizer( "JAVA : Code : String", " :", true); while (st3.hasMoreTokens()) System.out.println(st3.nextToken()); }}
Using Constructor 1 -
Hello
Geeks
How
are
you
Using Constructor 2 -
JAVA
Code
String
Using Constructor 3 -
JAVA
:
Code
:
String
This article is contributed by Mohit Gupta. 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.
solankimayank
sumitgumber28
aayushi2402
Java-Library
Java-Strings
Java
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
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 935,
"s": 52,
"text": "StringTokenizer class in Java is used to break a string into tokens. A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed. A token is returned by taking a substring of the string that was used to create the StringTokenizer object. It provides the first step in the parsing process often called lexer or scanner. The String Tokenizer class allows an application to break strings into tokens. It implements the Enumeration interface. This class is used for parsing data. To use String Tokenizer class we have to specify an input string and a string that contains delimiters. Delimiters are the characters that separate tokens. Each character in the delimiter string is considered a valid delimiter. Default delimiters are whitespaces, new line, space, and tab. "
},
{
"code": null,
"e": 950,
"s": 935,
"text": "Illustration: "
},
{
"code": null,
"e": 1031,
"s": 950,
"text": "Constructors of StringToken: Let us consider ‘str’ as the string to be tokenized"
},
{
"code": null,
"e": 1403,
"s": 1031,
"text": "StringTokenizer(String str): default delimiters like newline, space, tab, carriage return, and form feed.StringTokenizer(String str, String delim): delim is a set of delimiters that are used to tokenize the given string.StringTokenizer(String str, String delim, boolean flag): The first two parameters have the same meaning wherein The flag serves the following purpose."
},
{
"code": null,
"e": 1509,
"s": 1403,
"text": "StringTokenizer(String str): default delimiters like newline, space, tab, carriage return, and form feed."
},
{
"code": null,
"e": 1626,
"s": 1509,
"text": "StringTokenizer(String str, String delim): delim is a set of delimiters that are used to tokenize the given string."
},
{
"code": null,
"e": 1777,
"s": 1626,
"text": "StringTokenizer(String str, String delim, boolean flag): The first two parameters have the same meaning wherein The flag serves the following purpose."
},
{
"code": null,
"e": 1850,
"s": 1777,
"text": "3.1: If the flag is false, delimiter characters serve to separate tokens"
},
{
"code": null,
"e": 1859,
"s": 1850,
"text": "Example:"
},
{
"code": null,
"e": 1964,
"s": 1859,
"text": "Input : if string --> \"hello geeks\" and Delimiter is \" \", then \nOutput: tokens are \"hello\" and \"geeks\"."
},
{
"code": null,
"e": 2040,
"s": 1964,
"text": "3.2: If the flag is true, delimiter characters are considered to be tokens."
},
{
"code": null,
"e": 2049,
"s": 2040,
"text": "Example:"
},
{
"code": null,
"e": 2157,
"s": 2049,
"text": "Input : String --> is \"hello geeks\"and Delimiter is \" \", then \nOutput: Tokens --> \"hello\", \" \" and \"geeks\"."
},
{
"code": null,
"e": 2173,
"s": 2157,
"text": "Implementation:"
},
{
"code": null,
"e": 2178,
"s": 2173,
"text": "Java"
},
{
"code": "// Java Program to Illustrate StringTokenizer Class // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Constructor 1 System.out.println(\"Using Constructor 1 - \"); // Creating object of class inside main() method StringTokenizer st1 = new StringTokenizer( \"Hello Geeks How are you\", \" \"); // Condition holds true till there is single token // remaining using hasMoreTokens() method while (st1.hasMoreTokens()) // Getting next tokens System.out.println(st1.nextToken()); // Constructor 2 System.out.println(\"Using Constructor 2 - \"); // Again creating object of class inside main() // method StringTokenizer st2 = new StringTokenizer( \"JAVA : Code : String\", \" :\"); // If tokens are present while (st2.hasMoreTokens()) // Print all tokens System.out.println(st2.nextToken()); // Constructor 3 System.out.println(\"Using Constructor 3 - \"); // Again creating object of class inside main() // method StringTokenizer st3 = new StringTokenizer( \"JAVA : Code : String\", \" :\", true); while (st3.hasMoreTokens()) System.out.println(st3.nextToken()); }}",
"e": 3569,
"s": 2178,
"text": null
},
{
"code": null,
"e": 3708,
"s": 3569,
"text": "Using Constructor 1 - \nHello\nGeeks\nHow\nare\nyou\nUsing Constructor 2 - \nJAVA\nCode\nString\nUsing Constructor 3 - \nJAVA\n \n:\n \nCode\n \n:\n \nString"
},
{
"code": null,
"e": 4003,
"s": 3708,
"text": "This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4017,
"s": 4003,
"text": "solankimayank"
},
{
"code": null,
"e": 4031,
"s": 4017,
"text": "sumitgumber28"
},
{
"code": null,
"e": 4043,
"s": 4031,
"text": "aayushi2402"
},
{
"code": null,
"e": 4056,
"s": 4043,
"text": "Java-Library"
},
{
"code": null,
"e": 4069,
"s": 4056,
"text": "Java-Strings"
},
{
"code": null,
"e": 4074,
"s": 4069,
"text": "Java"
},
{
"code": null,
"e": 4087,
"s": 4074,
"text": "Java-Strings"
},
{
"code": null,
"e": 4092,
"s": 4087,
"text": "Java"
},
{
"code": null,
"e": 4190,
"s": 4092,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4241,
"s": 4190,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 4272,
"s": 4241,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 4291,
"s": 4272,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 4321,
"s": 4291,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 4336,
"s": 4321,
"text": "Stream In Java"
},
{
"code": null,
"e": 4354,
"s": 4336,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 4374,
"s": 4354,
"text": "Collections in Java"
},
{
"code": null,
"e": 4398,
"s": 4374,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 4430,
"s": 4398,
"text": "Multidimensional Arrays in Java"
}
] |
JavaScript | hasOwnProperty() Method
|
22 Nov, 2021
The hasOwnProperty() method in JavaScript is used to check whether the object has the specified property as its own property. This is useful for checking if the object has inherited the property rather than being it’s own.Syntax:
object.hasOwnProperty( prop )
Parameters: This method accepts single parameter prop which holds the name in the form of a String or a Symbol of the property to test.Return Value: It returns a boolean value indicating whether the object has the given property as its own property. Example 1: This example checks the properties on an object.
html
<!DOCTYPE html><html> <head> <title> JavaScript | hasOwnProperty() Method </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> hasOwnProperty() method in JavaScript </b> <p> Click on the button to check if the properties are of the object. </p> <p>Output for own property: <span class="outputProperty"></span> </p> <p>Output for not own property: <span class="outputNonProperty"></span> </p> <button onclick="checkProperty()"> Check properties </button> <script type="text/javascript"> function checkProperty() { let exampleObj = {}; exampleObj.height = 100; exampleObj.width = 100; // Checking for existing property result1 = exampleObj.hasOwnProperty("height"); // Checking for non-existing property result2 = exampleObj.hasOwnProperty("breadth"); document.querySelector(".outputProperty").textContent = result1; document.querySelector(".outputNonProperty").textContent = result2; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Example 2: This example checks the properties on an object of a class.
html
<!DOCTYPE html><html> <head> <title> JavaScript hasOwnProperty() method </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> hasOwnProperty() method in JavaScript </b> <p> Click on the button to check if the properties are of the object. </p> <p>Output for own property: <span class="outputProperty"></span> </p> <p>Output for not own property: <span class="outputNonProperty"></span> </p> <button onclick="checkProperty()"> Check properties </button> <script type="text/javascript"> function checkProperty() { function Car(a, b) { this.model = a; this.name = b; } let car1 = new Car("Mazda", "Laputa"); // Checking for existing property result1 = car1.hasOwnProperty("model"); // Checking for non-existing property result2 = car1.hasOwnProperty("wheels"); document.querySelector(".outputProperty").textContent = result1; document.querySelector(".outputNonProperty").textContent = result2; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Supported Browsers: The browsers supported by JavaScript hasOwnProperty() method are listed below:
Google Chrome 1 and above
Firefox 1 and above
Internet Explorer 5.5 and above
Edge 12 and above
Safari 3 and above
Opera 5 and above
ysachin2314
sumitgumber28
javascript-functions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 285,
"s": 53,
"text": "The hasOwnProperty() method in JavaScript is used to check whether the object has the specified property as its own property. This is useful for checking if the object has inherited the property rather than being it’s own.Syntax: "
},
{
"code": null,
"e": 315,
"s": 285,
"text": "object.hasOwnProperty( prop )"
},
{
"code": null,
"e": 626,
"s": 315,
"text": "Parameters: This method accepts single parameter prop which holds the name in the form of a String or a Symbol of the property to test.Return Value: It returns a boolean value indicating whether the object has the given property as its own property. Example 1: This example checks the properties on an object. "
},
{
"code": null,
"e": 631,
"s": 626,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript | hasOwnProperty() Method </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> hasOwnProperty() method in JavaScript </b> <p> Click on the button to check if the properties are of the object. </p> <p>Output for own property: <span class=\"outputProperty\"></span> </p> <p>Output for not own property: <span class=\"outputNonProperty\"></span> </p> <button onclick=\"checkProperty()\"> Check properties </button> <script type=\"text/javascript\"> function checkProperty() { let exampleObj = {}; exampleObj.height = 100; exampleObj.width = 100; // Checking for existing property result1 = exampleObj.hasOwnProperty(\"height\"); // Checking for non-existing property result2 = exampleObj.hasOwnProperty(\"breadth\"); document.querySelector(\".outputProperty\").textContent = result1; document.querySelector(\".outputNonProperty\").textContent = result2; } </script></body> </html>",
"e": 1875,
"s": 631,
"text": null
},
{
"code": null,
"e": 1885,
"s": 1875,
"text": "Output: "
},
{
"code": null,
"e": 1915,
"s": 1885,
"text": "Before clicking the button: "
},
{
"code": null,
"e": 1944,
"s": 1915,
"text": "After clicking the button: "
},
{
"code": null,
"e": 2016,
"s": 1944,
"text": "Example 2: This example checks the properties on an object of a class. "
},
{
"code": null,
"e": 2021,
"s": 2016,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript hasOwnProperty() method </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> hasOwnProperty() method in JavaScript </b> <p> Click on the button to check if the properties are of the object. </p> <p>Output for own property: <span class=\"outputProperty\"></span> </p> <p>Output for not own property: <span class=\"outputNonProperty\"></span> </p> <button onclick=\"checkProperty()\"> Check properties </button> <script type=\"text/javascript\"> function checkProperty() { function Car(a, b) { this.model = a; this.name = b; } let car1 = new Car(\"Mazda\", \"Laputa\"); // Checking for existing property result1 = car1.hasOwnProperty(\"model\"); // Checking for non-existing property result2 = car1.hasOwnProperty(\"wheels\"); document.querySelector(\".outputProperty\").textContent = result1; document.querySelector(\".outputNonProperty\").textContent = result2; } </script></body> </html>",
"e": 3320,
"s": 2021,
"text": null
},
{
"code": null,
"e": 3330,
"s": 3320,
"text": "Output: "
},
{
"code": null,
"e": 3360,
"s": 3330,
"text": "Before clicking the button: "
},
{
"code": null,
"e": 3389,
"s": 3360,
"text": "After clicking the button: "
},
{
"code": null,
"e": 3489,
"s": 3389,
"text": "Supported Browsers: The browsers supported by JavaScript hasOwnProperty() method are listed below: "
},
{
"code": null,
"e": 3515,
"s": 3489,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 3535,
"s": 3515,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 3567,
"s": 3535,
"text": "Internet Explorer 5.5 and above"
},
{
"code": null,
"e": 3585,
"s": 3567,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 3604,
"s": 3585,
"text": "Safari 3 and above"
},
{
"code": null,
"e": 3622,
"s": 3604,
"text": "Opera 5 and above"
},
{
"code": null,
"e": 3636,
"s": 3624,
"text": "ysachin2314"
},
{
"code": null,
"e": 3650,
"s": 3636,
"text": "sumitgumber28"
},
{
"code": null,
"e": 3671,
"s": 3650,
"text": "javascript-functions"
},
{
"code": null,
"e": 3678,
"s": 3671,
"text": "Picked"
},
{
"code": null,
"e": 3689,
"s": 3678,
"text": "JavaScript"
},
{
"code": null,
"e": 3706,
"s": 3689,
"text": "Web Technologies"
}
] |
Netstat command in Linux
|
24 May, 2019
Netstat command displays various network related information such as network connections, routing tables, interface statistics, masquerade connections, multicast memberships etc.,
Examples of some practical netstat command :
-a -all : Show both listening and non-listening sockets. With the –interfaces option, show interfaces that are not up# netstat -a | more : To show both listening and
non-listening sockets.List all tcp ports.# netstat -at : To list all tcp ports.
List all udp ports.# netstat -au : To list all udp ports.
List only listening ports.# netstat -l : To list only the listening ports.
List only listening TCP ports.# netstat -lt : To list only the listening tcp ports.
List only listening UDP ports.# netstat -lu : To list only the listening udp ports.
List only the listening UNIX ports# netstat -lx : To list only the listening UNIX ports.
List the statistics for all ports.# netstat -s : To list the statistics for all ports.
List the statistics for TCP (or) UDP ports.# netstat -st(TCP) : To list the statistics for TCP ports.
# netstat -su(UDP) : List the statistics for UDP ports.
Display PID and program names in the output.# netstat -pt : To display the PID and program names.
Print the netstat information continuously.netstat will print information continuously every few seconds.# netstat -c : To print the netstat information continuously.
The non-supportive address families in the system.# netstat --verbose : To get the non-supportive
address families in the system.
At the end, we have something like this :
The kernel routing information.# netstat -r : To get the kernel routing information.
The port on which a program is running.# netstat -ap | grep ssh : To get the port
on which a program is running.
Which process is using a particular port:# netstat -an | grep ':80' : To get the process
which is using the given port.
List of network interfaces.# netstat -i : To get the list of network interfaces.
Display extended information on the interfaces
(similar to ifconfig) using netstat -ie:
# netstat -ie : To display extended information
on the interfaces
Reference :Linux Manual page for netstatThis article is contributed by Kishlay Verma. 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.My Personal Notes
arrow_drop_upSave
-a -all : Show both listening and non-listening sockets. With the –interfaces option, show interfaces that are not up# netstat -a | more : To show both listening and
non-listening sockets.
# netstat -a | more : To show both listening and
non-listening sockets.
List all tcp ports.# netstat -at : To list all tcp ports.
# netstat -at : To list all tcp ports.
List all udp ports.# netstat -au : To list all udp ports.
# netstat -au : To list all udp ports.
List only listening ports.# netstat -l : To list only the listening ports.
# netstat -l : To list only the listening ports.
List only listening TCP ports.# netstat -lt : To list only the listening tcp ports.
# netstat -lt : To list only the listening tcp ports.
List only listening UDP ports.# netstat -lu : To list only the listening udp ports.
# netstat -lu : To list only the listening udp ports.
List only the listening UNIX ports# netstat -lx : To list only the listening UNIX ports.
# netstat -lx : To list only the listening UNIX ports.
List the statistics for all ports.# netstat -s : To list the statistics for all ports.
# netstat -s : To list the statistics for all ports.
List the statistics for TCP (or) UDP ports.# netstat -st(TCP) : To list the statistics for TCP ports.
# netstat -su(UDP) : List the statistics for UDP ports.
# netstat -st(TCP) : To list the statistics for TCP ports.
# netstat -su(UDP) : List the statistics for UDP ports.
Display PID and program names in the output.# netstat -pt : To display the PID and program names.
# netstat -pt : To display the PID and program names.
Print the netstat information continuously.netstat will print information continuously every few seconds.# netstat -c : To print the netstat information continuously.
netstat will print information continuously every few seconds.
# netstat -c : To print the netstat information continuously.
The non-supportive address families in the system.# netstat --verbose : To get the non-supportive
address families in the system.
At the end, we have something like this :
# netstat --verbose : To get the non-supportive
address families in the system.
At the end, we have something like this :
The kernel routing information.# netstat -r : To get the kernel routing information.
# netstat -r : To get the kernel routing information.
The port on which a program is running.# netstat -ap | grep ssh : To get the port
on which a program is running.
# netstat -ap | grep ssh : To get the port
on which a program is running.
Which process is using a particular port:# netstat -an | grep ':80' : To get the process
which is using the given port.
# netstat -an | grep ':80' : To get the process
which is using the given port.
List of network interfaces.# netstat -i : To get the list of network interfaces.
Display extended information on the interfaces
(similar to ifconfig) using netstat -ie:
# netstat -ie : To display extended information
on the interfaces
# netstat -i : To get the list of network interfaces.
Display extended information on the interfaces
(similar to ifconfig) using netstat -ie:
# netstat -ie : To display extended information
on the interfaces
Reference :Linux Manual page for netstat
This article is contributed by Kishlay Verma. 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.
linux-command
Linux-networking-commands
Computer Networks
Computer Networks Quiz
Linux-Unix
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 May, 2019"
},
{
"code": null,
"e": 232,
"s": 52,
"text": "Netstat command displays various network related information such as network connections, routing tables, interface statistics, masquerade connections, multicast memberships etc.,"
},
{
"code": null,
"e": 277,
"s": 232,
"text": "Examples of some practical netstat command :"
},
{
"code": null,
"e": 2653,
"s": 277,
"text": "-a -all : Show both listening and non-listening sockets. With the –interfaces option, show interfaces that are not up# netstat -a | more : To show both listening and \nnon-listening sockets.List all tcp ports.# netstat -at : To list all tcp ports.\nList all udp ports.# netstat -au : To list all udp ports.\nList only listening ports.# netstat -l : To list only the listening ports.\nList only listening TCP ports.# netstat -lt : To list only the listening tcp ports.\nList only listening UDP ports.# netstat -lu : To list only the listening udp ports.\nList only the listening UNIX ports# netstat -lx : To list only the listening UNIX ports.\nList the statistics for all ports.# netstat -s : To list the statistics for all ports.\nList the statistics for TCP (or) UDP ports.# netstat -st(TCP) : To list the statistics for TCP ports.\n# netstat -su(UDP) : List the statistics for UDP ports.\nDisplay PID and program names in the output.# netstat -pt : To display the PID and program names.\nPrint the netstat information continuously.netstat will print information continuously every few seconds.# netstat -c : To print the netstat information continuously.\nThe non-supportive address families in the system.# netstat --verbose : To get the non-supportive\naddress families in the system.\nAt the end, we have something like this : \nThe kernel routing information.# netstat -r : To get the kernel routing information.\nThe port on which a program is running.# netstat -ap | grep ssh : To get the port\non which a program is running.\nWhich process is using a particular port:# netstat -an | grep ':80' : To get the process\nwhich is using the given port.\nList of network interfaces.# netstat -i : To get the list of network interfaces.\nDisplay extended information on the interfaces \n(similar to ifconfig) using netstat -ie:\n\n# netstat -ie : To display extended information \non the interfaces\nReference :Linux Manual page for netstatThis article is contributed by Kishlay Verma. 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.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 2843,
"s": 2653,
"text": "-a -all : Show both listening and non-listening sockets. With the –interfaces option, show interfaces that are not up# netstat -a | more : To show both listening and \nnon-listening sockets."
},
{
"code": null,
"e": 2916,
"s": 2843,
"text": "# netstat -a | more : To show both listening and \nnon-listening sockets."
},
{
"code": null,
"e": 2975,
"s": 2916,
"text": "List all tcp ports.# netstat -at : To list all tcp ports.\n"
},
{
"code": null,
"e": 3015,
"s": 2975,
"text": "# netstat -at : To list all tcp ports.\n"
},
{
"code": null,
"e": 3074,
"s": 3015,
"text": "List all udp ports.# netstat -au : To list all udp ports.\n"
},
{
"code": null,
"e": 3114,
"s": 3074,
"text": "# netstat -au : To list all udp ports.\n"
},
{
"code": null,
"e": 3190,
"s": 3114,
"text": "List only listening ports.# netstat -l : To list only the listening ports.\n"
},
{
"code": null,
"e": 3240,
"s": 3190,
"text": "# netstat -l : To list only the listening ports.\n"
},
{
"code": null,
"e": 3325,
"s": 3240,
"text": "List only listening TCP ports.# netstat -lt : To list only the listening tcp ports.\n"
},
{
"code": null,
"e": 3380,
"s": 3325,
"text": "# netstat -lt : To list only the listening tcp ports.\n"
},
{
"code": null,
"e": 3465,
"s": 3380,
"text": "List only listening UDP ports.# netstat -lu : To list only the listening udp ports.\n"
},
{
"code": null,
"e": 3520,
"s": 3465,
"text": "# netstat -lu : To list only the listening udp ports.\n"
},
{
"code": null,
"e": 3610,
"s": 3520,
"text": "List only the listening UNIX ports# netstat -lx : To list only the listening UNIX ports.\n"
},
{
"code": null,
"e": 3666,
"s": 3610,
"text": "# netstat -lx : To list only the listening UNIX ports.\n"
},
{
"code": null,
"e": 3754,
"s": 3666,
"text": "List the statistics for all ports.# netstat -s : To list the statistics for all ports.\n"
},
{
"code": null,
"e": 3808,
"s": 3754,
"text": "# netstat -s : To list the statistics for all ports.\n"
},
{
"code": null,
"e": 3967,
"s": 3808,
"text": "List the statistics for TCP (or) UDP ports.# netstat -st(TCP) : To list the statistics for TCP ports.\n# netstat -su(UDP) : List the statistics for UDP ports.\n"
},
{
"code": null,
"e": 4027,
"s": 3967,
"text": "# netstat -st(TCP) : To list the statistics for TCP ports.\n"
},
{
"code": null,
"e": 4084,
"s": 4027,
"text": "# netstat -su(UDP) : List the statistics for UDP ports.\n"
},
{
"code": null,
"e": 4183,
"s": 4084,
"text": "Display PID and program names in the output.# netstat -pt : To display the PID and program names.\n"
},
{
"code": null,
"e": 4238,
"s": 4183,
"text": "# netstat -pt : To display the PID and program names.\n"
},
{
"code": null,
"e": 4406,
"s": 4238,
"text": "Print the netstat information continuously.netstat will print information continuously every few seconds.# netstat -c : To print the netstat information continuously.\n"
},
{
"code": null,
"e": 4469,
"s": 4406,
"text": "netstat will print information continuously every few seconds."
},
{
"code": null,
"e": 4532,
"s": 4469,
"text": "# netstat -c : To print the netstat information continuously.\n"
},
{
"code": null,
"e": 4706,
"s": 4532,
"text": "The non-supportive address families in the system.# netstat --verbose : To get the non-supportive\naddress families in the system.\nAt the end, we have something like this : \n"
},
{
"code": null,
"e": 4787,
"s": 4706,
"text": "# netstat --verbose : To get the non-supportive\naddress families in the system.\n"
},
{
"code": null,
"e": 4831,
"s": 4787,
"text": "At the end, we have something like this : \n"
},
{
"code": null,
"e": 4917,
"s": 4831,
"text": "The kernel routing information.# netstat -r : To get the kernel routing information.\n"
},
{
"code": null,
"e": 4972,
"s": 4917,
"text": "# netstat -r : To get the kernel routing information.\n"
},
{
"code": null,
"e": 5086,
"s": 4972,
"text": "The port on which a program is running.# netstat -ap | grep ssh : To get the port\non which a program is running.\n"
},
{
"code": null,
"e": 5161,
"s": 5086,
"text": "# netstat -ap | grep ssh : To get the port\non which a program is running.\n"
},
{
"code": null,
"e": 5282,
"s": 5161,
"text": "Which process is using a particular port:# netstat -an | grep ':80' : To get the process\nwhich is using the given port.\n"
},
{
"code": null,
"e": 5362,
"s": 5282,
"text": "# netstat -an | grep ':80' : To get the process\nwhich is using the given port.\n"
},
{
"code": null,
"e": 5601,
"s": 5362,
"text": "List of network interfaces.# netstat -i : To get the list of network interfaces.\nDisplay extended information on the interfaces \n(similar to ifconfig) using netstat -ie:\n\n# netstat -ie : To display extended information \non the interfaces\n"
},
{
"code": null,
"e": 5656,
"s": 5601,
"text": "# netstat -i : To get the list of network interfaces.\n"
},
{
"code": null,
"e": 5814,
"s": 5656,
"text": "Display extended information on the interfaces \n(similar to ifconfig) using netstat -ie:\n\n# netstat -ie : To display extended information \non the interfaces\n"
},
{
"code": null,
"e": 5855,
"s": 5814,
"text": "Reference :Linux Manual page for netstat"
},
{
"code": null,
"e": 6156,
"s": 5855,
"text": "This article is contributed by Kishlay Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 6281,
"s": 6156,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 6295,
"s": 6281,
"text": "linux-command"
},
{
"code": null,
"e": 6321,
"s": 6295,
"text": "Linux-networking-commands"
},
{
"code": null,
"e": 6339,
"s": 6321,
"text": "Computer Networks"
},
{
"code": null,
"e": 6362,
"s": 6339,
"text": "Computer Networks Quiz"
},
{
"code": null,
"e": 6373,
"s": 6362,
"text": "Linux-Unix"
},
{
"code": null,
"e": 6391,
"s": 6373,
"text": "Computer Networks"
}
] |
A beginner’s guide to joining data | by Skyler Dale | Towards Data Science
|
Joining data is one of the fundamental skills of data analysis. Unfortunately, it can also be a bit confusing when you’re just getting started, or when you’re making the transition from excel to SQL or Python.
In this article, I’ll walk through an intuitive explanation of what it means to join data and how to do it effectively.
The best way to understand joins is to work through a simple example.
Let’s say you work for a company that sells T-shirts on a website.
You have one dataset that tells you details about your website users. For simplicity’s sake, let’s say this table contains just a unique client ID, client name, and country of origin:
You have another dataset that tells you all of the purchases that those website users have made:
Your boss walks into the room and demands that you tell her which country has the most website sales.
To answer her question, you need to bring the data that tells you where your clients are located together with the data that tells you what they’ve purchased. In other words, for each transaction, you need to figure out where the client was located.
What makes this possible is the fact that there is some commonality between the two datasets. In this case, it’s the client ID.
To “join” is simply to combine data based on a common data point. Fittingly, that common data point is called a “join key.”
For this example, we can join the user data to the purchase data with the SQL query below, which uses “client ID” as the join key:
select purchases.client_id, purchases.sale, users.country from purchasesleft join userson purchases.client_id = users.client_id;
And voila:
Now we can see that Mexico has the most sales. (Note: if we had more than a few rows, we would want to use a “groupby” and a “sum” function. But since we don’t have much data in the above example, we can easily answer this question on sight and leave those topics for another day.)
If you’re new to data analysis, you may find yourself wondering, why do we need to join data in the first place? Why can’t the data just live in one table?
There are two main reasons for this. First, data often gets acquired from different sources. Your process for getting the users data and the transaction data might be separate.
If you’re a power user of excel, think about all the times you’ve had to do a vlookup to connect two data sources. In essence, that was a join.
The second reason has to do with speed. Generally, the more data you have in one table, the longer it will take to retrieve what you need from it.
Great, now we have the intuition behind what joins are and why we need them. Next, we’ll need to learn about the different types of joins.
This is an area where people often get tripped up, so let’s try to make this part very clear.
There is one reason why we need multiple types of joins. If you can remember the reason, then you will be able to remember the types.
Here’s the reason: When the values in your join key do not exist in both datasets that you are joining, the computer needs to know what to return.
Now let’s look at an example based on our dataset from earlier.
The client_id of “8367” is in the users table:
But its not in the transactions table:
Thus the “type” of join simply tells the computer what to do in this scenario.
As the proud author of the query — you have control over what you want the computer to return.
A “left join” tells the computer: “give me everything in the left table, even if it’s not in the right table.”
Remember from the example earlier — we used a left join and got only the client_ids from the left table:
A “full outer join” tells the computer, “give me all the records in both tables.”
As a result, we get the client ids from both tables, including 1902 and 8367 — which are only in the users table — as well as 1000, which is only in the purchases table.
Notice that the some of the cells in the table above have “null” (ie. missing) values. This makes sense because this data does not actually exist in the original tables.
We know client id 1000 made a $10 purchase, but don’t know where this client is from. If it was missing in the original data, it will be missing after the join.
Finally, an “inner join” tells the computer — “give me only the records whose join keys are in both tables.”
The above query returns:
Note that all of the non-overlapping client IDs — 1902, 8367, and 1000 — are missing from the result set.
A few things to consider as you learn more about joining data:
Right Joins: A “right join” tells the computer “give me everything in the right table even if it’s not in the left table”. I’ve never used a right join. Why? Because anytime you want to do a right join you can just flip the order of the tables and do a left join. One less thing to remember.Multi-key joins: You can join on more than one column value. (ie. left join on table1.id1 = table2.id1 AND table1.id2 = table2.id2)Duplicates: Always pay attention to the number of records in your table before and after a join. A common beginner mistake is to execute a join that creates unwanted duplicates. If you run into this scenario, you will have to think critically about how you can rewrite the join to give you what you truly want.
Right Joins: A “right join” tells the computer “give me everything in the right table even if it’s not in the left table”. I’ve never used a right join. Why? Because anytime you want to do a right join you can just flip the order of the tables and do a left join. One less thing to remember.
Multi-key joins: You can join on more than one column value. (ie. left join on table1.id1 = table2.id1 AND table1.id2 = table2.id2)
Duplicates: Always pay attention to the number of records in your table before and after a join. A common beginner mistake is to execute a join that creates unwanted duplicates. If you run into this scenario, you will have to think critically about how you can rewrite the join to give you what you truly want.
|
[
{
"code": null,
"e": 382,
"s": 172,
"text": "Joining data is one of the fundamental skills of data analysis. Unfortunately, it can also be a bit confusing when you’re just getting started, or when you’re making the transition from excel to SQL or Python."
},
{
"code": null,
"e": 502,
"s": 382,
"text": "In this article, I’ll walk through an intuitive explanation of what it means to join data and how to do it effectively."
},
{
"code": null,
"e": 572,
"s": 502,
"text": "The best way to understand joins is to work through a simple example."
},
{
"code": null,
"e": 639,
"s": 572,
"text": "Let’s say you work for a company that sells T-shirts on a website."
},
{
"code": null,
"e": 823,
"s": 639,
"text": "You have one dataset that tells you details about your website users. For simplicity’s sake, let’s say this table contains just a unique client ID, client name, and country of origin:"
},
{
"code": null,
"e": 920,
"s": 823,
"text": "You have another dataset that tells you all of the purchases that those website users have made:"
},
{
"code": null,
"e": 1022,
"s": 920,
"text": "Your boss walks into the room and demands that you tell her which country has the most website sales."
},
{
"code": null,
"e": 1272,
"s": 1022,
"text": "To answer her question, you need to bring the data that tells you where your clients are located together with the data that tells you what they’ve purchased. In other words, for each transaction, you need to figure out where the client was located."
},
{
"code": null,
"e": 1400,
"s": 1272,
"text": "What makes this possible is the fact that there is some commonality between the two datasets. In this case, it’s the client ID."
},
{
"code": null,
"e": 1524,
"s": 1400,
"text": "To “join” is simply to combine data based on a common data point. Fittingly, that common data point is called a “join key.”"
},
{
"code": null,
"e": 1655,
"s": 1524,
"text": "For this example, we can join the user data to the purchase data with the SQL query below, which uses “client ID” as the join key:"
},
{
"code": null,
"e": 1784,
"s": 1655,
"text": "select purchases.client_id, purchases.sale, users.country from purchasesleft join userson purchases.client_id = users.client_id;"
},
{
"code": null,
"e": 1795,
"s": 1784,
"text": "And voila:"
},
{
"code": null,
"e": 2077,
"s": 1795,
"text": "Now we can see that Mexico has the most sales. (Note: if we had more than a few rows, we would want to use a “groupby” and a “sum” function. But since we don’t have much data in the above example, we can easily answer this question on sight and leave those topics for another day.)"
},
{
"code": null,
"e": 2233,
"s": 2077,
"text": "If you’re new to data analysis, you may find yourself wondering, why do we need to join data in the first place? Why can’t the data just live in one table?"
},
{
"code": null,
"e": 2410,
"s": 2233,
"text": "There are two main reasons for this. First, data often gets acquired from different sources. Your process for getting the users data and the transaction data might be separate."
},
{
"code": null,
"e": 2554,
"s": 2410,
"text": "If you’re a power user of excel, think about all the times you’ve had to do a vlookup to connect two data sources. In essence, that was a join."
},
{
"code": null,
"e": 2701,
"s": 2554,
"text": "The second reason has to do with speed. Generally, the more data you have in one table, the longer it will take to retrieve what you need from it."
},
{
"code": null,
"e": 2840,
"s": 2701,
"text": "Great, now we have the intuition behind what joins are and why we need them. Next, we’ll need to learn about the different types of joins."
},
{
"code": null,
"e": 2934,
"s": 2840,
"text": "This is an area where people often get tripped up, so let’s try to make this part very clear."
},
{
"code": null,
"e": 3068,
"s": 2934,
"text": "There is one reason why we need multiple types of joins. If you can remember the reason, then you will be able to remember the types."
},
{
"code": null,
"e": 3215,
"s": 3068,
"text": "Here’s the reason: When the values in your join key do not exist in both datasets that you are joining, the computer needs to know what to return."
},
{
"code": null,
"e": 3279,
"s": 3215,
"text": "Now let’s look at an example based on our dataset from earlier."
},
{
"code": null,
"e": 3326,
"s": 3279,
"text": "The client_id of “8367” is in the users table:"
},
{
"code": null,
"e": 3365,
"s": 3326,
"text": "But its not in the transactions table:"
},
{
"code": null,
"e": 3444,
"s": 3365,
"text": "Thus the “type” of join simply tells the computer what to do in this scenario."
},
{
"code": null,
"e": 3539,
"s": 3444,
"text": "As the proud author of the query — you have control over what you want the computer to return."
},
{
"code": null,
"e": 3650,
"s": 3539,
"text": "A “left join” tells the computer: “give me everything in the left table, even if it’s not in the right table.”"
},
{
"code": null,
"e": 3755,
"s": 3650,
"text": "Remember from the example earlier — we used a left join and got only the client_ids from the left table:"
},
{
"code": null,
"e": 3837,
"s": 3755,
"text": "A “full outer join” tells the computer, “give me all the records in both tables.”"
},
{
"code": null,
"e": 4007,
"s": 3837,
"text": "As a result, we get the client ids from both tables, including 1902 and 8367 — which are only in the users table — as well as 1000, which is only in the purchases table."
},
{
"code": null,
"e": 4177,
"s": 4007,
"text": "Notice that the some of the cells in the table above have “null” (ie. missing) values. This makes sense because this data does not actually exist in the original tables."
},
{
"code": null,
"e": 4338,
"s": 4177,
"text": "We know client id 1000 made a $10 purchase, but don’t know where this client is from. If it was missing in the original data, it will be missing after the join."
},
{
"code": null,
"e": 4447,
"s": 4338,
"text": "Finally, an “inner join” tells the computer — “give me only the records whose join keys are in both tables.”"
},
{
"code": null,
"e": 4472,
"s": 4447,
"text": "The above query returns:"
},
{
"code": null,
"e": 4578,
"s": 4472,
"text": "Note that all of the non-overlapping client IDs — 1902, 8367, and 1000 — are missing from the result set."
},
{
"code": null,
"e": 4641,
"s": 4578,
"text": "A few things to consider as you learn more about joining data:"
},
{
"code": null,
"e": 5374,
"s": 4641,
"text": "Right Joins: A “right join” tells the computer “give me everything in the right table even if it’s not in the left table”. I’ve never used a right join. Why? Because anytime you want to do a right join you can just flip the order of the tables and do a left join. One less thing to remember.Multi-key joins: You can join on more than one column value. (ie. left join on table1.id1 = table2.id1 AND table1.id2 = table2.id2)Duplicates: Always pay attention to the number of records in your table before and after a join. A common beginner mistake is to execute a join that creates unwanted duplicates. If you run into this scenario, you will have to think critically about how you can rewrite the join to give you what you truly want."
},
{
"code": null,
"e": 5666,
"s": 5374,
"text": "Right Joins: A “right join” tells the computer “give me everything in the right table even if it’s not in the left table”. I’ve never used a right join. Why? Because anytime you want to do a right join you can just flip the order of the tables and do a left join. One less thing to remember."
},
{
"code": null,
"e": 5798,
"s": 5666,
"text": "Multi-key joins: You can join on more than one column value. (ie. left join on table1.id1 = table2.id1 AND table1.id2 = table2.id2)"
}
] |
JavaScript to Calculate the nth root of a number
|
We are required to write a JavaScript function that calculates the nth root of a number and returns it.
The code for this will be −
const findNthRoot = (m, n) => {
try {
let negate = n % 2 == 1 && m < 0;
if(negate)
m = −m;
let possible = Math.pow(m, 1 / n);
n = Math.pow(possible, n);
if(Math.abs(m − n) < 1 && (m > 0 == n > 0))
return negate ? −possible : possible;
} catch(e){
return null;
}
};
console.log(findNthRoot(45, 6));
And the output in the console will be −
1.8859727740585395
|
[
{
"code": null,
"e": 1166,
"s": 1062,
"text": "We are required to write a JavaScript function that calculates the nth root of a number and returns it."
},
{
"code": null,
"e": 1194,
"s": 1166,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1552,
"s": 1194,
"text": "const findNthRoot = (m, n) => {\n try {\n let negate = n % 2 == 1 && m < 0;\n if(negate)\n m = −m;\n let possible = Math.pow(m, 1 / n);\n n = Math.pow(possible, n);\n if(Math.abs(m − n) < 1 && (m > 0 == n > 0))\n return negate ? −possible : possible;\n } catch(e){\n return null;\n }\n};\nconsole.log(findNthRoot(45, 6));"
},
{
"code": null,
"e": 1592,
"s": 1552,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 1611,
"s": 1592,
"text": "1.8859727740585395"
}
] |
ES6 | Promises - GeeksforGeeks
|
25 Mar, 2022
Promises are a way to implement asynchronous programming in JavaScript(ES6 which is also known as ECMAScript-6). A Promise acts as a container for future values. Like if you order any food from any site to deliver it to your place that order record will be the promise and the food will be the value of that promise. So the order details are the container of the food you ordered. Let’s explain it with another example. You order an awesome camera online. After your order is placed you receive a receipt of the order. That receipt is a Promise that your order will be delivered to you. The receipt is a placeholder for the future value namely the camera. Promises used in JavaScript for asynchronous programming. For asynchronous programming, JavaScript uses callbacks , but there is a problem using the callback which is callback hell (multiple or dependent callbacks) or Pyramid of Doom. Using the ES6 Promise will simply avoid all the problems associated with the callback. Need of Promises: The Callbacks are great when dealing with basic cases. But in while developing a web application where you have a lot of code. Callbacks can be great trouble. In complex cases, every callback adds a level of nesting which can make your code really messy and hard to understand. In simple words, having multiple callbacks in the code, increases the complexity of the code in terms of readability, executability and many other terms. This excessive nesting of callbacks is often termed as Callback Hell. Example: Callback Hell
javascript
f1(function(x){ f2(x, function(y){ f3(y, function(z){ ... }); });});
To deal with this problem, we use Promises instead of callbacks. Making Promises: A Promise is created when we are unsure of whether or not the assigned task will be completed. The Promise object represents the eventual completion (or failure) of an async(asynchronous) operation and its resulting value. As the name suggests from real life itself, a Promise is either kept or broken. A Promise is always in one of the following states:
fulfilled: Action related to the promise succeeded.
rejected: Action related to the promise failed.
pending: Promise is still pending i.e not fulfilled or rejected yet.
settled: Promise has fulfilled or rejected
Syntax:
const promise = new Promise((resolve,reject) => {....});
Example:
javascript
const myPromise = new Promise((resolve, reject) => { if (Math.random() > 0) { resolve('Hello, I am positive number!'); } reject(new Error('I failed some times'));})
Callbacks to Promises: There are two types of callbacks which are used for handling promises .then() and .catch(). It can be used for handling promises in case of fulfillment (promise is kept) or rejection (promise is broken).
.then(): Invoked when a promise is kept or broken. It can be chained to handle the fulfillment or rejection of a promise. It takes in two functions as parameters. The first one is invoked if the promise is fulfilled and the second one(optional) is invoked if the promise is rejected. Example: Handling Promise rejection using .then()
javascript
var promise = new Promise(function(resolve, reject) { resolve('Hello, I am a Promise!');}) promise.then(function(promise_kept_message) { console.log(promise_kept_message); }, function(error) { // This function is invoked this time // as the Promise is rejected. console.log(error); })
.catch() can be used for handling the errors(if any). It takes only one function as a parameter which is used to handle the errors (if any). Example: Handling Promise rejection(or errors) using .catch()
javascript
const myPromise = new Promise((resolve, reject) => { if (Math.random() > 0) { console.log('resolving the promise ...'); resolve('Hello, Positive :)'); } reject(new Error('No place for Negative here :('));}); const Fulfilled = (fulfilledValue) => console.log(fulfilledValue);const Rejected = (error) => console.log(error);myPromise.then(Fulfilled, Rejected); myPromise.then((fulfilledValue) => { console.log(fulfilledValue);}}).catch(err => console.log(err));
amansingla
JavaScript-ES
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 24270,
"s": 24242,
"text": "\n25 Mar, 2022"
},
{
"code": null,
"e": 25793,
"s": 24270,
"text": "Promises are a way to implement asynchronous programming in JavaScript(ES6 which is also known as ECMAScript-6). A Promise acts as a container for future values. Like if you order any food from any site to deliver it to your place that order record will be the promise and the food will be the value of that promise. So the order details are the container of the food you ordered. Let’s explain it with another example. You order an awesome camera online. After your order is placed you receive a receipt of the order. That receipt is a Promise that your order will be delivered to you. The receipt is a placeholder for the future value namely the camera. Promises used in JavaScript for asynchronous programming. For asynchronous programming, JavaScript uses callbacks , but there is a problem using the callback which is callback hell (multiple or dependent callbacks) or Pyramid of Doom. Using the ES6 Promise will simply avoid all the problems associated with the callback. Need of Promises: The Callbacks are great when dealing with basic cases. But in while developing a web application where you have a lot of code. Callbacks can be great trouble. In complex cases, every callback adds a level of nesting which can make your code really messy and hard to understand. In simple words, having multiple callbacks in the code, increases the complexity of the code in terms of readability, executability and many other terms. This excessive nesting of callbacks is often termed as Callback Hell. Example: Callback Hell "
},
{
"code": null,
"e": 25804,
"s": 25793,
"text": "javascript"
},
{
"code": "f1(function(x){ f2(x, function(y){ f3(y, function(z){ ... }); });});",
"e": 25904,
"s": 25804,
"text": null
},
{
"code": null,
"e": 26341,
"s": 25904,
"text": "To deal with this problem, we use Promises instead of callbacks. Making Promises: A Promise is created when we are unsure of whether or not the assigned task will be completed. The Promise object represents the eventual completion (or failure) of an async(asynchronous) operation and its resulting value. As the name suggests from real life itself, a Promise is either kept or broken. A Promise is always in one of the following states:"
},
{
"code": null,
"e": 26393,
"s": 26341,
"text": "fulfilled: Action related to the promise succeeded."
},
{
"code": null,
"e": 26441,
"s": 26393,
"text": "rejected: Action related to the promise failed."
},
{
"code": null,
"e": 26510,
"s": 26441,
"text": "pending: Promise is still pending i.e not fulfilled or rejected yet."
},
{
"code": null,
"e": 26553,
"s": 26510,
"text": "settled: Promise has fulfilled or rejected"
},
{
"code": null,
"e": 26561,
"s": 26553,
"text": "Syntax:"
},
{
"code": null,
"e": 26619,
"s": 26561,
"text": "const promise = new Promise((resolve,reject) => {....}); "
},
{
"code": null,
"e": 26629,
"s": 26619,
"text": "Example: "
},
{
"code": null,
"e": 26640,
"s": 26629,
"text": "javascript"
},
{
"code": "const myPromise = new Promise((resolve, reject) => { if (Math.random() > 0) { resolve('Hello, I am positive number!'); } reject(new Error('I failed some times'));})",
"e": 26821,
"s": 26640,
"text": null
},
{
"code": null,
"e": 27048,
"s": 26821,
"text": "Callbacks to Promises: There are two types of callbacks which are used for handling promises .then() and .catch(). It can be used for handling promises in case of fulfillment (promise is kept) or rejection (promise is broken)."
},
{
"code": null,
"e": 27383,
"s": 27048,
"text": ".then(): Invoked when a promise is kept or broken. It can be chained to handle the fulfillment or rejection of a promise. It takes in two functions as parameters. The first one is invoked if the promise is fulfilled and the second one(optional) is invoked if the promise is rejected. Example: Handling Promise rejection using .then() "
},
{
"code": null,
"e": 27394,
"s": 27383,
"text": "javascript"
},
{
"code": "var promise = new Promise(function(resolve, reject) { resolve('Hello, I am a Promise!');}) promise.then(function(promise_kept_message) { console.log(promise_kept_message); }, function(error) { // This function is invoked this time // as the Promise is rejected. console.log(error); })",
"e": 27725,
"s": 27394,
"text": null
},
{
"code": null,
"e": 27929,
"s": 27725,
"text": ".catch() can be used for handling the errors(if any). It takes only one function as a parameter which is used to handle the errors (if any). Example: Handling Promise rejection(or errors) using .catch() "
},
{
"code": null,
"e": 27940,
"s": 27929,
"text": "javascript"
},
{
"code": "const myPromise = new Promise((resolve, reject) => { if (Math.random() > 0) { console.log('resolving the promise ...'); resolve('Hello, Positive :)'); } reject(new Error('No place for Negative here :('));}); const Fulfilled = (fulfilledValue) => console.log(fulfilledValue);const Rejected = (error) => console.log(error);myPromise.then(Fulfilled, Rejected); myPromise.then((fulfilledValue) => { console.log(fulfilledValue);}}).catch(err => console.log(err));",
"e": 28425,
"s": 27940,
"text": null
},
{
"code": null,
"e": 28436,
"s": 28425,
"text": "amansingla"
},
{
"code": null,
"e": 28450,
"s": 28436,
"text": "JavaScript-ES"
},
{
"code": null,
"e": 28457,
"s": 28450,
"text": "Picked"
},
{
"code": null,
"e": 28468,
"s": 28457,
"text": "JavaScript"
},
{
"code": null,
"e": 28485,
"s": 28468,
"text": "Web Technologies"
},
{
"code": null,
"e": 28583,
"s": 28485,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28628,
"s": 28583,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28689,
"s": 28628,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28761,
"s": 28689,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28813,
"s": 28761,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28859,
"s": 28813,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 28901,
"s": 28859,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28934,
"s": 28901,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28977,
"s": 28934,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29027,
"s": 28977,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to Install and Configure an NTP Client and Server on Linux?
|
This article will help to know how to configure an NTP (Network Time Protocol) server and client on RHEL/Cent OS Linux to manage the system clock with to help of an NTP server.
NPT is used to synchronize a computer’s machine’s time with another time source. In RHEL / CentOS Linux we can use NTP or OpenNTPD server, which provides client and server software for time synchronization.
The NTP package have utilities and daemons that will synchronize the machine time to Coordinated Universal Time (UTC) via the NTP protocol. The NTP package has ntpdate (Which updates the date and time from the remote machines using the network) and ntpd (A daemon which adjusts the system time).
# yum install ntp -y
Loaded plugins: fastestmirror, security
Setting up Install Process
Loading mirror speeds from cached hostfile
* base: ftp.iitm.ac.in
* epel: mirror01.idc.hinet.net
* extras: ftp.iitm.ac.in
* updates: ftp.iitm.ac.in
Resolving Dependencies
--> Running transaction check
---> Package ntp.x86_64 0:4.2.6p5-5.el6.ntosce will be updated
---> Package ntp.x86_64 0:4.2.6p5-5.el6.centos.4 will be an update
--> Processing Dependency: ntpdate = 4.2.6p5-5.el6.centos.4 for package: ntp-4.2.6p5-5.el6.c entos.4.x86_64
--> Running transaction check
---> Package ntpdate.x86_64 0:4.2.6p5-5.el6.centos will be updated
---> Package ntpdate.x86_64 0:4.2.6p5-5.el6.centos.4 will be an update
--> Finished Dependency Resolution
Dependencies Resolved
============================================================================================
Package Arch Version Repository Size
============================================================================================
Updating:
ntp x86_64 4.2.6p5-5.el6.centos.4 updates 595 k
Updating for dependencies:
ntpdate x86_64 4.2.6p5-5.el6.centos.4 updates 77 k
Transaction Summary
============================================================================================
Upgrade 2 Package(s)
Total download size: 672 k
Downloading Packages:
(1/2): ntp-4.2.6p5-5.el6.centos.4.x86_64.rpm | 595 kB 00:00
(2/2): ntpdate-4.2.6p5-5.el6.centos.4.x86_64.rpm | 77 kB 00:00
--------------------------------------------------------------------------------------------
Total 261 kB/s | 672 kB 00:02
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
Updating : ntpdate-4.2.6p5-5.el6.centos.4.x86_64 1/4
Updating : ntp-4.2.6p5-5.el6.centos.4.x86_64 2/4
Cleanup : ntp-4.2.6p5-5.el6.centos.x86_64 3/4
Cleanup : ntpdate-4.2.6p5-5.el6.centos.x86_64 4/4
Verifying : ntp-4.2.6p5-5.el6.centos.4.x86_64 1/4
Verifying : ntpdate-4.2.6p5-5.el6.centos.4.x86_64 2/4
Verifying : ntpdate-4.2.6p5-5.el6.centos.x86_64 3/4
Verifying : ntp-4.2.6p5-5.el6.centos.x86_64 4/4
Updated:
ntp.x86_64 0:4.2.6p5-5.el6.centos.4
Dependency Updated:
ntpdate.x86_64 0:4.2.6p5-5.el6.centos.4
Complete!
If we have lots of server and desktop machines in the environment and then we should have the NTP server so that all the servers can contact and update the NTP server provided by the ISP or the Public time located at ntp.org. The server then allows the other machines in our network to request the time date.
192.167.87.150 Local NTPD server
81.6.42.224 ISP NTP server
192.168.87.0/24 NTP clients network
Open the configuration file and add the following lines –
restrict default ignore
The Above will deny all the access to any machine, server or clients. We needed to add the specific authorization policy to settings
restrict 81.6.42.224 mask 255.255.255.245 nomodify notrap noquery
server 81.6.42.224
NTP server Now we needed to allow NTP clients to access the Server, to our network, we allow 192.168.87.0/24 network to synchronize the time over network located in the own environment
192.168.87.150
Open /etc/ntp.conf file and all the bellow lines so that it looks the local NTP server.
# Hosts on local network are less restricted.
restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap
Save the config file and restart the NTP services
# service ntpd start
Open /etc/ntp.conf and edit the file
# vi /etc/ntp.conf
And make sure the following line exists
# Server ntp.server.com
Where ntp.server.com is the hostname/IP address of the site. If your NTP server is located at 192.168.87.156 enter server 192.168.87.156 if we have a public NTP server then provide the server IP address.
Run the below command to update the ntpd file in cron’s and it will instructs crond to run the ntpd and set the clock and exis and -u use the user name ntp to do the clock changes.
# echo ’30 * * * * root /usr/sbin/ntpd -q -u ntp:ntp’ > /etc/cron.d/ntpd
After the successful configuration using the above steps we can configure a standalone an NTP client and also configure an NTP server in the local environment to an NTP server to all the local client and server.
|
[
{
"code": null,
"e": 1239,
"s": 1062,
"text": "This article will help to know how to configure an NTP (Network Time Protocol) server and client on RHEL/Cent OS Linux to manage the system clock with to help of an NTP server."
},
{
"code": null,
"e": 1446,
"s": 1239,
"text": "NPT is used to synchronize a computer’s machine’s time with another time source. In RHEL / CentOS Linux we can use NTP or OpenNTPD server, which provides client and server software for time synchronization."
},
{
"code": null,
"e": 1742,
"s": 1446,
"text": "The NTP package have utilities and daemons that will synchronize the machine time to Coordinated Universal Time (UTC) via the NTP protocol. The NTP package has ntpdate (Which updates the date and time from the remote machines using the network) and ntpd (A daemon which adjusts the system time)."
},
{
"code": null,
"e": 4098,
"s": 1742,
"text": "# yum install ntp -y\nLoaded plugins: fastestmirror, security\nSetting up Install Process\nLoading mirror speeds from cached hostfile\n * base: ftp.iitm.ac.in\n * epel: mirror01.idc.hinet.net\n * extras: ftp.iitm.ac.in\n * updates: ftp.iitm.ac.in\nResolving Dependencies\n--> Running transaction check\n---> Package ntp.x86_64 0:4.2.6p5-5.el6.ntosce will be updated\n---> Package ntp.x86_64 0:4.2.6p5-5.el6.centos.4 will be an update\n--> Processing Dependency: ntpdate = 4.2.6p5-5.el6.centos.4 for package: ntp-4.2.6p5-5.el6.c entos.4.x86_64\n--> Running transaction check\n---> Package ntpdate.x86_64 0:4.2.6p5-5.el6.centos will be updated\n---> Package ntpdate.x86_64 0:4.2.6p5-5.el6.centos.4 will be an update\n--> Finished Dependency Resolution\nDependencies Resolved\n============================================================================================\nPackage Arch Version Repository Size\n============================================================================================\nUpdating:\nntp x86_64 4.2.6p5-5.el6.centos.4 updates 595 k\nUpdating for dependencies:\nntpdate x86_64 4.2.6p5-5.el6.centos.4 updates 77 k\nTransaction Summary\n============================================================================================\nUpgrade 2 Package(s)\nTotal download size: 672 k\nDownloading Packages:\n(1/2): ntp-4.2.6p5-5.el6.centos.4.x86_64.rpm | 595 kB 00:00\n(2/2): ntpdate-4.2.6p5-5.el6.centos.4.x86_64.rpm | 77 kB 00:00\n--------------------------------------------------------------------------------------------\nTotal 261 kB/s | 672 kB 00:02\nRunning rpm_check_debug\nRunning Transaction Test\nTransaction Test Succeeded\nRunning Transaction\n Updating : ntpdate-4.2.6p5-5.el6.centos.4.x86_64 1/4\n Updating : ntp-4.2.6p5-5.el6.centos.4.x86_64 2/4\n Cleanup : ntp-4.2.6p5-5.el6.centos.x86_64 3/4\n Cleanup : ntpdate-4.2.6p5-5.el6.centos.x86_64 4/4\n Verifying : ntp-4.2.6p5-5.el6.centos.4.x86_64 1/4\n Verifying : ntpdate-4.2.6p5-5.el6.centos.4.x86_64 2/4\n Verifying : ntpdate-4.2.6p5-5.el6.centos.x86_64 3/4\n Verifying : ntp-4.2.6p5-5.el6.centos.x86_64 4/4\nUpdated:\n ntp.x86_64 0:4.2.6p5-5.el6.centos.4\nDependency Updated:\n ntpdate.x86_64 0:4.2.6p5-5.el6.centos.4\nComplete!"
},
{
"code": null,
"e": 4407,
"s": 4098,
"text": "If we have lots of server and desktop machines in the environment and then we should have the NTP server so that all the servers can contact and update the NTP server provided by the ISP or the Public time located at ntp.org. The server then allows the other machines in our network to request the time date."
},
{
"code": null,
"e": 4510,
"s": 4407,
"text": "192.167.87.150 Local NTPD server\n81.6.42.224 ISP NTP server\n192.168.87.0/24 NTP clients network"
},
{
"code": null,
"e": 4568,
"s": 4510,
"text": "Open the configuration file and add the following lines –"
},
{
"code": null,
"e": 4592,
"s": 4568,
"text": "restrict default ignore"
},
{
"code": null,
"e": 4725,
"s": 4592,
"text": "The Above will deny all the access to any machine, server or clients. We needed to add the specific authorization policy to settings"
},
{
"code": null,
"e": 4810,
"s": 4725,
"text": "restrict 81.6.42.224 mask 255.255.255.245 nomodify notrap noquery\nserver 81.6.42.224"
},
{
"code": null,
"e": 4995,
"s": 4810,
"text": "NTP server Now we needed to allow NTP clients to access the Server, to our network, we allow 192.168.87.0/24 network to synchronize the time over network located in the own environment"
},
{
"code": null,
"e": 5010,
"s": 4995,
"text": "192.168.87.150"
},
{
"code": null,
"e": 5098,
"s": 5010,
"text": "Open /etc/ntp.conf file and all the bellow lines so that it looks the local NTP server."
},
{
"code": null,
"e": 5200,
"s": 5098,
"text": "# Hosts on local network are less restricted.\nrestrict 192.168.1.0 mask 255.255.255.0 nomodify notrap"
},
{
"code": null,
"e": 5250,
"s": 5200,
"text": "Save the config file and restart the NTP services"
},
{
"code": null,
"e": 5271,
"s": 5250,
"text": "# service ntpd start"
},
{
"code": null,
"e": 5308,
"s": 5271,
"text": "Open /etc/ntp.conf and edit the file"
},
{
"code": null,
"e": 5327,
"s": 5308,
"text": "# vi /etc/ntp.conf"
},
{
"code": null,
"e": 5367,
"s": 5327,
"text": "And make sure the following line exists"
},
{
"code": null,
"e": 5391,
"s": 5367,
"text": "# Server ntp.server.com"
},
{
"code": null,
"e": 5595,
"s": 5391,
"text": "Where ntp.server.com is the hostname/IP address of the site. If your NTP server is located at 192.168.87.156 enter server 192.168.87.156 if we have a public NTP server then provide the server IP address."
},
{
"code": null,
"e": 5776,
"s": 5595,
"text": "Run the below command to update the ntpd file in cron’s and it will instructs crond to run the ntpd and set the clock and exis and -u use the user name ntp to do the clock changes."
},
{
"code": null,
"e": 5849,
"s": 5776,
"text": "# echo ’30 * * * * root /usr/sbin/ntpd -q -u ntp:ntp’ > /etc/cron.d/ntpd"
},
{
"code": null,
"e": 6061,
"s": 5849,
"text": "After the successful configuration using the above steps we can configure a standalone an NTP client and also configure an NTP server in the local environment to an NTP server to all the local client and server."
}
] |
Tryit Editor v3.6 - Show Node.js
|
var http = require('http');
http.createServer(function (req, res) {
// add a HTTP header:
res.writeHead(200, {'Content-Type': 'text/html'});
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "var http = require('http');"
},
{
"code": null,
"e": 30,
"s": 28,
"text": ""
},
{
"code": null,
"e": 70,
"s": 30,
"text": "http.createServer(function (req, res) {"
},
{
"code": null,
"e": 94,
"s": 70,
"text": " // add a HTTP header:"
}
] |
How to set src to the img tag in html from the system drive?
|
To use an image on a webpage, use the <img> tag. The tag allows you to add image source, alt, width, height, etc. The src is to add the image URL. The alt is the alternate text attribute, which is text that is visible when the image fails to load.
With HTML, add the image source as the path of your system drive. For that, add the src attribute as a link to the path of system drive where the image is stored. For example, file:/D:/images/logo.png
The following are the attributes:
Just keep in mind the <img> tag has no end tag.
You can try the following code to set src to the img tag in HTML from the system drive.Note: This will only work on your local system since the path is your local drive.
<!DOCTYPE html>
<html>
<head>
<title>
HTML img tag
<title>
</head>
<body>
<img src="file:/D:/images/logo.png" alt="Site Logo" width="50" height="50">
</body>
</html>
|
[
{
"code": null,
"e": 1310,
"s": 1062,
"text": "To use an image on a webpage, use the <img> tag. The tag allows you to add image source, alt, width, height, etc. The src is to add the image URL. The alt is the alternate text attribute, which is text that is visible when the image fails to load."
},
{
"code": null,
"e": 1511,
"s": 1310,
"text": "With HTML, add the image source as the path of your system drive. For that, add the src attribute as a link to the path of system drive where the image is stored. For example, file:/D:/images/logo.png"
},
{
"code": null,
"e": 1545,
"s": 1511,
"text": "The following are the attributes:"
},
{
"code": null,
"e": 1593,
"s": 1545,
"text": "Just keep in mind the <img> tag has no end tag."
},
{
"code": null,
"e": 1763,
"s": 1593,
"text": "You can try the following code to set src to the img tag in HTML from the system drive.Note: This will only work on your local system since the path is your local drive."
},
{
"code": null,
"e": 1969,
"s": 1763,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>\n HTML img tag\n <title>\n </head>\n\n <body>\n <img src=\"file:/D:/images/logo.png\" alt=\"Site Logo\" width=\"50\" height=\"50\">\n </body>\n</html>"
}
] |
Linear Regression Explained. A High Level Overview of Linear... | by Jason Wong | Towards Data Science
|
Regression analysis is a statistical methodology that allows us to determine the strength and relationship of two variables. Regression is not limited to two variables, we could have 2 or more variables showing a relationship. The results from the regression help in predicting an unknown value depending on the relationship with the predicting variables. For example, someone’s height and weight usually have a relationship. Generally, taller people tend to weigh more. We could use regression analysis to help predict the weight of an individual, given their height.
When there is a single input variable, the regression is referred to as Simple Linear Regression. We use the single variable (independent) to model a linear relationship with the target variable (dependent). We do this by fitting a model to describe the relationship. If there is more than predicting variable, the regression is referred to as Multiple Linear Regression.
You may have heard of Ordinary Least Squares Regression. When we are attempting to find the “best fit line”, the regression model can sometimes be referred to as Ordinary Least Squares Regression. This just means that we’re using the smallest sum of squared errors. The error is the difference between the predicted y value subtracted from the actual y value. The difference is squared so there is an absolute difference, and summed.
error = y_actual - y_predicted
Take a look at the graph to the left. When using the data points (green dots) to draw a regression line, we’re actually working with estimations. Our goal here is to find the line that best describes the data. When working with estimations, we can make use of the “hat” notation (^). The formula for drawing the “best fit line” when working with estimations will be the same as the straight line formula, but with hat notation.
Straight Line Formula: y = mx + c - Where {m} is the slope and {c} is the intercept
Straight Line Formula with estimations:
ŷ =m̂ x+ĉ
Or
ŷ =β̂ 0+β̂ 1x
We’re just estimating a proper intercept and slope. When we have drawn the “best fit line” we are ready to make some predictions. However, since our prediction is based on the parameter values we estimate, when we predict new y values given x, we will have error or vertical offset (blue lines). This error is denoted as |ŷ −y| where ŷ is on our regression line and y is the actual observed value (green dot).
When performing simple linear regression, the four main components are:
Dependent Variable — Target variable / will be estimated and predicted
Independent Variable — Predictor variable / used to estimate and predict
Slope — Angle of the line / denoted as m or β1
Intercept — Where function crosses the y-axis / denoted as c or β0
The last two, slope and intercept, are the coefficients/parameters of a linear regression model, so when we calculate the regression model, we’re just calculating these two. In the end, we’re trying to find the best-fit line describing the data, out of an infinite number of lines. To find the slope of a line, we can choose a random part of the line, and divide the change in x by the change in y.
Δy — Change in y
Δx — Change in x
We need to calculate some statistical measures before calculating the “best fit line”:
The formula above is multiplying the slope by the mean of x and subtracting that value from the mean of y.
Take another look at the plot above, we can see that:
Δy = 4.66
Δx = 8.64
4.66(change in y) / 8.64(change in x) = 0.54 (slope)
c (Intercept) = 6.38, where the line intersects with the y-axis
m (Slope) = 0.54
Δy = ((np.mean(X) * np.mean(Y)) - np.mean(X*Y))Δx = ((np.mean(X)**2) - np.mean(X*Y))m = Δy / Δx
c = np.mean(Y) - m * np.mean(X)
If we have a new value (x), we can calculate the prediction (y) with the data we already have.
new_x_value = 9y_predicted = (m * new_x_value) + cy_predicted#Output:11.233796296296294
We know that the goal of linear regression is to find the “best fit line” that describes the data. However, we saw above that the line won’t fully represent the relationship between variables. There will also be some error (y_actual - y_predicted). The R-Squared measure can be used to determine a how well a model fits the data. This measure is also known as the Coefficient of Determination.
R-Squared takes a simple model which uses the mean of the actual_y values to predict new_y values. The model will always predict this mean as the new_y regardless of the x value. This simple model is compared to a fit regression model to determine how well its fit.
The formula above can be read as:
Regression, being a parametric technique, relies on parameters learned from the data. This also means that the data must fulfill certain assumptions. These assumptions are necessary for obtaining reliable results. If the assumptions aren’t fulfilled, our predictions may be biased.
The plots used below were created using the Advertising dataset from Kaggle.
There is a linear relationship between the dependent variable (y) and the independent variable (x). We can check for linearity by creating a scatter plot.
The plot above is of TV advertisement spending and sales. This plot shows that there is a linear relationship between the two variables. We can interpret the plot to the right by saying “As TV advertisement spending increases, so do the sales. If you think you’re violating this assumption, try log-scaling your data.
This assumption states that the residuals (difference between actual_y and predicted_y) of a model are normally distributed. This assumption can be checked by created histograms or Q-Q-Plots.
Q-Q-Plots (quantile-quantile-plots) are scatterplots of two sets of quantiles plotted against each other.
To check the normality assumption using qq-plots, we’re looking for a pretty straight line. It is worth noting that this is only a visual check. Another method of checking the normality assumption is the Jarque-Bera (JB) test.
The plot above is a Q-Q-Plot of TV advertisement spending and sales. The “straight line” indicates that the residuals of the model are normally distributed.
Multicollinearity describes the correlation between the predictor variables. This assumption states that the predictor variables are independent. We can check this assumption by creating pair plots and/or heat maps. Another method would be to calculate the Variance Inflation Factor (VIF).
The variance inflation factor is a measure for the increase of the variance of the parameter estimates if an additional variable, given by exog_idx is added to the linear regression. It is a measure for multicollinearity of the design matrix, exog.
— Statsmodels User Guide
#Pairplotsns.pairplot(sales, vars = ['TV', 'radio', 'newspaper']);
Looking at the pairplot above, we can see that out of the three features in the “sales” dataset, there isn’t a high correlation between them.
#Heatmap (correlation matrix)sns.heatmap(sales.drop('sales', axis=1).corr(), annot=True, cmap='plasma');
Looking at the heatmap above, we can see the actual correlation coefficients if we set the annot= parameter to True. Radio and newspaper seem to show a correlation coefficient of 0.35 which tells us the features are not highly correlated.
#Variance Inflation Factor (VIF)from statsmodels.stats.outliers_influence import variance_inflation_factorr = sales[["newspaper", "radio"]].valuesvif_df = pd.DataFrame()vif_df["VIF"] = [variance_inflation_factor(r, i) for i in range(2)]vif_df["feature"] = ["newspaper", "radio"]vif_df
In general, a VIF value of 5 is too high. Looking at the dataframe to the left we see little multicollinearity between the newspaper and radio features.
What would it mean if we did have features showing multicollinearity? For example, let’s say that the newspaper and radio features show multicollinearity. This would make it difficult for us to separate the effects of just newspaper on sales.
Homoscedasticity refers to the variability of the dependent variable being equal across the independent variable values. We can check this assumption by creating a scatterplot of the model predictions and residuals, we’re looking for the residuals to equal across the regression line. We could also use a significance test such as the Breusch-Pagan test.
sns.scatterplot(fsm.predict(), fsm.resid);
Looking at the plot above, we can see the values do not look to be forming a pattern on the right side but are forming a pattern on the left side. This plot shows that the error increases with the predicted values, so it is heteroscedastic.
#Breusch-Pagan testlm, lm_p_value, fvalue, f_p_value = het_breuschpagan(fsm_resids, sales[["TV"]])print("F-statistic p-value:", f_p_value)
The Breusch-Pagan test returning a p-value this low tells us we can reject the null hypothesis (homoscedasticity), and therefore, we’re violating the Homoscedasticity assumption.
Autocorrelation refers to the model residuals not being independent. If there were to be a correlation in the error terms, our model’s accuracy would decrease. This assumption can be checked using the Durbin-Watson test or creating an error plot. For the Durbin-Watson (DB) test, we’re looking for a value between 1.5–2.5. A few things to know regarding the DB test:
2: No Autocorrelation
0–1.9: Positive Autocorrelation
2.1–4: Negative Autocorrelation
#Durbin-Watson test in OLS summaryfsm.summary()
Looking at the OLS Summary, we can see the Durbin-Watson score is 1.935, this score tells us there is no correlation between the model residuals.
Now that we’ve checked the assumptions, let’s fit a linear regression model and evaluate the summary table.
Importing necessary libraries and data
import pandas as pdimport numpy as npfrom matplotlib import pyplot as plt%matplotlib inlineimport seaborn as snsfrom scipy import statsfrom statsmodels.formula.api import olsfrom statsmodels.stats.diagnostic import het_breuschpaganfrom statsmodels.stats.outliers_influence import variance_inflation_factorfrom sklearn.linear_model import LinearRegression
sales = pd.read_csv('data/Advertising.csv', index_col=0)sales = sales[['TV', 'sales']]sales.head()
The sales feature is our target (dependent) and TV is our predictor (independent).
Creating formula for OLS model
formula = 'sales~TV'
Fitting the model
model = ols(formula=formula, data=sales).fit()
Viewing the model summary
model.summary()
The left part of the top table provides information on the data and model
The right part of the top table provides information on how well the model is fit
The middle table is a coefficient report
The bottom table provides information on residuals, autocorrelation, and multicollinearity
R-Squared: Percent of variance explained by the model.
Adj. R-Squared: R-Squared where additional independent variables are penalized
F-statistic: Significance of fit
Prob (F-statistic): Probability of seeing F-statistic from a sample
Log-likelihood: Log of the likelihood function
AIC: Akaike Information Criterion, penalizes model when more independent variables are added.
BIC: Bayesian Information Criterion, similar to AIC but with higher penalties
coef: Estimated coefficient value
std err: Standard error of the coefficient estimate
t: Measure of statistical significance for coefficient
P>|t|: Probability value that the coefficient is equal to 0
[0.025 0.975]: Lower and upper halves of 95% confidence interval
Omnibus: Omnibus D’Angostino’s test, statistical test for skewness and kurtosis
Prob(Omnibus): Omnibus statistic as a probability
Skew: Measure of data mean symmetry
Kurtosis: Measure of shape of the distribution
Durbin-Watson: Test for autocorrelation
Jarque-Bera (JB): Test for skewness & kurtosis
Prob (JB): Jarque-Bera statistic as a probability
Cond. No.: Test for multicollinearity
There you have it, a breakdown of linear regression analysis. Regression analysis is one of the first modeling techniques to learn as a data scientist. It can helpful when forecasting continuous values, e.g., sales, temperature. There are quite a few formulas to learn but they’re necessary to understand what’s happening “under the hood” when we run linear regression models. As you saw above there are many ways to check the assumptions of linear regression, hopefully you now have a better understanding of them. Thanks so much for taking the time to check out this post!
Bevans, R. (2020, October 26). Simple Linear Regression: An Easy Introduction & Examples. Retrieved from https://www.scribbr.com/statistics/simple-linear-regression/
Bevans, R. (2020, October 26). Multiple Linear Regression: A Quick and Simple Guide. Retrieved from https://www.scribbr.com/statistics/multiple-linear-regression/
International Encyclopedia of the Social Sciences. . Encyclopedia.com. 16 Oct. 2020 . (2020, November 27). Retrieved from https://www.encyclopedia.com/social-sciences/applied-and-social-sciences-magazines/ordinary-least-squares-regression
Jcf2d, W. B. (n.d.). University of Virginia Library Research Data Services Sciences. Retrieved from https://data.library.virginia.edu/understanding-q-q-plots/
Stephanie. (2020, September 16). Q Q Plots: Simple Definition & Example. Retrieved from https://www.statisticshowto.com/q-q-plots/
Assumptions of Linear Regression. (2020, June 22). Retrieved from https://www.statisticssolutions.com/assumptions-of-linear-regression/
McCarty, K. (2018, June 18). Interpreting Results from Linear Regression — Is the data appropriate? Retrieved from https://www.accelebrate.com/blog/interpreting-results-from-linear-regression-is-the-data-appropriate
Ordinary Least Squares regression (OLS). (n.d.). Retrieved from https://www.xlstat.com/en/solutions/features/ordinary-least-squares-regression-ols
Breusch pagan test — ols_test_breusch_pagan. (n.d.). Retrieved from https://olsrr.rsquaredacademy.com/reference/ols_test_breusch_pagan.html
Introduction. (n.d.). Retrieved from https://www.statsmodels.org/stable/index.html
Dey, S. (2020, April 01). Advertising.csv. Retrieved from https://www.kaggle.com/bumba5341/advertisingcsv
|
[
{
"code": null,
"e": 741,
"s": 172,
"text": "Regression analysis is a statistical methodology that allows us to determine the strength and relationship of two variables. Regression is not limited to two variables, we could have 2 or more variables showing a relationship. The results from the regression help in predicting an unknown value depending on the relationship with the predicting variables. For example, someone’s height and weight usually have a relationship. Generally, taller people tend to weigh more. We could use regression analysis to help predict the weight of an individual, given their height."
},
{
"code": null,
"e": 1113,
"s": 741,
"text": "When there is a single input variable, the regression is referred to as Simple Linear Regression. We use the single variable (independent) to model a linear relationship with the target variable (dependent). We do this by fitting a model to describe the relationship. If there is more than predicting variable, the regression is referred to as Multiple Linear Regression."
},
{
"code": null,
"e": 1547,
"s": 1113,
"text": "You may have heard of Ordinary Least Squares Regression. When we are attempting to find the “best fit line”, the regression model can sometimes be referred to as Ordinary Least Squares Regression. This just means that we’re using the smallest sum of squared errors. The error is the difference between the predicted y value subtracted from the actual y value. The difference is squared so there is an absolute difference, and summed."
},
{
"code": null,
"e": 1578,
"s": 1547,
"text": "error = y_actual - y_predicted"
},
{
"code": null,
"e": 2006,
"s": 1578,
"text": "Take a look at the graph to the left. When using the data points (green dots) to draw a regression line, we’re actually working with estimations. Our goal here is to find the line that best describes the data. When working with estimations, we can make use of the “hat” notation (^). The formula for drawing the “best fit line” when working with estimations will be the same as the straight line formula, but with hat notation."
},
{
"code": null,
"e": 2097,
"s": 2006,
"text": "Straight Line Formula: y = mx + c - Where {m} is the slope and {c} is the intercept"
},
{
"code": null,
"e": 2137,
"s": 2097,
"text": "Straight Line Formula with estimations:"
},
{
"code": null,
"e": 2149,
"s": 2137,
"text": "ŷ =m̂ x+ĉ"
},
{
"code": null,
"e": 2152,
"s": 2149,
"text": "Or"
},
{
"code": null,
"e": 2167,
"s": 2152,
"text": "ŷ =β̂ 0+β̂ 1x"
},
{
"code": null,
"e": 2579,
"s": 2167,
"text": "We’re just estimating a proper intercept and slope. When we have drawn the “best fit line” we are ready to make some predictions. However, since our prediction is based on the parameter values we estimate, when we predict new y values given x, we will have error or vertical offset (blue lines). This error is denoted as |ŷ −y| where ŷ is on our regression line and y is the actual observed value (green dot)."
},
{
"code": null,
"e": 2651,
"s": 2579,
"text": "When performing simple linear regression, the four main components are:"
},
{
"code": null,
"e": 2722,
"s": 2651,
"text": "Dependent Variable — Target variable / will be estimated and predicted"
},
{
"code": null,
"e": 2795,
"s": 2722,
"text": "Independent Variable — Predictor variable / used to estimate and predict"
},
{
"code": null,
"e": 2842,
"s": 2795,
"text": "Slope — Angle of the line / denoted as m or β1"
},
{
"code": null,
"e": 2909,
"s": 2842,
"text": "Intercept — Where function crosses the y-axis / denoted as c or β0"
},
{
"code": null,
"e": 3308,
"s": 2909,
"text": "The last two, slope and intercept, are the coefficients/parameters of a linear regression model, so when we calculate the regression model, we’re just calculating these two. In the end, we’re trying to find the best-fit line describing the data, out of an infinite number of lines. To find the slope of a line, we can choose a random part of the line, and divide the change in x by the change in y."
},
{
"code": null,
"e": 3325,
"s": 3308,
"text": "Δy — Change in y"
},
{
"code": null,
"e": 3342,
"s": 3325,
"text": "Δx — Change in x"
},
{
"code": null,
"e": 3429,
"s": 3342,
"text": "We need to calculate some statistical measures before calculating the “best fit line”:"
},
{
"code": null,
"e": 3536,
"s": 3429,
"text": "The formula above is multiplying the slope by the mean of x and subtracting that value from the mean of y."
},
{
"code": null,
"e": 3590,
"s": 3536,
"text": "Take another look at the plot above, we can see that:"
},
{
"code": null,
"e": 3600,
"s": 3590,
"text": "Δy = 4.66"
},
{
"code": null,
"e": 3610,
"s": 3600,
"text": "Δx = 8.64"
},
{
"code": null,
"e": 3663,
"s": 3610,
"text": "4.66(change in y) / 8.64(change in x) = 0.54 (slope)"
},
{
"code": null,
"e": 3727,
"s": 3663,
"text": "c (Intercept) = 6.38, where the line intersects with the y-axis"
},
{
"code": null,
"e": 3744,
"s": 3727,
"text": "m (Slope) = 0.54"
},
{
"code": null,
"e": 3840,
"s": 3744,
"text": "Δy = ((np.mean(X) * np.mean(Y)) - np.mean(X*Y))Δx = ((np.mean(X)**2) - np.mean(X*Y))m = Δy / Δx"
},
{
"code": null,
"e": 3872,
"s": 3840,
"text": "c = np.mean(Y) - m * np.mean(X)"
},
{
"code": null,
"e": 3967,
"s": 3872,
"text": "If we have a new value (x), we can calculate the prediction (y) with the data we already have."
},
{
"code": null,
"e": 4055,
"s": 3967,
"text": "new_x_value = 9y_predicted = (m * new_x_value) + cy_predicted#Output:11.233796296296294"
},
{
"code": null,
"e": 4449,
"s": 4055,
"text": "We know that the goal of linear regression is to find the “best fit line” that describes the data. However, we saw above that the line won’t fully represent the relationship between variables. There will also be some error (y_actual - y_predicted). The R-Squared measure can be used to determine a how well a model fits the data. This measure is also known as the Coefficient of Determination."
},
{
"code": null,
"e": 4715,
"s": 4449,
"text": "R-Squared takes a simple model which uses the mean of the actual_y values to predict new_y values. The model will always predict this mean as the new_y regardless of the x value. This simple model is compared to a fit regression model to determine how well its fit."
},
{
"code": null,
"e": 4749,
"s": 4715,
"text": "The formula above can be read as:"
},
{
"code": null,
"e": 5031,
"s": 4749,
"text": "Regression, being a parametric technique, relies on parameters learned from the data. This also means that the data must fulfill certain assumptions. These assumptions are necessary for obtaining reliable results. If the assumptions aren’t fulfilled, our predictions may be biased."
},
{
"code": null,
"e": 5108,
"s": 5031,
"text": "The plots used below were created using the Advertising dataset from Kaggle."
},
{
"code": null,
"e": 5263,
"s": 5108,
"text": "There is a linear relationship between the dependent variable (y) and the independent variable (x). We can check for linearity by creating a scatter plot."
},
{
"code": null,
"e": 5581,
"s": 5263,
"text": "The plot above is of TV advertisement spending and sales. This plot shows that there is a linear relationship between the two variables. We can interpret the plot to the right by saying “As TV advertisement spending increases, so do the sales. If you think you’re violating this assumption, try log-scaling your data."
},
{
"code": null,
"e": 5773,
"s": 5581,
"text": "This assumption states that the residuals (difference between actual_y and predicted_y) of a model are normally distributed. This assumption can be checked by created histograms or Q-Q-Plots."
},
{
"code": null,
"e": 5879,
"s": 5773,
"text": "Q-Q-Plots (quantile-quantile-plots) are scatterplots of two sets of quantiles plotted against each other."
},
{
"code": null,
"e": 6106,
"s": 5879,
"text": "To check the normality assumption using qq-plots, we’re looking for a pretty straight line. It is worth noting that this is only a visual check. Another method of checking the normality assumption is the Jarque-Bera (JB) test."
},
{
"code": null,
"e": 6263,
"s": 6106,
"text": "The plot above is a Q-Q-Plot of TV advertisement spending and sales. The “straight line” indicates that the residuals of the model are normally distributed."
},
{
"code": null,
"e": 6553,
"s": 6263,
"text": "Multicollinearity describes the correlation between the predictor variables. This assumption states that the predictor variables are independent. We can check this assumption by creating pair plots and/or heat maps. Another method would be to calculate the Variance Inflation Factor (VIF)."
},
{
"code": null,
"e": 6802,
"s": 6553,
"text": "The variance inflation factor is a measure for the increase of the variance of the parameter estimates if an additional variable, given by exog_idx is added to the linear regression. It is a measure for multicollinearity of the design matrix, exog."
},
{
"code": null,
"e": 6827,
"s": 6802,
"text": "— Statsmodels User Guide"
},
{
"code": null,
"e": 6894,
"s": 6827,
"text": "#Pairplotsns.pairplot(sales, vars = ['TV', 'radio', 'newspaper']);"
},
{
"code": null,
"e": 7036,
"s": 6894,
"text": "Looking at the pairplot above, we can see that out of the three features in the “sales” dataset, there isn’t a high correlation between them."
},
{
"code": null,
"e": 7141,
"s": 7036,
"text": "#Heatmap (correlation matrix)sns.heatmap(sales.drop('sales', axis=1).corr(), annot=True, cmap='plasma');"
},
{
"code": null,
"e": 7380,
"s": 7141,
"text": "Looking at the heatmap above, we can see the actual correlation coefficients if we set the annot= parameter to True. Radio and newspaper seem to show a correlation coefficient of 0.35 which tells us the features are not highly correlated."
},
{
"code": null,
"e": 7665,
"s": 7380,
"text": "#Variance Inflation Factor (VIF)from statsmodels.stats.outliers_influence import variance_inflation_factorr = sales[[\"newspaper\", \"radio\"]].valuesvif_df = pd.DataFrame()vif_df[\"VIF\"] = [variance_inflation_factor(r, i) for i in range(2)]vif_df[\"feature\"] = [\"newspaper\", \"radio\"]vif_df"
},
{
"code": null,
"e": 7818,
"s": 7665,
"text": "In general, a VIF value of 5 is too high. Looking at the dataframe to the left we see little multicollinearity between the newspaper and radio features."
},
{
"code": null,
"e": 8061,
"s": 7818,
"text": "What would it mean if we did have features showing multicollinearity? For example, let’s say that the newspaper and radio features show multicollinearity. This would make it difficult for us to separate the effects of just newspaper on sales."
},
{
"code": null,
"e": 8416,
"s": 8061,
"text": "Homoscedasticity refers to the variability of the dependent variable being equal across the independent variable values. We can check this assumption by creating a scatterplot of the model predictions and residuals, we’re looking for the residuals to equal across the regression line. We could also use a significance test such as the Breusch-Pagan test."
},
{
"code": null,
"e": 8459,
"s": 8416,
"text": "sns.scatterplot(fsm.predict(), fsm.resid);"
},
{
"code": null,
"e": 8700,
"s": 8459,
"text": "Looking at the plot above, we can see the values do not look to be forming a pattern on the right side but are forming a pattern on the left side. This plot shows that the error increases with the predicted values, so it is heteroscedastic."
},
{
"code": null,
"e": 8839,
"s": 8700,
"text": "#Breusch-Pagan testlm, lm_p_value, fvalue, f_p_value = het_breuschpagan(fsm_resids, sales[[\"TV\"]])print(\"F-statistic p-value:\", f_p_value)"
},
{
"code": null,
"e": 9018,
"s": 8839,
"text": "The Breusch-Pagan test returning a p-value this low tells us we can reject the null hypothesis (homoscedasticity), and therefore, we’re violating the Homoscedasticity assumption."
},
{
"code": null,
"e": 9385,
"s": 9018,
"text": "Autocorrelation refers to the model residuals not being independent. If there were to be a correlation in the error terms, our model’s accuracy would decrease. This assumption can be checked using the Durbin-Watson test or creating an error plot. For the Durbin-Watson (DB) test, we’re looking for a value between 1.5–2.5. A few things to know regarding the DB test:"
},
{
"code": null,
"e": 9407,
"s": 9385,
"text": "2: No Autocorrelation"
},
{
"code": null,
"e": 9439,
"s": 9407,
"text": "0–1.9: Positive Autocorrelation"
},
{
"code": null,
"e": 9471,
"s": 9439,
"text": "2.1–4: Negative Autocorrelation"
},
{
"code": null,
"e": 9519,
"s": 9471,
"text": "#Durbin-Watson test in OLS summaryfsm.summary()"
},
{
"code": null,
"e": 9665,
"s": 9519,
"text": "Looking at the OLS Summary, we can see the Durbin-Watson score is 1.935, this score tells us there is no correlation between the model residuals."
},
{
"code": null,
"e": 9773,
"s": 9665,
"text": "Now that we’ve checked the assumptions, let’s fit a linear regression model and evaluate the summary table."
},
{
"code": null,
"e": 9812,
"s": 9773,
"text": "Importing necessary libraries and data"
},
{
"code": null,
"e": 10167,
"s": 9812,
"text": "import pandas as pdimport numpy as npfrom matplotlib import pyplot as plt%matplotlib inlineimport seaborn as snsfrom scipy import statsfrom statsmodels.formula.api import olsfrom statsmodels.stats.diagnostic import het_breuschpaganfrom statsmodels.stats.outliers_influence import variance_inflation_factorfrom sklearn.linear_model import LinearRegression"
},
{
"code": null,
"e": 10266,
"s": 10167,
"text": "sales = pd.read_csv('data/Advertising.csv', index_col=0)sales = sales[['TV', 'sales']]sales.head()"
},
{
"code": null,
"e": 10349,
"s": 10266,
"text": "The sales feature is our target (dependent) and TV is our predictor (independent)."
},
{
"code": null,
"e": 10380,
"s": 10349,
"text": "Creating formula for OLS model"
},
{
"code": null,
"e": 10401,
"s": 10380,
"text": "formula = 'sales~TV'"
},
{
"code": null,
"e": 10419,
"s": 10401,
"text": "Fitting the model"
},
{
"code": null,
"e": 10466,
"s": 10419,
"text": "model = ols(formula=formula, data=sales).fit()"
},
{
"code": null,
"e": 10492,
"s": 10466,
"text": "Viewing the model summary"
},
{
"code": null,
"e": 10508,
"s": 10492,
"text": "model.summary()"
},
{
"code": null,
"e": 10582,
"s": 10508,
"text": "The left part of the top table provides information on the data and model"
},
{
"code": null,
"e": 10664,
"s": 10582,
"text": "The right part of the top table provides information on how well the model is fit"
},
{
"code": null,
"e": 10705,
"s": 10664,
"text": "The middle table is a coefficient report"
},
{
"code": null,
"e": 10796,
"s": 10705,
"text": "The bottom table provides information on residuals, autocorrelation, and multicollinearity"
},
{
"code": null,
"e": 10851,
"s": 10796,
"text": "R-Squared: Percent of variance explained by the model."
},
{
"code": null,
"e": 10930,
"s": 10851,
"text": "Adj. R-Squared: R-Squared where additional independent variables are penalized"
},
{
"code": null,
"e": 10963,
"s": 10930,
"text": "F-statistic: Significance of fit"
},
{
"code": null,
"e": 11031,
"s": 10963,
"text": "Prob (F-statistic): Probability of seeing F-statistic from a sample"
},
{
"code": null,
"e": 11078,
"s": 11031,
"text": "Log-likelihood: Log of the likelihood function"
},
{
"code": null,
"e": 11172,
"s": 11078,
"text": "AIC: Akaike Information Criterion, penalizes model when more independent variables are added."
},
{
"code": null,
"e": 11250,
"s": 11172,
"text": "BIC: Bayesian Information Criterion, similar to AIC but with higher penalties"
},
{
"code": null,
"e": 11284,
"s": 11250,
"text": "coef: Estimated coefficient value"
},
{
"code": null,
"e": 11336,
"s": 11284,
"text": "std err: Standard error of the coefficient estimate"
},
{
"code": null,
"e": 11391,
"s": 11336,
"text": "t: Measure of statistical significance for coefficient"
},
{
"code": null,
"e": 11451,
"s": 11391,
"text": "P>|t|: Probability value that the coefficient is equal to 0"
},
{
"code": null,
"e": 11516,
"s": 11451,
"text": "[0.025 0.975]: Lower and upper halves of 95% confidence interval"
},
{
"code": null,
"e": 11596,
"s": 11516,
"text": "Omnibus: Omnibus D’Angostino’s test, statistical test for skewness and kurtosis"
},
{
"code": null,
"e": 11646,
"s": 11596,
"text": "Prob(Omnibus): Omnibus statistic as a probability"
},
{
"code": null,
"e": 11682,
"s": 11646,
"text": "Skew: Measure of data mean symmetry"
},
{
"code": null,
"e": 11729,
"s": 11682,
"text": "Kurtosis: Measure of shape of the distribution"
},
{
"code": null,
"e": 11769,
"s": 11729,
"text": "Durbin-Watson: Test for autocorrelation"
},
{
"code": null,
"e": 11816,
"s": 11769,
"text": "Jarque-Bera (JB): Test for skewness & kurtosis"
},
{
"code": null,
"e": 11866,
"s": 11816,
"text": "Prob (JB): Jarque-Bera statistic as a probability"
},
{
"code": null,
"e": 11904,
"s": 11866,
"text": "Cond. No.: Test for multicollinearity"
},
{
"code": null,
"e": 12479,
"s": 11904,
"text": "There you have it, a breakdown of linear regression analysis. Regression analysis is one of the first modeling techniques to learn as a data scientist. It can helpful when forecasting continuous values, e.g., sales, temperature. There are quite a few formulas to learn but they’re necessary to understand what’s happening “under the hood” when we run linear regression models. As you saw above there are many ways to check the assumptions of linear regression, hopefully you now have a better understanding of them. Thanks so much for taking the time to check out this post!"
},
{
"code": null,
"e": 12645,
"s": 12479,
"text": "Bevans, R. (2020, October 26). Simple Linear Regression: An Easy Introduction & Examples. Retrieved from https://www.scribbr.com/statistics/simple-linear-regression/"
},
{
"code": null,
"e": 12808,
"s": 12645,
"text": "Bevans, R. (2020, October 26). Multiple Linear Regression: A Quick and Simple Guide. Retrieved from https://www.scribbr.com/statistics/multiple-linear-regression/"
},
{
"code": null,
"e": 13047,
"s": 12808,
"text": "International Encyclopedia of the Social Sciences. . Encyclopedia.com. 16 Oct. 2020 . (2020, November 27). Retrieved from https://www.encyclopedia.com/social-sciences/applied-and-social-sciences-magazines/ordinary-least-squares-regression"
},
{
"code": null,
"e": 13206,
"s": 13047,
"text": "Jcf2d, W. B. (n.d.). University of Virginia Library Research Data Services Sciences. Retrieved from https://data.library.virginia.edu/understanding-q-q-plots/"
},
{
"code": null,
"e": 13337,
"s": 13206,
"text": "Stephanie. (2020, September 16). Q Q Plots: Simple Definition & Example. Retrieved from https://www.statisticshowto.com/q-q-plots/"
},
{
"code": null,
"e": 13473,
"s": 13337,
"text": "Assumptions of Linear Regression. (2020, June 22). Retrieved from https://www.statisticssolutions.com/assumptions-of-linear-regression/"
},
{
"code": null,
"e": 13689,
"s": 13473,
"text": "McCarty, K. (2018, June 18). Interpreting Results from Linear Regression — Is the data appropriate? Retrieved from https://www.accelebrate.com/blog/interpreting-results-from-linear-regression-is-the-data-appropriate"
},
{
"code": null,
"e": 13836,
"s": 13689,
"text": "Ordinary Least Squares regression (OLS). (n.d.). Retrieved from https://www.xlstat.com/en/solutions/features/ordinary-least-squares-regression-ols"
},
{
"code": null,
"e": 13976,
"s": 13836,
"text": "Breusch pagan test — ols_test_breusch_pagan. (n.d.). Retrieved from https://olsrr.rsquaredacademy.com/reference/ols_test_breusch_pagan.html"
},
{
"code": null,
"e": 14059,
"s": 13976,
"text": "Introduction. (n.d.). Retrieved from https://www.statsmodels.org/stable/index.html"
}
] |
Find any one of the multiple repeating elements in read only array | Set 2 - GeeksforGeeks
|
22 Oct, 2021
Given a read-only array arr[] of size N + 1, find one of the multiple repeating elements in the array where the array contains integers only between 1 and N. Note: Read-only array means that the contents of the array can’t be modified.
Examples:
Input: N = 5, arr[] = {1, 1, 2, 3, 5, 4} Output: 1 Explanation: 1 is the only number repeated in the array.
Input: N = 10, arr[] = {10, 1, 2, 3, 5, 4, 9, 8, 5, 6, 4} Output: 5 Explanation: 5 is the one of the number repeated in the array.
In the previous post, we have discussed the same article with a space complexity O(N) and O(sqrt(N)).
Approach: This approach is based on Floyd’s Tortoise and Hare Algorithm (Cycle Detection Algorithm).
Use the function f(x) = arr[x] to construct the sequence:
arr[0], arr[arr[0]], arr[arr[arr[0]]], arr[arr[arr[arr[0]]]] .......
Each new element in the sequence is an element in arr[] at the index of the previous element.
Starting from x = arr[0], it will produce a linked list with a cycle.
The cycle appears because arr[] contains duplicate elements(at least one). The duplicate value is an entrance to the cycle. Given below is an example to show how cycle exists: For Example: Let the array arr[] = {2, 6, 4, 1, 3, 1, 5}
Starting from index 0, the traversal looks as follows:
arr[0] = 2 –> arr[2] = 4 –> arr[4] = 3 –> arr[3] = 1 –> arr[1] = 6 –> arr[6] = 5 –> arr[5] = 1.
The sequence forms cycle as shown below:
Algorithm consists of two parts and uses two pointers, usually called tortoise and hare.
hare = arr[arr[hare]] is twice as fast as tortoise = arr[tortoise].
Since the hare goes fast, it would be the first one who enters the cycle and starts to run around the cycle.
At some point, the tortoise enters the cycle as well, and since it’s moving slower the hare catches the tortoise up at some intersection point.
Note that the intersection point is not the cycle entrance in the general case, but the two intersect at somewhere middle in cycle.
Move tortoise to the starting point of sequence and hare remains within cycle and both move with the same speed i.e. tortoise = arr[tortoise] and hare = arr[hare]. Now they intersect at duplicate element.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the duplicate// value in the given array arr[]void findDuplicate(int arr[]){ // Initialise variables int tortoise = arr[0]; int hare = arr[0]; // Loop till we find the // duplicate element while (1) { tortoise = arr[tortoise]; // Hare moves with twice // the speed of tortoise hare = arr[arr[hare]]; if (tortoise == hare) break; } tortoise = arr[0]; // Loop to get start point // of the cycle as start // point will be the duplicate // element while (tortoise != hare) { tortoise = arr[tortoise]; hare = arr[hare]; } // Print the duplicate element cout << tortoise;} // Driver Codeint main(){ // Given array int arr[] = { 2, 6, 4, 1, 3, 1, 5 }; // Function Call findDuplicate(arr); return 0;}
// Java code for the above approachclass GFG{ // Function to find the duplicate// value in the given array arr[]static void findDuplicate(int arr[]){ // Initialise variables int tortoise = arr[0]; int hare = arr[0]; // Loop till we find the // duplicate element while (true) { tortoise = arr[tortoise]; // Hare moves with twice // the speed of tortoise hare = arr[arr[hare]]; if (tortoise == hare) break; } tortoise = arr[0]; // Loop to get start point // of the cycle as start // point will be the duplicate // element while (tortoise != hare) { tortoise = arr[tortoise]; hare = arr[hare]; } // Print the duplicate element System.out.print(tortoise);} // Driver Codepublic static void main (String []args){ // Given array int arr[] = { 2, 6, 4, 1, 3, 1, 5 }; // Function Call findDuplicate(arr);}} // This code is contributed by chitranayal
# Python3 program for the above approach # Function to find the duplicate# value in the given array arr[]def findDuplicate(arr): # Initialise variables tortoise = arr[0] hare = arr[0] # Loop till we find the # duplicate element while (1): tortoise = arr[tortoise] # Hare moves with twice # the speed of tortoise hare = arr[arr[hare]] if (tortoise == hare): break tortoise = arr[0] # Loop to get start point # of the cycle as start # point will be the duplicate # element while (tortoise != hare): tortoise = arr[tortoise] hare = arr[hare] # Print the duplicate element print (tortoise) # Driver Code # Given arrayarr = [ 2, 6, 4, 1, 3, 1, 5 ] # Function CallfindDuplicate(arr) # This code is contributed by PratikBasu
// C# program for the above approachusing System; class GFG{ // Function to find the duplicate// value in the given array []arrstatic void findDuplicate(int []arr){ // Initialise variables int tortoise = arr[0]; int hare = arr[0]; // Loop till we find the // duplicate element while (true) { tortoise = arr[tortoise]; // Hare moves with twice // the speed of tortoise hare = arr[arr[hare]]; if (tortoise == hare) break; } tortoise = arr[0]; // Loop to get start point // of the cycle as start // point will be the duplicate // element while (tortoise != hare) { tortoise = arr[tortoise]; hare = arr[hare]; } // Print the duplicate element Console.Write(tortoise);} // Driver Codepublic static void Main(String []args){ // Given array int []arr = { 2, 6, 4, 1, 3, 1, 5 }; // Function Call findDuplicate(arr);}} // This code is contributed by Amit Katiyar
<script> // JavaScript code for the above approach // Function to find the duplicate// value in the given array arr[]function findDuplicate(arr){ // Initialise variables let tortoise = arr[0]; let hare = arr[0]; // Loop till we find the // duplicate element while (true) { tortoise = arr[tortoise]; // Hare moves with twice // the speed of tortoise hare = arr[arr[hare]]; if (tortoise == hare) break; } tortoise = arr[0]; // Loop to get start point // of the cycle as start // point will be the duplicate // element while (tortoise != hare) { tortoise = arr[tortoise]; hare = arr[hare]; } // Print the duplicate element document.write(tortoise);} // Driver Code // Given arraylet arr = [ 2, 6, 4, 1, 3, 1, 5 ]; // Function CallfindDuplicate(arr); // This code is contributed by sanjoy_62 </script>
1
Time Complexity: O(N) Auxiliary Space: O(1)
PratikBasu
ukasp
amit143katiyar
sanjoy_62
khushboogoyal499
graph-cycle
Algorithms
Arrays
Data Structures
Graph
Data Structures
Arrays
Graph
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SCAN (Elevator) Disk Scheduling Algorithms
Program for SSTF disk scheduling algorithm
Quadratic Probing in Hashing
Rail Fence Cipher - Encryption and Decryption
Arrays in Java
Arrays in C/C++
Stack Data Structure (Introduction and Program)
Program for array rotation
Largest Sum Contiguous Subarray
|
[
{
"code": null,
"e": 24702,
"s": 24674,
"text": "\n22 Oct, 2021"
},
{
"code": null,
"e": 24938,
"s": 24702,
"text": "Given a read-only array arr[] of size N + 1, find one of the multiple repeating elements in the array where the array contains integers only between 1 and N. Note: Read-only array means that the contents of the array can’t be modified."
},
{
"code": null,
"e": 24949,
"s": 24938,
"text": "Examples: "
},
{
"code": null,
"e": 25057,
"s": 24949,
"text": "Input: N = 5, arr[] = {1, 1, 2, 3, 5, 4} Output: 1 Explanation: 1 is the only number repeated in the array."
},
{
"code": null,
"e": 25190,
"s": 25057,
"text": "Input: N = 10, arr[] = {10, 1, 2, 3, 5, 4, 9, 8, 5, 6, 4} Output: 5 Explanation: 5 is the one of the number repeated in the array. "
},
{
"code": null,
"e": 25292,
"s": 25190,
"text": "In the previous post, we have discussed the same article with a space complexity O(N) and O(sqrt(N))."
},
{
"code": null,
"e": 25394,
"s": 25292,
"text": "Approach: This approach is based on Floyd’s Tortoise and Hare Algorithm (Cycle Detection Algorithm). "
},
{
"code": null,
"e": 25452,
"s": 25394,
"text": "Use the function f(x) = arr[x] to construct the sequence:"
},
{
"code": null,
"e": 25523,
"s": 25452,
"text": "arr[0], arr[arr[0]], arr[arr[arr[0]]], arr[arr[arr[arr[0]]]] ....... "
},
{
"code": null,
"e": 25617,
"s": 25523,
"text": "Each new element in the sequence is an element in arr[] at the index of the previous element."
},
{
"code": null,
"e": 25687,
"s": 25617,
"text": "Starting from x = arr[0], it will produce a linked list with a cycle."
},
{
"code": null,
"e": 25922,
"s": 25687,
"text": "The cycle appears because arr[] contains duplicate elements(at least one). The duplicate value is an entrance to the cycle. Given below is an example to show how cycle exists: For Example: Let the array arr[] = {2, 6, 4, 1, 3, 1, 5} "
},
{
"code": null,
"e": 25978,
"s": 25922,
"text": "Starting from index 0, the traversal looks as follows: "
},
{
"code": null,
"e": 26076,
"s": 25978,
"text": "arr[0] = 2 –> arr[2] = 4 –> arr[4] = 3 –> arr[3] = 1 –> arr[1] = 6 –> arr[6] = 5 –> arr[5] = 1. "
},
{
"code": null,
"e": 26119,
"s": 26076,
"text": "The sequence forms cycle as shown below: "
},
{
"code": null,
"e": 26208,
"s": 26119,
"text": "Algorithm consists of two parts and uses two pointers, usually called tortoise and hare."
},
{
"code": null,
"e": 26277,
"s": 26208,
"text": " hare = arr[arr[hare]] is twice as fast as tortoise = arr[tortoise]."
},
{
"code": null,
"e": 26386,
"s": 26277,
"text": "Since the hare goes fast, it would be the first one who enters the cycle and starts to run around the cycle."
},
{
"code": null,
"e": 26530,
"s": 26386,
"text": "At some point, the tortoise enters the cycle as well, and since it’s moving slower the hare catches the tortoise up at some intersection point."
},
{
"code": null,
"e": 26662,
"s": 26530,
"text": "Note that the intersection point is not the cycle entrance in the general case, but the two intersect at somewhere middle in cycle."
},
{
"code": null,
"e": 26867,
"s": 26662,
"text": "Move tortoise to the starting point of sequence and hare remains within cycle and both move with the same speed i.e. tortoise = arr[tortoise] and hare = arr[hare]. Now they intersect at duplicate element."
},
{
"code": null,
"e": 26918,
"s": 26867,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26922,
"s": 26918,
"text": "C++"
},
{
"code": null,
"e": 26927,
"s": 26922,
"text": "Java"
},
{
"code": null,
"e": 26935,
"s": 26927,
"text": "Python3"
},
{
"code": null,
"e": 26938,
"s": 26935,
"text": "C#"
},
{
"code": null,
"e": 26949,
"s": 26938,
"text": "Javascript"
},
{
"code": "// C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the duplicate// value in the given array arr[]void findDuplicate(int arr[]){ // Initialise variables int tortoise = arr[0]; int hare = arr[0]; // Loop till we find the // duplicate element while (1) { tortoise = arr[tortoise]; // Hare moves with twice // the speed of tortoise hare = arr[arr[hare]]; if (tortoise == hare) break; } tortoise = arr[0]; // Loop to get start point // of the cycle as start // point will be the duplicate // element while (tortoise != hare) { tortoise = arr[tortoise]; hare = arr[hare]; } // Print the duplicate element cout << tortoise;} // Driver Codeint main(){ // Given array int arr[] = { 2, 6, 4, 1, 3, 1, 5 }; // Function Call findDuplicate(arr); return 0;}",
"e": 27873,
"s": 26949,
"text": null
},
{
"code": "// Java code for the above approachclass GFG{ // Function to find the duplicate// value in the given array arr[]static void findDuplicate(int arr[]){ // Initialise variables int tortoise = arr[0]; int hare = arr[0]; // Loop till we find the // duplicate element while (true) { tortoise = arr[tortoise]; // Hare moves with twice // the speed of tortoise hare = arr[arr[hare]]; if (tortoise == hare) break; } tortoise = arr[0]; // Loop to get start point // of the cycle as start // point will be the duplicate // element while (tortoise != hare) { tortoise = arr[tortoise]; hare = arr[hare]; } // Print the duplicate element System.out.print(tortoise);} // Driver Codepublic static void main (String []args){ // Given array int arr[] = { 2, 6, 4, 1, 3, 1, 5 }; // Function Call findDuplicate(arr);}} // This code is contributed by chitranayal",
"e": 28869,
"s": 27873,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the duplicate# value in the given array arr[]def findDuplicate(arr): # Initialise variables tortoise = arr[0] hare = arr[0] # Loop till we find the # duplicate element while (1): tortoise = arr[tortoise] # Hare moves with twice # the speed of tortoise hare = arr[arr[hare]] if (tortoise == hare): break tortoise = arr[0] # Loop to get start point # of the cycle as start # point will be the duplicate # element while (tortoise != hare): tortoise = arr[tortoise] hare = arr[hare] # Print the duplicate element print (tortoise) # Driver Code # Given arrayarr = [ 2, 6, 4, 1, 3, 1, 5 ] # Function CallfindDuplicate(arr) # This code is contributed by PratikBasu",
"e": 29696,
"s": 28869,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find the duplicate// value in the given array []arrstatic void findDuplicate(int []arr){ // Initialise variables int tortoise = arr[0]; int hare = arr[0]; // Loop till we find the // duplicate element while (true) { tortoise = arr[tortoise]; // Hare moves with twice // the speed of tortoise hare = arr[arr[hare]]; if (tortoise == hare) break; } tortoise = arr[0]; // Loop to get start point // of the cycle as start // point will be the duplicate // element while (tortoise != hare) { tortoise = arr[tortoise]; hare = arr[hare]; } // Print the duplicate element Console.Write(tortoise);} // Driver Codepublic static void Main(String []args){ // Given array int []arr = { 2, 6, 4, 1, 3, 1, 5 }; // Function Call findDuplicate(arr);}} // This code is contributed by Amit Katiyar",
"e": 30714,
"s": 29696,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach // Function to find the duplicate// value in the given array arr[]function findDuplicate(arr){ // Initialise variables let tortoise = arr[0]; let hare = arr[0]; // Loop till we find the // duplicate element while (true) { tortoise = arr[tortoise]; // Hare moves with twice // the speed of tortoise hare = arr[arr[hare]]; if (tortoise == hare) break; } tortoise = arr[0]; // Loop to get start point // of the cycle as start // point will be the duplicate // element while (tortoise != hare) { tortoise = arr[tortoise]; hare = arr[hare]; } // Print the duplicate element document.write(tortoise);} // Driver Code // Given arraylet arr = [ 2, 6, 4, 1, 3, 1, 5 ]; // Function CallfindDuplicate(arr); // This code is contributed by sanjoy_62 </script>",
"e": 31667,
"s": 30714,
"text": null
},
{
"code": null,
"e": 31669,
"s": 31667,
"text": "1"
},
{
"code": null,
"e": 31716,
"s": 31671,
"text": "Time Complexity: O(N) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 31727,
"s": 31716,
"text": "PratikBasu"
},
{
"code": null,
"e": 31733,
"s": 31727,
"text": "ukasp"
},
{
"code": null,
"e": 31748,
"s": 31733,
"text": "amit143katiyar"
},
{
"code": null,
"e": 31758,
"s": 31748,
"text": "sanjoy_62"
},
{
"code": null,
"e": 31775,
"s": 31758,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 31787,
"s": 31775,
"text": "graph-cycle"
},
{
"code": null,
"e": 31798,
"s": 31787,
"text": "Algorithms"
},
{
"code": null,
"e": 31805,
"s": 31798,
"text": "Arrays"
},
{
"code": null,
"e": 31821,
"s": 31805,
"text": "Data Structures"
},
{
"code": null,
"e": 31827,
"s": 31821,
"text": "Graph"
},
{
"code": null,
"e": 31843,
"s": 31827,
"text": "Data Structures"
},
{
"code": null,
"e": 31850,
"s": 31843,
"text": "Arrays"
},
{
"code": null,
"e": 31856,
"s": 31850,
"text": "Graph"
},
{
"code": null,
"e": 31867,
"s": 31856,
"text": "Algorithms"
},
{
"code": null,
"e": 31965,
"s": 31867,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31990,
"s": 31965,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 32033,
"s": 31990,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 32076,
"s": 32033,
"text": "Program for SSTF disk scheduling algorithm"
},
{
"code": null,
"e": 32105,
"s": 32076,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 32151,
"s": 32105,
"text": "Rail Fence Cipher - Encryption and Decryption"
},
{
"code": null,
"e": 32166,
"s": 32151,
"text": "Arrays in Java"
},
{
"code": null,
"e": 32182,
"s": 32166,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 32230,
"s": 32182,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 32257,
"s": 32230,
"text": "Program for array rotation"
}
] |
Graph Traversals - GeeksforGeeks
|
15 Nov, 2018
1) Breadth First Search
2) Depth First Search
3) Prim's Minimum Spanning Tree
4) Kruskal' Minimum Spanning Tree
1) Stack
2) Queue
3) Priority Queue
4) Union Find
1) Queue
2) Stack
3) Priority Queue
4) Union Find
1) Stack
2) Queue
3) Union Find
4) Priority Queue
1) Priority Queue
2) Queue
3) Stack
4) Union Find
In DFS, if 'v' is visited
after 'u', then one of the following is true.
1) (u, v) is an edge.
u
/ \
v w
/ / \
x y z
2) 'u' is a leaf node.
w
/ \
x v
/ / \
u y z
(I) a b e g h f
(II) a b f e h g
(III) a b f h g e
(IV) a f g h b e
In DFS, if a vertex 'v' is visited
after 'u', then one of the following is true.
1) (u, v) is an edge.
u
/ \
v w
/ / \
x y z
2) 'u' is a leaf node.
w
/ \
x v
/ / \
u y z
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
How to Read Text File Into List in Python?
Python Data Structures and Algorithms
|
[
{
"code": null,
"e": 27610,
"s": 27582,
"text": "\n15 Nov, 2018"
},
{
"code": null,
"e": 27811,
"s": 27610,
"text": "1) Breadth First Search \n2) Depth First Search \n3) Prim's Minimum Spanning Tree \n4) Kruskal' Minimum Spanning Tree \n"
},
{
"code": null,
"e": 27861,
"s": 27811,
"text": "1) Stack\n2) Queue\n3) Priority Queue\n4) Union Find"
},
{
"code": null,
"e": 27912,
"s": 27861,
"text": "1) Queue\n2) Stack\n3) Priority Queue\n4) Union Find\n"
},
{
"code": null,
"e": 27963,
"s": 27912,
"text": "1) Stack\n2) Queue\n3) Union Find\n4) Priority Queue "
},
{
"code": null,
"e": 28013,
"s": 27963,
"text": "1) Priority Queue\n2) Queue\n3) Stack\n4) Union Find"
},
{
"code": null,
"e": 28230,
"s": 28013,
"text": "In DFS, if 'v' is visited\nafter 'u', then one of the following is true.\n1) (u, v) is an edge.\n u\n / \\\n v w\n / / \\\nx y z\n\n2) 'u' is a leaf node.\n w\n / \\\n x v\n / / \\\nu y z "
},
{
"code": null,
"e": 28302,
"s": 28230,
"text": "(I) a b e g h f \n(II) a b f e h g\n(III) a b f h g e \n(IV) a f g h b e "
},
{
"code": null,
"e": 28527,
"s": 28302,
"text": "In DFS, if a vertex 'v' is visited\nafter 'u', then one of the following is true.\n1) (u, v) is an edge.\n u\n / \\\n v w\n / / \\\nx y z\n\n2) 'u' is a leaf node.\n w\n / \\\n x v\n / / \\\nu y z"
},
{
"code": null,
"e": 28625,
"s": 28527,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 28678,
"s": 28625,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 28739,
"s": 28678,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28777,
"s": 28739,
"text": "Array of Objects in C++ with Examples"
},
{
"code": null,
"e": 28835,
"s": 28777,
"text": "How to Convert Categorical Variable to Numeric in Pandas?"
},
{
"code": null,
"e": 28897,
"s": 28835,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 28938,
"s": 28897,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 28981,
"s": 28938,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 29017,
"s": 28981,
"text": "How to Read Text Files with Pandas?"
},
{
"code": null,
"e": 29060,
"s": 29017,
"text": "How to Read Text File Into List in Python?"
}
] |
PHP mysqli_use_result() Function
|
The mysqli_use_result() function starts the retrieval of the resultset from the previously executed query
mysqli_use_result($con)
con(Mandatory)
This is an object representing a connection to MySQL Server.
The mysqli_use_result() function returns a result object and the boolean value false in case of an error.
This function was first introduced in PHP Version 5 and works works in all the later versions.
Following example demonstrates the usage of the mysqli_use_result() function (in procedural style) −
<?php
//Creating a connection
$con = mysqli_connect("localhost", "root", "password", "test");
//Executing the multi query
$query = "SELECT * FROM players;SELECT * FROM emp;SELECT * FROM tutorials";
$res = mysqli_multi_query($con, $query);
$count = 0;
if ($res) {
do {
$count = $count+1;
mysqli_use_result($con);
} while (mysqli_next_result($con));
}
print("Number of result sets: ".$count);
mysqli_close($con);
?>
This will produce following result −
Number of result sets: 3
In object oriented style the syntax of this function is $con->use_result(); Following is the example of this function in object oriented style $minus;
<?php
$con = new mysqli("localhost", "root", "password", "test");
//Multi query
$res = $con->multi_query("SELECT * FROM players;SELECT * FROM emp;SELECT * FROM tutorials");
$count = 0;
if ($res) {
do {
$count = $count+1;
$con-> use_result();
} while ($con->next_result());
}
print("Number of result sets: ".$count);
//Closing the connection
$res = $con -> close();
?>
This will produce following result −
Number of result sets: 3
Following example retrieves the records of all the resultsets of the muti-query −
//Creating a connection
$con = mysqli_connect("localhost", "root", "password", "test");
//Executing the multi query
$query = "SELECT * FROM players;SELECT * FROM emp";
$res = mysqli_multi_query($con, $query);
if ($res) {
do {
if ($result = mysqli_use_result($con)) {
while ($row = mysqli_fetch_row($result)) {
print("Name: ".$row[0]."\n");
print("Age: ".$row[1]."\n");
}
mysqli_free_result($result);
}
if (mysqli_more_results($con)) {
print("\n");
}
} while (mysqli_use_result($con));
}
mysqli_close($con);
This will produce following result −
Name: Dhavan
Age: 33
Name: Rohit
Age: 28
Name: Kohli
Age: 25
Name: Raju
Age: 25
Name: Rahman
Age: 30
Name: Ramani
Age: 22
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2863,
"s": 2757,
"text": "The mysqli_use_result() function starts the retrieval of the resultset from the previously executed query"
},
{
"code": null,
"e": 2888,
"s": 2863,
"text": "mysqli_use_result($con)\n"
},
{
"code": null,
"e": 2903,
"s": 2888,
"text": "con(Mandatory)"
},
{
"code": null,
"e": 2964,
"s": 2903,
"text": "This is an object representing a connection to MySQL Server."
},
{
"code": null,
"e": 3070,
"s": 2964,
"text": "The mysqli_use_result() function returns a result object and the boolean value false in case of an error."
},
{
"code": null,
"e": 3165,
"s": 3070,
"text": "This function was first introduced in PHP Version 5 and works works in all the later versions."
},
{
"code": null,
"e": 3266,
"s": 3165,
"text": "Following example demonstrates the usage of the mysqli_use_result() function (in procedural style) −"
},
{
"code": null,
"e": 3740,
"s": 3266,
"text": "<?php\n //Creating a connection\n $con = mysqli_connect(\"localhost\", \"root\", \"password\", \"test\");\n\n //Executing the multi query\n $query = \"SELECT * FROM players;SELECT * FROM emp;SELECT * FROM tutorials\";\n $res = mysqli_multi_query($con, $query);\n\n $count = 0;\n\n if ($res) {\n do {\n $count = $count+1;\n\t mysqli_use_result($con);\n } while (mysqli_next_result($con));\n }\n print(\"Number of result sets: \".$count);\n mysqli_close($con);\n?>"
},
{
"code": null,
"e": 3777,
"s": 3740,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3803,
"s": 3777,
"text": "Number of result sets: 3\n"
},
{
"code": null,
"e": 3954,
"s": 3803,
"text": "In object oriented style the syntax of this function is $con->use_result(); Following is the example of this function in object oriented style $minus;"
},
{
"code": null,
"e": 4367,
"s": 3954,
"text": "<?php\n $con = new mysqli(\"localhost\", \"root\", \"password\", \"test\");\n\n //Multi query\n $res = $con->multi_query(\"SELECT * FROM players;SELECT * FROM emp;SELECT * FROM tutorials\");\n\n $count = 0;\n if ($res) {\n do {\n $count = $count+1;\n $con-> use_result();\n } while ($con->next_result());\n}\nprint(\"Number of result sets: \".$count);\n\n//Closing the connection\n$res = $con -> close();\n?>"
},
{
"code": null,
"e": 4404,
"s": 4367,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4430,
"s": 4404,
"text": "Number of result sets: 3\n"
},
{
"code": null,
"e": 4512,
"s": 4430,
"text": "Following example retrieves the records of all the resultsets of the muti-query −"
},
{
"code": null,
"e": 5112,
"s": 4512,
"text": "//Creating a connection\n$con = mysqli_connect(\"localhost\", \"root\", \"password\", \"test\");\n\n//Executing the multi query\n$query = \"SELECT * FROM players;SELECT * FROM emp\";\n\n$res = mysqli_multi_query($con, $query);\n\nif ($res) {\n do {\n if ($result = mysqli_use_result($con)) {\n while ($row = mysqli_fetch_row($result)) {\n print(\"Name: \".$row[0].\"\\n\");\n print(\"Age: \".$row[1].\"\\n\");\n }\n mysqli_free_result($result);\n }\n if (mysqli_more_results($con)) {\n print(\"\\n\");\n }\n } while (mysqli_use_result($con));\n}\nmysqli_close($con);"
},
{
"code": null,
"e": 5149,
"s": 5112,
"text": "This will produce following result −"
},
{
"code": null,
"e": 5273,
"s": 5149,
"text": "Name: Dhavan\nAge: 33\nName: Rohit\nAge: 28\nName: Kohli\nAge: 25\n\nName: Raju\nAge: 25\nName: Rahman\nAge: 30\nName: Ramani\nAge: 22\n"
},
{
"code": null,
"e": 5306,
"s": 5273,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 5322,
"s": 5306,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5355,
"s": 5322,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5366,
"s": 5355,
"text": " Syed Raza"
},
{
"code": null,
"e": 5401,
"s": 5366,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5418,
"s": 5401,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5451,
"s": 5418,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5466,
"s": 5451,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 5501,
"s": 5466,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 5513,
"s": 5501,
"text": " Azaz Patel"
},
{
"code": null,
"e": 5548,
"s": 5513,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5576,
"s": 5548,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 5583,
"s": 5576,
"text": " Print"
},
{
"code": null,
"e": 5594,
"s": 5583,
"text": " Add Notes"
}
] |
Visualizing models 101, using R. So you’ve got yourself a model, now... | by Peter Nistrup | Towards Data Science
|
This is (almost) a direct sequel to my previous article on “Model selection 101, using R”: (I should probably have made this a series huh?)
medium.com
So please check that out if you haven’t already as most examples will be using the same data and model from that analysis.
That being said, this is a sequel as well as a 101 in and of itself, meaning— like in the last article — that this will be mostly introductory. Go ahead to the end of this article if you want to download the data for yourself and follow along!
Make sure to follow my profile if you enjoy this article and want to see more!
In this article we’ll be taking a look at visualizing some of the findings you’ve made with your model, like the marginal effects of a given explanatory-variable on our response-variable.
We’ll be making pretty plots like this:
We have to do a little bit of house-keeping to prepare our data and models for proper visualization:
dat$gov.support <- exp(dat$gov.support)dat$employed <- factor(dat$employed, levels(dat$employed)[c(2,1)])
The first command applies the exp() transformation on our ‘gov.support’ values, this is because the values are log-transformed by default in the raw data. The reason we’re doing this is so that when we fit the model with ‘log(gov.support)’ we get the same results as in the previous article but we get the added benefit of ‘back’-transforming our data which I will show later!
The second command simply swaps the order of our categorical response-variable ‘employed’ so that our model-fits will default to fitting for ‘employed == “yes”’ even when not explicitly defining it. This is important because now we can fit our model without using a “logical” response-variable which checks whether or not ‘employed == “yes”’ or not.
This means that while the base-model from the last article was created like this:
fit.1 <- glm(employed == "yes" ~ ., data = dat, family = binomial)
Now we define it like this:
fit.1 <- glm(employed ~ . - gov.support + log(gov.support), data = dat, family = binomial)summary(fit.1)
Notice we don’t define a logical condition for our response-variable and we replace the new exponentially transformed ‘gov.support’ with a log transformation of the variable to revert back to our initial model:
As evident above we get the exact same summary as we did in the previous article before doing our “cleaning”.
The last thing I want to do is redefine our factor variables to be more clear:
dat$zero.young.children <- factor(dat$young.children == 0)dat$zero.school.children <- factor(dat$school.children == 0)dat$zero.children <- factor(dat$young.children + dat$school.children == 0)
This means our final fit looks like this:
glm(employed ~ foreigner + log(gov.support) + age + school.children + zero.young.children + zero.school.children + zero.children + I(age^2) + foreigner:age + foreigner:zero.children + age:school.children + log(gov.support):zero.young.children, family = binomial, data = dat)
Lets start by plotting what I find the most interesting, the relationship between “employed” and “gov.support”.
I’m using an absolutely brilliant package called “sjPlot” for this:
library("sjPlot")plot_model(full.fit, type = “pred”, terms = c(“gov.support”))
Giving us this plot:
Completely useless! What’s going on here? Well for our convenience ‘plot_model’ spits our the following error:
This is exactly why we needed to transform the data! Let’s try again:
plot_model(full.fit, type = “pred”, terms = c(“gov.support [exp]”))
This is pretty damn close to being useless as well, what’s going on now?
Lets try taking a look at our model and how it tries to capture the relationships in the data. There’s a few different ways to do this but lets just begin by looking at the coefficients of our full model:
What’s the first thing you notice when looking at this? For me it’s the factor-variable ‘zero.young.children’ having a coefficient of almost 13! This isn’t necessarily a problem though but lets take a look at the confidence-intervals of the coefficients:
confint(full.fit)
Right, this looks like trouble! Take a look at the span on ‘zero.young.children’ this means that we’ll have huge confidence-intervals in our marginal-effect plots. This is most likely why our plot has such a huge confidence-interval.
sjPlot can plot these as well:
plot_model(full.fit, transform = NULL, show.values = TRUE, axis.labels = “”, value.offset = .4)
This makes it real easy to see that the factor variable ‘zero.young.children’ is quite problematic with regard to making any plots with any real confidence.
Lets take a little detour and create a more simple model without any variable-interactions, turns out this is what we get:
simple.fit <- glm(employed ~ foreigner + age + zero.young.children + zero.children + log(gov.support) + I(age^2), family = binomial, data = dat)summary(simple.fit)
A small increase in AIC which isn’t a good thing but it’s not too much and we gain a lot of simplicity by using this model instead! (If we measure performance with BIC instead we actually find that this model is better due to BIC penalizing harder on complex models! 1047 vs 1068)
Lets look at the new coefficients:
plot_model(simple.fit, transform = NULL, show.values = TRUE, axis.labels = “”, value.offset = .4)
This look a lot better! Let’s try making our plot once more using this model instead!
plot_model(simple.fit, type = “pred”, terms = c(“gov.support [exp]”))
Nice, something useful! So obviously the probability of being employed is lower the more government support you’re entitled to. This makes quite a bit of intuitive sense! How about the difference between foreigners and non-foreigners? Well plot_model makes this real easy to do as well, just add it as a term!:
plot_model(simple.fit, type = “pred”, terms = c(“gov.support [exp]”, “foreigner”))
This is a breeze! So this model suggests that foreigners are more likely to be employed than non-foreigners given that the other variables are identical.
How about age? This required a slightly different approach because we don’t really assume a strictly positive or negative relationship with age which is why the power-transformation I(age2) makes sense. That is, we don’t expect a 10 year old to be employed, neither a 70 year old, but we do expect a 30 year old to be employed.
Sadly sjPlot doesn’t take too kindly to these kinds of power-transformations (Or I’m just an imbecile who can’t work it out), so I’m using the package ‘jtools’ instead:
effect_plot(simple.fit, pred = age, data = dat, interval = TRUE)
So it seems employment “tops” around the mid to late 30s and then tampers off, this also makes a lot of intuitive sense!
Now what about having children?:
plot_model(simple.fit, type = “pred”, terms = c(“gov.support [exp]”, “zero.children”))
Surprise surprise! Not having any children makes you more likely to be employed and on the market!
Now this probably seems a bit backwards but lets try to compare our plots to the coefficients of our model and try to make sense of it! (I’m a visual learner so this makes sense to me damn it!):
The categorical variables foreigner, zero.children and zero.young.children are easily interpreted, being a non-foreigner (foreignerno) lowers your Log-Odds of being employed by 1.12, not having any young kids improve your Log-Odds by 1.31 and not having any kids at all improves it by 1.06, you might wonder “Why doesn’t zero.children improve the odds more than zero.young.children” well, you have to consider than whenever zero.children is TRUE so is zero.young.children, basically giving an “accumulated improvement” to the Log-Odds.
Higher age improves your Log-Odds of being employed by 0.37, BUT the odds also declines by age2 * -0.0055, what does this mean? Well this is simply a concave 2. degree polynomial, somewhat similar to our plot of age, that is, we see an initial rise, followed by some maxima and then a decline.
That’s it! We’ve successfully replicated the values of our coefficient in a visual and intuitive manner, job well done.
If you want to follow along get the data here: https://github.com/pela15ae/statmod/blob/master/employment_data.txt and since it’s Danish you can run the code below to translate all variable-names and categorical values:
names(dat) <- c(“employed”, “foreigner”, “gov.support”, “age”, “education”, “young.children”, “school.children”)levels(dat$employed)[1] <- “yes”levels(dat$employed)[2] <- “no”levels(dat$foreigner)[1] <- “yes”levels(dat$foreigner)[2] <- “no”
Also take a look at data visualization on high-dimensional data:
medium.com
If you want to see and learn more, be sure to follow me on Medium🔍 and Twitter 🐦
|
[
{
"code": null,
"e": 312,
"s": 172,
"text": "This is (almost) a direct sequel to my previous article on “Model selection 101, using R”: (I should probably have made this a series huh?)"
},
{
"code": null,
"e": 323,
"s": 312,
"text": "medium.com"
},
{
"code": null,
"e": 446,
"s": 323,
"text": "So please check that out if you haven’t already as most examples will be using the same data and model from that analysis."
},
{
"code": null,
"e": 690,
"s": 446,
"text": "That being said, this is a sequel as well as a 101 in and of itself, meaning— like in the last article — that this will be mostly introductory. Go ahead to the end of this article if you want to download the data for yourself and follow along!"
},
{
"code": null,
"e": 769,
"s": 690,
"text": "Make sure to follow my profile if you enjoy this article and want to see more!"
},
{
"code": null,
"e": 957,
"s": 769,
"text": "In this article we’ll be taking a look at visualizing some of the findings you’ve made with your model, like the marginal effects of a given explanatory-variable on our response-variable."
},
{
"code": null,
"e": 997,
"s": 957,
"text": "We’ll be making pretty plots like this:"
},
{
"code": null,
"e": 1098,
"s": 997,
"text": "We have to do a little bit of house-keeping to prepare our data and models for proper visualization:"
},
{
"code": null,
"e": 1204,
"s": 1098,
"text": "dat$gov.support <- exp(dat$gov.support)dat$employed <- factor(dat$employed, levels(dat$employed)[c(2,1)])"
},
{
"code": null,
"e": 1581,
"s": 1204,
"text": "The first command applies the exp() transformation on our ‘gov.support’ values, this is because the values are log-transformed by default in the raw data. The reason we’re doing this is so that when we fit the model with ‘log(gov.support)’ we get the same results as in the previous article but we get the added benefit of ‘back’-transforming our data which I will show later!"
},
{
"code": null,
"e": 1931,
"s": 1581,
"text": "The second command simply swaps the order of our categorical response-variable ‘employed’ so that our model-fits will default to fitting for ‘employed == “yes”’ even when not explicitly defining it. This is important because now we can fit our model without using a “logical” response-variable which checks whether or not ‘employed == “yes”’ or not."
},
{
"code": null,
"e": 2013,
"s": 1931,
"text": "This means that while the base-model from the last article was created like this:"
},
{
"code": null,
"e": 2080,
"s": 2013,
"text": "fit.1 <- glm(employed == \"yes\" ~ ., data = dat, family = binomial)"
},
{
"code": null,
"e": 2108,
"s": 2080,
"text": "Now we define it like this:"
},
{
"code": null,
"e": 2213,
"s": 2108,
"text": "fit.1 <- glm(employed ~ . - gov.support + log(gov.support), data = dat, family = binomial)summary(fit.1)"
},
{
"code": null,
"e": 2424,
"s": 2213,
"text": "Notice we don’t define a logical condition for our response-variable and we replace the new exponentially transformed ‘gov.support’ with a log transformation of the variable to revert back to our initial model:"
},
{
"code": null,
"e": 2534,
"s": 2424,
"text": "As evident above we get the exact same summary as we did in the previous article before doing our “cleaning”."
},
{
"code": null,
"e": 2613,
"s": 2534,
"text": "The last thing I want to do is redefine our factor variables to be more clear:"
},
{
"code": null,
"e": 2806,
"s": 2613,
"text": "dat$zero.young.children <- factor(dat$young.children == 0)dat$zero.school.children <- factor(dat$school.children == 0)dat$zero.children <- factor(dat$young.children + dat$school.children == 0)"
},
{
"code": null,
"e": 2848,
"s": 2806,
"text": "This means our final fit looks like this:"
},
{
"code": null,
"e": 3307,
"s": 2848,
"text": "glm(employed ~ foreigner + log(gov.support) + age + school.children + zero.young.children + zero.school.children + zero.children + I(age^2) + foreigner:age + foreigner:zero.children + age:school.children + log(gov.support):zero.young.children, family = binomial, data = dat)"
},
{
"code": null,
"e": 3419,
"s": 3307,
"text": "Lets start by plotting what I find the most interesting, the relationship between “employed” and “gov.support”."
},
{
"code": null,
"e": 3487,
"s": 3419,
"text": "I’m using an absolutely brilliant package called “sjPlot” for this:"
},
{
"code": null,
"e": 3566,
"s": 3487,
"text": "library(\"sjPlot\")plot_model(full.fit, type = “pred”, terms = c(“gov.support”))"
},
{
"code": null,
"e": 3587,
"s": 3566,
"text": "Giving us this plot:"
},
{
"code": null,
"e": 3698,
"s": 3587,
"text": "Completely useless! What’s going on here? Well for our convenience ‘plot_model’ spits our the following error:"
},
{
"code": null,
"e": 3768,
"s": 3698,
"text": "This is exactly why we needed to transform the data! Let’s try again:"
},
{
"code": null,
"e": 3836,
"s": 3768,
"text": "plot_model(full.fit, type = “pred”, terms = c(“gov.support [exp]”))"
},
{
"code": null,
"e": 3909,
"s": 3836,
"text": "This is pretty damn close to being useless as well, what’s going on now?"
},
{
"code": null,
"e": 4114,
"s": 3909,
"text": "Lets try taking a look at our model and how it tries to capture the relationships in the data. There’s a few different ways to do this but lets just begin by looking at the coefficients of our full model:"
},
{
"code": null,
"e": 4369,
"s": 4114,
"text": "What’s the first thing you notice when looking at this? For me it’s the factor-variable ‘zero.young.children’ having a coefficient of almost 13! This isn’t necessarily a problem though but lets take a look at the confidence-intervals of the coefficients:"
},
{
"code": null,
"e": 4387,
"s": 4369,
"text": "confint(full.fit)"
},
{
"code": null,
"e": 4621,
"s": 4387,
"text": "Right, this looks like trouble! Take a look at the span on ‘zero.young.children’ this means that we’ll have huge confidence-intervals in our marginal-effect plots. This is most likely why our plot has such a huge confidence-interval."
},
{
"code": null,
"e": 4652,
"s": 4621,
"text": "sjPlot can plot these as well:"
},
{
"code": null,
"e": 4748,
"s": 4652,
"text": "plot_model(full.fit, transform = NULL, show.values = TRUE, axis.labels = “”, value.offset = .4)"
},
{
"code": null,
"e": 4905,
"s": 4748,
"text": "This makes it real easy to see that the factor variable ‘zero.young.children’ is quite problematic with regard to making any plots with any real confidence."
},
{
"code": null,
"e": 5028,
"s": 4905,
"text": "Lets take a little detour and create a more simple model without any variable-interactions, turns out this is what we get:"
},
{
"code": null,
"e": 5197,
"s": 5028,
"text": "simple.fit <- glm(employed ~ foreigner + age + zero.young.children + zero.children + log(gov.support) + I(age^2), family = binomial, data = dat)summary(simple.fit)"
},
{
"code": null,
"e": 5478,
"s": 5197,
"text": "A small increase in AIC which isn’t a good thing but it’s not too much and we gain a lot of simplicity by using this model instead! (If we measure performance with BIC instead we actually find that this model is better due to BIC penalizing harder on complex models! 1047 vs 1068)"
},
{
"code": null,
"e": 5513,
"s": 5478,
"text": "Lets look at the new coefficients:"
},
{
"code": null,
"e": 5611,
"s": 5513,
"text": "plot_model(simple.fit, transform = NULL, show.values = TRUE, axis.labels = “”, value.offset = .4)"
},
{
"code": null,
"e": 5697,
"s": 5611,
"text": "This look a lot better! Let’s try making our plot once more using this model instead!"
},
{
"code": null,
"e": 5767,
"s": 5697,
"text": "plot_model(simple.fit, type = “pred”, terms = c(“gov.support [exp]”))"
},
{
"code": null,
"e": 6078,
"s": 5767,
"text": "Nice, something useful! So obviously the probability of being employed is lower the more government support you’re entitled to. This makes quite a bit of intuitive sense! How about the difference between foreigners and non-foreigners? Well plot_model makes this real easy to do as well, just add it as a term!:"
},
{
"code": null,
"e": 6161,
"s": 6078,
"text": "plot_model(simple.fit, type = “pred”, terms = c(“gov.support [exp]”, “foreigner”))"
},
{
"code": null,
"e": 6315,
"s": 6161,
"text": "This is a breeze! So this model suggests that foreigners are more likely to be employed than non-foreigners given that the other variables are identical."
},
{
"code": null,
"e": 6643,
"s": 6315,
"text": "How about age? This required a slightly different approach because we don’t really assume a strictly positive or negative relationship with age which is why the power-transformation I(age2) makes sense. That is, we don’t expect a 10 year old to be employed, neither a 70 year old, but we do expect a 30 year old to be employed."
},
{
"code": null,
"e": 6812,
"s": 6643,
"text": "Sadly sjPlot doesn’t take too kindly to these kinds of power-transformations (Or I’m just an imbecile who can’t work it out), so I’m using the package ‘jtools’ instead:"
},
{
"code": null,
"e": 6877,
"s": 6812,
"text": "effect_plot(simple.fit, pred = age, data = dat, interval = TRUE)"
},
{
"code": null,
"e": 6998,
"s": 6877,
"text": "So it seems employment “tops” around the mid to late 30s and then tampers off, this also makes a lot of intuitive sense!"
},
{
"code": null,
"e": 7031,
"s": 6998,
"text": "Now what about having children?:"
},
{
"code": null,
"e": 7118,
"s": 7031,
"text": "plot_model(simple.fit, type = “pred”, terms = c(“gov.support [exp]”, “zero.children”))"
},
{
"code": null,
"e": 7217,
"s": 7118,
"text": "Surprise surprise! Not having any children makes you more likely to be employed and on the market!"
},
{
"code": null,
"e": 7412,
"s": 7217,
"text": "Now this probably seems a bit backwards but lets try to compare our plots to the coefficients of our model and try to make sense of it! (I’m a visual learner so this makes sense to me damn it!):"
},
{
"code": null,
"e": 7948,
"s": 7412,
"text": "The categorical variables foreigner, zero.children and zero.young.children are easily interpreted, being a non-foreigner (foreignerno) lowers your Log-Odds of being employed by 1.12, not having any young kids improve your Log-Odds by 1.31 and not having any kids at all improves it by 1.06, you might wonder “Why doesn’t zero.children improve the odds more than zero.young.children” well, you have to consider than whenever zero.children is TRUE so is zero.young.children, basically giving an “accumulated improvement” to the Log-Odds."
},
{
"code": null,
"e": 8242,
"s": 7948,
"text": "Higher age improves your Log-Odds of being employed by 0.37, BUT the odds also declines by age2 * -0.0055, what does this mean? Well this is simply a concave 2. degree polynomial, somewhat similar to our plot of age, that is, we see an initial rise, followed by some maxima and then a decline."
},
{
"code": null,
"e": 8362,
"s": 8242,
"text": "That’s it! We’ve successfully replicated the values of our coefficient in a visual and intuitive manner, job well done."
},
{
"code": null,
"e": 8582,
"s": 8362,
"text": "If you want to follow along get the data here: https://github.com/pela15ae/statmod/blob/master/employment_data.txt and since it’s Danish you can run the code below to translate all variable-names and categorical values:"
},
{
"code": null,
"e": 8823,
"s": 8582,
"text": "names(dat) <- c(“employed”, “foreigner”, “gov.support”, “age”, “education”, “young.children”, “school.children”)levels(dat$employed)[1] <- “yes”levels(dat$employed)[2] <- “no”levels(dat$foreigner)[1] <- “yes”levels(dat$foreigner)[2] <- “no”"
},
{
"code": null,
"e": 8888,
"s": 8823,
"text": "Also take a look at data visualization on high-dimensional data:"
},
{
"code": null,
"e": 8899,
"s": 8888,
"text": "medium.com"
}
] |
Display records with more than two occurrences in MySQL?
|
For this, you can use GROUP BY HAVING clause. Let us first create a table −
mysql> create table DemoTable
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Subject varchar(100)
-> );
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Subject) values('MySQL');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Subject) values('MongoDB');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable(Subject) values('MySQL');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Subject) values('Java');
Query OK, 1 row affected (0.56 sec)
mysql> insert into DemoTable(Subject) values('SQL Server');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Subject) values('MongoDB');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Subject) values('MySQL');
Query OK, 1 row affected (0.48 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+----+------------+
| Id | Subject |
+----+------------+
| 1 | MySQL |
| 2 | MongoDB |
| 3 | MySQL |
| 4 | Java |
| 5 | SQL Server |
| 6 | MongoDB |
| 7 | MySQL |
+----+------------+
7 rows in set (0.00 sec)
Following is the query to display distinct records with more than 2 occurrences in MySQL.
mysql> select Subject,count(Subject) freq from DemoTable
-> group by Subject
-> having count(Subject) > 2;
+---------+------+
| Subject | freq |
+---------+------+
| MySQL | 3 |
+---------+------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1138,
"s": 1062,
"text": "For this, you can use GROUP BY HAVING clause. Let us first create a table −"
},
{
"code": null,
"e": 1299,
"s": 1138,
"text": "mysql> create table DemoTable\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> Subject varchar(100)\n -> );\nQuery OK, 0 rows affected (0.53 sec)"
},
{
"code": null,
"e": 1355,
"s": 1299,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 2006,
"s": 1355,
"text": "mysql> insert into DemoTable(Subject) values('MySQL');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into DemoTable(Subject) values('MongoDB');\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> insert into DemoTable(Subject) values('MySQL');\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into DemoTable(Subject) values('Java');\nQuery OK, 1 row affected (0.56 sec)\n\nmysql> insert into DemoTable(Subject) values('SQL Server');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into DemoTable(Subject) values('MongoDB');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into DemoTable(Subject) values('MySQL');\nQuery OK, 1 row affected (0.48 sec)"
},
{
"code": null,
"e": 2066,
"s": 2006,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2097,
"s": 2066,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2342,
"s": 2097,
"text": "+----+------------+\n| Id | Subject |\n+----+------------+\n| 1 | MySQL |\n| 2 | MongoDB |\n| 3 | MySQL |\n| 4 | Java |\n| 5 | SQL Server |\n| 6 | MongoDB |\n| 7 | MySQL |\n+----+------------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2432,
"s": 2342,
"text": "Following is the query to display distinct records with more than 2 occurrences in MySQL."
},
{
"code": null,
"e": 2545,
"s": 2432,
"text": "mysql> select Subject,count(Subject) freq from DemoTable\n -> group by Subject\n -> having count(Subject) > 2;"
},
{
"code": null,
"e": 2664,
"s": 2545,
"text": "+---------+------+\n| Subject | freq |\n+---------+------+\n| MySQL | 3 |\n+---------+------+\n1 row in set (0.00 sec)"
}
] |
Inter Process Communication - Pipes
|
Pipe is a communication medium between two or more related or interrelated processes. It can be either within one process or a communication between the child and the parent processes. Communication can also be multi-level such as communication between the parent, the child and the grand-child, etc. Communication is achieved by one process writing into the pipe and other reading from the pipe. To achieve the pipe system call, create two files, one to write into the file and another to read from the file.
Pipe mechanism can be viewed with a real-time scenario such as filling water with the pipe into some container, say a bucket, and someone retrieving it, say with a mug. The filling process is nothing but writing into the pipe and the reading process is nothing but retrieving from the pipe. This implies that one output (water) is input for the other (bucket).
#include<unistd.h>
int pipe(int pipedes[2]);
This system call would create a pipe for one-way communication i.e., it creates two descriptors, first one is connected to read from the pipe and other one is connected to write into the pipe.
Descriptor pipedes[0] is for reading and pipedes[1] is for writing. Whatever is written into pipedes[1] can be read from pipedes[0].
This call would return zero on success and -1 in case of failure. To know the cause of failure, check with errno variable or perror() function.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
Even though the basic operations for file are read and write, it is essential to open the file before performing the operations and closing the file after completion of the required operations. Usually, by default, 3 descriptors opened for every process, which are used for input (standard input – stdin), output (standard output – stdout) and error (standard error – stderr) having file descriptors 0, 1 and 2 respectively.
This system call would return a file descriptor used for further file operations of read/write/seek (lseek). Usually file descriptors start from 3 and increase by one number as the number of files open.
The arguments passed to open system call are pathname (relative or absolute path), flags mentioning the purpose of opening file (say, opening for read, O_RDONLY, to write, O_WRONLY, to read and write, O_RDWR, to append to the existing file O_APPEND, to create file, if not exists with O_CREAT and so on) and the required mode providing permissions of read/write/execute for user or owner/group/others. Mode can be mentioned with symbols.
Read – 4, Write – 2 and Execute – 1.
For example: Octal value (starts with 0), 0764 implies owner has read, write and execute permissions, group has read and write permissions, other has read permissions. This can also be represented as S_IRWXU | S_IRGRP | S_IWGRP | S_IROTH, which implies or operation of 0700|0040|0020|0004 → 0764.
This system call, on success, returns the new file descriptor id and -1 in case of error. The cause of error can be identified with errno variable or perror() function.
#include<unistd.h>
int close(int fd)
The above system call closing already opened file descriptor. This implies the file is no longer in use and resources associated can be reused by any other process. This system call returns zero on success and -1 in case of error. The cause of error can be identified with errno variable or perror() function.
#include<unistd.h>
ssize_t read(int fd, void *buf, size_t count)
The above system call is to read from the specified file with arguments of file descriptor fd, proper buffer with allocated memory (either static or dynamic) and the size of buffer.
The file descriptor id is to identify the respective file, which is returned after calling open() or pipe() system call. The file needs to be opened before reading from the file. It automatically opens in case of calling pipe() system call.
This call would return the number of bytes read (or zero in case of encountering the end of the file) on success and -1 in case of failure. The return bytes can be smaller than the number of bytes requested, just in case no data is available or file is closed. Proper error number is set in case of failure.
To know the cause of failure, check with errno variable or perror() function.
#include<unistd.h>
ssize_t write(int fd, void *buf, size_t count)
The above system call is to write to the specified file with arguments of the file descriptor fd, a proper buffer with allocated memory (either static or dynamic) and the size of buffer.
The file descriptor id is to identify the respective file, which is returned after calling open() or pipe() system call.
The file needs to be opened before writing to the file. It automatically opens in case of calling pipe() system call.
This call would return the number of bytes written (or zero in case nothing is written) on success and -1 in case of failure. Proper error number is set in case of failure.
To know the cause of failure, check with errno variable or perror() function.
Following are some example programs.
Example program 1 − Program to write and read two messages using pipe.
Step 1 − Create a pipe.
Step 2 − Send a message to the pipe.
Step 3 − Retrieve the message from the pipe and write it to the standard output.
Step 4 − Send another message to the pipe.
Step 5 − Retrieve the message from the pipe and write it to the standard output.
Note − Retrieving messages can also be done after sending all messages.
Source Code: simplepipe.c
#include<stdio.h>
#include<unistd.h>
int main() {
int pipefds[2];
int returnstatus;
char writemessages[2][20]={"Hi", "Hello"};
char readmessage[20];
returnstatus = pipe(pipefds);
if (returnstatus == -1) {
printf("Unable to create pipe\n");
return 1;
}
printf("Writing to pipe - Message 1 is %s\n", writemessages[0]);
write(pipefds[1], writemessages[0], sizeof(writemessages[0]));
read(pipefds[0], readmessage, sizeof(readmessage));
printf("Reading from pipe – Message 1 is %s\n", readmessage);
printf("Writing to pipe - Message 2 is %s\n", writemessages[0]);
write(pipefds[1], writemessages[1], sizeof(writemessages[0]));
read(pipefds[0], readmessage, sizeof(readmessage));
printf("Reading from pipe – Message 2 is %s\n", readmessage);
return 0;
}
Note − Ideally, return status needs to be checked for every system call. To simplify the process, checks are not done for all the calls.
gcc -o simplepipe simplepipe.c
Writing to pipe - Message 1 is Hi
Reading from pipe – Message 1 is Hi
Writing to pipe - Message 2 is Hi
Reading from pipe – Message 2 is Hell
Example program 2 − Program to write and read two messages through the pipe using the parent and the child processes.
Step 1 − Create a pipe.
Step 2 − Create a child process.
Step 3 − Parent process writes to the pipe.
Step 4 − Child process retrieves the message from the pipe and writes it to the standard output.
Step 5 − Repeat step 3 and step 4 once again.
Source Code: pipewithprocesses.c
#include<stdio.h>
#include<unistd.h>
int main() {
int pipefds[2];
int returnstatus;
int pid;
char writemessages[2][20]={"Hi", "Hello"};
char readmessage[20];
returnstatus = pipe(pipefds);
if (returnstatus == -1) {
printf("Unable to create pipe\n");
return 1;
}
pid = fork();
// Child process
if (pid == 0) {
read(pipefds[0], readmessage, sizeof(readmessage));
printf("Child Process - Reading from pipe – Message 1 is %s\n", readmessage);
read(pipefds[0], readmessage, sizeof(readmessage));
printf("Child Process - Reading from pipe – Message 2 is %s\n", readmessage);
} else { //Parent process
printf("Parent Process - Writing to pipe - Message 1 is %s\n", writemessages[0]);
write(pipefds[1], writemessages[0], sizeof(writemessages[0]));
printf("Parent Process - Writing to pipe - Message 2 is %s\n", writemessages[1]);
write(pipefds[1], writemessages[1], sizeof(writemessages[1]));
}
return 0;
}
Compilation
gcc pipewithprocesses.c –o pipewithprocesses
Execution
Parent Process - Writing to pipe - Message 1 is Hi
Parent Process - Writing to pipe - Message 2 is Hello
Child Process - Reading from pipe – Message 1 is Hi
Child Process - Reading from pipe – Message 2 is Hello
Pipe communication is viewed as only one-way communication i.e., either the parent process writes and the child process reads or vice-versa but not both. However, what if both the parent and the child needs to write and read from the pipes simultaneously, the solution is a two-way communication using pipes. Two pipes are required to establish two-way communication.
Following are the steps to achieve two-way communication −
Step 1 − Create two pipes. First one is for the parent to write and child to read, say as pipe1. Second one is for the child to write and parent to read, say as pipe2.
Step 2 − Create a child process.
Step 3 − Close unwanted ends as only one end is needed for each communication.
Step 4 − Close unwanted ends in the parent process, read end of pipe1 and write end of pipe2.
Step 5 − Close the unwanted ends in the child process, write end of pipe1 and read end of pipe2.
Step 6 − Perform the communication as required.
Sample program 1 − Achieving two-way communication using pipes.
Step 1 − Create pipe1 for the parent process to write and the child process to read.
Step 2 − Create pipe2 for the child process to write and the parent process to read.
Step 3 − Close the unwanted ends of the pipe from the parent and child side.
Step 4 − Parent process to write a message and child process to read and display on the screen.
Step 5 − Child process to write a message and parent process to read and display on the screen.
Source Code: twowayspipe.c
#include<stdio.h>
#include<unistd.h>
int main() {
int pipefds1[2], pipefds2[2];
int returnstatus1, returnstatus2;
int pid;
char pipe1writemessage[20] = "Hi";
char pipe2writemessage[20] = "Hello";
char readmessage[20];
returnstatus1 = pipe(pipefds1);
if (returnstatus1 == -1) {
printf("Unable to create pipe 1 \n");
return 1;
}
returnstatus2 = pipe(pipefds2);
if (returnstatus2 == -1) {
printf("Unable to create pipe 2 \n");
return 1;
}
pid = fork();
if (pid != 0) // Parent process {
close(pipefds1[0]); // Close the unwanted pipe1 read side
close(pipefds2[1]); // Close the unwanted pipe2 write side
printf("In Parent: Writing to pipe 1 – Message is %s\n", pipe1writemessage);
write(pipefds1[1], pipe1writemessage, sizeof(pipe1writemessage));
read(pipefds2[0], readmessage, sizeof(readmessage));
printf("In Parent: Reading from pipe 2 – Message is %s\n", readmessage);
} else { //child process
close(pipefds1[1]); // Close the unwanted pipe1 write side
close(pipefds2[0]); // Close the unwanted pipe2 read side
read(pipefds1[0], readmessage, sizeof(readmessage));
printf("In Child: Reading from pipe 1 – Message is %s\n", readmessage);
printf("In Child: Writing to pipe 2 – Message is %s\n", pipe2writemessage);
write(pipefds2[1], pipe2writemessage, sizeof(pipe2writemessage));
}
return 0;
}
gcc twowayspipe.c –o twowayspipe
In Parent: Writing to pipe 1 – Message is Hi
In Child: Reading from pipe 1 – Message is Hi
In Child: Writing to pipe 2 – Message is Hello
In Parent: Reading from pipe 2 – Message is Hello
21 Lectures
2.5 hours
Asif Hussain
14 Lectures
57 mins
Kaushik Roy Chowdhury
5 Lectures
2 hours
Manish Gupta
35 Lectures
2.5 hours
Manish Gupta
16 Lectures
2 hours
Pranjal Srivastava
22 Lectures
2.5 hours
J Aatish Rao
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2381,
"s": 1871,
"text": "Pipe is a communication medium between two or more related or interrelated processes. It can be either within one process or a communication between the child and the parent processes. Communication can also be multi-level such as communication between the parent, the child and the grand-child, etc. Communication is achieved by one process writing into the pipe and other reading from the pipe. To achieve the pipe system call, create two files, one to write into the file and another to read from the file."
},
{
"code": null,
"e": 2742,
"s": 2381,
"text": "Pipe mechanism can be viewed with a real-time scenario such as filling water with the pipe into some container, say a bucket, and someone retrieving it, say with a mug. The filling process is nothing but writing into the pipe and the reading process is nothing but retrieving from the pipe. This implies that one output (water) is input for the other (bucket)."
},
{
"code": null,
"e": 2788,
"s": 2742,
"text": "#include<unistd.h>\n\nint pipe(int pipedes[2]);"
},
{
"code": null,
"e": 2981,
"s": 2788,
"text": "This system call would create a pipe for one-way communication i.e., it creates two descriptors, first one is connected to read from the pipe and other one is connected to write into the pipe."
},
{
"code": null,
"e": 3114,
"s": 2981,
"text": "Descriptor pipedes[0] is for reading and pipedes[1] is for writing. Whatever is written into pipedes[1] can be read from pipedes[0]."
},
{
"code": null,
"e": 3258,
"s": 3114,
"text": "This call would return zero on success and -1 in case of failure. To know the cause of failure, check with errno variable or perror() function."
},
{
"code": null,
"e": 3422,
"s": 3258,
"text": "#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n\nint open(const char *pathname, int flags);\nint open(const char *pathname, int flags, mode_t mode);"
},
{
"code": null,
"e": 3847,
"s": 3422,
"text": "Even though the basic operations for file are read and write, it is essential to open the file before performing the operations and closing the file after completion of the required operations. Usually, by default, 3 descriptors opened for every process, which are used for input (standard input – stdin), output (standard output – stdout) and error (standard error – stderr) having file descriptors 0, 1 and 2 respectively."
},
{
"code": null,
"e": 4050,
"s": 3847,
"text": "This system call would return a file descriptor used for further file operations of read/write/seek (lseek). Usually file descriptors start from 3 and increase by one number as the number of files open."
},
{
"code": null,
"e": 4488,
"s": 4050,
"text": "The arguments passed to open system call are pathname (relative or absolute path), flags mentioning the purpose of opening file (say, opening for read, O_RDONLY, to write, O_WRONLY, to read and write, O_RDWR, to append to the existing file O_APPEND, to create file, if not exists with O_CREAT and so on) and the required mode providing permissions of read/write/execute for user or owner/group/others. Mode can be mentioned with symbols."
},
{
"code": null,
"e": 4525,
"s": 4488,
"text": "Read – 4, Write – 2 and Execute – 1."
},
{
"code": null,
"e": 4822,
"s": 4525,
"text": "For example: Octal value (starts with 0), 0764 implies owner has read, write and execute permissions, group has read and write permissions, other has read permissions. This can also be represented as S_IRWXU | S_IRGRP | S_IWGRP | S_IROTH, which implies or operation of 0700|0040|0020|0004 → 0764."
},
{
"code": null,
"e": 4991,
"s": 4822,
"text": "This system call, on success, returns the new file descriptor id and -1 in case of error. The cause of error can be identified with errno variable or perror() function."
},
{
"code": null,
"e": 5029,
"s": 4991,
"text": "#include<unistd.h>\n\nint close(int fd)"
},
{
"code": null,
"e": 5339,
"s": 5029,
"text": "The above system call closing already opened file descriptor. This implies the file is no longer in use and resources associated can be reused by any other process. This system call returns zero on success and -1 in case of error. The cause of error can be identified with errno variable or perror() function."
},
{
"code": null,
"e": 5405,
"s": 5339,
"text": "#include<unistd.h>\n\nssize_t read(int fd, void *buf, size_t count)"
},
{
"code": null,
"e": 5587,
"s": 5405,
"text": "The above system call is to read from the specified file with arguments of file descriptor fd, proper buffer with allocated memory (either static or dynamic) and the size of buffer."
},
{
"code": null,
"e": 5828,
"s": 5587,
"text": "The file descriptor id is to identify the respective file, which is returned after calling open() or pipe() system call. The file needs to be opened before reading from the file. It automatically opens in case of calling pipe() system call."
},
{
"code": null,
"e": 6136,
"s": 5828,
"text": "This call would return the number of bytes read (or zero in case of encountering the end of the file) on success and -1 in case of failure. The return bytes can be smaller than the number of bytes requested, just in case no data is available or file is closed. Proper error number is set in case of failure."
},
{
"code": null,
"e": 6214,
"s": 6136,
"text": "To know the cause of failure, check with errno variable or perror() function."
},
{
"code": null,
"e": 6281,
"s": 6214,
"text": "#include<unistd.h>\n\nssize_t write(int fd, void *buf, size_t count)"
},
{
"code": null,
"e": 6468,
"s": 6281,
"text": "The above system call is to write to the specified file with arguments of the file descriptor fd, a proper buffer with allocated memory (either static or dynamic) and the size of buffer."
},
{
"code": null,
"e": 6589,
"s": 6468,
"text": "The file descriptor id is to identify the respective file, which is returned after calling open() or pipe() system call."
},
{
"code": null,
"e": 6707,
"s": 6589,
"text": "The file needs to be opened before writing to the file. It automatically opens in case of calling pipe() system call."
},
{
"code": null,
"e": 6880,
"s": 6707,
"text": "This call would return the number of bytes written (or zero in case nothing is written) on success and -1 in case of failure. Proper error number is set in case of failure."
},
{
"code": null,
"e": 6958,
"s": 6880,
"text": "To know the cause of failure, check with errno variable or perror() function."
},
{
"code": null,
"e": 6995,
"s": 6958,
"text": "Following are some example programs."
},
{
"code": null,
"e": 7066,
"s": 6995,
"text": "Example program 1 − Program to write and read two messages using pipe."
},
{
"code": null,
"e": 7090,
"s": 7066,
"text": "Step 1 − Create a pipe."
},
{
"code": null,
"e": 7127,
"s": 7090,
"text": "Step 2 − Send a message to the pipe."
},
{
"code": null,
"e": 7208,
"s": 7127,
"text": "Step 3 − Retrieve the message from the pipe and write it to the standard output."
},
{
"code": null,
"e": 7251,
"s": 7208,
"text": "Step 4 − Send another message to the pipe."
},
{
"code": null,
"e": 7332,
"s": 7251,
"text": "Step 5 − Retrieve the message from the pipe and write it to the standard output."
},
{
"code": null,
"e": 7404,
"s": 7332,
"text": "Note − Retrieving messages can also be done after sending all messages."
},
{
"code": null,
"e": 7430,
"s": 7404,
"text": "Source Code: simplepipe.c"
},
{
"code": null,
"e": 8247,
"s": 7430,
"text": "#include<stdio.h>\n#include<unistd.h>\n\nint main() {\n int pipefds[2];\n int returnstatus;\n char writemessages[2][20]={\"Hi\", \"Hello\"};\n char readmessage[20];\n returnstatus = pipe(pipefds);\n \n if (returnstatus == -1) {\n printf(\"Unable to create pipe\\n\");\n return 1;\n }\n \n printf(\"Writing to pipe - Message 1 is %s\\n\", writemessages[0]);\n write(pipefds[1], writemessages[0], sizeof(writemessages[0]));\n read(pipefds[0], readmessage, sizeof(readmessage));\n printf(\"Reading from pipe – Message 1 is %s\\n\", readmessage);\n printf(\"Writing to pipe - Message 2 is %s\\n\", writemessages[0]);\n write(pipefds[1], writemessages[1], sizeof(writemessages[0]));\n read(pipefds[0], readmessage, sizeof(readmessage));\n printf(\"Reading from pipe – Message 2 is %s\\n\", readmessage);\n return 0;\n}"
},
{
"code": null,
"e": 8384,
"s": 8247,
"text": "Note − Ideally, return status needs to be checked for every system call. To simplify the process, checks are not done for all the calls."
},
{
"code": null,
"e": 8416,
"s": 8384,
"text": "gcc -o simplepipe simplepipe.c\n"
},
{
"code": null,
"e": 8559,
"s": 8416,
"text": "Writing to pipe - Message 1 is Hi\nReading from pipe – Message 1 is Hi\nWriting to pipe - Message 2 is Hi\nReading from pipe – Message 2 is Hell\n"
},
{
"code": null,
"e": 8677,
"s": 8559,
"text": "Example program 2 − Program to write and read two messages through the pipe using the parent and the child processes."
},
{
"code": null,
"e": 8701,
"s": 8677,
"text": "Step 1 − Create a pipe."
},
{
"code": null,
"e": 8734,
"s": 8701,
"text": "Step 2 − Create a child process."
},
{
"code": null,
"e": 8778,
"s": 8734,
"text": "Step 3 − Parent process writes to the pipe."
},
{
"code": null,
"e": 8875,
"s": 8778,
"text": "Step 4 − Child process retrieves the message from the pipe and writes it to the standard output."
},
{
"code": null,
"e": 8921,
"s": 8875,
"text": "Step 5 − Repeat step 3 and step 4 once again."
},
{
"code": null,
"e": 8954,
"s": 8921,
"text": "Source Code: pipewithprocesses.c"
},
{
"code": null,
"e": 9959,
"s": 8954,
"text": "#include<stdio.h>\n#include<unistd.h>\n\nint main() {\n int pipefds[2];\n int returnstatus;\n int pid;\n char writemessages[2][20]={\"Hi\", \"Hello\"};\n char readmessage[20];\n returnstatus = pipe(pipefds);\n if (returnstatus == -1) {\n printf(\"Unable to create pipe\\n\");\n return 1;\n }\n pid = fork();\n \n // Child process\n if (pid == 0) {\n read(pipefds[0], readmessage, sizeof(readmessage));\n printf(\"Child Process - Reading from pipe – Message 1 is %s\\n\", readmessage);\n read(pipefds[0], readmessage, sizeof(readmessage));\n printf(\"Child Process - Reading from pipe – Message 2 is %s\\n\", readmessage);\n } else { //Parent process\n printf(\"Parent Process - Writing to pipe - Message 1 is %s\\n\", writemessages[0]);\n write(pipefds[1], writemessages[0], sizeof(writemessages[0]));\n printf(\"Parent Process - Writing to pipe - Message 2 is %s\\n\", writemessages[1]);\n write(pipefds[1], writemessages[1], sizeof(writemessages[1]));\n }\n return 0;\n}"
},
{
"code": null,
"e": 9971,
"s": 9959,
"text": "Compilation"
},
{
"code": null,
"e": 10017,
"s": 9971,
"text": "gcc pipewithprocesses.c –o pipewithprocesses\n"
},
{
"code": null,
"e": 10027,
"s": 10017,
"text": "Execution"
},
{
"code": null,
"e": 10240,
"s": 10027,
"text": "Parent Process - Writing to pipe - Message 1 is Hi\nParent Process - Writing to pipe - Message 2 is Hello\nChild Process - Reading from pipe – Message 1 is Hi\nChild Process - Reading from pipe – Message 2 is Hello\n"
},
{
"code": null,
"e": 10608,
"s": 10240,
"text": "Pipe communication is viewed as only one-way communication i.e., either the parent process writes and the child process reads or vice-versa but not both. However, what if both the parent and the child needs to write and read from the pipes simultaneously, the solution is a two-way communication using pipes. Two pipes are required to establish two-way communication."
},
{
"code": null,
"e": 10667,
"s": 10608,
"text": "Following are the steps to achieve two-way communication −"
},
{
"code": null,
"e": 10835,
"s": 10667,
"text": "Step 1 − Create two pipes. First one is for the parent to write and child to read, say as pipe1. Second one is for the child to write and parent to read, say as pipe2."
},
{
"code": null,
"e": 10868,
"s": 10835,
"text": "Step 2 − Create a child process."
},
{
"code": null,
"e": 10947,
"s": 10868,
"text": "Step 3 − Close unwanted ends as only one end is needed for each communication."
},
{
"code": null,
"e": 11041,
"s": 10947,
"text": "Step 4 − Close unwanted ends in the parent process, read end of pipe1 and write end of pipe2."
},
{
"code": null,
"e": 11138,
"s": 11041,
"text": "Step 5 − Close the unwanted ends in the child process, write end of pipe1 and read end of pipe2."
},
{
"code": null,
"e": 11186,
"s": 11138,
"text": "Step 6 − Perform the communication as required."
},
{
"code": null,
"e": 11250,
"s": 11186,
"text": "Sample program 1 − Achieving two-way communication using pipes."
},
{
"code": null,
"e": 11335,
"s": 11250,
"text": "Step 1 − Create pipe1 for the parent process to write and the child process to read."
},
{
"code": null,
"e": 11420,
"s": 11335,
"text": "Step 2 − Create pipe2 for the child process to write and the parent process to read."
},
{
"code": null,
"e": 11497,
"s": 11420,
"text": "Step 3 − Close the unwanted ends of the pipe from the parent and child side."
},
{
"code": null,
"e": 11593,
"s": 11497,
"text": "Step 4 − Parent process to write a message and child process to read and display on the screen."
},
{
"code": null,
"e": 11689,
"s": 11593,
"text": "Step 5 − Child process to write a message and parent process to read and display on the screen."
},
{
"code": null,
"e": 11716,
"s": 11689,
"text": "Source Code: twowayspipe.c"
},
{
"code": null,
"e": 13169,
"s": 11716,
"text": "#include<stdio.h>\n#include<unistd.h>\n\nint main() {\n int pipefds1[2], pipefds2[2];\n int returnstatus1, returnstatus2;\n int pid;\n char pipe1writemessage[20] = \"Hi\";\n char pipe2writemessage[20] = \"Hello\";\n char readmessage[20];\n returnstatus1 = pipe(pipefds1);\n \n if (returnstatus1 == -1) {\n printf(\"Unable to create pipe 1 \\n\");\n return 1;\n }\n returnstatus2 = pipe(pipefds2);\n \n if (returnstatus2 == -1) {\n printf(\"Unable to create pipe 2 \\n\");\n return 1;\n }\n pid = fork();\n \n if (pid != 0) // Parent process {\n close(pipefds1[0]); // Close the unwanted pipe1 read side\n close(pipefds2[1]); // Close the unwanted pipe2 write side\n printf(\"In Parent: Writing to pipe 1 – Message is %s\\n\", pipe1writemessage);\n write(pipefds1[1], pipe1writemessage, sizeof(pipe1writemessage));\n read(pipefds2[0], readmessage, sizeof(readmessage));\n printf(\"In Parent: Reading from pipe 2 – Message is %s\\n\", readmessage);\n } else { //child process\n close(pipefds1[1]); // Close the unwanted pipe1 write side\n close(pipefds2[0]); // Close the unwanted pipe2 read side\n read(pipefds1[0], readmessage, sizeof(readmessage));\n printf(\"In Child: Reading from pipe 1 – Message is %s\\n\", readmessage);\n printf(\"In Child: Writing to pipe 2 – Message is %s\\n\", pipe2writemessage);\n write(pipefds2[1], pipe2writemessage, sizeof(pipe2writemessage));\n }\n return 0;\n}"
},
{
"code": null,
"e": 13203,
"s": 13169,
"text": "gcc twowayspipe.c –o twowayspipe\n"
},
{
"code": null,
"e": 13392,
"s": 13203,
"text": "In Parent: Writing to pipe 1 – Message is Hi\nIn Child: Reading from pipe 1 – Message is Hi\nIn Child: Writing to pipe 2 – Message is Hello\nIn Parent: Reading from pipe 2 – Message is Hello\n"
},
{
"code": null,
"e": 13427,
"s": 13392,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 13441,
"s": 13427,
"text": " Asif Hussain"
},
{
"code": null,
"e": 13473,
"s": 13441,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 13496,
"s": 13473,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 13528,
"s": 13496,
"text": "\n 5 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 13542,
"s": 13528,
"text": " Manish Gupta"
},
{
"code": null,
"e": 13577,
"s": 13542,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 13591,
"s": 13577,
"text": " Manish Gupta"
},
{
"code": null,
"e": 13624,
"s": 13591,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 13644,
"s": 13624,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 13679,
"s": 13644,
"text": "\n 22 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 13693,
"s": 13679,
"text": " J Aatish Rao"
},
{
"code": null,
"e": 13700,
"s": 13693,
"text": " Print"
},
{
"code": null,
"e": 13711,
"s": 13700,
"text": " Add Notes"
}
] |
How to convert a string into uppercase in AngularJS?
|
Sometimes we may need to represent a name or a string in capital letters. To convert a string into uppercase in AngularJS, we can use the uppercase filter to change its case to uppercase.
In HTML Template Binding
{{uppercase_expression | uppercase}}
In JavaScript
$filter('uppercase')()
Create a file "uppercase.html" in your Angular project directory and copy-paste the following code snippet.
<!DOCTYPE html>
<html>
<head>
<title>uppercase Filter</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body ng-app="app"
style="text-align:Center">
<h1 style="color:green">
Welcome to Tutorials Point
</h1>
<h2 style="color: grey;">
AngularJS | UpperCase Filter
</h2>
<div ng-controller="example">
<p>
<h2>
Original: {{message}}
</h2>
<h2>
Modified: {{message | uppercase}}
</h2>
<p>
</div>
<script>
angular.module('app', [])
.controller('example',['$scope', function($scope) {
$scope.message = 'simply learning';
}]);
</script>
</body>
</html>
To run the above code, just go to your file and run it as a normal HTML file. You will see the following output on the browser window.
|
[
{
"code": null,
"e": 1250,
"s": 1062,
"text": "Sometimes we may need to represent a name or a string in capital letters. To convert a string into uppercase in AngularJS, we can use the uppercase filter to change its case to uppercase."
},
{
"code": null,
"e": 1275,
"s": 1250,
"text": "In HTML Template Binding"
},
{
"code": null,
"e": 1312,
"s": 1275,
"text": "{{uppercase_expression | uppercase}}"
},
{
"code": null,
"e": 1326,
"s": 1312,
"text": "In JavaScript"
},
{
"code": null,
"e": 1349,
"s": 1326,
"text": "$filter('uppercase')()"
},
{
"code": null,
"e": 1457,
"s": 1349,
"text": "Create a file \"uppercase.html\" in your Angular project directory and copy-paste the following code snippet."
},
{
"code": null,
"e": 2212,
"s": 1457,
"text": "<!DOCTYPE html>\n<html>\n\n<head>\n <title>uppercase Filter</title>\n <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js\"></script>\n</head>\n\n\n<body ng-app=\"app\"\n style=\"text-align:Center\">\n <h1 style=\"color:green\">\n Welcome to Tutorials Point\n </h1>\n <h2 style=\"color: grey;\">\n AngularJS | UpperCase Filter\n </h2>\n <div ng-controller=\"example\">\n <p>\n <h2>\n Original: {{message}}\n </h2>\n <h2>\n Modified: {{message | uppercase}}\n </h2>\n <p>\n </div>\n <script>\n angular.module('app', [])\n .controller('example',['$scope', function($scope) {\n $scope.message = 'simply learning';\n }]);\n </script>\n</body>\n</html>"
},
{
"code": null,
"e": 2347,
"s": 2212,
"text": "To run the above code, just go to your file and run it as a normal HTML file. You will see the following output on the browser window."
}
] |
How to train your deep learning models in a distributed fashion. | by Srikanth Machiraju | Towards Data Science
|
Deep learning algorithms are well suited for large data sets and also training deep learning networks needs large computation power. With GPUs / TPUs easily available on pay per use basis or for free (like Google collab), it is possible today to train a large neural network on cloud-like say Resnet 152 (152 layers) on ImageNet database which has around 14 million images. But is a multi-core GPU-enabled machine just enough to train huge models. Technically yes, but it might take weeks to train the model. So how do we reduce the training time? Any scalability issue can be solved using 2 approaches — scale-up or scale-out. We all know if we choose to scale up the capacity maxes out at some point, so the better alternative is scale-out. But, how do you do distributed training, if I have a model training using Jupyter notebook where do I start, can I perform distributed training for any deep learning model? This blog aims to answer these questions with a practical approach.
In this blog we will learn how to apply scaled out or in other words, Distributed Machine Learning Techniques on the cloud. We will understand how we go from a Jupyter notebook phase which is the most agile way of building ML models to a production-ready training script that can run on a cluster of GPUs using Azure ML and Horovod.
If you’re new to distributed machine learning, here are some of the concepts/terminologies you should know before moving ahead.
In a data-parallel method, the entire model is deployed to multiple nodes of a cluster and the data is sharded (horizontally split). Each instance of the model works on a part of the data.
In the Model parallel method, a layer (or group of layers) of the model is deployed on one node of a cluster, and the whole data is copied to the node, each node trains on the complete dataset.
The most common and easiest to implement is data parallelism, we will see a practical approach to it in the upcoming sections. One way of intuitively understanding how the data-parallel works is that the gradient is calculated for a small batch of data (say 30 images at once) in each GPU node and at the end of one round of forward-backward passes by the network, the updated weights are sent back to the initiating node. The weighted average of the weights from each node is applied to the model parameters. The updated model parameters are sent back to the nodes for the next round of iteration.
This is almost similar to what happens when you train in batches in a non-distributed fashion. The key question here although is how are model parameters stored and updated in a data-parallel approach. This brings us to the next topic, centralized and de-centralized training.
Both in model-parallel or data-parallel training, the key is communication between the nodes, it’s important to define how the parameters are initialized, how the weights/biases are updated.
There are two types of communication approaches. This applies to both the data-parallel and model parallel methods. In a centralized communication pattern, there exists a node or group of nodes responsible for synchronizing the model parameters, this node is called a parameter server. The advantage of the approach is it is easy to synchronize the model parameters, on the flip side the parameter server can itself become a bottleneck for a huge cluster. It is also a single point of failure. But of course, the bottleneck problem can be reduced to some extent by introducing multiple parallel servers and ensuring proper storage redundancy is applied.
In the de-centralized communication pattern, each node communicates with every other node to update the parameters. The advantage with this approach is that peer-peer updates are faster, sparse updates can be made by exchanging only what has changed and there is no single point of failure.
If you’re familiar with deep learning and know-how the weights are trained (if not you may read my articles here), the updated weights are computed as soon as the gradients of loss function are available. In a distributed training using the data-parallel approach, the model parameters which are weights and biases can be updated in 2 ways.
1. Synchronously: let’s say we are dealing with 10k images and 10 nodes, each node is given a subset of 1k images, once they finish the first iterations the updated model parameters are sent to the parameter server. This approach greatly enhances the accuracy of the model, but the downside of this approach of course is that the server must wait for all the nodes to complete the iteration, if there is a dead slow server it may bring down the speed of the whole training.
2. Asynchronous: In this case instead of waiting for all the nodes to send the weight updates, they are sent as soon as they are available, this increases the cluster utilization and improves the training speed but of course leads to stale gradients problem. Most of the frameworks which implement asynchronous updates apply some strategies to reduce the impact in favor of higher cluster utilization.
Remember synchronous or asynchronous updates apply to both centralized and de-centralized training methods. Similarly synchronous and asynchronous updates can be applied to both weights and the updates to the weights, i.e., from the equation Weight(new) = Weight(old) — LR * gradient loss, only the gradient losses with respect to the weights can be sent out after each iteration. To understand this better let us imagine we set up a cluster with synchronous updates and centralized training which means there is also a separate parameter service, each node sends the updates, and once all the updates are received on the parameter server, the new weights are computed, and then replicated across all the nodes for the next iteration.
Having discussed the pros and cons of how to store and update the model parameters, choosing the best one is always subjective to the problem, dataset, cluster size, and various factors. There is no one right solution for every problem.
Map/Reduce, Apache Spark, Baidu All Reduce, Horovod, Caffe2, Microsoft Cognitive Tool Kit (CNTK), DistBelief, Tensorflow, DIANNE, MXNet, Petumm are the top frameworks available for distributed machine learning. A brief introduction of each one of these is available here.
Among these, the following are supported on Azure today in the workspace (PaaS) model — Apache Spark, Horovod (its available both on Databricks and Azure ML), TensorFlow distributed training, and of course CNTK.
Distributed training can be done on Azure ML using frameworks like PyTorch, TensorFlow. Tensorflow’s distributed training support both centralized and decentralized training methods (more about it here), if you already have a notebook using distributed TF you can easily import it into Azure ML. For this post, we will learn about Horovod.
Horovod is an open-source distributed deep learning framework for TF, Keras, PyTorch, and Apache MXNet which makes distributed training easy by reducing the number of changes to be done to the training script to run on multiple GPU nodes in parallel. You can learn more about Horovod here.
You do not have to worry much amount setting up environments with Horovod, Azure ML provides curated training environments for setting up training using a variety of frameworks easily, one of them comes with TensorFlow and Horovod preloaded. These curated frameworks also allow customization if needed.
Note: You can also run native distributed TensorFlow on Azure ML using centralized or decentralized training methods explained above.
In this example, I was trying to perform an image classification with 2 classes using CNN. The images belong to chest X-rays, one class of images contains images with effusion detected and the other does not. For more information on the learning process, pre-processing, ablation experiments, etc. I recommend you to visit the code here.
The below image explains the journey from a notebook phase to running training experiments on a cluster in a distributed fashion.
Here is the code snippet where I run a single GPU training script on a Horovod enabled distributed training cluster with 4 nodes.
import osfrom azureml.core import ScriptRunConfigimport shutilfrom azureml.core import Experimentfrom azureml.core import Environmentfrom azureml.core.conda_dependencies import CondaDependenciesfrom azureml.widgets import RunDetailsfrom azureml.core.runconfig import MpiConfiguration## The training script capable of running in distributed environment is extracted to effusion_detector_distributed.pyproject_folder = './effusion_detector-distributed'os.makedirs(project_folder, exist_ok=True)shutil.copy('effusion_detector_distributed.py', project_folder)## choosing an experiment nameexperiment_name = 'tf-distributed-effusion-detector'experiment = Experiment(ws, name=experiment_name)# loading the env dependencies from conda configurationos.makedirs('./envs', exist_ok=True)tf_env = Environment.from_conda_specification(name="imageclassification", file_path="envs/distributed-tensorflow-with-horovod/conda_dependencies.yml")# Specify a GPU base imagetf_env.docker.enabled = Truetf_env.docker.base_image = 'mcr.microsoft.com/azureml/openmpi3.1.2-cuda10.1-cudnn7-ubuntu18.04'# using a cluster which can autoscale uptp 4 nodes.cluster_name = "gpus"compute_target = ComputeTarget(workspace=ws, name=cluster_name)# running the scriptargs = ['--data-folder', dataset.as_mount(), '--epochs', 20]src = ScriptRunConfig(source_directory=project_folder,script='effusion_detector_distributed.py',arguments=args,compute_target=compute_target,environment=tf_env, distributed_job_config=MpiConfiguration(node_count=4))run = experiment.submit(src)print(run)run.get_details()
Here is an image that shows the outcome of the training, the first experiment is done using distributed training (4 nodes of 6 GPU cores each) and the second one is done using a single machine with 6GPU core. Processing Unit used for a single machine and the cluster GPU — 1 x NVIDIA Tesla K80
Few noticeable differences I found in distributed training.
The training time is reduced from 7.5 min to 5 min.20 epochs were configured for the run, each node ran 5 epochs. (Note: This also means the early stopping could not be applied which had min tolerance set to 5 epochs, in the single machine training, the training finally stopped due to early stopping rule)
The training time is reduced from 7.5 min to 5 min.
20 epochs were configured for the run, each node ran 5 epochs. (Note: This also means the early stopping could not be applied which had min tolerance set to 5 epochs, in the single machine training, the training finally stopped due to early stopping rule)
3. Each worker process was given a private IP and the logs show that all of them were interconnected.
|
[
{
"code": null,
"e": 1156,
"s": 172,
"text": "Deep learning algorithms are well suited for large data sets and also training deep learning networks needs large computation power. With GPUs / TPUs easily available on pay per use basis or for free (like Google collab), it is possible today to train a large neural network on cloud-like say Resnet 152 (152 layers) on ImageNet database which has around 14 million images. But is a multi-core GPU-enabled machine just enough to train huge models. Technically yes, but it might take weeks to train the model. So how do we reduce the training time? Any scalability issue can be solved using 2 approaches — scale-up or scale-out. We all know if we choose to scale up the capacity maxes out at some point, so the better alternative is scale-out. But, how do you do distributed training, if I have a model training using Jupyter notebook where do I start, can I perform distributed training for any deep learning model? This blog aims to answer these questions with a practical approach."
},
{
"code": null,
"e": 1489,
"s": 1156,
"text": "In this blog we will learn how to apply scaled out or in other words, Distributed Machine Learning Techniques on the cloud. We will understand how we go from a Jupyter notebook phase which is the most agile way of building ML models to a production-ready training script that can run on a cluster of GPUs using Azure ML and Horovod."
},
{
"code": null,
"e": 1617,
"s": 1489,
"text": "If you’re new to distributed machine learning, here are some of the concepts/terminologies you should know before moving ahead."
},
{
"code": null,
"e": 1806,
"s": 1617,
"text": "In a data-parallel method, the entire model is deployed to multiple nodes of a cluster and the data is sharded (horizontally split). Each instance of the model works on a part of the data."
},
{
"code": null,
"e": 2000,
"s": 1806,
"text": "In the Model parallel method, a layer (or group of layers) of the model is deployed on one node of a cluster, and the whole data is copied to the node, each node trains on the complete dataset."
},
{
"code": null,
"e": 2599,
"s": 2000,
"text": "The most common and easiest to implement is data parallelism, we will see a practical approach to it in the upcoming sections. One way of intuitively understanding how the data-parallel works is that the gradient is calculated for a small batch of data (say 30 images at once) in each GPU node and at the end of one round of forward-backward passes by the network, the updated weights are sent back to the initiating node. The weighted average of the weights from each node is applied to the model parameters. The updated model parameters are sent back to the nodes for the next round of iteration."
},
{
"code": null,
"e": 2876,
"s": 2599,
"text": "This is almost similar to what happens when you train in batches in a non-distributed fashion. The key question here although is how are model parameters stored and updated in a data-parallel approach. This brings us to the next topic, centralized and de-centralized training."
},
{
"code": null,
"e": 3067,
"s": 2876,
"text": "Both in model-parallel or data-parallel training, the key is communication between the nodes, it’s important to define how the parameters are initialized, how the weights/biases are updated."
},
{
"code": null,
"e": 3721,
"s": 3067,
"text": "There are two types of communication approaches. This applies to both the data-parallel and model parallel methods. In a centralized communication pattern, there exists a node or group of nodes responsible for synchronizing the model parameters, this node is called a parameter server. The advantage of the approach is it is easy to synchronize the model parameters, on the flip side the parameter server can itself become a bottleneck for a huge cluster. It is also a single point of failure. But of course, the bottleneck problem can be reduced to some extent by introducing multiple parallel servers and ensuring proper storage redundancy is applied."
},
{
"code": null,
"e": 4012,
"s": 3721,
"text": "In the de-centralized communication pattern, each node communicates with every other node to update the parameters. The advantage with this approach is that peer-peer updates are faster, sparse updates can be made by exchanging only what has changed and there is no single point of failure."
},
{
"code": null,
"e": 4353,
"s": 4012,
"text": "If you’re familiar with deep learning and know-how the weights are trained (if not you may read my articles here), the updated weights are computed as soon as the gradients of loss function are available. In a distributed training using the data-parallel approach, the model parameters which are weights and biases can be updated in 2 ways."
},
{
"code": null,
"e": 4827,
"s": 4353,
"text": "1. Synchronously: let’s say we are dealing with 10k images and 10 nodes, each node is given a subset of 1k images, once they finish the first iterations the updated model parameters are sent to the parameter server. This approach greatly enhances the accuracy of the model, but the downside of this approach of course is that the server must wait for all the nodes to complete the iteration, if there is a dead slow server it may bring down the speed of the whole training."
},
{
"code": null,
"e": 5229,
"s": 4827,
"text": "2. Asynchronous: In this case instead of waiting for all the nodes to send the weight updates, they are sent as soon as they are available, this increases the cluster utilization and improves the training speed but of course leads to stale gradients problem. Most of the frameworks which implement asynchronous updates apply some strategies to reduce the impact in favor of higher cluster utilization."
},
{
"code": null,
"e": 5964,
"s": 5229,
"text": "Remember synchronous or asynchronous updates apply to both centralized and de-centralized training methods. Similarly synchronous and asynchronous updates can be applied to both weights and the updates to the weights, i.e., from the equation Weight(new) = Weight(old) — LR * gradient loss, only the gradient losses with respect to the weights can be sent out after each iteration. To understand this better let us imagine we set up a cluster with synchronous updates and centralized training which means there is also a separate parameter service, each node sends the updates, and once all the updates are received on the parameter server, the new weights are computed, and then replicated across all the nodes for the next iteration."
},
{
"code": null,
"e": 6201,
"s": 5964,
"text": "Having discussed the pros and cons of how to store and update the model parameters, choosing the best one is always subjective to the problem, dataset, cluster size, and various factors. There is no one right solution for every problem."
},
{
"code": null,
"e": 6473,
"s": 6201,
"text": "Map/Reduce, Apache Spark, Baidu All Reduce, Horovod, Caffe2, Microsoft Cognitive Tool Kit (CNTK), DistBelief, Tensorflow, DIANNE, MXNet, Petumm are the top frameworks available for distributed machine learning. A brief introduction of each one of these is available here."
},
{
"code": null,
"e": 6685,
"s": 6473,
"text": "Among these, the following are supported on Azure today in the workspace (PaaS) model — Apache Spark, Horovod (its available both on Databricks and Azure ML), TensorFlow distributed training, and of course CNTK."
},
{
"code": null,
"e": 7025,
"s": 6685,
"text": "Distributed training can be done on Azure ML using frameworks like PyTorch, TensorFlow. Tensorflow’s distributed training support both centralized and decentralized training methods (more about it here), if you already have a notebook using distributed TF you can easily import it into Azure ML. For this post, we will learn about Horovod."
},
{
"code": null,
"e": 7315,
"s": 7025,
"text": "Horovod is an open-source distributed deep learning framework for TF, Keras, PyTorch, and Apache MXNet which makes distributed training easy by reducing the number of changes to be done to the training script to run on multiple GPU nodes in parallel. You can learn more about Horovod here."
},
{
"code": null,
"e": 7618,
"s": 7315,
"text": "You do not have to worry much amount setting up environments with Horovod, Azure ML provides curated training environments for setting up training using a variety of frameworks easily, one of them comes with TensorFlow and Horovod preloaded. These curated frameworks also allow customization if needed."
},
{
"code": null,
"e": 7752,
"s": 7618,
"text": "Note: You can also run native distributed TensorFlow on Azure ML using centralized or decentralized training methods explained above."
},
{
"code": null,
"e": 8090,
"s": 7752,
"text": "In this example, I was trying to perform an image classification with 2 classes using CNN. The images belong to chest X-rays, one class of images contains images with effusion detected and the other does not. For more information on the learning process, pre-processing, ablation experiments, etc. I recommend you to visit the code here."
},
{
"code": null,
"e": 8220,
"s": 8090,
"text": "The below image explains the journey from a notebook phase to running training experiments on a cluster in a distributed fashion."
},
{
"code": null,
"e": 8350,
"s": 8220,
"text": "Here is the code snippet where I run a single GPU training script on a Horovod enabled distributed training cluster with 4 nodes."
},
{
"code": null,
"e": 9912,
"s": 8350,
"text": "import osfrom azureml.core import ScriptRunConfigimport shutilfrom azureml.core import Experimentfrom azureml.core import Environmentfrom azureml.core.conda_dependencies import CondaDependenciesfrom azureml.widgets import RunDetailsfrom azureml.core.runconfig import MpiConfiguration## The training script capable of running in distributed environment is extracted to effusion_detector_distributed.pyproject_folder = './effusion_detector-distributed'os.makedirs(project_folder, exist_ok=True)shutil.copy('effusion_detector_distributed.py', project_folder)## choosing an experiment nameexperiment_name = 'tf-distributed-effusion-detector'experiment = Experiment(ws, name=experiment_name)# loading the env dependencies from conda configurationos.makedirs('./envs', exist_ok=True)tf_env = Environment.from_conda_specification(name=\"imageclassification\", file_path=\"envs/distributed-tensorflow-with-horovod/conda_dependencies.yml\")# Specify a GPU base imagetf_env.docker.enabled = Truetf_env.docker.base_image = 'mcr.microsoft.com/azureml/openmpi3.1.2-cuda10.1-cudnn7-ubuntu18.04'# using a cluster which can autoscale uptp 4 nodes.cluster_name = \"gpus\"compute_target = ComputeTarget(workspace=ws, name=cluster_name)# running the scriptargs = ['--data-folder', dataset.as_mount(), '--epochs', 20]src = ScriptRunConfig(source_directory=project_folder,script='effusion_detector_distributed.py',arguments=args,compute_target=compute_target,environment=tf_env, distributed_job_config=MpiConfiguration(node_count=4))run = experiment.submit(src)print(run)run.get_details()"
},
{
"code": null,
"e": 10206,
"s": 9912,
"text": "Here is an image that shows the outcome of the training, the first experiment is done using distributed training (4 nodes of 6 GPU cores each) and the second one is done using a single machine with 6GPU core. Processing Unit used for a single machine and the cluster GPU — 1 x NVIDIA Tesla K80"
},
{
"code": null,
"e": 10266,
"s": 10206,
"text": "Few noticeable differences I found in distributed training."
},
{
"code": null,
"e": 10573,
"s": 10266,
"text": "The training time is reduced from 7.5 min to 5 min.20 epochs were configured for the run, each node ran 5 epochs. (Note: This also means the early stopping could not be applied which had min tolerance set to 5 epochs, in the single machine training, the training finally stopped due to early stopping rule)"
},
{
"code": null,
"e": 10625,
"s": 10573,
"text": "The training time is reduced from 7.5 min to 5 min."
},
{
"code": null,
"e": 10881,
"s": 10625,
"text": "20 epochs were configured for the run, each node ran 5 epochs. (Note: This also means the early stopping could not be applied which had min tolerance set to 5 epochs, in the single machine training, the training finally stopped due to early stopping rule)"
}
] |
How to change the color of the placeholder attribute with CSS?
|
To change the color of the placeholder attribute with CSS, the code is as follows −
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
padding: 20px;
}
input {
font-size: 40px;
font-weight: bold;
}
::placeholder {
color: rgb(70, 53, 167);
}
:-ms-input-placeholder {
color: rgb(66, 51, 155);
}
::-ms-input-placeholder {
color: rgb(122, 69, 182);
}
</style>
</head>
<body>
<h1>Placeholder color change example</h1>
<input type="text" placeholder="Some placeholder text" />
</body>
</html>
The above code will produce the following output −
|
[
{
"code": null,
"e": 1146,
"s": 1062,
"text": "To change the color of the placeholder attribute with CSS, the code is as follows −"
},
{
"code": null,
"e": 1157,
"s": 1146,
"text": " Live Demo"
},
{
"code": null,
"e": 1759,
"s": 1157,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n padding: 20px;\n }\n input {\n font-size: 40px;\n font-weight: bold;\n }\n ::placeholder {\n color: rgb(70, 53, 167);\n }\n :-ms-input-placeholder {\n color: rgb(66, 51, 155);\n }\n ::-ms-input-placeholder {\n color: rgb(122, 69, 182);\n }\n</style>\n</head>\n<body>\n<h1>Placeholder color change example</h1>\n<input type=\"text\" placeholder=\"Some placeholder text\" />\n</body>\n</html>"
},
{
"code": null,
"e": 1810,
"s": 1759,
"text": "The above code will produce the following output −"
}
] |
jQuery | prepend() with Examples - GeeksforGeeks
|
30 Aug, 2021
The prepend() method is an inbuilt method in jQuery which is used to insert a specified content at the beginning of the selected element.
Syntax:
$(selector).prepend(content, function)
Parameters: This method accept two parameters as mentioned above and described below:
content: It is required parameter which is used to specify the content need to be inserted.
function: It is optional parameter which is used to specify the function to perform after call.
Return Value: This method returns the selected element with the specified changes made by prepend() method.Below examples illustrate the prepend() method in jQuery:Example 1: This example does not contains optional parameter.
html
<!DOCTYPE html><html> <head> <title>The prepend Method</title> <script src=" https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function(){ $("button").click(function(){ $("p").prepend("Welcome to "); }); }); </script> <style> div { width: 350px; height: 100px; font-weight: bold; padding:20px; font-size: 25px; border: 2px solid green; } </style> </head> <body> <div> <p>GeeksforGeeks!</p> <!-- Click on this button to see the change --> <button>Click Here!</button> </div> </body></html>
Output: Before click on the button:
After click on the button:
Example 2: This example contains optional parameter.
html
<!DOCTYPE html><html> <head> <title>The prepend Method</title> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $("button").click(function() { $("p").prepend(function() { return "<b>Hello "; }); }); }); </script> <style> div { width: 350px; height: 100px; font-weight: bold; padding:20px; font-size: 25px; border: 2px solid green; } </style> </head> <body> <div> <p>Contributor!</p> <!-- Click on this button to see the change --> <button>Click Here!</button> </div> </body></html>
Output: Before click on the button:
After click on the button:
anikakapoor
jQuery-HTML/CSS
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to change the background color after clicking the button in JavaScript ?
How to Dynamically Add/Remove Table Rows using jQuery ?
|
[
{
"code": null,
"e": 25009,
"s": 24981,
"text": "\n30 Aug, 2021"
},
{
"code": null,
"e": 25148,
"s": 25009,
"text": "The prepend() method is an inbuilt method in jQuery which is used to insert a specified content at the beginning of the selected element. "
},
{
"code": null,
"e": 25158,
"s": 25148,
"text": "Syntax: "
},
{
"code": null,
"e": 25197,
"s": 25158,
"text": "$(selector).prepend(content, function)"
},
{
"code": null,
"e": 25285,
"s": 25197,
"text": "Parameters: This method accept two parameters as mentioned above and described below: "
},
{
"code": null,
"e": 25377,
"s": 25285,
"text": "content: It is required parameter which is used to specify the content need to be inserted."
},
{
"code": null,
"e": 25473,
"s": 25377,
"text": "function: It is optional parameter which is used to specify the function to perform after call."
},
{
"code": null,
"e": 25701,
"s": 25473,
"text": "Return Value: This method returns the selected element with the specified changes made by prepend() method.Below examples illustrate the prepend() method in jQuery:Example 1: This example does not contains optional parameter. "
},
{
"code": null,
"e": 25706,
"s": 25701,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>The prepend Method</title> <script src=\" https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function(){ $(\"button\").click(function(){ $(\"p\").prepend(\"Welcome to \"); }); }); </script> <style> div { width: 350px; height: 100px; font-weight: bold; padding:20px; font-size: 25px; border: 2px solid green; } </style> </head> <body> <div> <p>GeeksforGeeks!</p> <!-- Click on this button to see the change --> <button>Click Here!</button> </div> </body></html>",
"e": 26555,
"s": 25706,
"text": null
},
{
"code": null,
"e": 26593,
"s": 26555,
"text": "Output: Before click on the button: "
},
{
"code": null,
"e": 26622,
"s": 26593,
"text": "After click on the button: "
},
{
"code": null,
"e": 26676,
"s": 26622,
"text": "Example 2: This example contains optional parameter. "
},
{
"code": null,
"e": 26681,
"s": 26676,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>The prepend Method</title> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $(\"button\").click(function() { $(\"p\").prepend(function() { return \"<b>Hello \"; }); }); }); </script> <style> div { width: 350px; height: 100px; font-weight: bold; padding:20px; font-size: 25px; border: 2px solid green; } </style> </head> <body> <div> <p>Contributor!</p> <!-- Click on this button to see the change --> <button>Click Here!</button> </div> </body></html>",
"e": 27697,
"s": 26681,
"text": null
},
{
"code": null,
"e": 27735,
"s": 27697,
"text": "Output: Before click on the button: "
},
{
"code": null,
"e": 27764,
"s": 27735,
"text": "After click on the button: "
},
{
"code": null,
"e": 27776,
"s": 27764,
"text": "anikakapoor"
},
{
"code": null,
"e": 27792,
"s": 27776,
"text": "jQuery-HTML/CSS"
},
{
"code": null,
"e": 27803,
"s": 27792,
"text": "JavaScript"
},
{
"code": null,
"e": 27810,
"s": 27803,
"text": "JQuery"
},
{
"code": null,
"e": 27908,
"s": 27810,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27917,
"s": 27908,
"text": "Comments"
},
{
"code": null,
"e": 27930,
"s": 27917,
"text": "Old Comments"
},
{
"code": null,
"e": 27975,
"s": 27930,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28036,
"s": 27975,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28108,
"s": 28036,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28160,
"s": 28108,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28206,
"s": 28160,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 28252,
"s": 28206,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 28315,
"s": 28252,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 28344,
"s": 28315,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28421,
"s": 28344,
"text": "How to change the background color after clicking the button in JavaScript ?"
}
] |
The Complete Hands-On Machine Learning Crash Course | by Marco Peixeiro | Towards Data Science
|
Linear regression — theoryLinear regression — practiceLogistic regression — theoryLinear discriminant analysis (LDA) — theoryQuadratic discriminant analysis (QDA)— theoryLogistic regression, LDA and QDA — practiceResampling — theoryRegularization — theoryResampling and regularization — practiceDecision trees — theoryDecision trees — practiceSupport vector machine (SVM)— theorySupport vector machine (SVM) — practiceUnsupervised learning — theoryUnsupervised learning — practiceTime series analysis — theoryTime series analysis — practiceSources
Linear regression — theory
Linear regression — practice
Logistic regression — theory
Linear discriminant analysis (LDA) — theory
Quadratic discriminant analysis (QDA)— theory
Logistic regression, LDA and QDA — practice
Resampling — theory
Regularization — theory
Resampling and regularization — practice
Decision trees — theory
Decision trees — practice
Support vector machine (SVM)— theory
Support vector machine (SVM) — practice
Unsupervised learning — theory
Unsupervised learning — practice
Time series analysis — theory
Time series analysis — practice
Sources
For hands-on video tutorials on machine learning, deep learning, and artificial intelligence, checkout my YouTube channel.
Linear regression is probably the simplest approach for statistical learning. It is a good starting point for more advanced approaches, and in fact, many fancy statistical learning techniques can be seen as an extension of linear regression. Therefore, understanding this simple model will build a good base before moving on to more complex approaches.
Linear regression is very good to answer the following questions:
Is there a relationship between 2 variables?
How strong is the relationship?
Which variable contributes the most?
How accurately can we estimate the effect of each variable?
How accurately can we predict the target?
Is the relationship linear? (duh)
Is there an interaction effect?
Let’s assume we only have one variable and one target. Then, linear regression is expressed as:
In the equation above, the betas are the coefficients. These coefficients are what we need in order to make predictions with our model.
So how do we find these parameters?
To find the parameters, we need to minimize the least squares or the sum of squared errors. Of course, the linear model is not perfect and it will not predict all the data accurately, meaning that there is a difference between the actual value and the prediction. The error is easily calculated with:
But why are the errors squared?
We square the error, because the prediction can be either above or below the true value, resulting in a negative or positive difference respectively. If we did not square the errors, the sum of errors could decrease because of negative differences and not because the model is a good fit.
Also, squaring the errors penalizes large differences, and so the minimizing the squared errors “guarantees” a better model.
Let’s take a look at a graph to better understand.
In the graph above, the red dots are the true data and the blue line is linear model. The grey lines illustrate the errors between the predicted and the true values. The blue line is thus the one that minimizes the sum of the squared length of the grey lines.
After some math that is too heavy for this article, you can finally estimate the coefficients with the following equations:
Where x bar and y bar represent the mean.
Now that you have coefficients, how can you tell if they are relevant to predict your target?
The best way is to find the p-value. The p-value is used to quantify statistical significance; it allows to tell whether the null hypothesis is to be rejected or not.
The null hypothesis?
For any modelling task, the hypothesis is that there is some correlation between the features and the target. The null hypothesis is therefore the opposite: there is no correlation between the features and the target.
So, finding the p-value for each coefficient will tell if the variable is statistically significant to predict the target. As a general rule of thumb, if the p-value is less than 0.05: there is a strong relationship between the variable and the target.
You found out that your variable was statistically significant by finding its p-value. Great!
Now, how do you know if your linear model is any good?
To assess that, we usually use the RSE (residual standard error) and the R2 statistic.
The first error metric is simple to understand: the lower the residual errors, the better the model fits the data (in this case, the closer the data is to a linear relationship).
As for the R2 metric, it measures the proportion of variability in the target that can be explained using a feature X. Therefore, assuming a linear relationship, if feature X can explain (predict) the target, then the proportion is high and the R2 value will be close to 1. If the opposite is true, the R2 value is then closer to 0.
In real life situations, there will never be a single feature to predict a target. So, do we perform linear regression on one feature at a time? Of course not. We simply perform multiple linear regression.
The equation is very similar to simple linear regression; simply add the number of predictors and their corresponding coefficients:
Previously, in simple linear regression, we assess the relevancy of a feature by finding its p-value.
In the case of multiple linear regression, we use another metric: the F-statistic.
Here, the F-statistic is calculated for the overall model, whereas the p-value is specific to each predictor. If there is a strong relationship, then F will be much larger than 1. Otherwise, it will be approximately equal to 1.
How larger than 1 is large enough?
This is hard to answer. Usually, if there is a large number of data points, F could be slightly larger than 1 and suggest a strong relationship. For small data sets, then the F value must be way larger than 1 to suggest a strong relationship.
Why can’t we use the p-value in this case?
Since we are fitting many predictors, we need to consider a case where there are a lot of features (p is large). With a very large amount of predictors, there will always be about 5% of them that will have, by chance, a very small p-value even though they are not statistically significant. Therefore, we use the F-statistic to avoid considering unimportant predictors as significant predictors.
Just like in simple linear regression, the R2 can be used for multiple linear regression. However, know that adding more predictors will always increase the R2 value, because the model will necessarily better fit the training data.
Yet, this does not mean it will perform well on test data (making predictions for unknown data points).
Having multiple predictors in a linear model means that some predictors may have an influence on other predictors.
For example, you want to predict the salary of a person, knowing her age and number of years spent in school. Of course, the older the person, the more time that person could have spent in school. So how do we model this interaction effect?
Consider this very simple example with 2 predictors:
As you can see, we simply multiply both predictors together and associate a new coefficient. Simplifying the formula, we see now that the coefficient is influenced by the value of another feature.
As a general rule, if we include the interaction model, we should include the individual effect of a feature, even if its p-value is not significant. This is known as the hierarchical principle. The rationale behind this is that if two predictors are interacting, then including their individual contribution will have a small impact on the model.
Alright! Now that we know how it works, let’s make it work! We will work through both a simple and multiple linear regression in Python and I will show how to assess the quality of the parameters and the overall model in both situations.
You can grab the code and the data here.
I strongly recommend that you follow and recreate the steps in your own Jupyter notebook to take full advantage of this tutorial.
The data set contains information about money spent on advertisement and their generated sales. Money was spent on TV, radio and newspaper ads.
The objective is to use linear regression to understand how advertisement spending impacts sales.
The advantage of working with Python is that we have access to many libraries that allow us to rapidly read data, plot the data, and perform a linear regression.
I like to import all the necessary libraries on top of the notebook to keep everything organized. Import the following:
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import r2_scoreimport statsmodels.api as sm
Assuming that you downloaded the data set, place it in a data directory within your project folder. Then, read the data like so:
data = pd.read_csv("data/Advertising.csv")
To see what the data looks like, we do the following:
data.head()
And you should see this:
As you can see, the column Unnamed: 0 is redundant. Hence, we remove it.
data.drop(['Unnamed: 0'], axis=1)
Alright, our data is clean and ready for linear regression!
For simple linear regression, let’s consider only the effect of TV ads on sales. Before jumping right into the modelling, let’s take a look at what the data looks like.
We use matplotlib , a popular Python plotting library to make a scatter plot.
plt.figure(figsize=(16, 8))plt.scatter( data['TV'], data['sales'], c='black')plt.xlabel("Money spent on TV ads ($)")plt.ylabel("Sales ($)")plt.show()
Run this cell of code and you should see this graph:
As you can see, there is a clear relationship between the amount spent on TV ads and sales.
Let’s see how we can generate a linear approximation of this data.
X = data['TV'].values.reshape(-1,1)y = data['sales'].values.reshape(-1,1)reg = LinearRegression()reg.fit(X, y)print("The linear model is: Y = {:.5} + {:.5}X".format(reg.intercept_[0], reg.coef_[0][0]))
That’s it?
Yes! It is that simple to fit a straight line to the data set and see the parameters of the equation. In this case, we have
Let’s visualize how the line fits the data.
predictions = reg.predict(X)plt.figure(figsize=(16, 8))plt.scatter( data['TV'], data['sales'], c='black')plt.plot( data['TV'], predictions, c='blue', linewidth=2)plt.xlabel("Money spent on TV ads ($)")plt.ylabel("Sales ($)")plt.show()
And now, you see:
From the graph above, it seems that a simple linear regression can explain the general impact of amount spent on TV ads and sales.
Now, if you remember from this post, to see if the model is any good, we need to look at the R2 value and the p-value from each coefficient.
Here’s how we do it:
X = data['TV']y = data['sales']X2 = sm.add_constant(X)est = sm.OLS(y, X2)est2 = est.fit()print(est2.summary())
Which gives you this lovely output:
Looking at both coefficients, we have a p-value that is very low (although it is probably not exactly 0). This means that there is a strong correlation between these coefficients and the target (Sales).
Then, looking at the R2 value, we have 0.612. Therefore, about 60% of the variability of sales is explained by the amount spent on TV ads. This is okay, but definitely not the best we can to accurately predict the sales. Surely, spending on newspaper and radio ads must have a certain impact on sales.
Let’s see if a multiple linear regression will perform better.
Just like for simple linear regression, we will define our features and target variable and use scikit-learn library to perform linear regression.
Xs = data.drop(['sales', 'Unnamed: 0'], axis=1)y = data['sales'].reshape(-1,1)reg = LinearRegression()reg.fit(Xs, y)print("The linear model is: Y = {:.5} + {:.5}*TV + {:.5}*radio + {:.5}*newspaper".format(reg.intercept_[0], reg.coef_[0][0], reg.coef_[0][1], reg.coef_[0][2]))
Nothing more! From this code cell, we get the following equation:
Of course, we cannot visualize the impact of all three mediums on sales, since it has a total of four dimensions.
Notice that the coefficient for newspaper is negative, but also fairly small. Is it relevant to our model? Let’s see by calculating the F-statistic, R2 value and p-value for each coefficient.
As you must expect, the procedure here is very similar to what we did in simple linear regression.
X = np.column_stack((data['TV'], data['radio'], data['newspaper']))y = data['sales']X2 = sm.add_constant(X)est = sm.OLS(y, X2)est2 = est.fit()print(est2.summary())
And you get the following:
As you can see, the R2 is much higher than that of simple linear regression, with a value of 0.897!
Also, the F-statistic is 570.3. This is much greater than 1, and since our data set if fairly small (only 200 data points), it demonstrates that there is a strong relationship between ad spending and sales.
Finally, because we only have three predictors, we can consider their p-value to determine if they are relevant to the model or not. Of course, you notice that the third coefficient (the one for newspaper) has a large p-value. Therefore, ad spending on newspaper is not statistically significant. Removing that predictor would slightly reduce the R2 value, but we might make better predictions.
Previously, we saw that linear regression assumes the response variable is quantitative. However, in many situations, the response is actually qualitative, like the color of the eyes. This type of response is known as categorical.
Classification is the process of predicting a qualitative response. Methods used for classification often predict the probability of each of the categories of a qualitative variable as the basis for making the classification. In a certain way, they behave like regression methods.
With classification, we can answer questions like:
A person has a set of symptoms that could be attributed to one of three medical conditions. Which one?
Is a transaction fraudulent or not?
Categorical responses are often expressed as words. Of course, we cannot use words as input data for traditional statistical methods. We will see how to deal with that when we get to implement the algorithms.
For now, let’s see how logistic regression works.
When it comes to classification, we are determining the probability of an observation to be part of a certain class or not. Therefore, we wish to express the probability with a value between 0 and 1.
A probability close to 1 means the observation is very likely to be part of that category.
In order to generate values between 0 and 1, we express the probability using this equation:
The equation above is defined as the sigmoid function.
Plot this equation and you will see that this equation always results in a S-shaped curve bound between 0 and 1.
After some manipulation to equation above, you find that:
Take the log on both sides:
The equation above is known as the logit. As you can see, it is linear in X. Here, if the coefficients are positive, then an increase in X will result in a higher probability.
As in linear regression, we need a way to estimate the coefficients. For that, we maximize the likelihood function:
The intuition here is that we want coefficients such that the predicted probability (denoted with an apostrophe in the equation above) is as close as possible to the observed state.
Similarly to linear regression, we use the p-value to determine if the null hypothesis is rejected or not.
The Z-statistic is also widely used. A large absolute Z-statistic means that the null hypothesis is rejected.
Remember that the null hypothesis states: there is not correlation between the features and the target.
Of course, logistic regression can easily be extended to accommodate more than one predictor:
Note that using multiple logistic regression might give better results, because it can take into account correlations among predictors, a phenomenon known as confounding. Also, rarely will only one predictor be sufficient to make an accurate model for prediction.
Now, we understand how logistic regression works, but like any model, it presents some flaws:
When classes are well separated, parameters estimate from logistic regression tend to be unstable
When the data set is small, logistic regression is also unstable
Not the best to predict more than two classes
That’s where linear discriminant analysis (LDA) comes in handy. It is more stable than logistic regression and widely used to predict more than two classes.
The particularity of LDA is that it models the distribution of predictors separately in each of the response classes, and then it uses Bayes’ theorem to estimate the probability.
Alright, that’s a bit hard to understand. Let’s break it down.
(Sorry, Medium doesn’t support math equations. I tried my best to be as explicit as possible).
Suppose we want to classify an observation into one of K classes, where K is greater than or equal to 2. Then, let pi-k be the overall probability that an observation is associated to the kth class. Then, let f_k(X) denote the density function of X for an observation that comes from the kth class. This means that f_k(X) is large if the probability that an observation from the kth class has X = x. Then, Bayes’ theorem states:
The equation above can simply be abbreviated to:
Hopefully, this makes some sense!
The challenge here is to estimate the density function. Theoretically, Bayes’ classification has the lowest error rate. Therefore, our classifier needs to estimate the density function such as to approach the Bayes’ classifier.
Suppose we only have one predictor and that the density function normal. Then, you can express the density function as:
Now, we want to assign an observation X = x for which the P_k(X) is the largest. If you plug in the density function in P_k(X) and take the log, you find that you wish to maximize:
The equation above is called the discriminant. As you can see, it is a linear equation. Hence the name: linear discriminant analysis!
Now, assuming only two classes with equal distributions, you find:
This is the boundary equation. A graphical representation is shown hereunder.
Of course, this represents an ideal solution. In reality, we cannot exactly calculate the boundary line.
Therefore, LDA makes use of the following approximation:
For the average of all training observations
For the weighted average of sample variances for each class
Where n is the number of observations.
It is important to know that LDA assumes a normal distribution for each class, a class-specific mean, and a common variance.
Extending now for multiple predictors, we must assume that X is drawn from a multivariate Gaussian distribution, with a class-specific mean vector, and a common covariance matrix.
An example of a correlated and uncorrelated Gaussian distribution is shown below.
Now, expressing the discriminant equation using vector notation, we get:
As you can see, the equation remains the same. Only this time, we are using vector notation to accommodate many predictors.
With classification, it is sometimes irrelevant to use accuracy to assess the performance of a model.
Consider analyzing a highly imbalanced data set. For example, you are trying to determine if a transaction is fraudulent or not, but only 0.5% of your data set contains a fraudulent transaction. Then, you could predict that none of the transactions will be fraudulent, and have a 99.5% accuracy score! Of course, this is a very naive approach that does not help detect fraudulent transactions.
So what do we use?
Usually, we use sensitivity and specificity.
Sensitivity is the true positive rate: the proportions of actual positives correctly identified.
Specificity is the true negative rate: the proportion of actual negatives correctly identified.
Let’s give some context to better understand. Using the fraud detection problem, the sensitivity is the proportion of fraudulent transactions identified as fraudulent. The specificity is the proportion of non-fraudulent transactions identified as non-fraudulent.
Therefore, in an ideal situation, we want both a high sensitivity and specificity, although that might change depending on the context. For example, a bank might want to prioritize a higher sensitivity over specificity to make sure it identifies fraudulent transactions.
The ROC curve (receiver operating characteristic) is good to display the two types of error metrics described above. The overall performance of a classifier is given by the area under the ROC curve (AUC). Ideally, it should hug the upper left corner of the graph, and have an area close to 1.
Here, we keep the same assumptions as for LDA, but now, each observation from the kth class has its own covariance matrix.
For QDA, the discriminant is expressed as:
Without any surprises, you notice that the equation is now quadratic.
But, why choose QDA over LDA?
QDA is a better option for large data sets, as it tends to have a lower bias and a higher variance.
On the other hand, LDA is more suitable for smaller data sets, and it has a higher bias, and a lower variance.
Great! Now that we deeply understand how logistic regression, LDA, and QDA work, let’s apply each algorithm to solve a classification problem.
Mushrooms simply taste great! But with over 10 000 species of mushrooms only in North America, how can we tell which are edible?
This is the objective of this project. We will build a classifier that will determine if a certain mushroom is edible or poisonous.
I suggest you grab the data set and follow along. If you ever get stuck, feel free to consult the full notebook.
Let’s get to it!
The data set we will be using contains 8124 instances of mushrooms with 22 features. Among them, we find the mushroom’s cap shape, cap color, gill color, veil type, etc. Of course, it also tells us if the mushroom is edible or poisonous.
Let’s import some of the libraries that will help us import the data and manipulate it. In your notebook, run the following code:
A common first step for a data science project is to perform an exploratory data analysis (EDA). This step usually involves learning more about the data you are working with. You might want to know the shape of your data set (how many rows and columns), the number of empty values and visualize parts of the data to better understand the correlation between the features and the target.
Import the data and see the first five columns with the following code:
It’s always good to have the data set in a data folder within the project directory. Furthermore, we store the file path in a variable, such that if the path ever changes, we only have to change the variable assignment.
After running this code cell, you should see the first five rows. You notice that each feature is categorical, and a letter is used to define a certain value. Of course, the classifier cannot take letters as input, so we will have to change that eventually.
For now, let’s see if our data set is unbalanced. An unbalanced data set is when one class is much more present than the other. Ideally, in the context of classification, we want an equal number of instances of each class. Otherwise, we would need to implement advanced sampling methods, like minority oversampling.
In our case, we want to see if there is an equal number of poisonous and edible mushrooms in the data set. We can plot the frequency of each class like this:
And you get the following graph:
Awesome! It looks like a fairly balanced data set with an almost equal number of poisonous and edible mushrooms.
Now, I wanted to see how each feature affects the target. To do so, for each feature, I made a bar plot of all possible values separated by the class of mushroom. Doing it manually for all 22 features makes no sense, so we build this helper function:
The hue will give a color code to the poisonous and edible class. The data parameter will contain all features but the mushroom’s class. Running the cell code below:
You should get a list of 22 plots. Here’s an example of the output:
Take some time to look through all the plots.
Now, let’s see if we have any missing values. Run this piece of code:
And you should see each column with the number of missing values. Luckily, we have a data set with no missing values. This is very uncommon, but we won’t complain.
Now that we are familiar with the data, it is time to get it ready for modelling. As mentioned before, the features have letters to represent the different possible values, but we need to turn them into numbers.
To achieve that, we will use label encoding and one-hot encoding.
Let’s first use label encoding on the target column. Run the following code:
And you notice now that the column now contains 1 and 0.
Now, poisonous is represented by 1 and edible is represented by 0. Now, we can think of our classifier as “poisonous or not”. A poisonous mushroom gets a 1 (true), and an edible mushroom gets a 0 (false).
Hence, label encoding will turn a categorical feature into numerical. However, it is not recommended to use label encoding when there are more than two possible values.
Why?
Because it will then assign each value to either 0, 1 or 2. This is a problem, because the “2” could be considered as being more important and false correlations could be drawn from that.
To avoid this problem, we use one-hot encoding on the other features. To understand what it does, let’s consider the cap shape of the first entry point. You see it has a value of “x”, which stands for a convex cap shape. However, there is a total of six different cap shapes recorded in the data set. If we one-hot encode the feature, we should get:
As you can see, the cap shape is now a vector. A 1 denotes the actual cap shape value for an entry in the data set, and the rest is filled with 0. Again, you can think of 1 as true and 0 as false.
The drawback of one-hot encoding is that it introduces more columns to the data set. In the case of cap shape, we go from one column to six columns. For very large data sets, this might be a problem, but in our case, the additional columns should be manageable.
Let’s go ahead and one-hot encode the rest of the features:
And you should now see:
You notice that we went from 23 columns to 118. It is a five fold increase, but the number is not high enough to cause computer memory issues.
Now that our data set contains only numerical data, we are ready to start modelling and making predictions!
Before diving deep into modelling and making predictions, we need to split our data set into a training set and test set. That way, we can train an algorithm on the training set, and make predictions on the test set. The error metrics will be much more relevant this way, since the algorithm will make predictions on data it has not seen before.
We can easily split the data set like so:
Here, y is simply the target (poisonous or edible). Then, X is simply all features of the data set. Finally, we use the train_test_split function. The test_size parameter corresponds to the fraction of the data set that will be used for testing. Usually, we use 20%. Then, the random_state parameter is used for reproducibility. It can be set to any number, but it will ensure that every time the code runs, the data set will be split identically. If no random_state is provided, then the train and test set will differ, since the function splits it randomly.
All right, we are officially ready to start modelling and making predictions!
We will first use logistic regression. Throughout the following steps, we will use the area under the ROC curve and a confusion matrix as error metrics.
Let’s import all we need first:
Then, we make an instance of the LogisticRegression object and fit the model to the training set:
Then, we predict the probability that a mushroom is poisonous. Remember, we treat the mushrooms as being poisonous or non-poisonous.
Also, you must be reminded that logistic regression returns a probability. For now, let’s set the threshold to 0.5 That way, if the probability is greater than 0.5, a mushroom will be classified as poisonous. Of course, if the probability is less than the threshold, the mushroom is classified as edible.
This is exactly what is happening in the code cell below:
Notice that we calculated the probabilities on the test set.
Now, let’s see the confusion matrix. This will show us the true positive, true negative, false positive and false negative rates.
We output our confusion matrix like so:
And you should get:
Amazing! Our classifier is perfect! From the confusion matrix above, you see that our false positive and false negative rates are 0, meaning that all mushrooms were correctly classified as poisonous or edible!
Let’s print the area under the ROC curve. As you know, for a perfect classifier, it should be equal to 1.
Indeed, the code block above outputs 1! We can make our own function to visualize the ROC curve:
And you should see:
Congratulations! You built a perfect classifier with a basic logistic regression model.
Still, to gain more experience, let’s build a classifier using LDA and QDA, and see if we get similar results.
Following the same steps outlined for logistic regression:
If you run the code above, you should see that we get a perfect classifier again, with identical results to the classifier using logistic regression.
Now, we repeat the process, but using QDA:
And again, the results are the same!
Resampling and regularization are two important steps that can significantly improve both your model’s performance and your confidence in your model.
In this article, cross-validation will be extensively addressed as it is the most popular resampling method. Then, ridge regression and lasso will be introduced as regularization methods for linear models. Afterwards, resampling and regularization will be applied in a project setting.
I hope this article will serve as a reference for one of your future projects, and that it finds its way into your bookmarks.
Let’s get started!
Resampling methods are an indispensable tool in modern statistics. They involve repeatedly drawing samples from a training set and refitting a model of interest on each sample in order to obtain additional information about the fitted model. This allows us to gain more information that could not be available from fitting the model only once.
Usually, the objective of a data science project is to create a model using training data, and have it make predictions on new data. Hence, the resampling methods allow us to see how the model would perform on data it has not been trained on, without collecting new data.
Cross-validation (CV) is used to estimate the test error associated with a model to evaluate its performance or to select the appropriate level of flexibility. Evaluating a model’s performance is usually defined as model assessment, and model selection is used for selecting the level of flexibility. This terminology is widely used in the field of data science.
Now, there are different ways to perform cross-validation. Let’s explore each one of them.
This is the most basic approach. It simply involves randomly dividing the dataset into two parts: a training set and a validation set or hold-out set. The model is fit on the training set and the fitted model is used to make predictions on the validation set.
Above is a schematic of the validation set approach. You have n observations in a dataset, it was randomly split into two parts. The blue side represents the training set, and the orange side is the validation set. The numbers simply represent the rows.
Of course, with such a simple approach, there are some drawbacks.
First, the validation test error rate is highly variable depending on which observations are in the training and validation set.
Second, only a small subset of the observations are used to fit the model. However, we know that statistical methods tend to perform worse when trained on less data.
Above, on the left, you see the MSE when the validation set approach was applied only once. On the right, the process was repeated 10 times. As you can see, the MSE greatly varies.
This shows the significant variability of the MSE when the validation set approach is used.
Of course, there are methods that address these drawbacks.
The leave-one-out cross-validation (LOOCV) is a better option than the validation set approach. Instead of splitting the dataset into two subsets, only one observation is used for validation and the rest is used to fit the model.
Above is a schematic of LOOCV. As you can see, only one observation is used for validation and the rest is used for training. The process is then repeated multiple times.
After multiple runs, the error is estimated as:
Which is simply the mean of the errors of each run.
This method is much better, because it has far less bias, since more observations are used to fit the model. There is no randomness in the training/validation set splits. Therefore, we reduce the variability of the MSE, as shown below.
This approach involves randomly dividing the set of observations into k groups or folds of approximately equal size. The first fold is treated as a validation set and the model is fit on the remaining folds. The procedure is then repeated k times, where a different group is treated as the validation set.
Hence, you realize that LOOCV is a special case of k-fold cross validation where k is equal to total number of observations n. However, it is common to set k equal to 5 or 10.
Whereas LOOCV is computationally intensive for large datasets, k-fold is more general and it can be used with any model. In addition, it often gives more accurate estimates of test error than does LOOCV. Therefore, to assess and validate your model, the k-fold cross-validation approach is the best option.
Now that we know how cross-validation works and how it can improve our confidence in the model’s performance, let’s see how we can improve the model itself with regularization.
Regularization methods effectively prevent overfitting. Overfitting occurs when a model performs well on the training set, but then performs poorly on the validation set.
We have seen that linear models, such as linear regression and, by extension, logistic regression, use the least squares method to estimate the parameters.
Now, we explore how we can improve linear models by replacing least squares fitting with other fitting procedures. These methods will yield better prediction accuracy and model interpretability.
But why? Why use other fitting methods?
Least squares fitting works most of the time, but there are situations where it will fail.
For example, if your number of observations n is greater than the number of predictors p, then the least squares estimates will have a low variance and it performs well. On the other hand, with p is greater than n (more predictors than observations), then variance is infinite and the method cannot be used!
Also, multiple liner regression tends to add variables that are not actually associated with the response. This adds unnecessary complexity to the model. It would be good if there was a way to automatically perform feature selection, such as to include only the most relevant variables.
To achieve that, we introduce ridge regression and lasso. These are two common regularization methods, also called shrinkage methods.
Shrinking the estimated coefficients towards 0 can significantly improve the fit and reduce the variance of the coefficients. Here, we explore ridge regression and lasso.
Traditional linear fitting involves minimizing the RSS (residual sum of squares). In ridge regression, a new parameter is added, and now the parameters will minimize:
Where lambda is a tuning parameter. This parameter is found using cross-validation as it must minimize the test error. Therefore, a range of lambdas is used to fit the model and the lambda that minimizes the test error is the optimal value.
Here, ridge regression will include all p predictors in the model. Hence, it is a good method to improve the fit of the model, but it will not perform variable selection.
Similarly to ridge regression, lasso will minimizes:
Notice that we use the absolute value of the parameter beta instead of its squared value. Also, the same tuning parameter is present.
However, if lambda is large enough, some coefficients will effectively be 0! Therefore, lasso can also perform variable selection, making the model much easier to interpret.
We know how regularization and resampling works. Now, let’s apply these techniques in a project setting.
Fire up a Jupyter notebook and grab the dataset. If you ever get stuck, the solution notebook is also available.
Like with any project, we import our usual libraries that will help us perform basic data manipulation and plotting.
Now, we can start our exploratory data analysis.
We start off by importing our dataset and looking at the first five rows:
You should see:
Notice that the Unnamed: 0 column is useless. Let’s take it out.
And now, our dataset looks like this:
As you can see, we only have three advertising mediums, and sales is our target variable.
Let’s see how each variable impacts the sales by making a scatter plot. First, we build a helper function to make a scatter plot:
Now, we can generate three different plots for each feature.
And you get the following:
As you can see, TV and radio ads seem to be good predictors for sales, while there seems to be no correlations between sales and newspaper ads.
Luckily, our dataset does not require further processing, so we are ready to move on to modelling right away!
Let’s take a look at what the code looks like, before going through it.
First, we import the LinearRegression and cross_val_score objects. The first one will allow us to fit a linear model, while the second object will perform k-fold cross-validation.
Then, we define our features and target variable.
The cross_val_score will return an array of MSE for each cross-validation steps. In our case, we have five of them. Therefore, we take the mean of MSE and print it. You should get a negative MSE of -3.0729.
Now, let’s see if ridge regression or lasso will be better.
For ridge regression, we introduce GridSearchCV. This will allow us to automatically perform 5-fold cross-validation with a range of different regularization parameters in order to find the optimal value of alpha.
The code looks like this:
Then, we can find the best parameter and the best MSE with the following:
You should see that the optimal value of alpha is 20, with a negative MSE of -3.07267. This is a slight improvement upon the basic multiple linear regression.
For lasso, we follow a very similar process to ridge regression:
In this case, the optimal value for alpha is 1, and the negative MSE is -3.0414, which is the best score of all three models!
Tree-based methods can be used for regression or classification. They involve segmenting the prediction space into a number of simple regions. The set of splitting rules can be summarized in a tree, hence the name decision tree methods.
A single decision tree is often not as performant as linear regression, logistic regression, LDA, etc. However, by introducing bagging, random forests, and boosting, it can result in dramatic improvements in prediction accuracy at the expense of some loss in interpretation.
Before getting to the theory, we need some basic terminology.
Trees are drawn upside down. The final regions are termed leaves. The points inside the tree where a split occurs is an interval node. Finally, segments that connect nodes are branches.
To create a regression tree:
Divide the predictor space into J distinct and non-overlapping regionsFor every observation that falls in a region, predict the mean of the response value in that region
Divide the predictor space into J distinct and non-overlapping regions
For every observation that falls in a region, predict the mean of the response value in that region
Each region is split to minimize the RSS. To do so, it takes a top-down greedy approach also called recursive binary splitting.
Why top-down?
Because all observations are in a single region before the first split.
Why a greedy approach?
Because the best split occurs at a particular step, rather than looking ahead and making a split that will result in a better prediction in a future step.
Mathematically, we define the pair of half-planes as:
and we seek j and s to minimize:
However, this may lead to overfitting. Pruning the tree will result in a smaller subtree that we can validate with cross-validation.
A classification tree is very similar to a regression tree. However, we cannot use the mean value of the response, so we now predict the most commonly occurring class in a region. Of course, RSS cannot be used as a criterion. Instead, each split is done to minimize the classification error rate.
The classification error rate is simply the fraction of training observations in a region that do not belong to the most common class.
Unfortunately, this is not sensitive enough for tree-growing. In practice, two other methods are used.
There is the Gini index:
This is a measure of total variance across all classes. As you can see, the Gini index will be small if the proportion is close to 0 or 1, so it is a good measure of node purity.
A similar rationale is applied to the other method called cross-entropy:
Now that we have seen how a basic decision tree works, let’s see how we can improve its performance!
We know that bootstrap can compute the standard deviation of any quantity of interest. For decision trees, the variance is very high. Therefore, with bootstrap aggregation or bagging, we can reduce the variance and increase the performance of a decision tree.
Bagging involves repeatedly taking samples from a dataset. This generates B different bootstrap training sets. Then, we train on all bootstrapped training sets to get a prediction for each set, and we average the predictions.
Mathematically, the average prediction is:
Applying this to decision trees, it means that that we can construct a high number of trees which will have high variance and low bias. Then, we can average their predictions to reduce the variance to improve the performance of the decision trees.
Random forests provide an improvement over bagged trees by way of a small tweak that decorrelates the trees.
Like in bagging, multiple decision trees are built. However, at each split, a random sample of m predictors is chosen from all p predictors. The split is allowed to use only one of the m predictors, and typically:
In other words, at each split, the algorithm is not allowed to consider a majority of the available predictors!
Why?
Suppose that there is one very strong predictor in the dataset, along with other moderately strong predictors. Then, in the collection of bagged trees, they will all use this strong predictor in the top split. Consequently, all of the bagged trees will be very similar, and averaging their predictions will not reduce variance, since the predictions would be highly correlated.
Random forests overcome this problem by forcing each split to only consider a subset of predictors which effectively decorrelates the trees.
Of course, if m is equal to p, then it is just like bagging. Usually, the square root of p gives the best results as shown below.
Boosting works in a similar way to bagging, but the trees are grown sequentially: each tree uses information from the previously grown trees.
This means that the algorithm learns slowly. Each tree is fit to the residuals from the model rather than to the target variable. Hence, each tree is small and will slowly improve predictions in areas where it does not perform well.
There are three tuning parameters in boosting:
1. number of tree (B): unlike bagging and random forests, boosting can overfit if B is too large. Use cross-validation to choose the right amount of trees.
2. shrinkage parameter (alpha): a small positive number that controls the learning rate of boosting. It is typically set to 0.01 or 0.001.
3. number of splits in each tree (d): it controls the complexity of the boosted ensemble. Usually, a single split (d = 1) works well. It is also called the interaction depth.
As you can see above, an interaction depth of 1 seems to give the best results.
Now, let’s apply what we have learned to predict breast cancer. Many datasets about breast cancer contain information about the tumor. However, I was lucky to find a dataset that contains routine blood tests information of patients with and without breast cancer. Potentially, if we can accurately predict if a patient has cancer, that patient could receive very early treatments, even before a tumor is noticeable!
Of course, the dataset and full notebook are available here, and I strongly suggest that you code along.
Before starting our work on Jupyter, we can gain information about the dataset here.
First, you notice that the dataset is very small, with only 116 instances. This poses several challenges, because the decision trees might overfit the data, or our predictive model might not be the best, due to the lack of other observations. Yet, it is a good proof-of-concept that might demonstrate a real potential of predicting breast cancer from a simple blood test.
The dataset contains only the following ten attributes:
1. Age: age of the patient (years)
2. BMI: body mass index (kg/m2)
3. Glucose: glucose concentration in blood (mg/dL)
4. Insulin: insulin concentration in blood (microU/mL)
5. HOMA: Homeostatic Model Assessment of Insulin Resistance (glucose multiplied by insulin)
6. Leptin: concentration of leptin — the hormone of energy expenditure (ng/mL)
7. Adiponectin: concentration of adiponectin — a protein regulating glucose levels (micro g/mL)
8. Resistin: concentration of resistin — a protein secreted by adipose tissue (ng/mL)
9. MCP.1: concentration of MCP-1 — a protein that recruits monocytes to the sites of inflammation due to tissue injury or inflammation (pg/dL)
10. Classification: Healthy controls (1) or patient (2)
Now that we know what we will be working with, we can start by importing our usual libraries:
Then, define the path to the dataset and let’s preview it:
Great! Now, because this is a classification problem, let’s see if the classes are balanced:
The result should be:
As you can see, there is almost the same number of patients and healthy controls.
Now, it would be interesting to see the distribution and density of each feature for healthy people and patients. To do so, a violin plot is ideal. It shows both the density and distribution of a feature in a single plot. Let’s have nine violin plots: one for each feature:
Take time to review all the plots and try to find some differences between healthy controls and patients.
Finally, let’s check if we have missing values:
You should see that none of the columns have missing values! We are now ready to start modelling!
First, we need to encode the classes to 0 and 1:
Now, 0 represents a healthy control, and 1 represents a patient.
Then, we split the dataset into a training and test set:
Before writing our models, we need to define the appropriate error metric. In this case, since it is a classification problem, we could use a confusion matrix and use the classification error. Let’s write a helper function to plot the confusion matrix:
Awesome! Now, let’s implement a decision tree.
Using scikit-learn, a decision tree is implemented very easily:
You should get the following confusion matrix:
As you can see, it misclassified three instances. Therefore, let’s see if bagging, boosting or random forest can improve the performance of the tree.
To implement a decision tree with bagging, we write the following:
And you get the following confusion matrix:
Amazing! The model classified correctly all instances in the test set! For the sake of getting more practice, let’s also implement a random forest classifier and use boosting.
Here, for the random forest classifier, we specify the number of trees we want. Let’s go with 100:
And you get this confusion matrix:
Here, although only one instance was misclassified, the model in fact said that a patient was healthy, when in fact the person had cancer! This is a very undesirable situation.
Finally, for boosting:
And we get the following:
Again, only one instance was misclassified.
We have seen how to approach a classification problem with logistic regression, LDA, and decision trees. Now, yet another tool is introduced for classification: support vector machine.
The support vector machine is a generalization of a classifier called maximal margin classifier. The maximal margin classifier is simple, but it cannot be applied to the majority of datasets, since the classes must be separated by a linear boundary.
That is why the support vector classifier was introduced as an extension of the maximal margin classifier, which can be applied in a broader range of cases.
Finally, support vector machine is simply a further extension of the support vector classifier to accommodate non-linear class boundaries.
It can be used for both binary or multiclass classification.
Explaining the theory of SVMs can get very technical. Hopefully, this piece will make it easy to understand how SVMs work.
This method relies on separating classes using a hyperplane.
What is a hyperplane?
In a p-dimensional space, a hyperplane is a flat affine subspace of dimension p-1. Visually, in a 2D space, the hyperplane will be a line, and in a 3D space, it will be a flat plane.
Mathematically, the hyperplane is simply:
If X satisfies the equation above, then the point lies on the plane. Otherwise, it must be on one side of the plane as shown below.
In general, if the data can be perfectly separated using a hyperplane, then there is an infinite number of hyperplanes, since they can be shifted up or down, or slightly rotated without coming into contact with an observation.
That is why we use the maximal margin hyperplane or optimal separating hyperplane which is the separating hyperplane that is farthest from the observations. We calculate the perpendicular distance from each training observation given a hyperplane. This is known as the margin. Hence, the optimal separating hyperplane is the one with the largest margin.
As you can see above, there three points that are equidistant from the hyperplane. Those observations are known as support vectors, because if their position shifts, the hyperplane shifts as well. Interestingly, this means that the hyperplane depends only on the support vectors, and not on any other observations.
What if no separating plane exists?
In this case, there is no maximal margin classifier. We use a support vector classifier that can almost separate the classes using a soft margin called support vector classifier. However, further discussing this method gets very technical, and since it is not the most ideal approach, we will skip this subject for now.
The support vector machine is an extension of the support vector classifier that results from enlarging the feature space using kernels. The kernel approach is simply an efficient computational approach for accommodating a non-linear boundary between classes.
Without going into technical details, a kernel is a function that quantifies the similarity of two observations. The kernel can be of any degree. Using a kernel with degree greater than one leads to a more flexible decision boundary as shown below.
To better understand how the choice of kernel can impact the SVM algorithm, let’s implement it in four different scenarios.
This project is divided in four mini projects.
The first part will show how to perform classification with a linear kernel and how the regularization parameter C impacts the resulting hyperplane.
Then, the second part will show how to work with a Gaussian kernel to generate a non-linear hyperplane.
The third part simulates overlapping classes and we will use cross-validation to find the best parameters for the SVM.
Finally, we perform a very simple spam classifier using SVM.
The exercises above were taken from Andrew Ng’ course available for free on Coursera. I simply solve them with Python, which is not recommended by the instructor. Still, I highly recommend the course for any beginners.
As always, the notebook and data are available here.
Before we get started, let’s import some useful libraries:
Notice that we import loadmat here, because our data is in a matrix form.
Then, we store the paths to our datasets in different variables:
Finally, we will build a function to help us plot each dataset quickly:
Perfect!
Now, in this part, we will implement a support vector machine using a linear kernel, and we will see how the regularization parameter can impact the hyperplane.
First, let’s load and visualize the data:
And you should see:
Notice in the plot above the presence of an outlier on the left side. Let’s see how the regularization parameter will impact the hyperplane when in presence of an outlier.
The code block above simply fits a SVM to the data, and we use the predictions to plot the hyperplane. Notice that we use a regularization parameter of 1. The result should be the following:
As you can see, the hyperplane ignored the outlier. Therefore, a low regularization parameter will be generalize better. The test error will usually be higher than the cross-validation error.
Now, let’s increase the regularization parameter:
And you get:
Now, the outlier is on the right side of the hyperplane, but it also means that we are overfitting. Ultimately, this boundary would not perform well on unobserved data.
Now, we know that to accommodate non-linear boundaries, we need to change the kernel function. In this exercise, we will make use of a Gaussian kernel.
First, let’s plot our data:
And you should see:
Before implementing the SVM, you should know that the Gaussian kernel is expressed as:
Notice that there is a parameter sigma that determines how fast the similarity metric goes to zero as they are further apart.
Therefore, we implement it with the following code:
And you should get the following hyperplane:
Amazing! The hyperplane is not a perfect boundary, but it did a pretty good job at classifying most of the data. I suggest you try different values of sigma to see how it impacts the hyperplane.
Cross-validation is essential to choose the best tuning parameters for optimal performance from our model. Let’s see how can apply that to SVMs.
Of course, let’s see what the data looks like for this exercise:
And you get:
Notice that we have overlapping classes. Of course, our hyperplane will not be perfect, but we will use cross-validation to make sure it is the best we can get:
From the code cell above, you should get that the best regularization parameter is 1, and that sigma should be 0.1. Using these values, we can generate the hyperplane:
And get:
Finally, we train a spam classifier with a SVM. In this case, we will use a linear kernel. Also, we have separate datasets for training and testing, which will make our analysis a bit easier.
And you see that we get a training accuracy of 99.825%, and a test accuracy of 98.9%!
Unsupervised learning is a set of statistical tools for scenarios in which there is only a set of features and no targets. Therefore, we cannot make predictions, since there are no associated responses to each observation. Instead, we are interested in finding an interesting way to visualize data or in discovering subgroups of similar observations.
Unsupervised learning tends to be more challenging, because there is no clear objective for the analysis, and it is often subjective. Additionally, it is hard to assess if the obtained results are good, since there is no accepted mechanism for performing cross-validation or validating results on an independent dataset, because we do not know the true answer.
Two techniques will be the focus of this guide: principal component analysis and clustering.
PCA refers to the process by which principal components are computed and used to better understand the data. PCA can also be used for visualization.
What are principal components?
Suppose you want to visualize n observations with measurements on a set of p features as part of an exploratory data analysis. We could examine 2D scatter plots of 2 features at a time but would quickly get out of hand if there are a lot of predictors.
With PCA, we can find a low-dimensional representation of the dataset that contains as much as possible of the variation. Therefore, we only get the most interesting features, because they are responsible for the majority of the variance.
How are the principal components found?
The first principal component is the normalized linear combination of the features that have the largest variance:
The symbol phi is referred to as the loadings. The loadings must maximize:
And that’s all there is to it!
Clustering refers to a broad set of techniques for finding subgroups or clusters in a dataset. This helps us partition observations into distinct groups so that each group contains observations that are similar to each other. For example, in the scenario of breast cancer, the groups could represent the tumor grade. It is also very useful in marketing for market segmentation in order to identify a group of people that would be more receptive to a certain type of product.
There are many clustering methods, but we will focus on k-means clustering and hierarchical clustering. In k-means clustering, we wish to partition the data into a pre-specified number K of clusters. On the other hand, with hierarchical clustering, we do not know how many clusters we want. Instead, we want a dendrogram that allows us to view all the clusters obtained for each possible number of clusters.
This method simply separates the observations into K clusters. It assumes that:
1. Each observation belongs to at least one of the K clusters
2. The clusters do not overlap
Furthermore, variation within each cluster is minimized.
This is achieved by minimizing the sum of the squared Euclidean distance between each observation within a cluster:
To minimize, we follow this algorithm:
1. Randomly assign a number, from 1 to K, to each of the observations. These serves as initial cluster assignments for the observations.
2. Iterate until the cluster assignments stop changing:
2.a. For each of the K clusters, compute the cluster centroid. The kth cluster centroid is the vector of the p feature means for the observations in the kth cluster
2.b. Assign each observation to the cluster whose centroid is closest (shortest Euclidean distance)
Note that the algorithm above will find a local minimum. Therefore, the obtained results will depend on the initial random cluster assignment. Therefore, it is important to run the algorithm multiple times.
A potential disadvantage of k-means clustering is that it requires human input to specify the number of clusters. Hierarchical clustering, on the other hand, does not require an initial number of clusters.
The most common type of hierarchical clustering is bottom-up or agglomerative clustering. This refers to the fact that a dendrogram is generated starting from the leaves and combining clusters up to the trunk.
The algorithm is in fact very simple. It starts by defining a dissimilarity measure between each pair of observations, like the Euclidean distance. Then, it starts by assuming that each observation pertains to its own cluster. Then, the two most similar clusters are fused, so that there are n-1 clusters. Afterwards, other two similar clusters are fused, resulting in n-2 clusters. The process is repeated iteratively until all observations are part of a single cluster.
Although simple, something was not addressed. How to define a dissimilarity measure between clusters? This is achieved with the concept of linkage. The four most common types of linkage are summarized in the table below:
Complete, average and centroid are the most popular types of linkage, because single linkage tends to yield unbalanced dendrograms. Note that the resulting dendrogram strongly depends on the type of linkage used.
Also, choosing the appropriate dissimilarity measure is crucial. Euclidean distance was discussed extensively, but there is also correlation-based distance. This considers two features to be similar if they are highly correlated, meaning that they have similar profiles.
For example, consider an online retailer is interested in clustering shoppers based on their past shopping histories. The goal is to identify subgroups of similar shoppers, so they can be shown advertisements that are likely to interest them. Using Euclidean distance, then shoppers who have bought few items overall will be clustered together which might not be ideal. On the other hand, using correlation-based distance, shoppers with similar preferences (they bought items A and B, but not C and D) will be clustered together, even if they have bought of different volume of items.
In all cases, however, we still need human input to determine the final number of clusters to use once hierarchical clustering is complete.
Now that you understand how PCA and clustering methods work, let’s implement them in a small project setting.
This part will be divided into two mini projects. In the first one, we will use k-means clustering to perform color quantization on an image.
Then, in the second mini project, we will use PCA to reduce the dimensionality of a dataset, allowing to us to visualize it with a 2D plot.
Everything you need to code along is available here.
Spin up your Jupyter notebook, and let’s go!
Before starting on any implementation, we will import a few libraries that will become handy later on:
Unlike previous tutorials, we will not import datasets. Instead, we will use data provided by the scikit-learn library.
Quickly, color quantization is technique to reduce the number of distinct colors used in an image. This is especially useful to compress images while keeping the integrity of the image.
To get started, we import the following libraries:
Notice that we import a sample dataset called load_sample_image. This simply contains two images. We will use one of them to perform color quantization.
So, let’s show the image we will use for this exercise:
And you should see:
Now, for color quantization, different steps must be followed.
First, we need to change the image into a 2D matrix for manipulation:
Then, we train our model to aggregate colors in order to have 64 distinct colors in the image:
Then, we build a helper function to help us reconstruct the image with the number of specified colors:
Finally, we can now visualize how the image looks with only 64 colors, and how it compares to the original one:
Of course, we can see some differences, but overall, the integrity of the image is conserved! Do explore different number of clusters! For example, here is what you get if you specify 10 colors:
For this exercise, we will use PCA to reduce the dimensions of a dataset so we can easily visualize it.
Therefore, let’s import the iris dataset from scikit-learn:
Now, we will compute the first two principal components and see what proportion of the variance can be explained by each:
From the above code block, you should see that the first principal component contains 92% of the variance, while the second accounts for 5% of the variance. Therefore, this means that only two features are sufficient to explain 97% of the variance in the dataset!
Now, we can use this to easily plot the data in two dimensions:
And you get:
As you can see, PCA was useful to reduce the dimensionality of the dataset, allowing us to plot it, and visualize how each category is separated.
Whether we wish to predict the trend in financial markets or electricity consumption, time is an important factor that must now be considered in our models. For example, it would be interesting to forecast at what hour during the day is there going to be a peak consumption in electricity, such as to adjust the price or the production of electricity.
Enter time series. A time series is simply a series of data points ordered in time. In a time series, time is often the independent variable and the goal is usually to make a forecast for the future.
However, there are other aspects that come into play when dealing with time series.
Is it stationary?
Is there a seasonality?
Is the target variable autocorrelated?
Informally, autocorrelation is the similarity between observations as a function of the time lag between them.
Above is an example of an autocorrelation plot. Looking closely, you realize that the first value and the 24th value have a high autocorrelation. Similarly, the 12th and 36th observations are highly correlated. This means that we will find a very similar value at every 24 unit of time.
Notice how the plot looks like sinusoidal function. This is a hint for seasonality, and you can find its value by finding the period in the plot above, which would give 24h.
Seasonality refers to periodic fluctuations. For example, electricity consumption is high during the day and low during night, or online sales increase during Christmas before slowing down again.
As you can see above, there is a clear daily seasonality. Every day, you see a peak towards the evening, and the lowest points are the beginning and the end of each day.
Remember that seasonality can also be derived from an autocorrelation plot if it has a sinusoidal shape. Simply look at the period, and it gives the length of the season.
Stationarity is an important characteristic of time series. A time series is said to be stationary if its statistical properties do not change over time. In other words, it has constant mean and variance, and covariance is independent of time.
Looking again at the same plot, we see that the process above is stationary. The mean and variance do not vary over time.
Often, stock prices are not a stationary process, since we might see a growing trend, or its volatility might increase over time (meaning that variance is changing).
Ideally, we want to have a stationary time series for modelling. Of course, not all of them are stationary, but we can make different transformations to make them stationary.
You may have noticed in the title of the plot above Dickey-Fuller. This is the statistical test that we run to determine if a time series is stationary or not.
Without going into the technicalities of the Dickey-Fuller test, it test the null hypothesis that a unit root is present.
If it is, then p > 0, and the process is not stationary.
Otherwise, p = 0, the null hypothesis is rejected, and the process is considered to be stationary.
As an example, the process below is not stationary. Notice how the mean is not constant through time.
There are many ways to model a time series in order to make predictions. Here, I will present:
moving average
exponential smoothing
ARIMA
The moving average model is probably the most naive approach to time series modelling. This model simply states that the next observation is the mean of all past observations.
Although simple, this model might be surprisingly good and it represents a good starting point.
Otherwise, the moving average can be used to identify interesting trends in the data. We can define a window to apply the moving average model to smooth the time series, and highlight different trends.
In the plot above, we applied the moving average model to a 24h window. The green line smoothed the time series, and we can see that there are 2 peaks in a 24h period.
Of course, the longer the window, the smoother the trend will be. Below is an example of moving average on a smaller window.
Exponential smoothing uses a similar logic to moving average, but this time, a different decreasing weight is assigned to each observations. In other words, less importance is given to observations as we move further from the present.
Mathematically, exponential smoothing is expressed as:
Here, alpha is a smoothing factor that takes values between 0 and 1. It determines how fast the weight decreases for previous observations.
From the plot above, the dark blue line represents the exponential smoothing of the time series using a smoothing factor of 0.3, while the orange line uses a smoothing factor of 0.05.
As you can see, the smaller the smoothing factor, the smoother the time series will be. This makes sense, because as the smoothing factor approaches 0, we approach the moving average model.
Double exponential smoothing is used when there is a trend in the time series. In that case, we use this technique, which is simply a recursive use of exponential smoothing twice.
Mathematically:
Here, beta is the trend smoothing factor, and it takes values between 0 and 1.
Below, you can see how different values of alpha and beta affect the shape of the time series.
This method extends double exponential smoothing, by adding a seasonal smoothing factor. Of course, this is useful if you notice seasonality in your time series.
Mathematically, triple exponential smoothing is expressed as:
Where gamma is the seasonal smoothing factor and L is the length of the season.
SARIMA is actually the combination of simpler models to make a complex model that can model time series exhibiting non-stationary properties and seasonality.
At first, we have the autoregression model AR(p). This is basically a regression of the time series onto itself. Here, we assume that the current value depends on its previous values with some lag. It takes a parameter p which represents the maximum lag. To find it, we look at the partial autocorrelation plot and identify the lag after which most lags are not significant.
In the example below, p would be 4.
Then, we add the moving average model MA(q). This takes a parameter q which represents the biggest lag after which other lags are not significant on the autocorrelation plot.
Below, q would be 4.
After, we add the order of integration I(d). The parameter d represents the number of differences required to make the series stationary.
Finally, we add the final component: seasonality S(P, D, Q, s), where s is simply the season’s length. Furthermore, this component requires the parameters P and Q which are the same as p and q, but for the seasonal component. Finally, D is the order of seasonal integration representing the number of differences required to remove seasonality from the series.
Combining all, we get the SARIMA(p, d, q)(P, D, Q, s) model.
The main takeaway is: before modelling with SARIMA, we must apply transformations to our time series to remove seasonality and any non-stationary behaviors.
We will try to predict the stock price of a specific company. Now, predicting the stock price is virtually impossible. However, it remains a fun exercise and it will be a good way to practice what we have learned.
We will use the historical stock price of the New Germany Fund (GF) to try to predict the closing price in the next five trading days.
You can grab the dataset and notebook here.
As always, I highly recommend you code along! Start your notebook, and let’s go!
First, we import some libraries that will be helpful throughout our analysis. Also, we define the mean average percentage error (MAPE), as this will be our error metric.
First, we import some libraries that will be helpful throughout our analysis. Also, we define the mean average percentage error (MAPE), as this will be our error metric.
Then, we import our dataset and we previous the first ten entries, and you should get
As you can see, we have a few entries concerning a different stock than the New Germany Fund (GF). Also, we have an entry concerning intraday information, but we only want end of day (EOD) information.
First, we remove unwanted entries.
Then, we remove unwanted columns, as we solely want to focus on the stock’s closing price.
If you preview the dataset, you should see:
Awesome! We are ready for exploratory data analysis!
We plot the closing price over the entire time period of our dataset.
You should get:
Clearly, you see that this is not a stationary process, and it is hard to tell if there is some kind of seasonality.
Let’s use the moving average model to smooth our time series. For that, we will use a helper function that will run the moving average model on a specified time window and it will plot the result smoothed curve:
Using a time window of 5 days, we get:
As you can see, we can hardly see a trend, because it is too close to actual curve. Let’s see the result of smoothing by the previous month, and previous quarter.
Trends are easier to spot now. Notice how the 30-day and 90-day trend show a downward curve at the end. This might mean that the stock is likely to go down in the following days.
Now, let’s use exponential smoothing to see if it can pick up a better trend.
Here, we use 0.05 and 0.3 as values for the smoothing factor. Feel free to try other values and see what the result is.
As you can see, an alpha value of 0.05 smoothed the curve while picking up most of the upward and downward trends.
Now, let’s use double exponential smoothing.
And you get:
Again, experiment with different alpha and beta combinations to get better looking curves.
As outlined previously, we must turn our series into a stationary process in order to model it. Therefore, let’s apply the Dickey-Fuller test to see if it is a stationary process:
You should see:
By the Dickey-Fuller test, the time series is unsurprisingly non-stationary. Also, looking at the autocorrelation plot, we see that it is very high, and it seems that there is no clear seasonality.
Therefore, to get rid of the high autocorrelation and to make the process stationary, let’s take the first difference (line 23 in the code block). We simply subtract the time series from itself with a lag of one day, and we get:
Awesome! Our series is now stationary and we can start modelling!
Now, for SARIMA, we first define a few parameters and a range of values for other parameters to generate a list of all possible combinations of p, q, d, P, Q, D, s.
Now, in the code cell above, we have 625 different combinations! We will try each combination and train SARIMA with each so to find the best performing model. This might take while depending on your computer’s processing power.
Once this is done, we print out a summary of the best model, and you should see:
Awesome! We finally predict the closing price of the next five trading days and evaluate the MAPE of the model.
In this case, we have a MAPE of 0.79%, which is very good!
Now, to compare our prediction with actual data, we take financial data from Yahoo Finance and create a dataframe.
Then, we make a plot to see how far we were from the actual closing prices:
It seems that we are a bit off in our predictions. In fact, the predicted price is essentially flat, meaning that our model is probably not performing well.
Again, this is not due to our procedure, but to the fact that predicting stock prices is essentially impossible
An Introduction to Statistical Learning — Gareth James et al.Machine Learning — Andrew NgOpen Machine Learning Course: Time Series — Dmitriy Sergeev
An Introduction to Statistical Learning — Gareth James et al.
Machine Learning — Andrew Ng
Open Machine Learning Course: Time Series — Dmitriy Sergeev
|
[
{
"code": null,
"e": 719,
"s": 171,
"text": "Linear regression — theoryLinear regression — practiceLogistic regression — theoryLinear discriminant analysis (LDA) — theoryQuadratic discriminant analysis (QDA)— theoryLogistic regression, LDA and QDA — practiceResampling — theoryRegularization — theoryResampling and regularization — practiceDecision trees — theoryDecision trees — practiceSupport vector machine (SVM)— theorySupport vector machine (SVM) — practiceUnsupervised learning — theoryUnsupervised learning — practiceTime series analysis — theoryTime series analysis — practiceSources"
},
{
"code": null,
"e": 746,
"s": 719,
"text": "Linear regression — theory"
},
{
"code": null,
"e": 775,
"s": 746,
"text": "Linear regression — practice"
},
{
"code": null,
"e": 804,
"s": 775,
"text": "Logistic regression — theory"
},
{
"code": null,
"e": 848,
"s": 804,
"text": "Linear discriminant analysis (LDA) — theory"
},
{
"code": null,
"e": 894,
"s": 848,
"text": "Quadratic discriminant analysis (QDA)— theory"
},
{
"code": null,
"e": 938,
"s": 894,
"text": "Logistic regression, LDA and QDA — practice"
},
{
"code": null,
"e": 958,
"s": 938,
"text": "Resampling — theory"
},
{
"code": null,
"e": 982,
"s": 958,
"text": "Regularization — theory"
},
{
"code": null,
"e": 1023,
"s": 982,
"text": "Resampling and regularization — practice"
},
{
"code": null,
"e": 1047,
"s": 1023,
"text": "Decision trees — theory"
},
{
"code": null,
"e": 1073,
"s": 1047,
"text": "Decision trees — practice"
},
{
"code": null,
"e": 1110,
"s": 1073,
"text": "Support vector machine (SVM)— theory"
},
{
"code": null,
"e": 1150,
"s": 1110,
"text": "Support vector machine (SVM) — practice"
},
{
"code": null,
"e": 1181,
"s": 1150,
"text": "Unsupervised learning — theory"
},
{
"code": null,
"e": 1214,
"s": 1181,
"text": "Unsupervised learning — practice"
},
{
"code": null,
"e": 1244,
"s": 1214,
"text": "Time series analysis — theory"
},
{
"code": null,
"e": 1276,
"s": 1244,
"text": "Time series analysis — practice"
},
{
"code": null,
"e": 1284,
"s": 1276,
"text": "Sources"
},
{
"code": null,
"e": 1407,
"s": 1284,
"text": "For hands-on video tutorials on machine learning, deep learning, and artificial intelligence, checkout my YouTube channel."
},
{
"code": null,
"e": 1760,
"s": 1407,
"text": "Linear regression is probably the simplest approach for statistical learning. It is a good starting point for more advanced approaches, and in fact, many fancy statistical learning techniques can be seen as an extension of linear regression. Therefore, understanding this simple model will build a good base before moving on to more complex approaches."
},
{
"code": null,
"e": 1826,
"s": 1760,
"text": "Linear regression is very good to answer the following questions:"
},
{
"code": null,
"e": 1871,
"s": 1826,
"text": "Is there a relationship between 2 variables?"
},
{
"code": null,
"e": 1903,
"s": 1871,
"text": "How strong is the relationship?"
},
{
"code": null,
"e": 1940,
"s": 1903,
"text": "Which variable contributes the most?"
},
{
"code": null,
"e": 2000,
"s": 1940,
"text": "How accurately can we estimate the effect of each variable?"
},
{
"code": null,
"e": 2042,
"s": 2000,
"text": "How accurately can we predict the target?"
},
{
"code": null,
"e": 2076,
"s": 2042,
"text": "Is the relationship linear? (duh)"
},
{
"code": null,
"e": 2108,
"s": 2076,
"text": "Is there an interaction effect?"
},
{
"code": null,
"e": 2204,
"s": 2108,
"text": "Let’s assume we only have one variable and one target. Then, linear regression is expressed as:"
},
{
"code": null,
"e": 2340,
"s": 2204,
"text": "In the equation above, the betas are the coefficients. These coefficients are what we need in order to make predictions with our model."
},
{
"code": null,
"e": 2376,
"s": 2340,
"text": "So how do we find these parameters?"
},
{
"code": null,
"e": 2677,
"s": 2376,
"text": "To find the parameters, we need to minimize the least squares or the sum of squared errors. Of course, the linear model is not perfect and it will not predict all the data accurately, meaning that there is a difference between the actual value and the prediction. The error is easily calculated with:"
},
{
"code": null,
"e": 2709,
"s": 2677,
"text": "But why are the errors squared?"
},
{
"code": null,
"e": 2998,
"s": 2709,
"text": "We square the error, because the prediction can be either above or below the true value, resulting in a negative or positive difference respectively. If we did not square the errors, the sum of errors could decrease because of negative differences and not because the model is a good fit."
},
{
"code": null,
"e": 3123,
"s": 2998,
"text": "Also, squaring the errors penalizes large differences, and so the minimizing the squared errors “guarantees” a better model."
},
{
"code": null,
"e": 3174,
"s": 3123,
"text": "Let’s take a look at a graph to better understand."
},
{
"code": null,
"e": 3434,
"s": 3174,
"text": "In the graph above, the red dots are the true data and the blue line is linear model. The grey lines illustrate the errors between the predicted and the true values. The blue line is thus the one that minimizes the sum of the squared length of the grey lines."
},
{
"code": null,
"e": 3558,
"s": 3434,
"text": "After some math that is too heavy for this article, you can finally estimate the coefficients with the following equations:"
},
{
"code": null,
"e": 3600,
"s": 3558,
"text": "Where x bar and y bar represent the mean."
},
{
"code": null,
"e": 3694,
"s": 3600,
"text": "Now that you have coefficients, how can you tell if they are relevant to predict your target?"
},
{
"code": null,
"e": 3861,
"s": 3694,
"text": "The best way is to find the p-value. The p-value is used to quantify statistical significance; it allows to tell whether the null hypothesis is to be rejected or not."
},
{
"code": null,
"e": 3882,
"s": 3861,
"text": "The null hypothesis?"
},
{
"code": null,
"e": 4100,
"s": 3882,
"text": "For any modelling task, the hypothesis is that there is some correlation between the features and the target. The null hypothesis is therefore the opposite: there is no correlation between the features and the target."
},
{
"code": null,
"e": 4353,
"s": 4100,
"text": "So, finding the p-value for each coefficient will tell if the variable is statistically significant to predict the target. As a general rule of thumb, if the p-value is less than 0.05: there is a strong relationship between the variable and the target."
},
{
"code": null,
"e": 4447,
"s": 4353,
"text": "You found out that your variable was statistically significant by finding its p-value. Great!"
},
{
"code": null,
"e": 4502,
"s": 4447,
"text": "Now, how do you know if your linear model is any good?"
},
{
"code": null,
"e": 4589,
"s": 4502,
"text": "To assess that, we usually use the RSE (residual standard error) and the R2 statistic."
},
{
"code": null,
"e": 4768,
"s": 4589,
"text": "The first error metric is simple to understand: the lower the residual errors, the better the model fits the data (in this case, the closer the data is to a linear relationship)."
},
{
"code": null,
"e": 5101,
"s": 4768,
"text": "As for the R2 metric, it measures the proportion of variability in the target that can be explained using a feature X. Therefore, assuming a linear relationship, if feature X can explain (predict) the target, then the proportion is high and the R2 value will be close to 1. If the opposite is true, the R2 value is then closer to 0."
},
{
"code": null,
"e": 5307,
"s": 5101,
"text": "In real life situations, there will never be a single feature to predict a target. So, do we perform linear regression on one feature at a time? Of course not. We simply perform multiple linear regression."
},
{
"code": null,
"e": 5439,
"s": 5307,
"text": "The equation is very similar to simple linear regression; simply add the number of predictors and their corresponding coefficients:"
},
{
"code": null,
"e": 5541,
"s": 5439,
"text": "Previously, in simple linear regression, we assess the relevancy of a feature by finding its p-value."
},
{
"code": null,
"e": 5624,
"s": 5541,
"text": "In the case of multiple linear regression, we use another metric: the F-statistic."
},
{
"code": null,
"e": 5852,
"s": 5624,
"text": "Here, the F-statistic is calculated for the overall model, whereas the p-value is specific to each predictor. If there is a strong relationship, then F will be much larger than 1. Otherwise, it will be approximately equal to 1."
},
{
"code": null,
"e": 5887,
"s": 5852,
"text": "How larger than 1 is large enough?"
},
{
"code": null,
"e": 6130,
"s": 5887,
"text": "This is hard to answer. Usually, if there is a large number of data points, F could be slightly larger than 1 and suggest a strong relationship. For small data sets, then the F value must be way larger than 1 to suggest a strong relationship."
},
{
"code": null,
"e": 6173,
"s": 6130,
"text": "Why can’t we use the p-value in this case?"
},
{
"code": null,
"e": 6569,
"s": 6173,
"text": "Since we are fitting many predictors, we need to consider a case where there are a lot of features (p is large). With a very large amount of predictors, there will always be about 5% of them that will have, by chance, a very small p-value even though they are not statistically significant. Therefore, we use the F-statistic to avoid considering unimportant predictors as significant predictors."
},
{
"code": null,
"e": 6801,
"s": 6569,
"text": "Just like in simple linear regression, the R2 can be used for multiple linear regression. However, know that adding more predictors will always increase the R2 value, because the model will necessarily better fit the training data."
},
{
"code": null,
"e": 6905,
"s": 6801,
"text": "Yet, this does not mean it will perform well on test data (making predictions for unknown data points)."
},
{
"code": null,
"e": 7020,
"s": 6905,
"text": "Having multiple predictors in a linear model means that some predictors may have an influence on other predictors."
},
{
"code": null,
"e": 7261,
"s": 7020,
"text": "For example, you want to predict the salary of a person, knowing her age and number of years spent in school. Of course, the older the person, the more time that person could have spent in school. So how do we model this interaction effect?"
},
{
"code": null,
"e": 7314,
"s": 7261,
"text": "Consider this very simple example with 2 predictors:"
},
{
"code": null,
"e": 7511,
"s": 7314,
"text": "As you can see, we simply multiply both predictors together and associate a new coefficient. Simplifying the formula, we see now that the coefficient is influenced by the value of another feature."
},
{
"code": null,
"e": 7859,
"s": 7511,
"text": "As a general rule, if we include the interaction model, we should include the individual effect of a feature, even if its p-value is not significant. This is known as the hierarchical principle. The rationale behind this is that if two predictors are interacting, then including their individual contribution will have a small impact on the model."
},
{
"code": null,
"e": 8097,
"s": 7859,
"text": "Alright! Now that we know how it works, let’s make it work! We will work through both a simple and multiple linear regression in Python and I will show how to assess the quality of the parameters and the overall model in both situations."
},
{
"code": null,
"e": 8138,
"s": 8097,
"text": "You can grab the code and the data here."
},
{
"code": null,
"e": 8268,
"s": 8138,
"text": "I strongly recommend that you follow and recreate the steps in your own Jupyter notebook to take full advantage of this tutorial."
},
{
"code": null,
"e": 8412,
"s": 8268,
"text": "The data set contains information about money spent on advertisement and their generated sales. Money was spent on TV, radio and newspaper ads."
},
{
"code": null,
"e": 8510,
"s": 8412,
"text": "The objective is to use linear regression to understand how advertisement spending impacts sales."
},
{
"code": null,
"e": 8672,
"s": 8510,
"text": "The advantage of working with Python is that we have access to many libraries that allow us to rapidly read data, plot the data, and perform a linear regression."
},
{
"code": null,
"e": 8792,
"s": 8672,
"text": "I like to import all the necessary libraries on top of the notebook to keep everything organized. Import the following:"
},
{
"code": null,
"e": 8974,
"s": 8792,
"text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import r2_scoreimport statsmodels.api as sm"
},
{
"code": null,
"e": 9103,
"s": 8974,
"text": "Assuming that you downloaded the data set, place it in a data directory within your project folder. Then, read the data like so:"
},
{
"code": null,
"e": 9146,
"s": 9103,
"text": "data = pd.read_csv(\"data/Advertising.csv\")"
},
{
"code": null,
"e": 9200,
"s": 9146,
"text": "To see what the data looks like, we do the following:"
},
{
"code": null,
"e": 9212,
"s": 9200,
"text": "data.head()"
},
{
"code": null,
"e": 9237,
"s": 9212,
"text": "And you should see this:"
},
{
"code": null,
"e": 9310,
"s": 9237,
"text": "As you can see, the column Unnamed: 0 is redundant. Hence, we remove it."
},
{
"code": null,
"e": 9344,
"s": 9310,
"text": "data.drop(['Unnamed: 0'], axis=1)"
},
{
"code": null,
"e": 9404,
"s": 9344,
"text": "Alright, our data is clean and ready for linear regression!"
},
{
"code": null,
"e": 9573,
"s": 9404,
"text": "For simple linear regression, let’s consider only the effect of TV ads on sales. Before jumping right into the modelling, let’s take a look at what the data looks like."
},
{
"code": null,
"e": 9651,
"s": 9573,
"text": "We use matplotlib , a popular Python plotting library to make a scatter plot."
},
{
"code": null,
"e": 9810,
"s": 9651,
"text": "plt.figure(figsize=(16, 8))plt.scatter( data['TV'], data['sales'], c='black')plt.xlabel(\"Money spent on TV ads ($)\")plt.ylabel(\"Sales ($)\")plt.show()"
},
{
"code": null,
"e": 9863,
"s": 9810,
"text": "Run this cell of code and you should see this graph:"
},
{
"code": null,
"e": 9955,
"s": 9863,
"text": "As you can see, there is a clear relationship between the amount spent on TV ads and sales."
},
{
"code": null,
"e": 10022,
"s": 9955,
"text": "Let’s see how we can generate a linear approximation of this data."
},
{
"code": null,
"e": 10224,
"s": 10022,
"text": "X = data['TV'].values.reshape(-1,1)y = data['sales'].values.reshape(-1,1)reg = LinearRegression()reg.fit(X, y)print(\"The linear model is: Y = {:.5} + {:.5}X\".format(reg.intercept_[0], reg.coef_[0][0]))"
},
{
"code": null,
"e": 10235,
"s": 10224,
"text": "That’s it?"
},
{
"code": null,
"e": 10359,
"s": 10235,
"text": "Yes! It is that simple to fit a straight line to the data set and see the parameters of the equation. In this case, we have"
},
{
"code": null,
"e": 10403,
"s": 10359,
"text": "Let’s visualize how the line fits the data."
},
{
"code": null,
"e": 10659,
"s": 10403,
"text": "predictions = reg.predict(X)plt.figure(figsize=(16, 8))plt.scatter( data['TV'], data['sales'], c='black')plt.plot( data['TV'], predictions, c='blue', linewidth=2)plt.xlabel(\"Money spent on TV ads ($)\")plt.ylabel(\"Sales ($)\")plt.show()"
},
{
"code": null,
"e": 10677,
"s": 10659,
"text": "And now, you see:"
},
{
"code": null,
"e": 10808,
"s": 10677,
"text": "From the graph above, it seems that a simple linear regression can explain the general impact of amount spent on TV ads and sales."
},
{
"code": null,
"e": 10949,
"s": 10808,
"text": "Now, if you remember from this post, to see if the model is any good, we need to look at the R2 value and the p-value from each coefficient."
},
{
"code": null,
"e": 10970,
"s": 10949,
"text": "Here’s how we do it:"
},
{
"code": null,
"e": 11081,
"s": 10970,
"text": "X = data['TV']y = data['sales']X2 = sm.add_constant(X)est = sm.OLS(y, X2)est2 = est.fit()print(est2.summary())"
},
{
"code": null,
"e": 11117,
"s": 11081,
"text": "Which gives you this lovely output:"
},
{
"code": null,
"e": 11320,
"s": 11117,
"text": "Looking at both coefficients, we have a p-value that is very low (although it is probably not exactly 0). This means that there is a strong correlation between these coefficients and the target (Sales)."
},
{
"code": null,
"e": 11622,
"s": 11320,
"text": "Then, looking at the R2 value, we have 0.612. Therefore, about 60% of the variability of sales is explained by the amount spent on TV ads. This is okay, but definitely not the best we can to accurately predict the sales. Surely, spending on newspaper and radio ads must have a certain impact on sales."
},
{
"code": null,
"e": 11685,
"s": 11622,
"text": "Let’s see if a multiple linear regression will perform better."
},
{
"code": null,
"e": 11832,
"s": 11685,
"text": "Just like for simple linear regression, we will define our features and target variable and use scikit-learn library to perform linear regression."
},
{
"code": null,
"e": 12108,
"s": 11832,
"text": "Xs = data.drop(['sales', 'Unnamed: 0'], axis=1)y = data['sales'].reshape(-1,1)reg = LinearRegression()reg.fit(Xs, y)print(\"The linear model is: Y = {:.5} + {:.5}*TV + {:.5}*radio + {:.5}*newspaper\".format(reg.intercept_[0], reg.coef_[0][0], reg.coef_[0][1], reg.coef_[0][2]))"
},
{
"code": null,
"e": 12174,
"s": 12108,
"text": "Nothing more! From this code cell, we get the following equation:"
},
{
"code": null,
"e": 12288,
"s": 12174,
"text": "Of course, we cannot visualize the impact of all three mediums on sales, since it has a total of four dimensions."
},
{
"code": null,
"e": 12480,
"s": 12288,
"text": "Notice that the coefficient for newspaper is negative, but also fairly small. Is it relevant to our model? Let’s see by calculating the F-statistic, R2 value and p-value for each coefficient."
},
{
"code": null,
"e": 12579,
"s": 12480,
"text": "As you must expect, the procedure here is very similar to what we did in simple linear regression."
},
{
"code": null,
"e": 12743,
"s": 12579,
"text": "X = np.column_stack((data['TV'], data['radio'], data['newspaper']))y = data['sales']X2 = sm.add_constant(X)est = sm.OLS(y, X2)est2 = est.fit()print(est2.summary())"
},
{
"code": null,
"e": 12770,
"s": 12743,
"text": "And you get the following:"
},
{
"code": null,
"e": 12870,
"s": 12770,
"text": "As you can see, the R2 is much higher than that of simple linear regression, with a value of 0.897!"
},
{
"code": null,
"e": 13077,
"s": 12870,
"text": "Also, the F-statistic is 570.3. This is much greater than 1, and since our data set if fairly small (only 200 data points), it demonstrates that there is a strong relationship between ad spending and sales."
},
{
"code": null,
"e": 13472,
"s": 13077,
"text": "Finally, because we only have three predictors, we can consider their p-value to determine if they are relevant to the model or not. Of course, you notice that the third coefficient (the one for newspaper) has a large p-value. Therefore, ad spending on newspaper is not statistically significant. Removing that predictor would slightly reduce the R2 value, but we might make better predictions."
},
{
"code": null,
"e": 13703,
"s": 13472,
"text": "Previously, we saw that linear regression assumes the response variable is quantitative. However, in many situations, the response is actually qualitative, like the color of the eyes. This type of response is known as categorical."
},
{
"code": null,
"e": 13984,
"s": 13703,
"text": "Classification is the process of predicting a qualitative response. Methods used for classification often predict the probability of each of the categories of a qualitative variable as the basis for making the classification. In a certain way, they behave like regression methods."
},
{
"code": null,
"e": 14035,
"s": 13984,
"text": "With classification, we can answer questions like:"
},
{
"code": null,
"e": 14138,
"s": 14035,
"text": "A person has a set of symptoms that could be attributed to one of three medical conditions. Which one?"
},
{
"code": null,
"e": 14174,
"s": 14138,
"text": "Is a transaction fraudulent or not?"
},
{
"code": null,
"e": 14383,
"s": 14174,
"text": "Categorical responses are often expressed as words. Of course, we cannot use words as input data for traditional statistical methods. We will see how to deal with that when we get to implement the algorithms."
},
{
"code": null,
"e": 14433,
"s": 14383,
"text": "For now, let’s see how logistic regression works."
},
{
"code": null,
"e": 14633,
"s": 14433,
"text": "When it comes to classification, we are determining the probability of an observation to be part of a certain class or not. Therefore, we wish to express the probability with a value between 0 and 1."
},
{
"code": null,
"e": 14724,
"s": 14633,
"text": "A probability close to 1 means the observation is very likely to be part of that category."
},
{
"code": null,
"e": 14817,
"s": 14724,
"text": "In order to generate values between 0 and 1, we express the probability using this equation:"
},
{
"code": null,
"e": 14872,
"s": 14817,
"text": "The equation above is defined as the sigmoid function."
},
{
"code": null,
"e": 14985,
"s": 14872,
"text": "Plot this equation and you will see that this equation always results in a S-shaped curve bound between 0 and 1."
},
{
"code": null,
"e": 15043,
"s": 14985,
"text": "After some manipulation to equation above, you find that:"
},
{
"code": null,
"e": 15071,
"s": 15043,
"text": "Take the log on both sides:"
},
{
"code": null,
"e": 15247,
"s": 15071,
"text": "The equation above is known as the logit. As you can see, it is linear in X. Here, if the coefficients are positive, then an increase in X will result in a higher probability."
},
{
"code": null,
"e": 15363,
"s": 15247,
"text": "As in linear regression, we need a way to estimate the coefficients. For that, we maximize the likelihood function:"
},
{
"code": null,
"e": 15545,
"s": 15363,
"text": "The intuition here is that we want coefficients such that the predicted probability (denoted with an apostrophe in the equation above) is as close as possible to the observed state."
},
{
"code": null,
"e": 15652,
"s": 15545,
"text": "Similarly to linear regression, we use the p-value to determine if the null hypothesis is rejected or not."
},
{
"code": null,
"e": 15762,
"s": 15652,
"text": "The Z-statistic is also widely used. A large absolute Z-statistic means that the null hypothesis is rejected."
},
{
"code": null,
"e": 15866,
"s": 15762,
"text": "Remember that the null hypothesis states: there is not correlation between the features and the target."
},
{
"code": null,
"e": 15960,
"s": 15866,
"text": "Of course, logistic regression can easily be extended to accommodate more than one predictor:"
},
{
"code": null,
"e": 16224,
"s": 15960,
"text": "Note that using multiple logistic regression might give better results, because it can take into account correlations among predictors, a phenomenon known as confounding. Also, rarely will only one predictor be sufficient to make an accurate model for prediction."
},
{
"code": null,
"e": 16318,
"s": 16224,
"text": "Now, we understand how logistic regression works, but like any model, it presents some flaws:"
},
{
"code": null,
"e": 16416,
"s": 16318,
"text": "When classes are well separated, parameters estimate from logistic regression tend to be unstable"
},
{
"code": null,
"e": 16481,
"s": 16416,
"text": "When the data set is small, logistic regression is also unstable"
},
{
"code": null,
"e": 16527,
"s": 16481,
"text": "Not the best to predict more than two classes"
},
{
"code": null,
"e": 16684,
"s": 16527,
"text": "That’s where linear discriminant analysis (LDA) comes in handy. It is more stable than logistic regression and widely used to predict more than two classes."
},
{
"code": null,
"e": 16863,
"s": 16684,
"text": "The particularity of LDA is that it models the distribution of predictors separately in each of the response classes, and then it uses Bayes’ theorem to estimate the probability."
},
{
"code": null,
"e": 16926,
"s": 16863,
"text": "Alright, that’s a bit hard to understand. Let’s break it down."
},
{
"code": null,
"e": 17021,
"s": 16926,
"text": "(Sorry, Medium doesn’t support math equations. I tried my best to be as explicit as possible)."
},
{
"code": null,
"e": 17450,
"s": 17021,
"text": "Suppose we want to classify an observation into one of K classes, where K is greater than or equal to 2. Then, let pi-k be the overall probability that an observation is associated to the kth class. Then, let f_k(X) denote the density function of X for an observation that comes from the kth class. This means that f_k(X) is large if the probability that an observation from the kth class has X = x. Then, Bayes’ theorem states:"
},
{
"code": null,
"e": 17499,
"s": 17450,
"text": "The equation above can simply be abbreviated to:"
},
{
"code": null,
"e": 17533,
"s": 17499,
"text": "Hopefully, this makes some sense!"
},
{
"code": null,
"e": 17761,
"s": 17533,
"text": "The challenge here is to estimate the density function. Theoretically, Bayes’ classification has the lowest error rate. Therefore, our classifier needs to estimate the density function such as to approach the Bayes’ classifier."
},
{
"code": null,
"e": 17881,
"s": 17761,
"text": "Suppose we only have one predictor and that the density function normal. Then, you can express the density function as:"
},
{
"code": null,
"e": 18062,
"s": 17881,
"text": "Now, we want to assign an observation X = x for which the P_k(X) is the largest. If you plug in the density function in P_k(X) and take the log, you find that you wish to maximize:"
},
{
"code": null,
"e": 18196,
"s": 18062,
"text": "The equation above is called the discriminant. As you can see, it is a linear equation. Hence the name: linear discriminant analysis!"
},
{
"code": null,
"e": 18263,
"s": 18196,
"text": "Now, assuming only two classes with equal distributions, you find:"
},
{
"code": null,
"e": 18341,
"s": 18263,
"text": "This is the boundary equation. A graphical representation is shown hereunder."
},
{
"code": null,
"e": 18446,
"s": 18341,
"text": "Of course, this represents an ideal solution. In reality, we cannot exactly calculate the boundary line."
},
{
"code": null,
"e": 18503,
"s": 18446,
"text": "Therefore, LDA makes use of the following approximation:"
},
{
"code": null,
"e": 18548,
"s": 18503,
"text": "For the average of all training observations"
},
{
"code": null,
"e": 18608,
"s": 18548,
"text": "For the weighted average of sample variances for each class"
},
{
"code": null,
"e": 18647,
"s": 18608,
"text": "Where n is the number of observations."
},
{
"code": null,
"e": 18772,
"s": 18647,
"text": "It is important to know that LDA assumes a normal distribution for each class, a class-specific mean, and a common variance."
},
{
"code": null,
"e": 18952,
"s": 18772,
"text": "Extending now for multiple predictors, we must assume that X is drawn from a multivariate Gaussian distribution, with a class-specific mean vector, and a common covariance matrix."
},
{
"code": null,
"e": 19034,
"s": 18952,
"text": "An example of a correlated and uncorrelated Gaussian distribution is shown below."
},
{
"code": null,
"e": 19107,
"s": 19034,
"text": "Now, expressing the discriminant equation using vector notation, we get:"
},
{
"code": null,
"e": 19231,
"s": 19107,
"text": "As you can see, the equation remains the same. Only this time, we are using vector notation to accommodate many predictors."
},
{
"code": null,
"e": 19333,
"s": 19231,
"text": "With classification, it is sometimes irrelevant to use accuracy to assess the performance of a model."
},
{
"code": null,
"e": 19727,
"s": 19333,
"text": "Consider analyzing a highly imbalanced data set. For example, you are trying to determine if a transaction is fraudulent or not, but only 0.5% of your data set contains a fraudulent transaction. Then, you could predict that none of the transactions will be fraudulent, and have a 99.5% accuracy score! Of course, this is a very naive approach that does not help detect fraudulent transactions."
},
{
"code": null,
"e": 19746,
"s": 19727,
"text": "So what do we use?"
},
{
"code": null,
"e": 19791,
"s": 19746,
"text": "Usually, we use sensitivity and specificity."
},
{
"code": null,
"e": 19888,
"s": 19791,
"text": "Sensitivity is the true positive rate: the proportions of actual positives correctly identified."
},
{
"code": null,
"e": 19984,
"s": 19888,
"text": "Specificity is the true negative rate: the proportion of actual negatives correctly identified."
},
{
"code": null,
"e": 20247,
"s": 19984,
"text": "Let’s give some context to better understand. Using the fraud detection problem, the sensitivity is the proportion of fraudulent transactions identified as fraudulent. The specificity is the proportion of non-fraudulent transactions identified as non-fraudulent."
},
{
"code": null,
"e": 20518,
"s": 20247,
"text": "Therefore, in an ideal situation, we want both a high sensitivity and specificity, although that might change depending on the context. For example, a bank might want to prioritize a higher sensitivity over specificity to make sure it identifies fraudulent transactions."
},
{
"code": null,
"e": 20811,
"s": 20518,
"text": "The ROC curve (receiver operating characteristic) is good to display the two types of error metrics described above. The overall performance of a classifier is given by the area under the ROC curve (AUC). Ideally, it should hug the upper left corner of the graph, and have an area close to 1."
},
{
"code": null,
"e": 20934,
"s": 20811,
"text": "Here, we keep the same assumptions as for LDA, but now, each observation from the kth class has its own covariance matrix."
},
{
"code": null,
"e": 20977,
"s": 20934,
"text": "For QDA, the discriminant is expressed as:"
},
{
"code": null,
"e": 21047,
"s": 20977,
"text": "Without any surprises, you notice that the equation is now quadratic."
},
{
"code": null,
"e": 21077,
"s": 21047,
"text": "But, why choose QDA over LDA?"
},
{
"code": null,
"e": 21177,
"s": 21077,
"text": "QDA is a better option for large data sets, as it tends to have a lower bias and a higher variance."
},
{
"code": null,
"e": 21288,
"s": 21177,
"text": "On the other hand, LDA is more suitable for smaller data sets, and it has a higher bias, and a lower variance."
},
{
"code": null,
"e": 21431,
"s": 21288,
"text": "Great! Now that we deeply understand how logistic regression, LDA, and QDA work, let’s apply each algorithm to solve a classification problem."
},
{
"code": null,
"e": 21560,
"s": 21431,
"text": "Mushrooms simply taste great! But with over 10 000 species of mushrooms only in North America, how can we tell which are edible?"
},
{
"code": null,
"e": 21692,
"s": 21560,
"text": "This is the objective of this project. We will build a classifier that will determine if a certain mushroom is edible or poisonous."
},
{
"code": null,
"e": 21805,
"s": 21692,
"text": "I suggest you grab the data set and follow along. If you ever get stuck, feel free to consult the full notebook."
},
{
"code": null,
"e": 21822,
"s": 21805,
"text": "Let’s get to it!"
},
{
"code": null,
"e": 22060,
"s": 21822,
"text": "The data set we will be using contains 8124 instances of mushrooms with 22 features. Among them, we find the mushroom’s cap shape, cap color, gill color, veil type, etc. Of course, it also tells us if the mushroom is edible or poisonous."
},
{
"code": null,
"e": 22190,
"s": 22060,
"text": "Let’s import some of the libraries that will help us import the data and manipulate it. In your notebook, run the following code:"
},
{
"code": null,
"e": 22577,
"s": 22190,
"text": "A common first step for a data science project is to perform an exploratory data analysis (EDA). This step usually involves learning more about the data you are working with. You might want to know the shape of your data set (how many rows and columns), the number of empty values and visualize parts of the data to better understand the correlation between the features and the target."
},
{
"code": null,
"e": 22649,
"s": 22577,
"text": "Import the data and see the first five columns with the following code:"
},
{
"code": null,
"e": 22869,
"s": 22649,
"text": "It’s always good to have the data set in a data folder within the project directory. Furthermore, we store the file path in a variable, such that if the path ever changes, we only have to change the variable assignment."
},
{
"code": null,
"e": 23127,
"s": 22869,
"text": "After running this code cell, you should see the first five rows. You notice that each feature is categorical, and a letter is used to define a certain value. Of course, the classifier cannot take letters as input, so we will have to change that eventually."
},
{
"code": null,
"e": 23443,
"s": 23127,
"text": "For now, let’s see if our data set is unbalanced. An unbalanced data set is when one class is much more present than the other. Ideally, in the context of classification, we want an equal number of instances of each class. Otherwise, we would need to implement advanced sampling methods, like minority oversampling."
},
{
"code": null,
"e": 23601,
"s": 23443,
"text": "In our case, we want to see if there is an equal number of poisonous and edible mushrooms in the data set. We can plot the frequency of each class like this:"
},
{
"code": null,
"e": 23634,
"s": 23601,
"text": "And you get the following graph:"
},
{
"code": null,
"e": 23747,
"s": 23634,
"text": "Awesome! It looks like a fairly balanced data set with an almost equal number of poisonous and edible mushrooms."
},
{
"code": null,
"e": 23998,
"s": 23747,
"text": "Now, I wanted to see how each feature affects the target. To do so, for each feature, I made a bar plot of all possible values separated by the class of mushroom. Doing it manually for all 22 features makes no sense, so we build this helper function:"
},
{
"code": null,
"e": 24164,
"s": 23998,
"text": "The hue will give a color code to the poisonous and edible class. The data parameter will contain all features but the mushroom’s class. Running the cell code below:"
},
{
"code": null,
"e": 24232,
"s": 24164,
"text": "You should get a list of 22 plots. Here’s an example of the output:"
},
{
"code": null,
"e": 24278,
"s": 24232,
"text": "Take some time to look through all the plots."
},
{
"code": null,
"e": 24348,
"s": 24278,
"text": "Now, let’s see if we have any missing values. Run this piece of code:"
},
{
"code": null,
"e": 24512,
"s": 24348,
"text": "And you should see each column with the number of missing values. Luckily, we have a data set with no missing values. This is very uncommon, but we won’t complain."
},
{
"code": null,
"e": 24724,
"s": 24512,
"text": "Now that we are familiar with the data, it is time to get it ready for modelling. As mentioned before, the features have letters to represent the different possible values, but we need to turn them into numbers."
},
{
"code": null,
"e": 24790,
"s": 24724,
"text": "To achieve that, we will use label encoding and one-hot encoding."
},
{
"code": null,
"e": 24867,
"s": 24790,
"text": "Let’s first use label encoding on the target column. Run the following code:"
},
{
"code": null,
"e": 24924,
"s": 24867,
"text": "And you notice now that the column now contains 1 and 0."
},
{
"code": null,
"e": 25129,
"s": 24924,
"text": "Now, poisonous is represented by 1 and edible is represented by 0. Now, we can think of our classifier as “poisonous or not”. A poisonous mushroom gets a 1 (true), and an edible mushroom gets a 0 (false)."
},
{
"code": null,
"e": 25298,
"s": 25129,
"text": "Hence, label encoding will turn a categorical feature into numerical. However, it is not recommended to use label encoding when there are more than two possible values."
},
{
"code": null,
"e": 25303,
"s": 25298,
"text": "Why?"
},
{
"code": null,
"e": 25491,
"s": 25303,
"text": "Because it will then assign each value to either 0, 1 or 2. This is a problem, because the “2” could be considered as being more important and false correlations could be drawn from that."
},
{
"code": null,
"e": 25841,
"s": 25491,
"text": "To avoid this problem, we use one-hot encoding on the other features. To understand what it does, let’s consider the cap shape of the first entry point. You see it has a value of “x”, which stands for a convex cap shape. However, there is a total of six different cap shapes recorded in the data set. If we one-hot encode the feature, we should get:"
},
{
"code": null,
"e": 26038,
"s": 25841,
"text": "As you can see, the cap shape is now a vector. A 1 denotes the actual cap shape value for an entry in the data set, and the rest is filled with 0. Again, you can think of 1 as true and 0 as false."
},
{
"code": null,
"e": 26300,
"s": 26038,
"text": "The drawback of one-hot encoding is that it introduces more columns to the data set. In the case of cap shape, we go from one column to six columns. For very large data sets, this might be a problem, but in our case, the additional columns should be manageable."
},
{
"code": null,
"e": 26360,
"s": 26300,
"text": "Let’s go ahead and one-hot encode the rest of the features:"
},
{
"code": null,
"e": 26384,
"s": 26360,
"text": "And you should now see:"
},
{
"code": null,
"e": 26527,
"s": 26384,
"text": "You notice that we went from 23 columns to 118. It is a five fold increase, but the number is not high enough to cause computer memory issues."
},
{
"code": null,
"e": 26635,
"s": 26527,
"text": "Now that our data set contains only numerical data, we are ready to start modelling and making predictions!"
},
{
"code": null,
"e": 26981,
"s": 26635,
"text": "Before diving deep into modelling and making predictions, we need to split our data set into a training set and test set. That way, we can train an algorithm on the training set, and make predictions on the test set. The error metrics will be much more relevant this way, since the algorithm will make predictions on data it has not seen before."
},
{
"code": null,
"e": 27023,
"s": 26981,
"text": "We can easily split the data set like so:"
},
{
"code": null,
"e": 27583,
"s": 27023,
"text": "Here, y is simply the target (poisonous or edible). Then, X is simply all features of the data set. Finally, we use the train_test_split function. The test_size parameter corresponds to the fraction of the data set that will be used for testing. Usually, we use 20%. Then, the random_state parameter is used for reproducibility. It can be set to any number, but it will ensure that every time the code runs, the data set will be split identically. If no random_state is provided, then the train and test set will differ, since the function splits it randomly."
},
{
"code": null,
"e": 27661,
"s": 27583,
"text": "All right, we are officially ready to start modelling and making predictions!"
},
{
"code": null,
"e": 27814,
"s": 27661,
"text": "We will first use logistic regression. Throughout the following steps, we will use the area under the ROC curve and a confusion matrix as error metrics."
},
{
"code": null,
"e": 27846,
"s": 27814,
"text": "Let’s import all we need first:"
},
{
"code": null,
"e": 27944,
"s": 27846,
"text": "Then, we make an instance of the LogisticRegression object and fit the model to the training set:"
},
{
"code": null,
"e": 28077,
"s": 27944,
"text": "Then, we predict the probability that a mushroom is poisonous. Remember, we treat the mushrooms as being poisonous or non-poisonous."
},
{
"code": null,
"e": 28382,
"s": 28077,
"text": "Also, you must be reminded that logistic regression returns a probability. For now, let’s set the threshold to 0.5 That way, if the probability is greater than 0.5, a mushroom will be classified as poisonous. Of course, if the probability is less than the threshold, the mushroom is classified as edible."
},
{
"code": null,
"e": 28440,
"s": 28382,
"text": "This is exactly what is happening in the code cell below:"
},
{
"code": null,
"e": 28501,
"s": 28440,
"text": "Notice that we calculated the probabilities on the test set."
},
{
"code": null,
"e": 28631,
"s": 28501,
"text": "Now, let’s see the confusion matrix. This will show us the true positive, true negative, false positive and false negative rates."
},
{
"code": null,
"e": 28671,
"s": 28631,
"text": "We output our confusion matrix like so:"
},
{
"code": null,
"e": 28691,
"s": 28671,
"text": "And you should get:"
},
{
"code": null,
"e": 28901,
"s": 28691,
"text": "Amazing! Our classifier is perfect! From the confusion matrix above, you see that our false positive and false negative rates are 0, meaning that all mushrooms were correctly classified as poisonous or edible!"
},
{
"code": null,
"e": 29007,
"s": 28901,
"text": "Let’s print the area under the ROC curve. As you know, for a perfect classifier, it should be equal to 1."
},
{
"code": null,
"e": 29104,
"s": 29007,
"text": "Indeed, the code block above outputs 1! We can make our own function to visualize the ROC curve:"
},
{
"code": null,
"e": 29124,
"s": 29104,
"text": "And you should see:"
},
{
"code": null,
"e": 29212,
"s": 29124,
"text": "Congratulations! You built a perfect classifier with a basic logistic regression model."
},
{
"code": null,
"e": 29323,
"s": 29212,
"text": "Still, to gain more experience, let’s build a classifier using LDA and QDA, and see if we get similar results."
},
{
"code": null,
"e": 29382,
"s": 29323,
"text": "Following the same steps outlined for logistic regression:"
},
{
"code": null,
"e": 29532,
"s": 29382,
"text": "If you run the code above, you should see that we get a perfect classifier again, with identical results to the classifier using logistic regression."
},
{
"code": null,
"e": 29575,
"s": 29532,
"text": "Now, we repeat the process, but using QDA:"
},
{
"code": null,
"e": 29612,
"s": 29575,
"text": "And again, the results are the same!"
},
{
"code": null,
"e": 29762,
"s": 29612,
"text": "Resampling and regularization are two important steps that can significantly improve both your model’s performance and your confidence in your model."
},
{
"code": null,
"e": 30048,
"s": 29762,
"text": "In this article, cross-validation will be extensively addressed as it is the most popular resampling method. Then, ridge regression and lasso will be introduced as regularization methods for linear models. Afterwards, resampling and regularization will be applied in a project setting."
},
{
"code": null,
"e": 30174,
"s": 30048,
"text": "I hope this article will serve as a reference for one of your future projects, and that it finds its way into your bookmarks."
},
{
"code": null,
"e": 30193,
"s": 30174,
"text": "Let’s get started!"
},
{
"code": null,
"e": 30537,
"s": 30193,
"text": "Resampling methods are an indispensable tool in modern statistics. They involve repeatedly drawing samples from a training set and refitting a model of interest on each sample in order to obtain additional information about the fitted model. This allows us to gain more information that could not be available from fitting the model only once."
},
{
"code": null,
"e": 30809,
"s": 30537,
"text": "Usually, the objective of a data science project is to create a model using training data, and have it make predictions on new data. Hence, the resampling methods allow us to see how the model would perform on data it has not been trained on, without collecting new data."
},
{
"code": null,
"e": 31172,
"s": 30809,
"text": "Cross-validation (CV) is used to estimate the test error associated with a model to evaluate its performance or to select the appropriate level of flexibility. Evaluating a model’s performance is usually defined as model assessment, and model selection is used for selecting the level of flexibility. This terminology is widely used in the field of data science."
},
{
"code": null,
"e": 31263,
"s": 31172,
"text": "Now, there are different ways to perform cross-validation. Let’s explore each one of them."
},
{
"code": null,
"e": 31523,
"s": 31263,
"text": "This is the most basic approach. It simply involves randomly dividing the dataset into two parts: a training set and a validation set or hold-out set. The model is fit on the training set and the fitted model is used to make predictions on the validation set."
},
{
"code": null,
"e": 31777,
"s": 31523,
"text": "Above is a schematic of the validation set approach. You have n observations in a dataset, it was randomly split into two parts. The blue side represents the training set, and the orange side is the validation set. The numbers simply represent the rows."
},
{
"code": null,
"e": 31843,
"s": 31777,
"text": "Of course, with such a simple approach, there are some drawbacks."
},
{
"code": null,
"e": 31972,
"s": 31843,
"text": "First, the validation test error rate is highly variable depending on which observations are in the training and validation set."
},
{
"code": null,
"e": 32138,
"s": 31972,
"text": "Second, only a small subset of the observations are used to fit the model. However, we know that statistical methods tend to perform worse when trained on less data."
},
{
"code": null,
"e": 32319,
"s": 32138,
"text": "Above, on the left, you see the MSE when the validation set approach was applied only once. On the right, the process was repeated 10 times. As you can see, the MSE greatly varies."
},
{
"code": null,
"e": 32411,
"s": 32319,
"text": "This shows the significant variability of the MSE when the validation set approach is used."
},
{
"code": null,
"e": 32470,
"s": 32411,
"text": "Of course, there are methods that address these drawbacks."
},
{
"code": null,
"e": 32700,
"s": 32470,
"text": "The leave-one-out cross-validation (LOOCV) is a better option than the validation set approach. Instead of splitting the dataset into two subsets, only one observation is used for validation and the rest is used to fit the model."
},
{
"code": null,
"e": 32871,
"s": 32700,
"text": "Above is a schematic of LOOCV. As you can see, only one observation is used for validation and the rest is used for training. The process is then repeated multiple times."
},
{
"code": null,
"e": 32919,
"s": 32871,
"text": "After multiple runs, the error is estimated as:"
},
{
"code": null,
"e": 32971,
"s": 32919,
"text": "Which is simply the mean of the errors of each run."
},
{
"code": null,
"e": 33207,
"s": 32971,
"text": "This method is much better, because it has far less bias, since more observations are used to fit the model. There is no randomness in the training/validation set splits. Therefore, we reduce the variability of the MSE, as shown below."
},
{
"code": null,
"e": 33513,
"s": 33207,
"text": "This approach involves randomly dividing the set of observations into k groups or folds of approximately equal size. The first fold is treated as a validation set and the model is fit on the remaining folds. The procedure is then repeated k times, where a different group is treated as the validation set."
},
{
"code": null,
"e": 33689,
"s": 33513,
"text": "Hence, you realize that LOOCV is a special case of k-fold cross validation where k is equal to total number of observations n. However, it is common to set k equal to 5 or 10."
},
{
"code": null,
"e": 33996,
"s": 33689,
"text": "Whereas LOOCV is computationally intensive for large datasets, k-fold is more general and it can be used with any model. In addition, it often gives more accurate estimates of test error than does LOOCV. Therefore, to assess and validate your model, the k-fold cross-validation approach is the best option."
},
{
"code": null,
"e": 34173,
"s": 33996,
"text": "Now that we know how cross-validation works and how it can improve our confidence in the model’s performance, let’s see how we can improve the model itself with regularization."
},
{
"code": null,
"e": 34344,
"s": 34173,
"text": "Regularization methods effectively prevent overfitting. Overfitting occurs when a model performs well on the training set, but then performs poorly on the validation set."
},
{
"code": null,
"e": 34500,
"s": 34344,
"text": "We have seen that linear models, such as linear regression and, by extension, logistic regression, use the least squares method to estimate the parameters."
},
{
"code": null,
"e": 34695,
"s": 34500,
"text": "Now, we explore how we can improve linear models by replacing least squares fitting with other fitting procedures. These methods will yield better prediction accuracy and model interpretability."
},
{
"code": null,
"e": 34735,
"s": 34695,
"text": "But why? Why use other fitting methods?"
},
{
"code": null,
"e": 34826,
"s": 34735,
"text": "Least squares fitting works most of the time, but there are situations where it will fail."
},
{
"code": null,
"e": 35134,
"s": 34826,
"text": "For example, if your number of observations n is greater than the number of predictors p, then the least squares estimates will have a low variance and it performs well. On the other hand, with p is greater than n (more predictors than observations), then variance is infinite and the method cannot be used!"
},
{
"code": null,
"e": 35421,
"s": 35134,
"text": "Also, multiple liner regression tends to add variables that are not actually associated with the response. This adds unnecessary complexity to the model. It would be good if there was a way to automatically perform feature selection, such as to include only the most relevant variables."
},
{
"code": null,
"e": 35555,
"s": 35421,
"text": "To achieve that, we introduce ridge regression and lasso. These are two common regularization methods, also called shrinkage methods."
},
{
"code": null,
"e": 35726,
"s": 35555,
"text": "Shrinking the estimated coefficients towards 0 can significantly improve the fit and reduce the variance of the coefficients. Here, we explore ridge regression and lasso."
},
{
"code": null,
"e": 35893,
"s": 35726,
"text": "Traditional linear fitting involves minimizing the RSS (residual sum of squares). In ridge regression, a new parameter is added, and now the parameters will minimize:"
},
{
"code": null,
"e": 36134,
"s": 35893,
"text": "Where lambda is a tuning parameter. This parameter is found using cross-validation as it must minimize the test error. Therefore, a range of lambdas is used to fit the model and the lambda that minimizes the test error is the optimal value."
},
{
"code": null,
"e": 36305,
"s": 36134,
"text": "Here, ridge regression will include all p predictors in the model. Hence, it is a good method to improve the fit of the model, but it will not perform variable selection."
},
{
"code": null,
"e": 36358,
"s": 36305,
"text": "Similarly to ridge regression, lasso will minimizes:"
},
{
"code": null,
"e": 36492,
"s": 36358,
"text": "Notice that we use the absolute value of the parameter beta instead of its squared value. Also, the same tuning parameter is present."
},
{
"code": null,
"e": 36666,
"s": 36492,
"text": "However, if lambda is large enough, some coefficients will effectively be 0! Therefore, lasso can also perform variable selection, making the model much easier to interpret."
},
{
"code": null,
"e": 36771,
"s": 36666,
"text": "We know how regularization and resampling works. Now, let’s apply these techniques in a project setting."
},
{
"code": null,
"e": 36884,
"s": 36771,
"text": "Fire up a Jupyter notebook and grab the dataset. If you ever get stuck, the solution notebook is also available."
},
{
"code": null,
"e": 37001,
"s": 36884,
"text": "Like with any project, we import our usual libraries that will help us perform basic data manipulation and plotting."
},
{
"code": null,
"e": 37050,
"s": 37001,
"text": "Now, we can start our exploratory data analysis."
},
{
"code": null,
"e": 37124,
"s": 37050,
"text": "We start off by importing our dataset and looking at the first five rows:"
},
{
"code": null,
"e": 37140,
"s": 37124,
"text": "You should see:"
},
{
"code": null,
"e": 37205,
"s": 37140,
"text": "Notice that the Unnamed: 0 column is useless. Let’s take it out."
},
{
"code": null,
"e": 37243,
"s": 37205,
"text": "And now, our dataset looks like this:"
},
{
"code": null,
"e": 37333,
"s": 37243,
"text": "As you can see, we only have three advertising mediums, and sales is our target variable."
},
{
"code": null,
"e": 37463,
"s": 37333,
"text": "Let’s see how each variable impacts the sales by making a scatter plot. First, we build a helper function to make a scatter plot:"
},
{
"code": null,
"e": 37524,
"s": 37463,
"text": "Now, we can generate three different plots for each feature."
},
{
"code": null,
"e": 37551,
"s": 37524,
"text": "And you get the following:"
},
{
"code": null,
"e": 37695,
"s": 37551,
"text": "As you can see, TV and radio ads seem to be good predictors for sales, while there seems to be no correlations between sales and newspaper ads."
},
{
"code": null,
"e": 37805,
"s": 37695,
"text": "Luckily, our dataset does not require further processing, so we are ready to move on to modelling right away!"
},
{
"code": null,
"e": 37877,
"s": 37805,
"text": "Let’s take a look at what the code looks like, before going through it."
},
{
"code": null,
"e": 38057,
"s": 37877,
"text": "First, we import the LinearRegression and cross_val_score objects. The first one will allow us to fit a linear model, while the second object will perform k-fold cross-validation."
},
{
"code": null,
"e": 38107,
"s": 38057,
"text": "Then, we define our features and target variable."
},
{
"code": null,
"e": 38314,
"s": 38107,
"text": "The cross_val_score will return an array of MSE for each cross-validation steps. In our case, we have five of them. Therefore, we take the mean of MSE and print it. You should get a negative MSE of -3.0729."
},
{
"code": null,
"e": 38374,
"s": 38314,
"text": "Now, let’s see if ridge regression or lasso will be better."
},
{
"code": null,
"e": 38588,
"s": 38374,
"text": "For ridge regression, we introduce GridSearchCV. This will allow us to automatically perform 5-fold cross-validation with a range of different regularization parameters in order to find the optimal value of alpha."
},
{
"code": null,
"e": 38614,
"s": 38588,
"text": "The code looks like this:"
},
{
"code": null,
"e": 38688,
"s": 38614,
"text": "Then, we can find the best parameter and the best MSE with the following:"
},
{
"code": null,
"e": 38847,
"s": 38688,
"text": "You should see that the optimal value of alpha is 20, with a negative MSE of -3.07267. This is a slight improvement upon the basic multiple linear regression."
},
{
"code": null,
"e": 38912,
"s": 38847,
"text": "For lasso, we follow a very similar process to ridge regression:"
},
{
"code": null,
"e": 39038,
"s": 38912,
"text": "In this case, the optimal value for alpha is 1, and the negative MSE is -3.0414, which is the best score of all three models!"
},
{
"code": null,
"e": 39275,
"s": 39038,
"text": "Tree-based methods can be used for regression or classification. They involve segmenting the prediction space into a number of simple regions. The set of splitting rules can be summarized in a tree, hence the name decision tree methods."
},
{
"code": null,
"e": 39550,
"s": 39275,
"text": "A single decision tree is often not as performant as linear regression, logistic regression, LDA, etc. However, by introducing bagging, random forests, and boosting, it can result in dramatic improvements in prediction accuracy at the expense of some loss in interpretation."
},
{
"code": null,
"e": 39612,
"s": 39550,
"text": "Before getting to the theory, we need some basic terminology."
},
{
"code": null,
"e": 39798,
"s": 39612,
"text": "Trees are drawn upside down. The final regions are termed leaves. The points inside the tree where a split occurs is an interval node. Finally, segments that connect nodes are branches."
},
{
"code": null,
"e": 39827,
"s": 39798,
"text": "To create a regression tree:"
},
{
"code": null,
"e": 39997,
"s": 39827,
"text": "Divide the predictor space into J distinct and non-overlapping regionsFor every observation that falls in a region, predict the mean of the response value in that region"
},
{
"code": null,
"e": 40068,
"s": 39997,
"text": "Divide the predictor space into J distinct and non-overlapping regions"
},
{
"code": null,
"e": 40168,
"s": 40068,
"text": "For every observation that falls in a region, predict the mean of the response value in that region"
},
{
"code": null,
"e": 40296,
"s": 40168,
"text": "Each region is split to minimize the RSS. To do so, it takes a top-down greedy approach also called recursive binary splitting."
},
{
"code": null,
"e": 40310,
"s": 40296,
"text": "Why top-down?"
},
{
"code": null,
"e": 40382,
"s": 40310,
"text": "Because all observations are in a single region before the first split."
},
{
"code": null,
"e": 40405,
"s": 40382,
"text": "Why a greedy approach?"
},
{
"code": null,
"e": 40560,
"s": 40405,
"text": "Because the best split occurs at a particular step, rather than looking ahead and making a split that will result in a better prediction in a future step."
},
{
"code": null,
"e": 40614,
"s": 40560,
"text": "Mathematically, we define the pair of half-planes as:"
},
{
"code": null,
"e": 40647,
"s": 40614,
"text": "and we seek j and s to minimize:"
},
{
"code": null,
"e": 40780,
"s": 40647,
"text": "However, this may lead to overfitting. Pruning the tree will result in a smaller subtree that we can validate with cross-validation."
},
{
"code": null,
"e": 41077,
"s": 40780,
"text": "A classification tree is very similar to a regression tree. However, we cannot use the mean value of the response, so we now predict the most commonly occurring class in a region. Of course, RSS cannot be used as a criterion. Instead, each split is done to minimize the classification error rate."
},
{
"code": null,
"e": 41212,
"s": 41077,
"text": "The classification error rate is simply the fraction of training observations in a region that do not belong to the most common class."
},
{
"code": null,
"e": 41315,
"s": 41212,
"text": "Unfortunately, this is not sensitive enough for tree-growing. In practice, two other methods are used."
},
{
"code": null,
"e": 41340,
"s": 41315,
"text": "There is the Gini index:"
},
{
"code": null,
"e": 41519,
"s": 41340,
"text": "This is a measure of total variance across all classes. As you can see, the Gini index will be small if the proportion is close to 0 or 1, so it is a good measure of node purity."
},
{
"code": null,
"e": 41592,
"s": 41519,
"text": "A similar rationale is applied to the other method called cross-entropy:"
},
{
"code": null,
"e": 41693,
"s": 41592,
"text": "Now that we have seen how a basic decision tree works, let’s see how we can improve its performance!"
},
{
"code": null,
"e": 41953,
"s": 41693,
"text": "We know that bootstrap can compute the standard deviation of any quantity of interest. For decision trees, the variance is very high. Therefore, with bootstrap aggregation or bagging, we can reduce the variance and increase the performance of a decision tree."
},
{
"code": null,
"e": 42179,
"s": 41953,
"text": "Bagging involves repeatedly taking samples from a dataset. This generates B different bootstrap training sets. Then, we train on all bootstrapped training sets to get a prediction for each set, and we average the predictions."
},
{
"code": null,
"e": 42222,
"s": 42179,
"text": "Mathematically, the average prediction is:"
},
{
"code": null,
"e": 42470,
"s": 42222,
"text": "Applying this to decision trees, it means that that we can construct a high number of trees which will have high variance and low bias. Then, we can average their predictions to reduce the variance to improve the performance of the decision trees."
},
{
"code": null,
"e": 42579,
"s": 42470,
"text": "Random forests provide an improvement over bagged trees by way of a small tweak that decorrelates the trees."
},
{
"code": null,
"e": 42793,
"s": 42579,
"text": "Like in bagging, multiple decision trees are built. However, at each split, a random sample of m predictors is chosen from all p predictors. The split is allowed to use only one of the m predictors, and typically:"
},
{
"code": null,
"e": 42905,
"s": 42793,
"text": "In other words, at each split, the algorithm is not allowed to consider a majority of the available predictors!"
},
{
"code": null,
"e": 42910,
"s": 42905,
"text": "Why?"
},
{
"code": null,
"e": 43288,
"s": 42910,
"text": "Suppose that there is one very strong predictor in the dataset, along with other moderately strong predictors. Then, in the collection of bagged trees, they will all use this strong predictor in the top split. Consequently, all of the bagged trees will be very similar, and averaging their predictions will not reduce variance, since the predictions would be highly correlated."
},
{
"code": null,
"e": 43429,
"s": 43288,
"text": "Random forests overcome this problem by forcing each split to only consider a subset of predictors which effectively decorrelates the trees."
},
{
"code": null,
"e": 43559,
"s": 43429,
"text": "Of course, if m is equal to p, then it is just like bagging. Usually, the square root of p gives the best results as shown below."
},
{
"code": null,
"e": 43701,
"s": 43559,
"text": "Boosting works in a similar way to bagging, but the trees are grown sequentially: each tree uses information from the previously grown trees."
},
{
"code": null,
"e": 43934,
"s": 43701,
"text": "This means that the algorithm learns slowly. Each tree is fit to the residuals from the model rather than to the target variable. Hence, each tree is small and will slowly improve predictions in areas where it does not perform well."
},
{
"code": null,
"e": 43981,
"s": 43934,
"text": "There are three tuning parameters in boosting:"
},
{
"code": null,
"e": 44137,
"s": 43981,
"text": "1. number of tree (B): unlike bagging and random forests, boosting can overfit if B is too large. Use cross-validation to choose the right amount of trees."
},
{
"code": null,
"e": 44276,
"s": 44137,
"text": "2. shrinkage parameter (alpha): a small positive number that controls the learning rate of boosting. It is typically set to 0.01 or 0.001."
},
{
"code": null,
"e": 44451,
"s": 44276,
"text": "3. number of splits in each tree (d): it controls the complexity of the boosted ensemble. Usually, a single split (d = 1) works well. It is also called the interaction depth."
},
{
"code": null,
"e": 44531,
"s": 44451,
"text": "As you can see above, an interaction depth of 1 seems to give the best results."
},
{
"code": null,
"e": 44947,
"s": 44531,
"text": "Now, let’s apply what we have learned to predict breast cancer. Many datasets about breast cancer contain information about the tumor. However, I was lucky to find a dataset that contains routine blood tests information of patients with and without breast cancer. Potentially, if we can accurately predict if a patient has cancer, that patient could receive very early treatments, even before a tumor is noticeable!"
},
{
"code": null,
"e": 45052,
"s": 44947,
"text": "Of course, the dataset and full notebook are available here, and I strongly suggest that you code along."
},
{
"code": null,
"e": 45137,
"s": 45052,
"text": "Before starting our work on Jupyter, we can gain information about the dataset here."
},
{
"code": null,
"e": 45509,
"s": 45137,
"text": "First, you notice that the dataset is very small, with only 116 instances. This poses several challenges, because the decision trees might overfit the data, or our predictive model might not be the best, due to the lack of other observations. Yet, it is a good proof-of-concept that might demonstrate a real potential of predicting breast cancer from a simple blood test."
},
{
"code": null,
"e": 45565,
"s": 45509,
"text": "The dataset contains only the following ten attributes:"
},
{
"code": null,
"e": 45600,
"s": 45565,
"text": "1. Age: age of the patient (years)"
},
{
"code": null,
"e": 45632,
"s": 45600,
"text": "2. BMI: body mass index (kg/m2)"
},
{
"code": null,
"e": 45683,
"s": 45632,
"text": "3. Glucose: glucose concentration in blood (mg/dL)"
},
{
"code": null,
"e": 45738,
"s": 45683,
"text": "4. Insulin: insulin concentration in blood (microU/mL)"
},
{
"code": null,
"e": 45830,
"s": 45738,
"text": "5. HOMA: Homeostatic Model Assessment of Insulin Resistance (glucose multiplied by insulin)"
},
{
"code": null,
"e": 45909,
"s": 45830,
"text": "6. Leptin: concentration of leptin — the hormone of energy expenditure (ng/mL)"
},
{
"code": null,
"e": 46005,
"s": 45909,
"text": "7. Adiponectin: concentration of adiponectin — a protein regulating glucose levels (micro g/mL)"
},
{
"code": null,
"e": 46091,
"s": 46005,
"text": "8. Resistin: concentration of resistin — a protein secreted by adipose tissue (ng/mL)"
},
{
"code": null,
"e": 46234,
"s": 46091,
"text": "9. MCP.1: concentration of MCP-1 — a protein that recruits monocytes to the sites of inflammation due to tissue injury or inflammation (pg/dL)"
},
{
"code": null,
"e": 46290,
"s": 46234,
"text": "10. Classification: Healthy controls (1) or patient (2)"
},
{
"code": null,
"e": 46384,
"s": 46290,
"text": "Now that we know what we will be working with, we can start by importing our usual libraries:"
},
{
"code": null,
"e": 46443,
"s": 46384,
"text": "Then, define the path to the dataset and let’s preview it:"
},
{
"code": null,
"e": 46536,
"s": 46443,
"text": "Great! Now, because this is a classification problem, let’s see if the classes are balanced:"
},
{
"code": null,
"e": 46558,
"s": 46536,
"text": "The result should be:"
},
{
"code": null,
"e": 46640,
"s": 46558,
"text": "As you can see, there is almost the same number of patients and healthy controls."
},
{
"code": null,
"e": 46914,
"s": 46640,
"text": "Now, it would be interesting to see the distribution and density of each feature for healthy people and patients. To do so, a violin plot is ideal. It shows both the density and distribution of a feature in a single plot. Let’s have nine violin plots: one for each feature:"
},
{
"code": null,
"e": 47020,
"s": 46914,
"text": "Take time to review all the plots and try to find some differences between healthy controls and patients."
},
{
"code": null,
"e": 47068,
"s": 47020,
"text": "Finally, let’s check if we have missing values:"
},
{
"code": null,
"e": 47166,
"s": 47068,
"text": "You should see that none of the columns have missing values! We are now ready to start modelling!"
},
{
"code": null,
"e": 47215,
"s": 47166,
"text": "First, we need to encode the classes to 0 and 1:"
},
{
"code": null,
"e": 47280,
"s": 47215,
"text": "Now, 0 represents a healthy control, and 1 represents a patient."
},
{
"code": null,
"e": 47337,
"s": 47280,
"text": "Then, we split the dataset into a training and test set:"
},
{
"code": null,
"e": 47590,
"s": 47337,
"text": "Before writing our models, we need to define the appropriate error metric. In this case, since it is a classification problem, we could use a confusion matrix and use the classification error. Let’s write a helper function to plot the confusion matrix:"
},
{
"code": null,
"e": 47637,
"s": 47590,
"text": "Awesome! Now, let’s implement a decision tree."
},
{
"code": null,
"e": 47701,
"s": 47637,
"text": "Using scikit-learn, a decision tree is implemented very easily:"
},
{
"code": null,
"e": 47748,
"s": 47701,
"text": "You should get the following confusion matrix:"
},
{
"code": null,
"e": 47898,
"s": 47748,
"text": "As you can see, it misclassified three instances. Therefore, let’s see if bagging, boosting or random forest can improve the performance of the tree."
},
{
"code": null,
"e": 47965,
"s": 47898,
"text": "To implement a decision tree with bagging, we write the following:"
},
{
"code": null,
"e": 48009,
"s": 47965,
"text": "And you get the following confusion matrix:"
},
{
"code": null,
"e": 48185,
"s": 48009,
"text": "Amazing! The model classified correctly all instances in the test set! For the sake of getting more practice, let’s also implement a random forest classifier and use boosting."
},
{
"code": null,
"e": 48284,
"s": 48185,
"text": "Here, for the random forest classifier, we specify the number of trees we want. Let’s go with 100:"
},
{
"code": null,
"e": 48319,
"s": 48284,
"text": "And you get this confusion matrix:"
},
{
"code": null,
"e": 48496,
"s": 48319,
"text": "Here, although only one instance was misclassified, the model in fact said that a patient was healthy, when in fact the person had cancer! This is a very undesirable situation."
},
{
"code": null,
"e": 48519,
"s": 48496,
"text": "Finally, for boosting:"
},
{
"code": null,
"e": 48545,
"s": 48519,
"text": "And we get the following:"
},
{
"code": null,
"e": 48589,
"s": 48545,
"text": "Again, only one instance was misclassified."
},
{
"code": null,
"e": 48774,
"s": 48589,
"text": "We have seen how to approach a classification problem with logistic regression, LDA, and decision trees. Now, yet another tool is introduced for classification: support vector machine."
},
{
"code": null,
"e": 49024,
"s": 48774,
"text": "The support vector machine is a generalization of a classifier called maximal margin classifier. The maximal margin classifier is simple, but it cannot be applied to the majority of datasets, since the classes must be separated by a linear boundary."
},
{
"code": null,
"e": 49181,
"s": 49024,
"text": "That is why the support vector classifier was introduced as an extension of the maximal margin classifier, which can be applied in a broader range of cases."
},
{
"code": null,
"e": 49320,
"s": 49181,
"text": "Finally, support vector machine is simply a further extension of the support vector classifier to accommodate non-linear class boundaries."
},
{
"code": null,
"e": 49381,
"s": 49320,
"text": "It can be used for both binary or multiclass classification."
},
{
"code": null,
"e": 49504,
"s": 49381,
"text": "Explaining the theory of SVMs can get very technical. Hopefully, this piece will make it easy to understand how SVMs work."
},
{
"code": null,
"e": 49565,
"s": 49504,
"text": "This method relies on separating classes using a hyperplane."
},
{
"code": null,
"e": 49587,
"s": 49565,
"text": "What is a hyperplane?"
},
{
"code": null,
"e": 49770,
"s": 49587,
"text": "In a p-dimensional space, a hyperplane is a flat affine subspace of dimension p-1. Visually, in a 2D space, the hyperplane will be a line, and in a 3D space, it will be a flat plane."
},
{
"code": null,
"e": 49812,
"s": 49770,
"text": "Mathematically, the hyperplane is simply:"
},
{
"code": null,
"e": 49944,
"s": 49812,
"text": "If X satisfies the equation above, then the point lies on the plane. Otherwise, it must be on one side of the plane as shown below."
},
{
"code": null,
"e": 50171,
"s": 49944,
"text": "In general, if the data can be perfectly separated using a hyperplane, then there is an infinite number of hyperplanes, since they can be shifted up or down, or slightly rotated without coming into contact with an observation."
},
{
"code": null,
"e": 50525,
"s": 50171,
"text": "That is why we use the maximal margin hyperplane or optimal separating hyperplane which is the separating hyperplane that is farthest from the observations. We calculate the perpendicular distance from each training observation given a hyperplane. This is known as the margin. Hence, the optimal separating hyperplane is the one with the largest margin."
},
{
"code": null,
"e": 50840,
"s": 50525,
"text": "As you can see above, there three points that are equidistant from the hyperplane. Those observations are known as support vectors, because if their position shifts, the hyperplane shifts as well. Interestingly, this means that the hyperplane depends only on the support vectors, and not on any other observations."
},
{
"code": null,
"e": 50876,
"s": 50840,
"text": "What if no separating plane exists?"
},
{
"code": null,
"e": 51196,
"s": 50876,
"text": "In this case, there is no maximal margin classifier. We use a support vector classifier that can almost separate the classes using a soft margin called support vector classifier. However, further discussing this method gets very technical, and since it is not the most ideal approach, we will skip this subject for now."
},
{
"code": null,
"e": 51456,
"s": 51196,
"text": "The support vector machine is an extension of the support vector classifier that results from enlarging the feature space using kernels. The kernel approach is simply an efficient computational approach for accommodating a non-linear boundary between classes."
},
{
"code": null,
"e": 51705,
"s": 51456,
"text": "Without going into technical details, a kernel is a function that quantifies the similarity of two observations. The kernel can be of any degree. Using a kernel with degree greater than one leads to a more flexible decision boundary as shown below."
},
{
"code": null,
"e": 51829,
"s": 51705,
"text": "To better understand how the choice of kernel can impact the SVM algorithm, let’s implement it in four different scenarios."
},
{
"code": null,
"e": 51876,
"s": 51829,
"text": "This project is divided in four mini projects."
},
{
"code": null,
"e": 52025,
"s": 51876,
"text": "The first part will show how to perform classification with a linear kernel and how the regularization parameter C impacts the resulting hyperplane."
},
{
"code": null,
"e": 52129,
"s": 52025,
"text": "Then, the second part will show how to work with a Gaussian kernel to generate a non-linear hyperplane."
},
{
"code": null,
"e": 52248,
"s": 52129,
"text": "The third part simulates overlapping classes and we will use cross-validation to find the best parameters for the SVM."
},
{
"code": null,
"e": 52309,
"s": 52248,
"text": "Finally, we perform a very simple spam classifier using SVM."
},
{
"code": null,
"e": 52528,
"s": 52309,
"text": "The exercises above were taken from Andrew Ng’ course available for free on Coursera. I simply solve them with Python, which is not recommended by the instructor. Still, I highly recommend the course for any beginners."
},
{
"code": null,
"e": 52581,
"s": 52528,
"text": "As always, the notebook and data are available here."
},
{
"code": null,
"e": 52640,
"s": 52581,
"text": "Before we get started, let’s import some useful libraries:"
},
{
"code": null,
"e": 52714,
"s": 52640,
"text": "Notice that we import loadmat here, because our data is in a matrix form."
},
{
"code": null,
"e": 52779,
"s": 52714,
"text": "Then, we store the paths to our datasets in different variables:"
},
{
"code": null,
"e": 52851,
"s": 52779,
"text": "Finally, we will build a function to help us plot each dataset quickly:"
},
{
"code": null,
"e": 52860,
"s": 52851,
"text": "Perfect!"
},
{
"code": null,
"e": 53021,
"s": 52860,
"text": "Now, in this part, we will implement a support vector machine using a linear kernel, and we will see how the regularization parameter can impact the hyperplane."
},
{
"code": null,
"e": 53063,
"s": 53021,
"text": "First, let’s load and visualize the data:"
},
{
"code": null,
"e": 53083,
"s": 53063,
"text": "And you should see:"
},
{
"code": null,
"e": 53255,
"s": 53083,
"text": "Notice in the plot above the presence of an outlier on the left side. Let’s see how the regularization parameter will impact the hyperplane when in presence of an outlier."
},
{
"code": null,
"e": 53446,
"s": 53255,
"text": "The code block above simply fits a SVM to the data, and we use the predictions to plot the hyperplane. Notice that we use a regularization parameter of 1. The result should be the following:"
},
{
"code": null,
"e": 53638,
"s": 53446,
"text": "As you can see, the hyperplane ignored the outlier. Therefore, a low regularization parameter will be generalize better. The test error will usually be higher than the cross-validation error."
},
{
"code": null,
"e": 53688,
"s": 53638,
"text": "Now, let’s increase the regularization parameter:"
},
{
"code": null,
"e": 53701,
"s": 53688,
"text": "And you get:"
},
{
"code": null,
"e": 53870,
"s": 53701,
"text": "Now, the outlier is on the right side of the hyperplane, but it also means that we are overfitting. Ultimately, this boundary would not perform well on unobserved data."
},
{
"code": null,
"e": 54022,
"s": 53870,
"text": "Now, we know that to accommodate non-linear boundaries, we need to change the kernel function. In this exercise, we will make use of a Gaussian kernel."
},
{
"code": null,
"e": 54050,
"s": 54022,
"text": "First, let’s plot our data:"
},
{
"code": null,
"e": 54070,
"s": 54050,
"text": "And you should see:"
},
{
"code": null,
"e": 54157,
"s": 54070,
"text": "Before implementing the SVM, you should know that the Gaussian kernel is expressed as:"
},
{
"code": null,
"e": 54283,
"s": 54157,
"text": "Notice that there is a parameter sigma that determines how fast the similarity metric goes to zero as they are further apart."
},
{
"code": null,
"e": 54335,
"s": 54283,
"text": "Therefore, we implement it with the following code:"
},
{
"code": null,
"e": 54380,
"s": 54335,
"text": "And you should get the following hyperplane:"
},
{
"code": null,
"e": 54575,
"s": 54380,
"text": "Amazing! The hyperplane is not a perfect boundary, but it did a pretty good job at classifying most of the data. I suggest you try different values of sigma to see how it impacts the hyperplane."
},
{
"code": null,
"e": 54720,
"s": 54575,
"text": "Cross-validation is essential to choose the best tuning parameters for optimal performance from our model. Let’s see how can apply that to SVMs."
},
{
"code": null,
"e": 54785,
"s": 54720,
"text": "Of course, let’s see what the data looks like for this exercise:"
},
{
"code": null,
"e": 54798,
"s": 54785,
"text": "And you get:"
},
{
"code": null,
"e": 54959,
"s": 54798,
"text": "Notice that we have overlapping classes. Of course, our hyperplane will not be perfect, but we will use cross-validation to make sure it is the best we can get:"
},
{
"code": null,
"e": 55127,
"s": 54959,
"text": "From the code cell above, you should get that the best regularization parameter is 1, and that sigma should be 0.1. Using these values, we can generate the hyperplane:"
},
{
"code": null,
"e": 55136,
"s": 55127,
"text": "And get:"
},
{
"code": null,
"e": 55328,
"s": 55136,
"text": "Finally, we train a spam classifier with a SVM. In this case, we will use a linear kernel. Also, we have separate datasets for training and testing, which will make our analysis a bit easier."
},
{
"code": null,
"e": 55414,
"s": 55328,
"text": "And you see that we get a training accuracy of 99.825%, and a test accuracy of 98.9%!"
},
{
"code": null,
"e": 55765,
"s": 55414,
"text": "Unsupervised learning is a set of statistical tools for scenarios in which there is only a set of features and no targets. Therefore, we cannot make predictions, since there are no associated responses to each observation. Instead, we are interested in finding an interesting way to visualize data or in discovering subgroups of similar observations."
},
{
"code": null,
"e": 56126,
"s": 55765,
"text": "Unsupervised learning tends to be more challenging, because there is no clear objective for the analysis, and it is often subjective. Additionally, it is hard to assess if the obtained results are good, since there is no accepted mechanism for performing cross-validation or validating results on an independent dataset, because we do not know the true answer."
},
{
"code": null,
"e": 56219,
"s": 56126,
"text": "Two techniques will be the focus of this guide: principal component analysis and clustering."
},
{
"code": null,
"e": 56368,
"s": 56219,
"text": "PCA refers to the process by which principal components are computed and used to better understand the data. PCA can also be used for visualization."
},
{
"code": null,
"e": 56399,
"s": 56368,
"text": "What are principal components?"
},
{
"code": null,
"e": 56652,
"s": 56399,
"text": "Suppose you want to visualize n observations with measurements on a set of p features as part of an exploratory data analysis. We could examine 2D scatter plots of 2 features at a time but would quickly get out of hand if there are a lot of predictors."
},
{
"code": null,
"e": 56891,
"s": 56652,
"text": "With PCA, we can find a low-dimensional representation of the dataset that contains as much as possible of the variation. Therefore, we only get the most interesting features, because they are responsible for the majority of the variance."
},
{
"code": null,
"e": 56931,
"s": 56891,
"text": "How are the principal components found?"
},
{
"code": null,
"e": 57046,
"s": 56931,
"text": "The first principal component is the normalized linear combination of the features that have the largest variance:"
},
{
"code": null,
"e": 57121,
"s": 57046,
"text": "The symbol phi is referred to as the loadings. The loadings must maximize:"
},
{
"code": null,
"e": 57152,
"s": 57121,
"text": "And that’s all there is to it!"
},
{
"code": null,
"e": 57627,
"s": 57152,
"text": "Clustering refers to a broad set of techniques for finding subgroups or clusters in a dataset. This helps us partition observations into distinct groups so that each group contains observations that are similar to each other. For example, in the scenario of breast cancer, the groups could represent the tumor grade. It is also very useful in marketing for market segmentation in order to identify a group of people that would be more receptive to a certain type of product."
},
{
"code": null,
"e": 58035,
"s": 57627,
"text": "There are many clustering methods, but we will focus on k-means clustering and hierarchical clustering. In k-means clustering, we wish to partition the data into a pre-specified number K of clusters. On the other hand, with hierarchical clustering, we do not know how many clusters we want. Instead, we want a dendrogram that allows us to view all the clusters obtained for each possible number of clusters."
},
{
"code": null,
"e": 58115,
"s": 58035,
"text": "This method simply separates the observations into K clusters. It assumes that:"
},
{
"code": null,
"e": 58177,
"s": 58115,
"text": "1. Each observation belongs to at least one of the K clusters"
},
{
"code": null,
"e": 58208,
"s": 58177,
"text": "2. The clusters do not overlap"
},
{
"code": null,
"e": 58265,
"s": 58208,
"text": "Furthermore, variation within each cluster is minimized."
},
{
"code": null,
"e": 58381,
"s": 58265,
"text": "This is achieved by minimizing the sum of the squared Euclidean distance between each observation within a cluster:"
},
{
"code": null,
"e": 58420,
"s": 58381,
"text": "To minimize, we follow this algorithm:"
},
{
"code": null,
"e": 58557,
"s": 58420,
"text": "1. Randomly assign a number, from 1 to K, to each of the observations. These serves as initial cluster assignments for the observations."
},
{
"code": null,
"e": 58613,
"s": 58557,
"text": "2. Iterate until the cluster assignments stop changing:"
},
{
"code": null,
"e": 58778,
"s": 58613,
"text": "2.a. For each of the K clusters, compute the cluster centroid. The kth cluster centroid is the vector of the p feature means for the observations in the kth cluster"
},
{
"code": null,
"e": 58878,
"s": 58778,
"text": "2.b. Assign each observation to the cluster whose centroid is closest (shortest Euclidean distance)"
},
{
"code": null,
"e": 59085,
"s": 58878,
"text": "Note that the algorithm above will find a local minimum. Therefore, the obtained results will depend on the initial random cluster assignment. Therefore, it is important to run the algorithm multiple times."
},
{
"code": null,
"e": 59291,
"s": 59085,
"text": "A potential disadvantage of k-means clustering is that it requires human input to specify the number of clusters. Hierarchical clustering, on the other hand, does not require an initial number of clusters."
},
{
"code": null,
"e": 59501,
"s": 59291,
"text": "The most common type of hierarchical clustering is bottom-up or agglomerative clustering. This refers to the fact that a dendrogram is generated starting from the leaves and combining clusters up to the trunk."
},
{
"code": null,
"e": 59973,
"s": 59501,
"text": "The algorithm is in fact very simple. It starts by defining a dissimilarity measure between each pair of observations, like the Euclidean distance. Then, it starts by assuming that each observation pertains to its own cluster. Then, the two most similar clusters are fused, so that there are n-1 clusters. Afterwards, other two similar clusters are fused, resulting in n-2 clusters. The process is repeated iteratively until all observations are part of a single cluster."
},
{
"code": null,
"e": 60194,
"s": 59973,
"text": "Although simple, something was not addressed. How to define a dissimilarity measure between clusters? This is achieved with the concept of linkage. The four most common types of linkage are summarized in the table below:"
},
{
"code": null,
"e": 60407,
"s": 60194,
"text": "Complete, average and centroid are the most popular types of linkage, because single linkage tends to yield unbalanced dendrograms. Note that the resulting dendrogram strongly depends on the type of linkage used."
},
{
"code": null,
"e": 60678,
"s": 60407,
"text": "Also, choosing the appropriate dissimilarity measure is crucial. Euclidean distance was discussed extensively, but there is also correlation-based distance. This considers two features to be similar if they are highly correlated, meaning that they have similar profiles."
},
{
"code": null,
"e": 61263,
"s": 60678,
"text": "For example, consider an online retailer is interested in clustering shoppers based on their past shopping histories. The goal is to identify subgroups of similar shoppers, so they can be shown advertisements that are likely to interest them. Using Euclidean distance, then shoppers who have bought few items overall will be clustered together which might not be ideal. On the other hand, using correlation-based distance, shoppers with similar preferences (they bought items A and B, but not C and D) will be clustered together, even if they have bought of different volume of items."
},
{
"code": null,
"e": 61403,
"s": 61263,
"text": "In all cases, however, we still need human input to determine the final number of clusters to use once hierarchical clustering is complete."
},
{
"code": null,
"e": 61513,
"s": 61403,
"text": "Now that you understand how PCA and clustering methods work, let’s implement them in a small project setting."
},
{
"code": null,
"e": 61655,
"s": 61513,
"text": "This part will be divided into two mini projects. In the first one, we will use k-means clustering to perform color quantization on an image."
},
{
"code": null,
"e": 61795,
"s": 61655,
"text": "Then, in the second mini project, we will use PCA to reduce the dimensionality of a dataset, allowing to us to visualize it with a 2D plot."
},
{
"code": null,
"e": 61848,
"s": 61795,
"text": "Everything you need to code along is available here."
},
{
"code": null,
"e": 61893,
"s": 61848,
"text": "Spin up your Jupyter notebook, and let’s go!"
},
{
"code": null,
"e": 61996,
"s": 61893,
"text": "Before starting on any implementation, we will import a few libraries that will become handy later on:"
},
{
"code": null,
"e": 62116,
"s": 61996,
"text": "Unlike previous tutorials, we will not import datasets. Instead, we will use data provided by the scikit-learn library."
},
{
"code": null,
"e": 62302,
"s": 62116,
"text": "Quickly, color quantization is technique to reduce the number of distinct colors used in an image. This is especially useful to compress images while keeping the integrity of the image."
},
{
"code": null,
"e": 62353,
"s": 62302,
"text": "To get started, we import the following libraries:"
},
{
"code": null,
"e": 62506,
"s": 62353,
"text": "Notice that we import a sample dataset called load_sample_image. This simply contains two images. We will use one of them to perform color quantization."
},
{
"code": null,
"e": 62562,
"s": 62506,
"text": "So, let’s show the image we will use for this exercise:"
},
{
"code": null,
"e": 62582,
"s": 62562,
"text": "And you should see:"
},
{
"code": null,
"e": 62645,
"s": 62582,
"text": "Now, for color quantization, different steps must be followed."
},
{
"code": null,
"e": 62715,
"s": 62645,
"text": "First, we need to change the image into a 2D matrix for manipulation:"
},
{
"code": null,
"e": 62810,
"s": 62715,
"text": "Then, we train our model to aggregate colors in order to have 64 distinct colors in the image:"
},
{
"code": null,
"e": 62913,
"s": 62810,
"text": "Then, we build a helper function to help us reconstruct the image with the number of specified colors:"
},
{
"code": null,
"e": 63025,
"s": 62913,
"text": "Finally, we can now visualize how the image looks with only 64 colors, and how it compares to the original one:"
},
{
"code": null,
"e": 63220,
"s": 63025,
"text": "Of course, we can see some differences, but overall, the integrity of the image is conserved! Do explore different number of clusters! For example, here is what you get if you specify 10 colors:"
},
{
"code": null,
"e": 63324,
"s": 63220,
"text": "For this exercise, we will use PCA to reduce the dimensions of a dataset so we can easily visualize it."
},
{
"code": null,
"e": 63384,
"s": 63324,
"text": "Therefore, let’s import the iris dataset from scikit-learn:"
},
{
"code": null,
"e": 63506,
"s": 63384,
"text": "Now, we will compute the first two principal components and see what proportion of the variance can be explained by each:"
},
{
"code": null,
"e": 63770,
"s": 63506,
"text": "From the above code block, you should see that the first principal component contains 92% of the variance, while the second accounts for 5% of the variance. Therefore, this means that only two features are sufficient to explain 97% of the variance in the dataset!"
},
{
"code": null,
"e": 63834,
"s": 63770,
"text": "Now, we can use this to easily plot the data in two dimensions:"
},
{
"code": null,
"e": 63847,
"s": 63834,
"text": "And you get:"
},
{
"code": null,
"e": 63993,
"s": 63847,
"text": "As you can see, PCA was useful to reduce the dimensionality of the dataset, allowing us to plot it, and visualize how each category is separated."
},
{
"code": null,
"e": 64345,
"s": 63993,
"text": "Whether we wish to predict the trend in financial markets or electricity consumption, time is an important factor that must now be considered in our models. For example, it would be interesting to forecast at what hour during the day is there going to be a peak consumption in electricity, such as to adjust the price or the production of electricity."
},
{
"code": null,
"e": 64545,
"s": 64345,
"text": "Enter time series. A time series is simply a series of data points ordered in time. In a time series, time is often the independent variable and the goal is usually to make a forecast for the future."
},
{
"code": null,
"e": 64629,
"s": 64545,
"text": "However, there are other aspects that come into play when dealing with time series."
},
{
"code": null,
"e": 64647,
"s": 64629,
"text": "Is it stationary?"
},
{
"code": null,
"e": 64671,
"s": 64647,
"text": "Is there a seasonality?"
},
{
"code": null,
"e": 64710,
"s": 64671,
"text": "Is the target variable autocorrelated?"
},
{
"code": null,
"e": 64821,
"s": 64710,
"text": "Informally, autocorrelation is the similarity between observations as a function of the time lag between them."
},
{
"code": null,
"e": 65108,
"s": 64821,
"text": "Above is an example of an autocorrelation plot. Looking closely, you realize that the first value and the 24th value have a high autocorrelation. Similarly, the 12th and 36th observations are highly correlated. This means that we will find a very similar value at every 24 unit of time."
},
{
"code": null,
"e": 65282,
"s": 65108,
"text": "Notice how the plot looks like sinusoidal function. This is a hint for seasonality, and you can find its value by finding the period in the plot above, which would give 24h."
},
{
"code": null,
"e": 65478,
"s": 65282,
"text": "Seasonality refers to periodic fluctuations. For example, electricity consumption is high during the day and low during night, or online sales increase during Christmas before slowing down again."
},
{
"code": null,
"e": 65648,
"s": 65478,
"text": "As you can see above, there is a clear daily seasonality. Every day, you see a peak towards the evening, and the lowest points are the beginning and the end of each day."
},
{
"code": null,
"e": 65819,
"s": 65648,
"text": "Remember that seasonality can also be derived from an autocorrelation plot if it has a sinusoidal shape. Simply look at the period, and it gives the length of the season."
},
{
"code": null,
"e": 66063,
"s": 65819,
"text": "Stationarity is an important characteristic of time series. A time series is said to be stationary if its statistical properties do not change over time. In other words, it has constant mean and variance, and covariance is independent of time."
},
{
"code": null,
"e": 66185,
"s": 66063,
"text": "Looking again at the same plot, we see that the process above is stationary. The mean and variance do not vary over time."
},
{
"code": null,
"e": 66351,
"s": 66185,
"text": "Often, stock prices are not a stationary process, since we might see a growing trend, or its volatility might increase over time (meaning that variance is changing)."
},
{
"code": null,
"e": 66526,
"s": 66351,
"text": "Ideally, we want to have a stationary time series for modelling. Of course, not all of them are stationary, but we can make different transformations to make them stationary."
},
{
"code": null,
"e": 66686,
"s": 66526,
"text": "You may have noticed in the title of the plot above Dickey-Fuller. This is the statistical test that we run to determine if a time series is stationary or not."
},
{
"code": null,
"e": 66808,
"s": 66686,
"text": "Without going into the technicalities of the Dickey-Fuller test, it test the null hypothesis that a unit root is present."
},
{
"code": null,
"e": 66865,
"s": 66808,
"text": "If it is, then p > 0, and the process is not stationary."
},
{
"code": null,
"e": 66964,
"s": 66865,
"text": "Otherwise, p = 0, the null hypothesis is rejected, and the process is considered to be stationary."
},
{
"code": null,
"e": 67066,
"s": 66964,
"text": "As an example, the process below is not stationary. Notice how the mean is not constant through time."
},
{
"code": null,
"e": 67161,
"s": 67066,
"text": "There are many ways to model a time series in order to make predictions. Here, I will present:"
},
{
"code": null,
"e": 67176,
"s": 67161,
"text": "moving average"
},
{
"code": null,
"e": 67198,
"s": 67176,
"text": "exponential smoothing"
},
{
"code": null,
"e": 67204,
"s": 67198,
"text": "ARIMA"
},
{
"code": null,
"e": 67380,
"s": 67204,
"text": "The moving average model is probably the most naive approach to time series modelling. This model simply states that the next observation is the mean of all past observations."
},
{
"code": null,
"e": 67476,
"s": 67380,
"text": "Although simple, this model might be surprisingly good and it represents a good starting point."
},
{
"code": null,
"e": 67678,
"s": 67476,
"text": "Otherwise, the moving average can be used to identify interesting trends in the data. We can define a window to apply the moving average model to smooth the time series, and highlight different trends."
},
{
"code": null,
"e": 67846,
"s": 67678,
"text": "In the plot above, we applied the moving average model to a 24h window. The green line smoothed the time series, and we can see that there are 2 peaks in a 24h period."
},
{
"code": null,
"e": 67971,
"s": 67846,
"text": "Of course, the longer the window, the smoother the trend will be. Below is an example of moving average on a smaller window."
},
{
"code": null,
"e": 68206,
"s": 67971,
"text": "Exponential smoothing uses a similar logic to moving average, but this time, a different decreasing weight is assigned to each observations. In other words, less importance is given to observations as we move further from the present."
},
{
"code": null,
"e": 68261,
"s": 68206,
"text": "Mathematically, exponential smoothing is expressed as:"
},
{
"code": null,
"e": 68401,
"s": 68261,
"text": "Here, alpha is a smoothing factor that takes values between 0 and 1. It determines how fast the weight decreases for previous observations."
},
{
"code": null,
"e": 68585,
"s": 68401,
"text": "From the plot above, the dark blue line represents the exponential smoothing of the time series using a smoothing factor of 0.3, while the orange line uses a smoothing factor of 0.05."
},
{
"code": null,
"e": 68775,
"s": 68585,
"text": "As you can see, the smaller the smoothing factor, the smoother the time series will be. This makes sense, because as the smoothing factor approaches 0, we approach the moving average model."
},
{
"code": null,
"e": 68955,
"s": 68775,
"text": "Double exponential smoothing is used when there is a trend in the time series. In that case, we use this technique, which is simply a recursive use of exponential smoothing twice."
},
{
"code": null,
"e": 68971,
"s": 68955,
"text": "Mathematically:"
},
{
"code": null,
"e": 69050,
"s": 68971,
"text": "Here, beta is the trend smoothing factor, and it takes values between 0 and 1."
},
{
"code": null,
"e": 69145,
"s": 69050,
"text": "Below, you can see how different values of alpha and beta affect the shape of the time series."
},
{
"code": null,
"e": 69307,
"s": 69145,
"text": "This method extends double exponential smoothing, by adding a seasonal smoothing factor. Of course, this is useful if you notice seasonality in your time series."
},
{
"code": null,
"e": 69369,
"s": 69307,
"text": "Mathematically, triple exponential smoothing is expressed as:"
},
{
"code": null,
"e": 69449,
"s": 69369,
"text": "Where gamma is the seasonal smoothing factor and L is the length of the season."
},
{
"code": null,
"e": 69607,
"s": 69449,
"text": "SARIMA is actually the combination of simpler models to make a complex model that can model time series exhibiting non-stationary properties and seasonality."
},
{
"code": null,
"e": 69982,
"s": 69607,
"text": "At first, we have the autoregression model AR(p). This is basically a regression of the time series onto itself. Here, we assume that the current value depends on its previous values with some lag. It takes a parameter p which represents the maximum lag. To find it, we look at the partial autocorrelation plot and identify the lag after which most lags are not significant."
},
{
"code": null,
"e": 70018,
"s": 69982,
"text": "In the example below, p would be 4."
},
{
"code": null,
"e": 70193,
"s": 70018,
"text": "Then, we add the moving average model MA(q). This takes a parameter q which represents the biggest lag after which other lags are not significant on the autocorrelation plot."
},
{
"code": null,
"e": 70214,
"s": 70193,
"text": "Below, q would be 4."
},
{
"code": null,
"e": 70352,
"s": 70214,
"text": "After, we add the order of integration I(d). The parameter d represents the number of differences required to make the series stationary."
},
{
"code": null,
"e": 70713,
"s": 70352,
"text": "Finally, we add the final component: seasonality S(P, D, Q, s), where s is simply the season’s length. Furthermore, this component requires the parameters P and Q which are the same as p and q, but for the seasonal component. Finally, D is the order of seasonal integration representing the number of differences required to remove seasonality from the series."
},
{
"code": null,
"e": 70774,
"s": 70713,
"text": "Combining all, we get the SARIMA(p, d, q)(P, D, Q, s) model."
},
{
"code": null,
"e": 70931,
"s": 70774,
"text": "The main takeaway is: before modelling with SARIMA, we must apply transformations to our time series to remove seasonality and any non-stationary behaviors."
},
{
"code": null,
"e": 71145,
"s": 70931,
"text": "We will try to predict the stock price of a specific company. Now, predicting the stock price is virtually impossible. However, it remains a fun exercise and it will be a good way to practice what we have learned."
},
{
"code": null,
"e": 71280,
"s": 71145,
"text": "We will use the historical stock price of the New Germany Fund (GF) to try to predict the closing price in the next five trading days."
},
{
"code": null,
"e": 71324,
"s": 71280,
"text": "You can grab the dataset and notebook here."
},
{
"code": null,
"e": 71405,
"s": 71324,
"text": "As always, I highly recommend you code along! Start your notebook, and let’s go!"
},
{
"code": null,
"e": 71575,
"s": 71405,
"text": "First, we import some libraries that will be helpful throughout our analysis. Also, we define the mean average percentage error (MAPE), as this will be our error metric."
},
{
"code": null,
"e": 71745,
"s": 71575,
"text": "First, we import some libraries that will be helpful throughout our analysis. Also, we define the mean average percentage error (MAPE), as this will be our error metric."
},
{
"code": null,
"e": 71831,
"s": 71745,
"text": "Then, we import our dataset and we previous the first ten entries, and you should get"
},
{
"code": null,
"e": 72033,
"s": 71831,
"text": "As you can see, we have a few entries concerning a different stock than the New Germany Fund (GF). Also, we have an entry concerning intraday information, but we only want end of day (EOD) information."
},
{
"code": null,
"e": 72068,
"s": 72033,
"text": "First, we remove unwanted entries."
},
{
"code": null,
"e": 72159,
"s": 72068,
"text": "Then, we remove unwanted columns, as we solely want to focus on the stock’s closing price."
},
{
"code": null,
"e": 72203,
"s": 72159,
"text": "If you preview the dataset, you should see:"
},
{
"code": null,
"e": 72256,
"s": 72203,
"text": "Awesome! We are ready for exploratory data analysis!"
},
{
"code": null,
"e": 72326,
"s": 72256,
"text": "We plot the closing price over the entire time period of our dataset."
},
{
"code": null,
"e": 72342,
"s": 72326,
"text": "You should get:"
},
{
"code": null,
"e": 72459,
"s": 72342,
"text": "Clearly, you see that this is not a stationary process, and it is hard to tell if there is some kind of seasonality."
},
{
"code": null,
"e": 72671,
"s": 72459,
"text": "Let’s use the moving average model to smooth our time series. For that, we will use a helper function that will run the moving average model on a specified time window and it will plot the result smoothed curve:"
},
{
"code": null,
"e": 72710,
"s": 72671,
"text": "Using a time window of 5 days, we get:"
},
{
"code": null,
"e": 72873,
"s": 72710,
"text": "As you can see, we can hardly see a trend, because it is too close to actual curve. Let’s see the result of smoothing by the previous month, and previous quarter."
},
{
"code": null,
"e": 73052,
"s": 72873,
"text": "Trends are easier to spot now. Notice how the 30-day and 90-day trend show a downward curve at the end. This might mean that the stock is likely to go down in the following days."
},
{
"code": null,
"e": 73130,
"s": 73052,
"text": "Now, let’s use exponential smoothing to see if it can pick up a better trend."
},
{
"code": null,
"e": 73250,
"s": 73130,
"text": "Here, we use 0.05 and 0.3 as values for the smoothing factor. Feel free to try other values and see what the result is."
},
{
"code": null,
"e": 73365,
"s": 73250,
"text": "As you can see, an alpha value of 0.05 smoothed the curve while picking up most of the upward and downward trends."
},
{
"code": null,
"e": 73410,
"s": 73365,
"text": "Now, let’s use double exponential smoothing."
},
{
"code": null,
"e": 73423,
"s": 73410,
"text": "And you get:"
},
{
"code": null,
"e": 73514,
"s": 73423,
"text": "Again, experiment with different alpha and beta combinations to get better looking curves."
},
{
"code": null,
"e": 73694,
"s": 73514,
"text": "As outlined previously, we must turn our series into a stationary process in order to model it. Therefore, let’s apply the Dickey-Fuller test to see if it is a stationary process:"
},
{
"code": null,
"e": 73710,
"s": 73694,
"text": "You should see:"
},
{
"code": null,
"e": 73908,
"s": 73710,
"text": "By the Dickey-Fuller test, the time series is unsurprisingly non-stationary. Also, looking at the autocorrelation plot, we see that it is very high, and it seems that there is no clear seasonality."
},
{
"code": null,
"e": 74137,
"s": 73908,
"text": "Therefore, to get rid of the high autocorrelation and to make the process stationary, let’s take the first difference (line 23 in the code block). We simply subtract the time series from itself with a lag of one day, and we get:"
},
{
"code": null,
"e": 74203,
"s": 74137,
"text": "Awesome! Our series is now stationary and we can start modelling!"
},
{
"code": null,
"e": 74368,
"s": 74203,
"text": "Now, for SARIMA, we first define a few parameters and a range of values for other parameters to generate a list of all possible combinations of p, q, d, P, Q, D, s."
},
{
"code": null,
"e": 74596,
"s": 74368,
"text": "Now, in the code cell above, we have 625 different combinations! We will try each combination and train SARIMA with each so to find the best performing model. This might take while depending on your computer’s processing power."
},
{
"code": null,
"e": 74677,
"s": 74596,
"text": "Once this is done, we print out a summary of the best model, and you should see:"
},
{
"code": null,
"e": 74789,
"s": 74677,
"text": "Awesome! We finally predict the closing price of the next five trading days and evaluate the MAPE of the model."
},
{
"code": null,
"e": 74848,
"s": 74789,
"text": "In this case, we have a MAPE of 0.79%, which is very good!"
},
{
"code": null,
"e": 74963,
"s": 74848,
"text": "Now, to compare our prediction with actual data, we take financial data from Yahoo Finance and create a dataframe."
},
{
"code": null,
"e": 75039,
"s": 74963,
"text": "Then, we make a plot to see how far we were from the actual closing prices:"
},
{
"code": null,
"e": 75196,
"s": 75039,
"text": "It seems that we are a bit off in our predictions. In fact, the predicted price is essentially flat, meaning that our model is probably not performing well."
},
{
"code": null,
"e": 75308,
"s": 75196,
"text": "Again, this is not due to our procedure, but to the fact that predicting stock prices is essentially impossible"
},
{
"code": null,
"e": 75457,
"s": 75308,
"text": "An Introduction to Statistical Learning — Gareth James et al.Machine Learning — Andrew NgOpen Machine Learning Course: Time Series — Dmitriy Sergeev"
},
{
"code": null,
"e": 75519,
"s": 75457,
"text": "An Introduction to Statistical Learning — Gareth James et al."
},
{
"code": null,
"e": 75548,
"s": 75519,
"text": "Machine Learning — Andrew Ng"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.