title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
JavaScript | Callbacks
|
17 Jul, 2018
Callbacks are a great way to handle something after something else has been completed. By something here we mean a function execution. If we want to execute a function right after the return of some other function, then callbacks can be used.
JavaScript functions have the type of Objects. So, much like any other objects (String, Arrays etc.), They can be passed as an argument to any other function while calling.
<script> // add() function is called with arguments a, b // and callback, callback will be executed just // after ending of add() function function add(a, b , callback){ document.write(`The sum of ${a} and ${b} is ${a+b}.` +"<br>"); callback(); } // disp() function is called just // after the ending of add() function function disp(){ document.write('This must be printed after addition'); } // Calling add() function add(5,6,disp); </script>
Output:
The sum of 5 and 6 is 11.
This must be printed after addition
Explanation:Here are the two functions – add(a, b, callback) and disp(). Here add() is called with the disp() function i.e. passed in as the third argument to the add function along with two numbers.
As a result, the add() is invoked with 1, 2 and the disp() which is the callback. The add() prints the addition of the two numbers and as soon as that is done, the callback function is fired! Consequently, we see whatever is inside the disp() as the output below the addition output.
Code #2:An alternate way to implement above code is shown below with anonymous functions being passed.
<script> // add() function is called with arguments a, b // and callback, callback will be executed just // after ending of add() function function add(a, b , callback){ document.write(`The sum of ${a} and ${b} is ${a+b}.` +"<br>"); callback(); } // add() function is called with arguments given below add(5,6,function disp(){ document.write('This must be printed after addition.'); }); </script>
Output:
The sum of 5 and 6 is 11.
This must be printed after addition.
Callbacks are primarily used while handling asynchronous operations like – making an API request to the Google Maps, fetching/writing some data from/into a file, registering event listeners and related stuff. All the operations mentioned uses callbacks. This way once the data/error from the asynchronous operation is returned, the callbacks are used to do something with that inside our code.
javascript-basics
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Jul, 2018"
},
{
"code": null,
"e": 295,
"s": 52,
"text": "Callbacks are a great way to handle something after something else has been completed. By something here we mean a function execution. If we want to execute a function right after the return of some other function, then callbacks can be used."
},
{
"code": null,
"e": 468,
"s": 295,
"text": "JavaScript functions have the type of Objects. So, much like any other objects (String, Arrays etc.), They can be passed as an argument to any other function while calling."
},
{
"code": "<script> // add() function is called with arguments a, b // and callback, callback will be executed just // after ending of add() function function add(a, b , callback){ document.write(`The sum of ${a} and ${b} is ${a+b}.` +\"<br>\"); callback(); } // disp() function is called just // after the ending of add() function function disp(){ document.write('This must be printed after addition'); } // Calling add() function add(5,6,disp); </script>",
"e": 962,
"s": 468,
"text": null
},
{
"code": null,
"e": 970,
"s": 962,
"text": "Output:"
},
{
"code": null,
"e": 1032,
"s": 970,
"text": "The sum of 5 and 6 is 11.\nThis must be printed after addition"
},
{
"code": null,
"e": 1232,
"s": 1032,
"text": "Explanation:Here are the two functions – add(a, b, callback) and disp(). Here add() is called with the disp() function i.e. passed in as the third argument to the add function along with two numbers."
},
{
"code": null,
"e": 1516,
"s": 1232,
"text": "As a result, the add() is invoked with 1, 2 and the disp() which is the callback. The add() prints the addition of the two numbers and as soon as that is done, the callback function is fired! Consequently, we see whatever is inside the disp() as the output below the addition output."
},
{
"code": null,
"e": 1619,
"s": 1516,
"text": "Code #2:An alternate way to implement above code is shown below with anonymous functions being passed."
},
{
"code": "<script> // add() function is called with arguments a, b // and callback, callback will be executed just // after ending of add() function function add(a, b , callback){ document.write(`The sum of ${a} and ${b} is ${a+b}.` +\"<br>\"); callback(); } // add() function is called with arguments given below add(5,6,function disp(){ document.write('This must be printed after addition.'); }); </script>",
"e": 2048,
"s": 1619,
"text": null
},
{
"code": null,
"e": 2056,
"s": 2048,
"text": "Output:"
},
{
"code": null,
"e": 2119,
"s": 2056,
"text": "The sum of 5 and 6 is 11.\nThis must be printed after addition."
},
{
"code": null,
"e": 2513,
"s": 2119,
"text": "Callbacks are primarily used while handling asynchronous operations like – making an API request to the Google Maps, fetching/writing some data from/into a file, registering event listeners and related stuff. All the operations mentioned uses callbacks. This way once the data/error from the asynchronous operation is returned, the callbacks are used to do something with that inside our code."
},
{
"code": null,
"e": 2531,
"s": 2513,
"text": "javascript-basics"
},
{
"code": null,
"e": 2542,
"s": 2531,
"text": "JavaScript"
}
] |
Python List append() Method
|
04 Aug, 2021
The Python List append() method is used for appending and adding elements to the end of the List.
Syntax: list.append(item)
Parameters:
item: an item to be added at the end of the list
Returns:
The method doesn’t return any value
Python
# my_listmy_list = ['geeks', 'for'] # Add 'geeks' to the listmy_list.append('geeks') print my_list
Output:
['geeks', 'for', 'geeks']
Python
# my_listmy_list = ['geeks', 'for', 'geeks'] # another listanother_list = [6, 0, 4, 1] # append another_list to my_listmy_list.append(another_list) print my_list
Output:
['geeks', 'for', 'geeks', [6, 0, 4, 1]]
Note: A list is an object. If you append another list onto a list, the parameter list will be a single object at the end of the list.
python-list
python-list-functions
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Aug, 2021"
},
{
"code": null,
"e": 151,
"s": 52,
"text": "The Python List append() method is used for appending and adding elements to the end of the List. "
},
{
"code": null,
"e": 177,
"s": 151,
"text": "Syntax: list.append(item)"
},
{
"code": null,
"e": 189,
"s": 177,
"text": "Parameters:"
},
{
"code": null,
"e": 238,
"s": 189,
"text": "item: an item to be added at the end of the list"
},
{
"code": null,
"e": 247,
"s": 238,
"text": "Returns:"
},
{
"code": null,
"e": 284,
"s": 247,
"text": "The method doesn’t return any value "
},
{
"code": null,
"e": 291,
"s": 284,
"text": "Python"
},
{
"code": "# my_listmy_list = ['geeks', 'for'] # Add 'geeks' to the listmy_list.append('geeks') print my_list",
"e": 392,
"s": 291,
"text": null
},
{
"code": null,
"e": 400,
"s": 392,
"text": "Output:"
},
{
"code": null,
"e": 426,
"s": 400,
"text": "['geeks', 'for', 'geeks']"
},
{
"code": null,
"e": 433,
"s": 426,
"text": "Python"
},
{
"code": "# my_listmy_list = ['geeks', 'for', 'geeks'] # another listanother_list = [6, 0, 4, 1] # append another_list to my_listmy_list.append(another_list) print my_list",
"e": 598,
"s": 433,
"text": null
},
{
"code": null,
"e": 606,
"s": 598,
"text": "Output:"
},
{
"code": null,
"e": 646,
"s": 606,
"text": "['geeks', 'for', 'geeks', [6, 0, 4, 1]]"
},
{
"code": null,
"e": 780,
"s": 646,
"text": "Note: A list is an object. If you append another list onto a list, the parameter list will be a single object at the end of the list."
},
{
"code": null,
"e": 792,
"s": 780,
"text": "python-list"
},
{
"code": null,
"e": 814,
"s": 792,
"text": "python-list-functions"
},
{
"code": null,
"e": 821,
"s": 814,
"text": "Python"
},
{
"code": null,
"e": 833,
"s": 821,
"text": "python-list"
}
] |
How to Make TextView and EditText Selectable in Android?
|
21 Apr, 2021
In this article, we are going to implement a very important feature related to TextView. While using any social media app or like using Facebook you may have seen there is a particular type of TextView which you cannot copy like a caption that people write on their posts. You can select the message but there few texts which cannot select or copy. So here we are going to learn how to implement that feature.
Step 1: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="20dp" android:gravity="center" android:orientation="vertical" tools:context=".SelectText"> <TextView android:id="@+id/select" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Geeks For Geeks " android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:textSize="30dp" /> </LinearLayout>
Step 2: Working with the MainActivity.java file
This is something that enables our text to be get selected and then we can copy that text
select.setTextIsSelectable(true);
This disables our text to be get selected or even by default it is set as false. Hence you cannot select a text in default mode
select.setTextIsSelectable(false);
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file.
Java
import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat;import androidx.core.content.ContextCompat; import android.Manifest;import android.content.pm.PackageManager;import android.os.Bundle;import android.telephony.SmsManager;import android.view.View;import android.widget.Button;import android.widget.CheckBox;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast; import org.w3c.dom.Text; public class SelectText extends AppCompatActivity { TextView select; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_text); select = findViewById(R.id.select); select.setTextIsSelectable(true); }}
Make Changes in the XML file. Add this line in your TextView.
android:textIsSelectable="true"
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="20dp" android:gravity="center" android:orientation="vertical" tools:context=".SelectText"> <TextView android:id="@+id/select" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textIsSelectable="true" android:text="Geeks For Geeks " android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:textSize="30dp" /> </LinearLayout>
Output:
Step 1: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. We will create a simple EditText.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="20dp" android:gravity="center" android:orientation="vertical" tools:context=".SelectText"> <EditText android:id="@+id/selecte" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:cursorVisible="false" android:textSize="30dp" /> </LinearLayout>
Step 2: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. In EditText By default, we can select text. Here firstly we will hide the cursor in the layout.xml file
android:cursorVisible="false"
And added an eventlistener for long click and display the cursor only when a selection starts.
selecte.setCursorVisible(true);
Java
import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat;import androidx.core.content.ContextCompat; import android.Manifest;import android.content.pm.PackageManager;import android.os.Bundle;import android.telephony.SmsManager;import android.view.View;import android.widget.Button;import android.widget.CheckBox;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast; import org.w3c.dom.Text; public class SelectText extends AppCompatActivity { EditText selecte; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_text); selecte = findViewById(R.id.selecte); selecte.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { selecte.setCursorVisible(true); Toast.makeText(SelectText.this,"Visible",Toast.LENGTH_LONG).show(); return false; } }); }}
Output:
Android-View
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 438,
"s": 28,
"text": "In this article, we are going to implement a very important feature related to TextView. While using any social media app or like using Facebook you may have seen there is a particular type of TextView which you cannot copy like a caption that people write on their posts. You can select the message but there few texts which cannot select or copy. So here we are going to learn how to implement that feature."
},
{
"code": null,
"e": 486,
"s": 438,
"text": "Step 1: Working with the activity_main.xml file"
},
{
"code": null,
"e": 629,
"s": 486,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 633,
"s": 629,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:padding=\"20dp\" android:gravity=\"center\" android:orientation=\"vertical\" tools:context=\".SelectText\"> <TextView android:id=\"@+id/select\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Geeks For Geeks \" android:layout_alignParentTop=\"true\" android:layout_centerHorizontal=\"true\" android:textSize=\"30dp\" /> </LinearLayout>",
"e": 1314,
"s": 633,
"text": null
},
{
"code": null,
"e": 1362,
"s": 1314,
"text": "Step 2: Working with the MainActivity.java file"
},
{
"code": null,
"e": 1452,
"s": 1362,
"text": "This is something that enables our text to be get selected and then we can copy that text"
},
{
"code": null,
"e": 1486,
"s": 1452,
"text": "select.setTextIsSelectable(true);"
},
{
"code": null,
"e": 1614,
"s": 1486,
"text": "This disables our text to be get selected or even by default it is set as false. Hence you cannot select a text in default mode"
},
{
"code": null,
"e": 1649,
"s": 1614,
"text": "select.setTextIsSelectable(false);"
},
{
"code": null,
"e": 1766,
"s": 1649,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. "
},
{
"code": null,
"e": 1771,
"s": 1766,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat;import androidx.core.content.ContextCompat; import android.Manifest;import android.content.pm.PackageManager;import android.os.Bundle;import android.telephony.SmsManager;import android.view.View;import android.widget.Button;import android.widget.CheckBox;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast; import org.w3c.dom.Text; public class SelectText extends AppCompatActivity { TextView select; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_text); select = findViewById(R.id.select); select.setTextIsSelectable(true); }}",
"e": 2577,
"s": 1771,
"text": null
},
{
"code": null,
"e": 2639,
"s": 2577,
"text": "Make Changes in the XML file. Add this line in your TextView."
},
{
"code": null,
"e": 2671,
"s": 2639,
"text": "android:textIsSelectable=\"true\""
},
{
"code": null,
"e": 2675,
"s": 2671,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:padding=\"20dp\" android:gravity=\"center\" android:orientation=\"vertical\" tools:context=\".SelectText\"> <TextView android:id=\"@+id/select\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textIsSelectable=\"true\" android:text=\"Geeks For Geeks \" android:layout_alignParentTop=\"true\" android:layout_centerHorizontal=\"true\" android:textSize=\"30dp\" /> </LinearLayout>",
"e": 3392,
"s": 2675,
"text": null
},
{
"code": null,
"e": 3400,
"s": 3392,
"text": "Output:"
},
{
"code": null,
"e": 3448,
"s": 3400,
"text": "Step 1: Working with the activity_main.xml file"
},
{
"code": null,
"e": 3625,
"s": 3448,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. We will create a simple EditText. "
},
{
"code": null,
"e": 3629,
"s": 3625,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:padding=\"20dp\" android:gravity=\"center\" android:orientation=\"vertical\" tools:context=\".SelectText\"> <EditText android:id=\"@+id/selecte\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_alignParentTop=\"true\" android:layout_centerHorizontal=\"true\" android:cursorVisible=\"false\" android:textSize=\"30dp\" /> </LinearLayout>",
"e": 4306,
"s": 3629,
"text": null
},
{
"code": null,
"e": 4354,
"s": 4306,
"text": "Step 2: Working with the MainActivity.java file"
},
{
"code": null,
"e": 4575,
"s": 4354,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. In EditText By default, we can select text. Here firstly we will hide the cursor in the layout.xml file "
},
{
"code": null,
"e": 4605,
"s": 4575,
"text": "android:cursorVisible=\"false\""
},
{
"code": null,
"e": 4700,
"s": 4605,
"text": "And added an eventlistener for long click and display the cursor only when a selection starts."
},
{
"code": null,
"e": 4732,
"s": 4700,
"text": "selecte.setCursorVisible(true);"
},
{
"code": null,
"e": 4737,
"s": 4732,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat;import androidx.core.content.ContextCompat; import android.Manifest;import android.content.pm.PackageManager;import android.os.Bundle;import android.telephony.SmsManager;import android.view.View;import android.widget.Button;import android.widget.CheckBox;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast; import org.w3c.dom.Text; public class SelectText extends AppCompatActivity { EditText selecte; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_text); selecte = findViewById(R.id.selecte); selecte.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { selecte.setCursorVisible(true); Toast.makeText(SelectText.this,\"Visible\",Toast.LENGTH_LONG).show(); return false; } }); }}",
"e": 5825,
"s": 4737,
"text": null
},
{
"code": null,
"e": 5833,
"s": 5825,
"text": "Output:"
},
{
"code": null,
"e": 5846,
"s": 5833,
"text": "Android-View"
},
{
"code": null,
"e": 5854,
"s": 5846,
"text": "Android"
},
{
"code": null,
"e": 5859,
"s": 5854,
"text": "Java"
},
{
"code": null,
"e": 5864,
"s": 5859,
"text": "Java"
},
{
"code": null,
"e": 5872,
"s": 5864,
"text": "Android"
}
] |
JP Morgan Archives - GeeksforGeeks
|
JP Morgan Chase Interview Questions
JP Morgan Chase & Co. (JPMC) Interview Experience | (Full time Software Engineer)
JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021
JP Morgan Chase - Code for Good Interview Experience for Software Engineer FTE
JP Morgan Interview Experience for Quantitative Researcher | On-Campus 2022
Convert given Array of Strings to a Camel Case format sentence
JPMorgan Chase - Code for Good Interview Experience for Software Engineer FTE
JP Morgan Interview experience | SDET Role for Experienced
JP Morgan Code for Good Internship Interview Experience 2021
JP Morgan Chase Interview Experience for Software Engineer 2021
|
[
{
"code": null,
"e": 24166,
"s": 24130,
"text": "JP Morgan Chase Interview Questions"
},
{
"code": null,
"e": 24248,
"s": 24166,
"text": "JP Morgan Chase & Co. (JPMC) Interview Experience | (Full time Software Engineer)"
},
{
"code": null,
"e": 24320,
"s": 24248,
"text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021"
},
{
"code": null,
"e": 24399,
"s": 24320,
"text": "JP Morgan Chase - Code for Good Interview Experience for Software Engineer FTE"
},
{
"code": null,
"e": 24475,
"s": 24399,
"text": "JP Morgan Interview Experience for Quantitative Researcher | On-Campus 2022"
},
{
"code": null,
"e": 24538,
"s": 24475,
"text": "Convert given Array of Strings to a Camel Case format sentence"
},
{
"code": null,
"e": 24616,
"s": 24538,
"text": "JPMorgan Chase - Code for Good Interview Experience for Software Engineer FTE"
},
{
"code": null,
"e": 24675,
"s": 24616,
"text": "JP Morgan Interview experience | SDET Role for Experienced"
},
{
"code": null,
"e": 24736,
"s": 24675,
"text": "JP Morgan Code for Good Internship Interview Experience 2021"
}
] |
How to create a REST API using Java Spring Boot
|
01 Jun, 2020
Representational state transfer (REST) is a software architectural style that defines a set of constraints to be used for creating Web services. Web services that conform to the REST architectural style, called RESTful Web services, provide interoperability between computer systems on the Internet. RESTful Web services allow the requesting systems to access and manipulate textual representations of Web resources by using a uniform and predefined set of stateless operations. Other kinds of Web services, such as SOAP Web services, expose their own arbitrary sets of operations.
In this article, we will understand how to create a rest API using spring boot.
Spring is widely used for creating scalable applications. For web applications, Spring provides Spring MVC which is a widely used module of spring which is used to create scalable web applications. But the main disadvantage of spring projects is that configuration is really time-consuming and can be a bit overwhelming for the new developers. The solution to this is Spring Boot. Spring Boot is built on the top of the spring and contains all the features of spring. In this article, we will create a REST API to add employees to the employee list and get the list of employees. In order to do this, we first have to create a simple Spring Boot project in any of the IDE’s and follow the steps:
Initially, we need to define the employee entity. Therefore, the following employee class is defined:package com.example.demo; // Creating an entity Employeepublic class Employee { public Employee() {} // Parameterized Constructor // to assign the values // to the properties of // the entity public Employee( Integer id, String firstName, String lastName, String email) { super(); this.id = id; this.firstName = firstName; this.lastName = lastName; this.email = email; } private Integer id; private String firstName; private String lastName; private String email; // Overriding the toString method // to find all the values @Override public String toString() { return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]"; } // Getters and setters of // the properties public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName( String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName( String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; }}Now, we need to create a storage class which stores the list of all the employees:package com.example.demo; import java.util.ArrayList;import java.util.List; // Class to store the list of// all the employees in an// Array Listpublic class Employees { private List<Employee> employeeList; // Method to return the list // of employees public List<Employee> getEmployeeList() { if (employeeList == null) { employeeList = new ArrayList<>(); } return employeeList; } public void setEmployeeList( List<Employee> employeeList) { this.employeeList = employeeList; }}Till now, we have defined the entity employee and created a storage class. Now, we need to access the employees. So, we create a class from where we will create an object of the storage class to store the employees:package com.example.demo; import org.springframework .stereotype .Repository; // Importing the employees class to// use the defined properties// in this classimport com.example.demo.Employees; @Repository // Class to create a list// of employeespublic class EmployeeDAO { private static Employees list = new Employees(); // This static block is executed // before executing the main // block static { // Creating a few employees // and adding them to the list list.getEmployeeList().add( new Employee( 1, "Prem", "Tiwari", "[email protected]")); list.getEmployeeList().add( new Employee( 2, "Vikash", "Kumar", "[email protected]")); list.getEmployeeList().add( new Employee( 3, "Ritesh", "Ojha", "[email protected]")); } // Method to return the list public Employees getAllEmployees() { return list; } // Method to add an employee // to the employees list public void addEmployee(Employee employee) { list.getEmployeeList() .add(employee); }}Finally, we need to create a controller class which is the actual implementation of the REST API. According to the REST rules, every new entry in the database has to be called by the POST method and all the requests from the database must be called using the GET method. The same methods are implemented in the following code:package com.example.demo; import java.net.URI;import org.springframework.beans .factory.annotation.Autowired;import org.springframework.http .ResponseEntity;import org.springframework.web.bind .annotation.GetMapping;import org.springframework.web.bind .annotation.PostMapping;import org.springframework.web.bind .annotation.RequestBody;import org.springframework.web.bind .annotation.RequestMapping;import org.springframework.web.bind .annotation.RestController;import org.springframework.web.servlet .support.ServletUriComponentsBuilder; // Import the above-defined classes// to use the properties of those// classesimport com.example.demo.Employees;import com.example.demo.EmployeeDAO;import com.example.demo.Employee; // Creating the REST controller@RestController@RequestMapping(path = "/employees")public class EmployeeController { @Autowired private EmployeeDAO employeeDao; // Implementing a GET method // to get the list of all // the employees @GetMapping( path = "/", produces = "application/json") public Employees getEmployees() { return employeeDao .getAllEmployees(); } // Create a POST method // to add an employee // to the list @PostMapping( path = "/", consumes = "application/json", produces = "application/json") public ResponseEntity<Object> addEmployee( @RequestBody Employee employee) { // Creating an ID of an employee // from the number of employees Integer id = employeeDao .getAllEmployees() .getEmployeeList() .size() + 1; employee.setId(id); employeeDao .addEmployee(employee); URI location = ServletUriComponentsBuilder .fromCurrentRequest() .path("/{id}") .buildAndExpand( employee.getId()) .toUri(); return ResponseEntity .created(location) .build(); }}After implementing all the classes in the project, run the project as Spring Boot App. Once the server starts running, we can send the requests through the browser or postman. We can access the running app by going into the following URL:http://localhost:8080/employees/
Initially, we need to define the employee entity. Therefore, the following employee class is defined:package com.example.demo; // Creating an entity Employeepublic class Employee { public Employee() {} // Parameterized Constructor // to assign the values // to the properties of // the entity public Employee( Integer id, String firstName, String lastName, String email) { super(); this.id = id; this.firstName = firstName; this.lastName = lastName; this.email = email; } private Integer id; private String firstName; private String lastName; private String email; // Overriding the toString method // to find all the values @Override public String toString() { return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]"; } // Getters and setters of // the properties public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName( String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName( String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; }}
package com.example.demo; // Creating an entity Employeepublic class Employee { public Employee() {} // Parameterized Constructor // to assign the values // to the properties of // the entity public Employee( Integer id, String firstName, String lastName, String email) { super(); this.id = id; this.firstName = firstName; this.lastName = lastName; this.email = email; } private Integer id; private String firstName; private String lastName; private String email; // Overriding the toString method // to find all the values @Override public String toString() { return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]"; } // Getters and setters of // the properties public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName( String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName( String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; }}
Now, we need to create a storage class which stores the list of all the employees:package com.example.demo; import java.util.ArrayList;import java.util.List; // Class to store the list of// all the employees in an// Array Listpublic class Employees { private List<Employee> employeeList; // Method to return the list // of employees public List<Employee> getEmployeeList() { if (employeeList == null) { employeeList = new ArrayList<>(); } return employeeList; } public void setEmployeeList( List<Employee> employeeList) { this.employeeList = employeeList; }}
package com.example.demo; import java.util.ArrayList;import java.util.List; // Class to store the list of// all the employees in an// Array Listpublic class Employees { private List<Employee> employeeList; // Method to return the list // of employees public List<Employee> getEmployeeList() { if (employeeList == null) { employeeList = new ArrayList<>(); } return employeeList; } public void setEmployeeList( List<Employee> employeeList) { this.employeeList = employeeList; }}
Till now, we have defined the entity employee and created a storage class. Now, we need to access the employees. So, we create a class from where we will create an object of the storage class to store the employees:package com.example.demo; import org.springframework .stereotype .Repository; // Importing the employees class to// use the defined properties// in this classimport com.example.demo.Employees; @Repository // Class to create a list// of employeespublic class EmployeeDAO { private static Employees list = new Employees(); // This static block is executed // before executing the main // block static { // Creating a few employees // and adding them to the list list.getEmployeeList().add( new Employee( 1, "Prem", "Tiwari", "[email protected]")); list.getEmployeeList().add( new Employee( 2, "Vikash", "Kumar", "[email protected]")); list.getEmployeeList().add( new Employee( 3, "Ritesh", "Ojha", "[email protected]")); } // Method to return the list public Employees getAllEmployees() { return list; } // Method to add an employee // to the employees list public void addEmployee(Employee employee) { list.getEmployeeList() .add(employee); }}
package com.example.demo; import org.springframework .stereotype .Repository; // Importing the employees class to// use the defined properties// in this classimport com.example.demo.Employees; @Repository // Class to create a list// of employeespublic class EmployeeDAO { private static Employees list = new Employees(); // This static block is executed // before executing the main // block static { // Creating a few employees // and adding them to the list list.getEmployeeList().add( new Employee( 1, "Prem", "Tiwari", "[email protected]")); list.getEmployeeList().add( new Employee( 2, "Vikash", "Kumar", "[email protected]")); list.getEmployeeList().add( new Employee( 3, "Ritesh", "Ojha", "[email protected]")); } // Method to return the list public Employees getAllEmployees() { return list; } // Method to add an employee // to the employees list public void addEmployee(Employee employee) { list.getEmployeeList() .add(employee); }}
Finally, we need to create a controller class which is the actual implementation of the REST API. According to the REST rules, every new entry in the database has to be called by the POST method and all the requests from the database must be called using the GET method. The same methods are implemented in the following code:package com.example.demo; import java.net.URI;import org.springframework.beans .factory.annotation.Autowired;import org.springframework.http .ResponseEntity;import org.springframework.web.bind .annotation.GetMapping;import org.springframework.web.bind .annotation.PostMapping;import org.springframework.web.bind .annotation.RequestBody;import org.springframework.web.bind .annotation.RequestMapping;import org.springframework.web.bind .annotation.RestController;import org.springframework.web.servlet .support.ServletUriComponentsBuilder; // Import the above-defined classes// to use the properties of those// classesimport com.example.demo.Employees;import com.example.demo.EmployeeDAO;import com.example.demo.Employee; // Creating the REST controller@RestController@RequestMapping(path = "/employees")public class EmployeeController { @Autowired private EmployeeDAO employeeDao; // Implementing a GET method // to get the list of all // the employees @GetMapping( path = "/", produces = "application/json") public Employees getEmployees() { return employeeDao .getAllEmployees(); } // Create a POST method // to add an employee // to the list @PostMapping( path = "/", consumes = "application/json", produces = "application/json") public ResponseEntity<Object> addEmployee( @RequestBody Employee employee) { // Creating an ID of an employee // from the number of employees Integer id = employeeDao .getAllEmployees() .getEmployeeList() .size() + 1; employee.setId(id); employeeDao .addEmployee(employee); URI location = ServletUriComponentsBuilder .fromCurrentRequest() .path("/{id}") .buildAndExpand( employee.getId()) .toUri(); return ResponseEntity .created(location) .build(); }}
package com.example.demo; import java.net.URI;import org.springframework.beans .factory.annotation.Autowired;import org.springframework.http .ResponseEntity;import org.springframework.web.bind .annotation.GetMapping;import org.springframework.web.bind .annotation.PostMapping;import org.springframework.web.bind .annotation.RequestBody;import org.springframework.web.bind .annotation.RequestMapping;import org.springframework.web.bind .annotation.RestController;import org.springframework.web.servlet .support.ServletUriComponentsBuilder; // Import the above-defined classes// to use the properties of those// classesimport com.example.demo.Employees;import com.example.demo.EmployeeDAO;import com.example.demo.Employee; // Creating the REST controller@RestController@RequestMapping(path = "/employees")public class EmployeeController { @Autowired private EmployeeDAO employeeDao; // Implementing a GET method // to get the list of all // the employees @GetMapping( path = "/", produces = "application/json") public Employees getEmployees() { return employeeDao .getAllEmployees(); } // Create a POST method // to add an employee // to the list @PostMapping( path = "/", consumes = "application/json", produces = "application/json") public ResponseEntity<Object> addEmployee( @RequestBody Employee employee) { // Creating an ID of an employee // from the number of employees Integer id = employeeDao .getAllEmployees() .getEmployeeList() .size() + 1; employee.setId(id); employeeDao .addEmployee(employee); URI location = ServletUriComponentsBuilder .fromCurrentRequest() .path("/{id}") .buildAndExpand( employee.getId()) .toUri(); return ResponseEntity .created(location) .build(); }}
After implementing all the classes in the project, run the project as Spring Boot App. Once the server starts running, we can send the requests through the browser or postman. We can access the running app by going into the following URL:http://localhost:8080/employees/
http://localhost:8080/employees/
Output: The following is the output generated on running the above project:
When a GET request is performed:When a POST request is performed:Again hitting the GET request after performing the POST request:
When a GET request is performed:
When a POST request is performed:
Again hitting the GET request after performing the POST request:
java-advanced
Java-Spring
rest-framework
Web-API
Advanced Computer Subject
Java
Web Technologies
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reinforcement learning
ML | Linear Regression
Fuzzy Logic | Introduction
System Design Tutorial
Game Playing in Artificial Intelligence
Arrays in Java
Arrays.sort() in Java with examples
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Jun, 2020"
},
{
"code": null,
"e": 634,
"s": 52,
"text": "Representational state transfer (REST) is a software architectural style that defines a set of constraints to be used for creating Web services. Web services that conform to the REST architectural style, called RESTful Web services, provide interoperability between computer systems on the Internet. RESTful Web services allow the requesting systems to access and manipulate textual representations of Web resources by using a uniform and predefined set of stateless operations. Other kinds of Web services, such as SOAP Web services, expose their own arbitrary sets of operations."
},
{
"code": null,
"e": 714,
"s": 634,
"text": "In this article, we will understand how to create a rest API using spring boot."
},
{
"code": null,
"e": 1410,
"s": 714,
"text": "Spring is widely used for creating scalable applications. For web applications, Spring provides Spring MVC which is a widely used module of spring which is used to create scalable web applications. But the main disadvantage of spring projects is that configuration is really time-consuming and can be a bit overwhelming for the new developers. The solution to this is Spring Boot. Spring Boot is built on the top of the spring and contains all the features of spring. In this article, we will create a REST API to add employees to the employee list and get the list of employees. In order to do this, we first have to create a simple Spring Boot project in any of the IDE’s and follow the steps:"
},
{
"code": null,
"e": 8048,
"s": 1410,
"text": "Initially, we need to define the employee entity. Therefore, the following employee class is defined:package com.example.demo; // Creating an entity Employeepublic class Employee { public Employee() {} // Parameterized Constructor // to assign the values // to the properties of // the entity public Employee( Integer id, String firstName, String lastName, String email) { super(); this.id = id; this.firstName = firstName; this.lastName = lastName; this.email = email; } private Integer id; private String firstName; private String lastName; private String email; // Overriding the toString method // to find all the values @Override public String toString() { return \"Employee [id=\" + id + \", firstName=\" + firstName + \", lastName=\" + lastName + \", email=\" + email + \"]\"; } // Getters and setters of // the properties public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName( String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName( String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; }}Now, we need to create a storage class which stores the list of all the employees:package com.example.demo; import java.util.ArrayList;import java.util.List; // Class to store the list of// all the employees in an// Array Listpublic class Employees { private List<Employee> employeeList; // Method to return the list // of employees public List<Employee> getEmployeeList() { if (employeeList == null) { employeeList = new ArrayList<>(); } return employeeList; } public void setEmployeeList( List<Employee> employeeList) { this.employeeList = employeeList; }}Till now, we have defined the entity employee and created a storage class. Now, we need to access the employees. So, we create a class from where we will create an object of the storage class to store the employees:package com.example.demo; import org.springframework .stereotype .Repository; // Importing the employees class to// use the defined properties// in this classimport com.example.demo.Employees; @Repository // Class to create a list// of employeespublic class EmployeeDAO { private static Employees list = new Employees(); // This static block is executed // before executing the main // block static { // Creating a few employees // and adding them to the list list.getEmployeeList().add( new Employee( 1, \"Prem\", \"Tiwari\", \"[email protected]\")); list.getEmployeeList().add( new Employee( 2, \"Vikash\", \"Kumar\", \"[email protected]\")); list.getEmployeeList().add( new Employee( 3, \"Ritesh\", \"Ojha\", \"[email protected]\")); } // Method to return the list public Employees getAllEmployees() { return list; } // Method to add an employee // to the employees list public void addEmployee(Employee employee) { list.getEmployeeList() .add(employee); }}Finally, we need to create a controller class which is the actual implementation of the REST API. According to the REST rules, every new entry in the database has to be called by the POST method and all the requests from the database must be called using the GET method. The same methods are implemented in the following code:package com.example.demo; import java.net.URI;import org.springframework.beans .factory.annotation.Autowired;import org.springframework.http .ResponseEntity;import org.springframework.web.bind .annotation.GetMapping;import org.springframework.web.bind .annotation.PostMapping;import org.springframework.web.bind .annotation.RequestBody;import org.springframework.web.bind .annotation.RequestMapping;import org.springframework.web.bind .annotation.RestController;import org.springframework.web.servlet .support.ServletUriComponentsBuilder; // Import the above-defined classes// to use the properties of those// classesimport com.example.demo.Employees;import com.example.demo.EmployeeDAO;import com.example.demo.Employee; // Creating the REST controller@RestController@RequestMapping(path = \"/employees\")public class EmployeeController { @Autowired private EmployeeDAO employeeDao; // Implementing a GET method // to get the list of all // the employees @GetMapping( path = \"/\", produces = \"application/json\") public Employees getEmployees() { return employeeDao .getAllEmployees(); } // Create a POST method // to add an employee // to the list @PostMapping( path = \"/\", consumes = \"application/json\", produces = \"application/json\") public ResponseEntity<Object> addEmployee( @RequestBody Employee employee) { // Creating an ID of an employee // from the number of employees Integer id = employeeDao .getAllEmployees() .getEmployeeList() .size() + 1; employee.setId(id); employeeDao .addEmployee(employee); URI location = ServletUriComponentsBuilder .fromCurrentRequest() .path(\"/{id}\") .buildAndExpand( employee.getId()) .toUri(); return ResponseEntity .created(location) .build(); }}After implementing all the classes in the project, run the project as Spring Boot App. Once the server starts running, we can send the requests through the browser or postman. We can access the running app by going into the following URL:http://localhost:8080/employees/\n"
},
{
"code": null,
"e": 9712,
"s": 8048,
"text": "Initially, we need to define the employee entity. Therefore, the following employee class is defined:package com.example.demo; // Creating an entity Employeepublic class Employee { public Employee() {} // Parameterized Constructor // to assign the values // to the properties of // the entity public Employee( Integer id, String firstName, String lastName, String email) { super(); this.id = id; this.firstName = firstName; this.lastName = lastName; this.email = email; } private Integer id; private String firstName; private String lastName; private String email; // Overriding the toString method // to find all the values @Override public String toString() { return \"Employee [id=\" + id + \", firstName=\" + firstName + \", lastName=\" + lastName + \", email=\" + email + \"]\"; } // Getters and setters of // the properties public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName( String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName( String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; }}"
},
{
"code": "package com.example.demo; // Creating an entity Employeepublic class Employee { public Employee() {} // Parameterized Constructor // to assign the values // to the properties of // the entity public Employee( Integer id, String firstName, String lastName, String email) { super(); this.id = id; this.firstName = firstName; this.lastName = lastName; this.email = email; } private Integer id; private String firstName; private String lastName; private String email; // Overriding the toString method // to find all the values @Override public String toString() { return \"Employee [id=\" + id + \", firstName=\" + firstName + \", lastName=\" + lastName + \", email=\" + email + \"]\"; } // Getters and setters of // the properties public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName( String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName( String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; }}",
"e": 11275,
"s": 9712,
"text": null
},
{
"code": null,
"e": 11984,
"s": 11275,
"text": "Now, we need to create a storage class which stores the list of all the employees:package com.example.demo; import java.util.ArrayList;import java.util.List; // Class to store the list of// all the employees in an// Array Listpublic class Employees { private List<Employee> employeeList; // Method to return the list // of employees public List<Employee> getEmployeeList() { if (employeeList == null) { employeeList = new ArrayList<>(); } return employeeList; } public void setEmployeeList( List<Employee> employeeList) { this.employeeList = employeeList; }}"
},
{
"code": "package com.example.demo; import java.util.ArrayList;import java.util.List; // Class to store the list of// all the employees in an// Array Listpublic class Employees { private List<Employee> employeeList; // Method to return the list // of employees public List<Employee> getEmployeeList() { if (employeeList == null) { employeeList = new ArrayList<>(); } return employeeList; } public void setEmployeeList( List<Employee> employeeList) { this.employeeList = employeeList; }}",
"e": 12611,
"s": 11984,
"text": null
},
{
"code": null,
"e": 14142,
"s": 12611,
"text": "Till now, we have defined the entity employee and created a storage class. Now, we need to access the employees. So, we create a class from where we will create an object of the storage class to store the employees:package com.example.demo; import org.springframework .stereotype .Repository; // Importing the employees class to// use the defined properties// in this classimport com.example.demo.Employees; @Repository // Class to create a list// of employeespublic class EmployeeDAO { private static Employees list = new Employees(); // This static block is executed // before executing the main // block static { // Creating a few employees // and adding them to the list list.getEmployeeList().add( new Employee( 1, \"Prem\", \"Tiwari\", \"[email protected]\")); list.getEmployeeList().add( new Employee( 2, \"Vikash\", \"Kumar\", \"[email protected]\")); list.getEmployeeList().add( new Employee( 3, \"Ritesh\", \"Ojha\", \"[email protected]\")); } // Method to return the list public Employees getAllEmployees() { return list; } // Method to add an employee // to the employees list public void addEmployee(Employee employee) { list.getEmployeeList() .add(employee); }}"
},
{
"code": "package com.example.demo; import org.springframework .stereotype .Repository; // Importing the employees class to// use the defined properties// in this classimport com.example.demo.Employees; @Repository // Class to create a list// of employeespublic class EmployeeDAO { private static Employees list = new Employees(); // This static block is executed // before executing the main // block static { // Creating a few employees // and adding them to the list list.getEmployeeList().add( new Employee( 1, \"Prem\", \"Tiwari\", \"[email protected]\")); list.getEmployeeList().add( new Employee( 2, \"Vikash\", \"Kumar\", \"[email protected]\")); list.getEmployeeList().add( new Employee( 3, \"Ritesh\", \"Ojha\", \"[email protected]\")); } // Method to return the list public Employees getAllEmployees() { return list; } // Method to add an employee // to the employees list public void addEmployee(Employee employee) { list.getEmployeeList() .add(employee); }}",
"e": 15458,
"s": 14142,
"text": null
},
{
"code": null,
"e": 17924,
"s": 15458,
"text": "Finally, we need to create a controller class which is the actual implementation of the REST API. According to the REST rules, every new entry in the database has to be called by the POST method and all the requests from the database must be called using the GET method. The same methods are implemented in the following code:package com.example.demo; import java.net.URI;import org.springframework.beans .factory.annotation.Autowired;import org.springframework.http .ResponseEntity;import org.springframework.web.bind .annotation.GetMapping;import org.springframework.web.bind .annotation.PostMapping;import org.springframework.web.bind .annotation.RequestBody;import org.springframework.web.bind .annotation.RequestMapping;import org.springframework.web.bind .annotation.RestController;import org.springframework.web.servlet .support.ServletUriComponentsBuilder; // Import the above-defined classes// to use the properties of those// classesimport com.example.demo.Employees;import com.example.demo.EmployeeDAO;import com.example.demo.Employee; // Creating the REST controller@RestController@RequestMapping(path = \"/employees\")public class EmployeeController { @Autowired private EmployeeDAO employeeDao; // Implementing a GET method // to get the list of all // the employees @GetMapping( path = \"/\", produces = \"application/json\") public Employees getEmployees() { return employeeDao .getAllEmployees(); } // Create a POST method // to add an employee // to the list @PostMapping( path = \"/\", consumes = \"application/json\", produces = \"application/json\") public ResponseEntity<Object> addEmployee( @RequestBody Employee employee) { // Creating an ID of an employee // from the number of employees Integer id = employeeDao .getAllEmployees() .getEmployeeList() .size() + 1; employee.setId(id); employeeDao .addEmployee(employee); URI location = ServletUriComponentsBuilder .fromCurrentRequest() .path(\"/{id}\") .buildAndExpand( employee.getId()) .toUri(); return ResponseEntity .created(location) .build(); }}"
},
{
"code": "package com.example.demo; import java.net.URI;import org.springframework.beans .factory.annotation.Autowired;import org.springframework.http .ResponseEntity;import org.springframework.web.bind .annotation.GetMapping;import org.springframework.web.bind .annotation.PostMapping;import org.springframework.web.bind .annotation.RequestBody;import org.springframework.web.bind .annotation.RequestMapping;import org.springframework.web.bind .annotation.RestController;import org.springframework.web.servlet .support.ServletUriComponentsBuilder; // Import the above-defined classes// to use the properties of those// classesimport com.example.demo.Employees;import com.example.demo.EmployeeDAO;import com.example.demo.Employee; // Creating the REST controller@RestController@RequestMapping(path = \"/employees\")public class EmployeeController { @Autowired private EmployeeDAO employeeDao; // Implementing a GET method // to get the list of all // the employees @GetMapping( path = \"/\", produces = \"application/json\") public Employees getEmployees() { return employeeDao .getAllEmployees(); } // Create a POST method // to add an employee // to the list @PostMapping( path = \"/\", consumes = \"application/json\", produces = \"application/json\") public ResponseEntity<Object> addEmployee( @RequestBody Employee employee) { // Creating an ID of an employee // from the number of employees Integer id = employeeDao .getAllEmployees() .getEmployeeList() .size() + 1; employee.setId(id); employeeDao .addEmployee(employee); URI location = ServletUriComponentsBuilder .fromCurrentRequest() .path(\"/{id}\") .buildAndExpand( employee.getId()) .toUri(); return ResponseEntity .created(location) .build(); }}",
"e": 20064,
"s": 17924,
"text": null
},
{
"code": null,
"e": 20336,
"s": 20064,
"text": "After implementing all the classes in the project, run the project as Spring Boot App. Once the server starts running, we can send the requests through the browser or postman. We can access the running app by going into the following URL:http://localhost:8080/employees/\n"
},
{
"code": null,
"e": 20370,
"s": 20336,
"text": "http://localhost:8080/employees/\n"
},
{
"code": null,
"e": 20446,
"s": 20370,
"text": "Output: The following is the output generated on running the above project:"
},
{
"code": null,
"e": 20576,
"s": 20446,
"text": "When a GET request is performed:When a POST request is performed:Again hitting the GET request after performing the POST request:"
},
{
"code": null,
"e": 20609,
"s": 20576,
"text": "When a GET request is performed:"
},
{
"code": null,
"e": 20643,
"s": 20609,
"text": "When a POST request is performed:"
},
{
"code": null,
"e": 20708,
"s": 20643,
"text": "Again hitting the GET request after performing the POST request:"
},
{
"code": null,
"e": 20722,
"s": 20708,
"text": "java-advanced"
},
{
"code": null,
"e": 20734,
"s": 20722,
"text": "Java-Spring"
},
{
"code": null,
"e": 20749,
"s": 20734,
"text": "rest-framework"
},
{
"code": null,
"e": 20757,
"s": 20749,
"text": "Web-API"
},
{
"code": null,
"e": 20783,
"s": 20757,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 20788,
"s": 20783,
"text": "Java"
},
{
"code": null,
"e": 20805,
"s": 20788,
"text": "Web Technologies"
},
{
"code": null,
"e": 20810,
"s": 20805,
"text": "Java"
},
{
"code": null,
"e": 20908,
"s": 20810,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 20931,
"s": 20908,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 20954,
"s": 20931,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 20981,
"s": 20954,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 21004,
"s": 20981,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 21044,
"s": 21004,
"text": "Game Playing in Artificial Intelligence"
},
{
"code": null,
"e": 21059,
"s": 21044,
"text": "Arrays in Java"
},
{
"code": null,
"e": 21095,
"s": 21059,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 21139,
"s": 21095,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 21161,
"s": 21139,
"text": "For-each loop in Java"
}
] |
Python | PanedWindow Widget in Tkinter
|
07 Jun, 2019
Tkinter supports a variety of widgets to make GUI more and more attractive and functional. The PanedWindow widget is a geometry manager widget, which can contain one or more child widgets panes. The child widgets can be resized by the user, by moving separator lines sashes using the mouse.
Syntax: PanedWindow(master, **options)
Parameters:master: parent widget or main Tk() objectoptions: which are passed in config method or directly in the constructor
PanedWindow can be used to implement common 2-panes or 3-panes but multiple panes can be used.
Code #1:PanedWindow with only two panes
# Importing everything from tkinter modulefrom tkinter import * from tkinter import ttk # main tkinter windowroot = Tk() # panedwindow objectpw = PanedWindow(orient ='vertical') # Button widgettop = ttk.Button(pw, text ="Click Me !\nI'm a Button")top.pack(side = TOP) # This will add button widget to the panedwindowpw.add(top) # Checkbutton Widgetbot = Checkbutton(pw, text ="Choose Me !")bot.pack(side = TOP) # This will add Checkbutton to panedwindowpw.add(bot) # expand is used so that widgets can expand# fill is used to let widgets adjust itself# according to the size of main windowpw.pack(fill = BOTH, expand = True) # This method is used to show sashpw.configure(sashrelief = RAISED) # Infinite loop can be destroyed by# keyboard or mouse interruptmainloop()
Output: Code #2: PanedWindow with multiple panes
# Importing everything from tkinter modulefrom tkinter import * from tkinter import ttk # main tkinter windowroot = Tk() # panedwindow objectpw = PanedWindow(orient ='vertical') # Button widgettop = ttk.Button(pw, text ="Click Me !\nI'm a Button")top.pack(side = TOP) # This will add button widget to the panedwindowpw.add(top) # Checkbutton Widgetbot = Checkbutton(pw, text ="Choose Me !")bot.pack(side = TOP) # This will add Checkbutton to panedwindowpw.add(bot) # adding Label widgetlabel = Label(pw, text ="I'm a Label")label.pack(side = TOP) pw.add(label) # Tkinter string variablestring = StringVar() # Entry widget with some styling in fontsentry = Entry(pw, textvariable = string, font =('arial', 15, 'bold'))entry.pack() # Focus force is used to focus on particular# widget that means widget is already selected for operationsentry.focus_force() pw.add(entry) # expand is used so that widgets can expand# fill is used to let widgets adjust itself# according to the size of main windowpw.pack(fill = BOTH, expand = True) # This method is used to show sashpw.configure(sashrelief = RAISED) # Infinite loop can be destroyed by# keyboard or mouse interruptmainloop()
Output:
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
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 ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jun, 2019"
},
{
"code": null,
"e": 319,
"s": 28,
"text": "Tkinter supports a variety of widgets to make GUI more and more attractive and functional. The PanedWindow widget is a geometry manager widget, which can contain one or more child widgets panes. The child widgets can be resized by the user, by moving separator lines sashes using the mouse."
},
{
"code": null,
"e": 358,
"s": 319,
"text": "Syntax: PanedWindow(master, **options)"
},
{
"code": null,
"e": 484,
"s": 358,
"text": "Parameters:master: parent widget or main Tk() objectoptions: which are passed in config method or directly in the constructor"
},
{
"code": null,
"e": 579,
"s": 484,
"text": "PanedWindow can be used to implement common 2-panes or 3-panes but multiple panes can be used."
},
{
"code": null,
"e": 619,
"s": 579,
"text": "Code #1:PanedWindow with only two panes"
},
{
"code": "# Importing everything from tkinter modulefrom tkinter import * from tkinter import ttk # main tkinter windowroot = Tk() # panedwindow objectpw = PanedWindow(orient ='vertical') # Button widgettop = ttk.Button(pw, text =\"Click Me !\\nI'm a Button\")top.pack(side = TOP) # This will add button widget to the panedwindowpw.add(top) # Checkbutton Widgetbot = Checkbutton(pw, text =\"Choose Me !\")bot.pack(side = TOP) # This will add Checkbutton to panedwindowpw.add(bot) # expand is used so that widgets can expand# fill is used to let widgets adjust itself# according to the size of main windowpw.pack(fill = BOTH, expand = True) # This method is used to show sashpw.configure(sashrelief = RAISED) # Infinite loop can be destroyed by# keyboard or mouse interruptmainloop()",
"e": 1396,
"s": 619,
"text": null
},
{
"code": null,
"e": 1445,
"s": 1396,
"text": "Output: Code #2: PanedWindow with multiple panes"
},
{
"code": "# Importing everything from tkinter modulefrom tkinter import * from tkinter import ttk # main tkinter windowroot = Tk() # panedwindow objectpw = PanedWindow(orient ='vertical') # Button widgettop = ttk.Button(pw, text =\"Click Me !\\nI'm a Button\")top.pack(side = TOP) # This will add button widget to the panedwindowpw.add(top) # Checkbutton Widgetbot = Checkbutton(pw, text =\"Choose Me !\")bot.pack(side = TOP) # This will add Checkbutton to panedwindowpw.add(bot) # adding Label widgetlabel = Label(pw, text =\"I'm a Label\")label.pack(side = TOP) pw.add(label) # Tkinter string variablestring = StringVar() # Entry widget with some styling in fontsentry = Entry(pw, textvariable = string, font =('arial', 15, 'bold'))entry.pack() # Focus force is used to focus on particular# widget that means widget is already selected for operationsentry.focus_force() pw.add(entry) # expand is used so that widgets can expand# fill is used to let widgets adjust itself# according to the size of main windowpw.pack(fill = BOTH, expand = True) # This method is used to show sashpw.configure(sashrelief = RAISED) # Infinite loop can be destroyed by# keyboard or mouse interruptmainloop()",
"e": 2632,
"s": 1445,
"text": null
},
{
"code": null,
"e": 2640,
"s": 2632,
"text": "Output:"
},
{
"code": null,
"e": 2651,
"s": 2640,
"text": "Python-gui"
},
{
"code": null,
"e": 2666,
"s": 2651,
"text": "Python-tkinter"
},
{
"code": null,
"e": 2673,
"s": 2666,
"text": "Python"
},
{
"code": null,
"e": 2771,
"s": 2673,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2799,
"s": 2771,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 2849,
"s": 2799,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 2871,
"s": 2849,
"text": "Python map() function"
},
{
"code": null,
"e": 2915,
"s": 2871,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 2957,
"s": 2915,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2979,
"s": 2957,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3014,
"s": 2979,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3040,
"s": 3014,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3072,
"s": 3040,
"text": "How to Install PIP on Windows ?"
}
] |
Python | Ways to flatten a 2D list
|
03 Aug, 2021
Given a 2D list, write a Python program to convert the given list into a flattened list.
Method #1: Using chain.iterable()
Python3
# Python code to demonstrate# converting 2d list into 1d list# using chain.from_iterables # import chainfrom itertools import chain ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]] # printing initial listprint ("initial list ", str(ini_list)) # converting 2d list into 1d# using chain.from_iterablesflatten_list = list(chain.from_iterable(ini_list)) # printing flatten_listprint ("final_result", str(flatten_list))
initial list [[1, 2, 3], [3, 6, 7], [7, 5, 4]]
final_result [1, 2, 3, 3, 6, 7, 7, 5, 4]
Method #2: Using list comprehension
Python3
# Python code to demonstrate# converting 2d list into 1d list# using list comprehension # import chainfrom itertools import chain ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]] # printing initial listprint ("initial list ", str(ini_list)) # converting 2d list into 1d# using list comprehensionflatten_list = [j for sub in ini_list for j in sub] # printing flatten_listprint ("final_result", str(flatten_list))
initial list [[1, 2, 3], [3, 6, 7], [7, 5, 4]]
final_result [1, 2, 3, 3, 6, 7, 7, 5, 4]
Method #3: Using functools.reduce
Python3
# Python code to demonstrate# converting 2d list into 1d list# using functools.reduce # import functoolsfrom functools import reduce ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]] # printing initial listprint ("initial list ", str(ini_list)) # converting 2d list into 1d# using functools.reduceflatten_list = reduce(lambda z, y :z + y, ini_list) # printing flatten_listprint ("final_result", str(flatten_list))
initial list [[1, 2, 3], [3, 6, 7], [7, 5, 4]]
final_result [1, 2, 3, 3, 6, 7, 7, 5, 4]
Method #4: Using sumsum has an optional argument: sum(iterable [, start])
Python3
# Python code to demonstrate# converting 2d list into 1d list# using sum ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]] # printing initial listprint ("initial list ", str(ini_list)) # converting 2d list into 1dflatten_list = sum(ini_list, []) # printing flatten_listprint ("final_result", str(flatten_list)) # This code is contributed by# Mayank Chaudhary - chaudhary_19
Output:
initial list [[1, 2, 3], [3, 6, 7], [7, 5, 4]]
final_result [1, 2, 3, 3, 6, 7, 7, 5, 4]
Method #5: Using lambda
Python3
#Python 3 code to flatten nested list#contributed by S Lakshman Rao - kaapalxini_list=[[1, 2, 3], [3, 6, 7], [7, 5, 4]] #Using lambda flatten_list = lambda y:[x for a in y for x in flatten_list(a)] if type(y) is list else [y] print("Initial list ",ini_list) #printing initial list print("Flattened List ",flatten_list(ini_list)) # printing flattened list
Output:
Initial list [[1, 2, 3], [3, 6, 7], [7, 5, 4]]
Flattened List [1, 2, 3, 3, 6, 7, 7, 5, 4]
Method #6: Using numpy
Python3
#Python 3 code to flatten nested list#Contributed by S Lakshman Rao - kaapalximport numpy ini_list=[[1, 2, 3], [3, 6, 7], [7 ,5, 4]] print("Initial list ",ini_list) #Printing Initial list print("Flattened List ",list(numpy.concatenate(ini_list).flat))#Using numpy to flatten list and printing the result
Output:
Initial list [[1, 2, 3], [3, 6, 7], [7, 5, 4]]
Flattened List [1, 2, 3, 3, 6, 7, 7, 5, 4]
chaudhary_19
kaapalx
arorakashish0911
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 | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 144,
"s": 54,
"text": "Given a 2D list, write a Python program to convert the given list into a flattened list. "
},
{
"code": null,
"e": 179,
"s": 144,
"text": "Method #1: Using chain.iterable() "
},
{
"code": null,
"e": 187,
"s": 179,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# converting 2d list into 1d list# using chain.from_iterables # import chainfrom itertools import chain ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]] # printing initial listprint (\"initial list \", str(ini_list)) # converting 2d list into 1d# using chain.from_iterablesflatten_list = list(chain.from_iterable(ini_list)) # printing flatten_listprint (\"final_result\", str(flatten_list))",
"e": 632,
"s": 187,
"text": null
},
{
"code": null,
"e": 721,
"s": 632,
"text": "initial list [[1, 2, 3], [3, 6, 7], [7, 5, 4]]\nfinal_result [1, 2, 3, 3, 6, 7, 7, 5, 4]"
},
{
"code": null,
"e": 760,
"s": 723,
"text": "Method #2: Using list comprehension "
},
{
"code": null,
"e": 768,
"s": 760,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# converting 2d list into 1d list# using list comprehension # import chainfrom itertools import chain ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]] # printing initial listprint (\"initial list \", str(ini_list)) # converting 2d list into 1d# using list comprehensionflatten_list = [j for sub in ini_list for j in sub] # printing flatten_listprint (\"final_result\", str(flatten_list))",
"e": 1210,
"s": 768,
"text": null
},
{
"code": null,
"e": 1299,
"s": 1210,
"text": "initial list [[1, 2, 3], [3, 6, 7], [7, 5, 4]]\nfinal_result [1, 2, 3, 3, 6, 7, 7, 5, 4]"
},
{
"code": null,
"e": 1337,
"s": 1301,
"text": "Method #3: Using functools.reduce "
},
{
"code": null,
"e": 1345,
"s": 1337,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# converting 2d list into 1d list# using functools.reduce # import functoolsfrom functools import reduce ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]] # printing initial listprint (\"initial list \", str(ini_list)) # converting 2d list into 1d# using functools.reduceflatten_list = reduce(lambda z, y :z + y, ini_list) # printing flatten_listprint (\"final_result\", str(flatten_list))",
"e": 1788,
"s": 1345,
"text": null
},
{
"code": null,
"e": 1877,
"s": 1788,
"text": "initial list [[1, 2, 3], [3, 6, 7], [7, 5, 4]]\nfinal_result [1, 2, 3, 3, 6, 7, 7, 5, 4]"
},
{
"code": null,
"e": 1953,
"s": 1879,
"text": "Method #4: Using sumsum has an optional argument: sum(iterable [, start])"
},
{
"code": null,
"e": 1961,
"s": 1953,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# converting 2d list into 1d list# using sum ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]] # printing initial listprint (\"initial list \", str(ini_list)) # converting 2d list into 1dflatten_list = sum(ini_list, []) # printing flatten_listprint (\"final_result\", str(flatten_list)) # This code is contributed by# Mayank Chaudhary - chaudhary_19",
"e": 2352,
"s": 1961,
"text": null
},
{
"code": null,
"e": 2361,
"s": 2352,
"text": "Output: "
},
{
"code": null,
"e": 2450,
"s": 2361,
"text": "initial list [[1, 2, 3], [3, 6, 7], [7, 5, 4]]\nfinal_result [1, 2, 3, 3, 6, 7, 7, 5, 4]"
},
{
"code": null,
"e": 2476,
"s": 2450,
"text": "Method #5: Using lambda "
},
{
"code": null,
"e": 2484,
"s": 2476,
"text": "Python3"
},
{
"code": "#Python 3 code to flatten nested list#contributed by S Lakshman Rao - kaapalxini_list=[[1, 2, 3], [3, 6, 7], [7, 5, 4]] #Using lambda flatten_list = lambda y:[x for a in y for x in flatten_list(a)] if type(y) is list else [y] print(\"Initial list \",ini_list) #printing initial list print(\"Flattened List \",flatten_list(ini_list)) # printing flattened list",
"e": 2857,
"s": 2484,
"text": null
},
{
"code": null,
"e": 2866,
"s": 2857,
"text": "Output: "
},
{
"code": null,
"e": 2958,
"s": 2866,
"text": "Initial list [[1, 2, 3], [3, 6, 7], [7, 5, 4]]\nFlattened List [1, 2, 3, 3, 6, 7, 7, 5, 4]"
},
{
"code": null,
"e": 2983,
"s": 2958,
"text": "Method #6: Using numpy "
},
{
"code": null,
"e": 2991,
"s": 2983,
"text": "Python3"
},
{
"code": "#Python 3 code to flatten nested list#Contributed by S Lakshman Rao - kaapalximport numpy ini_list=[[1, 2, 3], [3, 6, 7], [7 ,5, 4]] print(\"Initial list \",ini_list) #Printing Initial list print(\"Flattened List \",list(numpy.concatenate(ini_list).flat))#Using numpy to flatten list and printing the result",
"e": 3313,
"s": 2991,
"text": null
},
{
"code": null,
"e": 3322,
"s": 3313,
"text": "Output: "
},
{
"code": null,
"e": 3414,
"s": 3322,
"text": "Initial list [[1, 2, 3], [3, 6, 7], [7, 5, 4]]\nFlattened List [1, 2, 3, 3, 6, 7, 7, 5, 4]"
},
{
"code": null,
"e": 3429,
"s": 3416,
"text": "chaudhary_19"
},
{
"code": null,
"e": 3437,
"s": 3429,
"text": "kaapalx"
},
{
"code": null,
"e": 3454,
"s": 3437,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3475,
"s": 3454,
"text": "Python list-programs"
},
{
"code": null,
"e": 3482,
"s": 3475,
"text": "Python"
},
{
"code": null,
"e": 3498,
"s": 3482,
"text": "Python Programs"
},
{
"code": null,
"e": 3596,
"s": 3498,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3638,
"s": 3596,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3660,
"s": 3638,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3695,
"s": 3660,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3721,
"s": 3695,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3753,
"s": 3721,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3796,
"s": 3753,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 3818,
"s": 3796,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3857,
"s": 3818,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3895,
"s": 3857,
"text": "Python | Convert a list to dictionary"
}
] |
Python | Sort a tuple by its float element
|
24 Dec, 2017
In this article, we will see how we can sort a tuple (consisting of float elements) using its float elements. Here we will see how to do this by using the built-in method sorted() and how can this be done using in place method of sorting.
Examples:
Input : tuple = [('lucky', '18.265'), ('nikhil', '14.107'),
('akash', '24.541'), ('anand', '4.256'), ('gaurav', '10.365')]
Output : [('akash', '24.541'), ('lucky', '18.265'),
('nikhil', '14.107'), ('gaurav', '10.365'), ('anand', '4.256')]
Input : tuple = [('234', '9.4'), ('543', '16.9'), ('756', '5.5'),
('132', '4.2'), ('342', '7.3')]
Output : [('543', '16.9'), ('234', '9.4'), ('342', '7.3'),
('756', '5.5'), ('132', '4.2')]
We can understand this from the image shown below:
Method 1 : Use of sorted() method
Sorted() sorts a tuple and always returns a tuple with the elements in a sorted manner, without modifying the original sequence. It takes three parameters from which two are optional, here we tried to use all of the three:
Iterable : sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted.Key(optional) : A function that would server as a key or a basis of sort comparison.Reverse(optional) : If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.
Iterable : sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted.
Key(optional) : A function that would server as a key or a basis of sort comparison.
Reverse(optional) : If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.
To sort this in ascending order we could have just ignored the third parameter.
# Python code to sort the tuples using float element# Function to sort using sorted()def Sort(tup): # reverse = True (Sorts in Descending order) # key is set to sort using float elements # lambda has been used return(sorted(tup, key = lambda x: float(x[1]), reverse = True)) # Driver Codetup = [('lucky', '18.265'), ('nikhil', '14.107'), ('akash', '24.541'), ('anand', '4.256'), ('gaurav', '10.365')]print(Sort(tup))
Output:
[('akash', '24.541'), ('lucky', '18.265'), ('nikhil', '14.107'),
('gaurav', '10.365'), ('anand', '4.256')]
Method 2 : In-place way of sorting using sort():
While sorting via this method the actual content of the tuple is changed, while in the previous method the content of the original tuple remained the same.
# Python code to sort the tuples using float element# Inplace way to sort using sort()def Sort(tup): # reverse = True (Sorts in Descending order) # key is set to sort using float elements # lambda has been used tup.sort(key = lambda x: float(x[1]), reverse = True) print(tup) # Driver Codetup = [('lucky', '18.265'), ('nikhil', '14.107'), ('akash', '24.541'), ('anand', '4.256'), ('gaurav', '10.365')]Sort(tup)
Output:
[('akash', '24.541'), ('lucky', '18.265'), ('nikhil', '14.107'),
('gaurav', '10.365'), ('anand', '4.256')]
For more reference visit:sorted() in Pythonlambda in Python
python-tuple
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Dec, 2017"
},
{
"code": null,
"e": 292,
"s": 53,
"text": "In this article, we will see how we can sort a tuple (consisting of float elements) using its float elements. Here we will see how to do this by using the built-in method sorted() and how can this be done using in place method of sorting."
},
{
"code": null,
"e": 302,
"s": 292,
"text": "Examples:"
},
{
"code": null,
"e": 792,
"s": 302,
"text": "Input : tuple = [('lucky', '18.265'), ('nikhil', '14.107'), \n ('akash', '24.541'), ('anand', '4.256'), ('gaurav', '10.365')]\nOutput : [('akash', '24.541'), ('lucky', '18.265'), \n ('nikhil', '14.107'), ('gaurav', '10.365'), ('anand', '4.256')]\n\nInput : tuple = [('234', '9.4'), ('543', '16.9'), ('756', '5.5'), \n ('132', '4.2'), ('342', '7.3')]\nOutput : [('543', '16.9'), ('234', '9.4'), ('342', '7.3'), \n ('756', '5.5'), ('132', '4.2')]\n"
},
{
"code": null,
"e": 843,
"s": 792,
"text": "We can understand this from the image shown below:"
},
{
"code": null,
"e": 877,
"s": 843,
"text": "Method 1 : Use of sorted() method"
},
{
"code": null,
"e": 1100,
"s": 877,
"text": "Sorted() sorts a tuple and always returns a tuple with the elements in a sorted manner, without modifying the original sequence. It takes three parameters from which two are optional, here we tried to use all of the three:"
},
{
"code": null,
"e": 1444,
"s": 1100,
"text": "Iterable : sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted.Key(optional) : A function that would server as a key or a basis of sort comparison.Reverse(optional) : If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false."
},
{
"code": null,
"e": 1576,
"s": 1444,
"text": "Iterable : sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted."
},
{
"code": null,
"e": 1661,
"s": 1576,
"text": "Key(optional) : A function that would server as a key or a basis of sort comparison."
},
{
"code": null,
"e": 1790,
"s": 1661,
"text": "Reverse(optional) : If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false."
},
{
"code": null,
"e": 1870,
"s": 1790,
"text": "To sort this in ascending order we could have just ignored the third parameter."
},
{
"code": "# Python code to sort the tuples using float element# Function to sort using sorted()def Sort(tup): # reverse = True (Sorts in Descending order) # key is set to sort using float elements # lambda has been used return(sorted(tup, key = lambda x: float(x[1]), reverse = True)) # Driver Codetup = [('lucky', '18.265'), ('nikhil', '14.107'), ('akash', '24.541'), ('anand', '4.256'), ('gaurav', '10.365')]print(Sort(tup))",
"e": 2304,
"s": 1870,
"text": null
},
{
"code": null,
"e": 2312,
"s": 2304,
"text": "Output:"
},
{
"code": null,
"e": 2421,
"s": 2312,
"text": "[('akash', '24.541'), ('lucky', '18.265'), ('nikhil', '14.107'),\n ('gaurav', '10.365'), ('anand', '4.256')]\n"
},
{
"code": null,
"e": 2470,
"s": 2421,
"text": "Method 2 : In-place way of sorting using sort():"
},
{
"code": null,
"e": 2626,
"s": 2470,
"text": "While sorting via this method the actual content of the tuple is changed, while in the previous method the content of the original tuple remained the same."
},
{
"code": "# Python code to sort the tuples using float element# Inplace way to sort using sort()def Sort(tup): # reverse = True (Sorts in Descending order) # key is set to sort using float elements # lambda has been used tup.sort(key = lambda x: float(x[1]), reverse = True) print(tup) # Driver Codetup = [('lucky', '18.265'), ('nikhil', '14.107'), ('akash', '24.541'), ('anand', '4.256'), ('gaurav', '10.365')]Sort(tup)",
"e": 3057,
"s": 2626,
"text": null
},
{
"code": null,
"e": 3065,
"s": 3057,
"text": "Output:"
},
{
"code": null,
"e": 3175,
"s": 3065,
"text": "[('akash', '24.541'), ('lucky', '18.265'), ('nikhil', '14.107'), \n ('gaurav', '10.365'), ('anand', '4.256')]\n"
},
{
"code": null,
"e": 3235,
"s": 3175,
"text": "For more reference visit:sorted() in Pythonlambda in Python"
},
{
"code": null,
"e": 3248,
"s": 3235,
"text": "python-tuple"
},
{
"code": null,
"e": 3255,
"s": 3248,
"text": "Python"
}
] |
cmd | cls command
|
29 Sep, 2020
Cls is a internal command found inside windows command interpreter cmd, that is used for clearing the console window.It does so by removing the entry of all previously entered commands, and their corresponding outputs. The command was first introduced in the MSDOS Version 2. Initially it was for command.com (command processor for MSDOS), which is the predecessor of cmd.exe (AKA Command Prompt).It is one of the most used commands, and is offered by all Operating Systems in one way or another (ex. Linux has a command named clear which serves the same purpose). In this article, we would learn about this command and how to use it.
Description of the Command :
CLS : Clears the screen.
Note –In order to obtain the above text execute the cls /? command on cmd.
Using Command :The command serves only one purpose, and that is to clear the output screen. For doing so execute the command without any parameters.
Example –For this example, we would be using the following console window.
This window currently contains output from the dir command. In order to clear this output (and others before it) execute the CLS command. After command execution, the windows appear as follows.
It is clear that from the above image, that all the previous output has been removed.
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Sep, 2020"
},
{
"code": null,
"e": 663,
"s": 28,
"text": "Cls is a internal command found inside windows command interpreter cmd, that is used for clearing the console window.It does so by removing the entry of all previously entered commands, and their corresponding outputs. The command was first introduced in the MSDOS Version 2. Initially it was for command.com (command processor for MSDOS), which is the predecessor of cmd.exe (AKA Command Prompt).It is one of the most used commands, and is offered by all Operating Systems in one way or another (ex. Linux has a command named clear which serves the same purpose). In this article, we would learn about this command and how to use it."
},
{
"code": null,
"e": 692,
"s": 663,
"text": "Description of the Command :"
},
{
"code": null,
"e": 718,
"s": 692,
"text": "CLS : Clears the screen.\n"
},
{
"code": null,
"e": 793,
"s": 718,
"text": "Note –In order to obtain the above text execute the cls /? command on cmd."
},
{
"code": null,
"e": 942,
"s": 793,
"text": "Using Command :The command serves only one purpose, and that is to clear the output screen. For doing so execute the command without any parameters."
},
{
"code": null,
"e": 1017,
"s": 942,
"text": "Example –For this example, we would be using the following console window."
},
{
"code": null,
"e": 1211,
"s": 1017,
"text": "This window currently contains output from the dir command. In order to clear this output (and others before it) execute the CLS command. After command execution, the windows appear as follows."
},
{
"code": null,
"e": 1297,
"s": 1211,
"text": "It is clear that from the above image, that all the previous output has been removed."
},
{
"code": null,
"e": 1302,
"s": 1297,
"text": "Misc"
},
{
"code": null,
"e": 1307,
"s": 1302,
"text": "Misc"
},
{
"code": null,
"e": 1312,
"s": 1307,
"text": "Misc"
}
] |
Hangman Game in Python
|
11 Mar, 2022
Hangman Wiki: The origins of Hangman are obscure meaning not discovered, but it seems to have arisen in Victorian times, ” says Tony Augarde, author of The Oxford Guide to Word Games. The game is mentioned in Alice Bertha Gomme’s “Traditional Games” in 1894 under the name “Birds, Beasts and Fishes.” The rules are simple; a player writes down the first and last letters of a word and another player guesses the letters in between. In other sources, [where?] the game is called “Gallows”, “The Game of Hangin”, or “Hanger”.
Implementation
This is a simple Hangman game using Python programming language. Beginners can use this as a small project to boost their programming skills and understanding logic.
The Hangman program randomly selects a secret word from a list of secret words. The random module will provide this ability, so line 1 in program imports it.The Game: Here, a random word (a fruit name) is picked up from our collection and the player gets limited chances to win the game.When a letter in that word is guessed correctly, that letter position in the word is made visible. In this way, all letters of the word are to be guessed before all the chances are over. For convenience, we have given length of word + 2 chances. For example, word to be guessed is mango, then user gets 5 + 2 = 7 chances, as mango is a five letter word.
The Hangman program randomly selects a secret word from a list of secret words. The random module will provide this ability, so line 1 in program imports it.
The Game: Here, a random word (a fruit name) is picked up from our collection and the player gets limited chances to win the game.
When a letter in that word is guessed correctly, that letter position in the word is made visible. In this way, all letters of the word are to be guessed before all the chances are over.
For convenience, we have given length of word + 2 chances. For example, word to be guessed is mango, then user gets 5 + 2 = 7 chances, as mango is a five letter word.
Python
# Python Program to illustrate# Hangman Gameimport randomfrom collections import Counter someWords = '''apple banana mango strawberryorange grape pineapple apricot lemon coconut watermeloncherry papaya berry peach lychee muskmelon''' someWords = someWords.split(' ')# randomly choose a secret word from our "someWords" LIST.word = random.choice(someWords) if __name__ == '__main__': print('Guess the word! HINT: word is a name of a fruit') for i in word: # For printing the empty spaces for letters of the word print('_', end = ' ') print() playing = True # list for storing the letters guessed by the player letterGuessed = '' chances = len(word) + 2 correct = 0 flag = 0 try: while (chances != 0) and flag == 0: #flag is updated when the word is correctly guessed print() chances -= 1 try: guess = str(input('Enter a letter to guess: ')) except: print('Enter only a letter!') continue # Validation of the guess if not guess.isalpha(): print('Enter only a LETTER') continue else if len(guess) > 1: print('Enter only a SINGLE letter') continue else if guess in letterGuessed: print('You have already guessed that letter') continue # If letter is guessed correctly if guess in word: k = word.count(guess) #k stores the number of times the guessed letter occurs in the word for _ in range(k): letterGuessed += guess # The guess letter is added as many times as it occurs # Print the word for char in word: if char in letterGuessed and (Counter(letterGuessed) != Counter(word)): print(char, end = ' ') correct += 1 # If user has guessed all the letters else if (Counter(letterGuessed) == Counter(word)): # Once the correct word is guessed fully, # the game ends, even if chances remain print("The word is: ", end=' ') print(word) flag = 1 print('Congratulations, You won!') break # To break out of the for loop break # To break out of the while loop else: print('_', end = ' ') # If user has used all of his chances if chances <= 0 and (Counter(letterGuessed) != Counter(word)): print() print('You lost! Try again..') print('The word was {}'.format(word)) except KeyboardInterrupt: print() print('Bye! Try again.') exit()
Note: Please run the program on your terminal.
omkarpathak@omkarpathak-Inspiron-3542:~/Documents/
Python-Programs$ python P37_HangmanGame.py
Guess the word! HINT: word is a name of a fruit
_ _ _ _ _
Enter a letter to guess: m
_ _ m _ _
Enter a letter to guess: o
_ _ m o _
Enter a letter to guess: l
l _ m o _
Enter a letter to guess: e
l e m o _
Enter a letter to guess: n
l e m o n
Congratulations, You won!
Try it yourself Exercises:
You can further enhance program by adding timer after every Guess
You can also give hints from the beginning to make the task a bit easier for user
You can also decrease the chance by one only if player’s guess is WRONG. If the guess is right, player’s chance is not reduced
Python Hangman Game - YouTubeOmkar Pathak4 subscribersPython Hangman GameWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:44•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Yt4I98jFIuU" 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 Omkar Pathak. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
dkp1903
simmytarika5
Python-projects
python-utility
Project
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Mar, 2022"
},
{
"code": null,
"e": 580,
"s": 54,
"text": "Hangman Wiki: The origins of Hangman are obscure meaning not discovered, but it seems to have arisen in Victorian times, ” says Tony Augarde, author of The Oxford Guide to Word Games. The game is mentioned in Alice Bertha Gomme’s “Traditional Games” in 1894 under the name “Birds, Beasts and Fishes.” The rules are simple; a player writes down the first and last letters of a word and another player guesses the letters in between. In other sources, [where?] the game is called “Gallows”, “The Game of Hangin”, or “Hanger”. "
},
{
"code": null,
"e": 595,
"s": 580,
"text": "Implementation"
},
{
"code": null,
"e": 763,
"s": 595,
"text": "This is a simple Hangman game using Python programming language. Beginners can use this as a small project to boost their programming skills and understanding logic. "
},
{
"code": null,
"e": 1404,
"s": 763,
"text": "The Hangman program randomly selects a secret word from a list of secret words. The random module will provide this ability, so line 1 in program imports it.The Game: Here, a random word (a fruit name) is picked up from our collection and the player gets limited chances to win the game.When a letter in that word is guessed correctly, that letter position in the word is made visible. In this way, all letters of the word are to be guessed before all the chances are over. For convenience, we have given length of word + 2 chances. For example, word to be guessed is mango, then user gets 5 + 2 = 7 chances, as mango is a five letter word."
},
{
"code": null,
"e": 1562,
"s": 1404,
"text": "The Hangman program randomly selects a secret word from a list of secret words. The random module will provide this ability, so line 1 in program imports it."
},
{
"code": null,
"e": 1693,
"s": 1562,
"text": "The Game: Here, a random word (a fruit name) is picked up from our collection and the player gets limited chances to win the game."
},
{
"code": null,
"e": 1881,
"s": 1693,
"text": "When a letter in that word is guessed correctly, that letter position in the word is made visible. In this way, all letters of the word are to be guessed before all the chances are over. "
},
{
"code": null,
"e": 2048,
"s": 1881,
"text": "For convenience, we have given length of word + 2 chances. For example, word to be guessed is mango, then user gets 5 + 2 = 7 chances, as mango is a five letter word."
},
{
"code": null,
"e": 2057,
"s": 2050,
"text": "Python"
},
{
"code": "# Python Program to illustrate# Hangman Gameimport randomfrom collections import Counter someWords = '''apple banana mango strawberryorange grape pineapple apricot lemon coconut watermeloncherry papaya berry peach lychee muskmelon''' someWords = someWords.split(' ')# randomly choose a secret word from our \"someWords\" LIST.word = random.choice(someWords) if __name__ == '__main__': print('Guess the word! HINT: word is a name of a fruit') for i in word: # For printing the empty spaces for letters of the word print('_', end = ' ') print() playing = True # list for storing the letters guessed by the player letterGuessed = '' chances = len(word) + 2 correct = 0 flag = 0 try: while (chances != 0) and flag == 0: #flag is updated when the word is correctly guessed print() chances -= 1 try: guess = str(input('Enter a letter to guess: ')) except: print('Enter only a letter!') continue # Validation of the guess if not guess.isalpha(): print('Enter only a LETTER') continue else if len(guess) > 1: print('Enter only a SINGLE letter') continue else if guess in letterGuessed: print('You have already guessed that letter') continue # If letter is guessed correctly if guess in word: k = word.count(guess) #k stores the number of times the guessed letter occurs in the word for _ in range(k): letterGuessed += guess # The guess letter is added as many times as it occurs # Print the word for char in word: if char in letterGuessed and (Counter(letterGuessed) != Counter(word)): print(char, end = ' ') correct += 1 # If user has guessed all the letters else if (Counter(letterGuessed) == Counter(word)): # Once the correct word is guessed fully, # the game ends, even if chances remain print(\"The word is: \", end=' ') print(word) flag = 1 print('Congratulations, You won!') break # To break out of the for loop break # To break out of the while loop else: print('_', end = ' ') # If user has used all of his chances if chances <= 0 and (Counter(letterGuessed) != Counter(word)): print() print('You lost! Try again..') print('The word was {}'.format(word)) except KeyboardInterrupt: print() print('Bye! Try again.') exit()",
"e": 4970,
"s": 2057,
"text": null
},
{
"code": null,
"e": 5019,
"s": 4970,
"text": "Note: Please run the program on your terminal. "
},
{
"code": null,
"e": 5390,
"s": 5019,
"text": "omkarpathak@omkarpathak-Inspiron-3542:~/Documents/\nPython-Programs$ python P37_HangmanGame.py \nGuess the word! HINT: word is a name of a fruit\n_ _ _ _ _ \n\nEnter a letter to guess: m\n_ _ m _ _ \nEnter a letter to guess: o\n_ _ m o _ \nEnter a letter to guess: l\nl _ m o _ \nEnter a letter to guess: e\nl e m o _ \nEnter a letter to guess: n\nl e m o n \nCongratulations, You won!"
},
{
"code": null,
"e": 5419,
"s": 5390,
"text": "Try it yourself Exercises: "
},
{
"code": null,
"e": 5485,
"s": 5419,
"text": "You can further enhance program by adding timer after every Guess"
},
{
"code": null,
"e": 5567,
"s": 5485,
"text": "You can also give hints from the beginning to make the task a bit easier for user"
},
{
"code": null,
"e": 5694,
"s": 5567,
"text": "You can also decrease the chance by one only if player’s guess is WRONG. If the guess is right, player’s chance is not reduced"
},
{
"code": null,
"e": 6516,
"s": 5696,
"text": "Python Hangman Game - YouTubeOmkar Pathak4 subscribersPython Hangman GameWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:44•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Yt4I98jFIuU\" 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": 6937,
"s": 6516,
"text": "This article is contributed by Omkar Pathak. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 6945,
"s": 6937,
"text": "dkp1903"
},
{
"code": null,
"e": 6958,
"s": 6945,
"text": "simmytarika5"
},
{
"code": null,
"e": 6974,
"s": 6958,
"text": "Python-projects"
},
{
"code": null,
"e": 6989,
"s": 6974,
"text": "python-utility"
},
{
"code": null,
"e": 6997,
"s": 6989,
"text": "Project"
},
{
"code": null,
"e": 7004,
"s": 6997,
"text": "Python"
}
] |
Event Binding in Angular 8
|
14 Sep, 2020
In Angular 8, event binding is used to handle the events raised by the user actions like button click, mouse movement, keystrokes, etc. When the DOM event happens at an element(e.g. click, keydown, keyup), it calls the specified method in the particular component.
Using Event Binding we can bind data from DOM to the component and hence can use that data for further purposes.
Syntax:
< element (event) = function() >
Approach:
Define a function in the app.component.ts file which will do the given task.
In the app.component.html file, bind the function to the given event on the HTML element.
Example 1: Using click event on the input element.
app.component.html
HTML
<h1> GeeksforGeeks</h1><input (click)="gfg($event)" value="Geeks">
app.component.ts
Javascript
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { gfg(event) { console.log(event.toElement.value); } }
Output:
Example 2: Using keyup event on the input element.
app.component.html
HTML
<!-- event is passed to function --><input (keyup)="onKeyUp($event)"> <p>{{text}}</p>
app.component.ts
Javascript
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { text = ''; onKeyUp(x) { // Appending the updated value // to the variable this.text += x.target.value + ' | '; } }
Output:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Auth Guards in Angular 9/10/11
Routing in Angular 9/10
How to bundle an Angular app for production?
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
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": "\n14 Sep, 2020"
},
{
"code": null,
"e": 294,
"s": 28,
"text": "In Angular 8, event binding is used to handle the events raised by the user actions like button click, mouse movement, keystrokes, etc. When the DOM event happens at an element(e.g. click, keydown, keyup), it calls the specified method in the particular component. "
},
{
"code": null,
"e": 407,
"s": 294,
"text": "Using Event Binding we can bind data from DOM to the component and hence can use that data for further purposes."
},
{
"code": null,
"e": 415,
"s": 407,
"text": "Syntax:"
},
{
"code": null,
"e": 448,
"s": 415,
"text": "< element (event) = function() >"
},
{
"code": null,
"e": 459,
"s": 448,
"text": "Approach: "
},
{
"code": null,
"e": 536,
"s": 459,
"text": "Define a function in the app.component.ts file which will do the given task."
},
{
"code": null,
"e": 626,
"s": 536,
"text": "In the app.component.html file, bind the function to the given event on the HTML element."
},
{
"code": null,
"e": 677,
"s": 626,
"text": "Example 1: Using click event on the input element."
},
{
"code": null,
"e": 696,
"s": 677,
"text": "app.component.html"
},
{
"code": null,
"e": 701,
"s": 696,
"text": "HTML"
},
{
"code": "<h1> GeeksforGeeks</h1><input (click)=\"gfg($event)\" value=\"Geeks\">",
"e": 769,
"s": 701,
"text": null
},
{
"code": null,
"e": 786,
"s": 769,
"text": "app.component.ts"
},
{
"code": null,
"e": 797,
"s": 786,
"text": "Javascript"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { gfg(event) { console.log(event.toElement.value); } }",
"e": 1067,
"s": 797,
"text": null
},
{
"code": null,
"e": 1075,
"s": 1067,
"text": "Output:"
},
{
"code": null,
"e": 1126,
"s": 1075,
"text": "Example 2: Using keyup event on the input element."
},
{
"code": null,
"e": 1145,
"s": 1126,
"text": "app.component.html"
},
{
"code": null,
"e": 1150,
"s": 1145,
"text": "HTML"
},
{
"code": "<!-- event is passed to function --><input (keyup)=\"onKeyUp($event)\"> <p>{{text}}</p>",
"e": 1241,
"s": 1150,
"text": null
},
{
"code": null,
"e": 1258,
"s": 1241,
"text": "app.component.ts"
},
{
"code": null,
"e": 1269,
"s": 1258,
"text": "Javascript"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { text = ''; onKeyUp(x) { // Appending the updated value // to the variable this.text += x.target.value + ' | '; } }",
"e": 1610,
"s": 1269,
"text": null
},
{
"code": null,
"e": 1618,
"s": 1610,
"text": "Output:"
},
{
"code": null,
"e": 1633,
"s": 1618,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 1640,
"s": 1633,
"text": "Picked"
},
{
"code": null,
"e": 1650,
"s": 1640,
"text": "AngularJS"
},
{
"code": null,
"e": 1667,
"s": 1650,
"text": "Web Technologies"
},
{
"code": null,
"e": 1765,
"s": 1667,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1796,
"s": 1765,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 1820,
"s": 1796,
"text": "Routing in Angular 9/10"
},
{
"code": null,
"e": 1865,
"s": 1820,
"text": "How to bundle an Angular app for production?"
},
{
"code": null,
"e": 1907,
"s": 1865,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 1942,
"s": 1907,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 2004,
"s": 1942,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2037,
"s": 2004,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2098,
"s": 2037,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2148,
"s": 2098,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python - Heat Maps
|
A heatmap contains values representing various shades of the same colour for each value to be plotted. Usually the darker shades of the chart represent higher values than the lighter shade. For a very different value a completely different colour can also be used.
The below example is a two-dimensional plot of values which are mapped to the indices and columns of the chart.
from pandas import DataFrame
import matplotlib.pyplot as plt
data=[{2,3,4,1},{6,3,5,2},{6,3,5,4},{3,7,5,4},{2,8,1,5}]
Index= ['I1', 'I2','I3','I4','I5']
Cols = ['C1', 'C2', 'C3','C4']
df = DataFrame(data, index=Index, columns=Cols)
plt.pcolor(df)
plt.show()
Its output is as follows −
|
[
{
"code": null,
"e": 2930,
"s": 2663,
"text": "A heatmap contains values representing various shades of the same colour for each value to be plotted. Usually the darker shades of the chart represent higher values than the lighter shade. For a very different value a completely different colour can also be used. "
},
{
"code": null,
"e": 3042,
"s": 2930,
"text": "The below example is a two-dimensional plot of values which are mapped to the indices and columns of the chart."
},
{
"code": null,
"e": 3302,
"s": 3042,
"text": "from pandas import DataFrame\nimport matplotlib.pyplot as plt\n\ndata=[{2,3,4,1},{6,3,5,2},{6,3,5,4},{3,7,5,4},{2,8,1,5}]\nIndex= ['I1', 'I2','I3','I4','I5']\nCols = ['C1', 'C2', 'C3','C4']\ndf = DataFrame(data, index=Index, columns=Cols)\n\nplt.pcolor(df)\nplt.show()"
}
] |
Scatter Plot Matrix
|
21 Nov, 2021
In a dataset, for k set of variables/columns (X1, X2, ....Xk), the scatter plot matrix plot all the pairwise scatter between different variables in the form of a matrix.
Scatter plot matrix answer the following questions:
Are there any pair-wise relationships between different variables? And if there are relationships, what is the nature of these relationships?
Are there any outliers in the dataset?
Is there any clustering by groups present in the dataset on the basis of a particular variable?
For k variables in the dataset, the scatter plot matrix contains k rows and k columns. Each row and column represents as a single scatter plot. Each individual plot (i, j) can be defined as:
Vertical Axis: Variable Xj
Horizontal Axis: Variable Xi
Below are some important factors we consider when plotting the Scatter plot matrix:
The plot lies on the diagonal is just a 45 line because we are plotting here Xi vs Xi. However, we can plot the histogram for the Xi in the diagonals or just leave it blank.
Since Xi vs Xj is equivalent to Xj vs Xi with the axes reversed, we can also omit the plots below the diagonal.
It can be more helpful if we overlay some line plot on the scattered points in the plots to give more understanding of the plot.
The idea of the pair-wise plot can also be extended to different other plots such as qunatile-quantile plots or bihistogram.
For this implementation, we will be using the Titanic dataset. This dataset can be downloaded from Kaggle. Before plotting the scatter matrix, we will be performing some preprocessing operations on the dataframe to obtain it into the desired form.
Python3
import pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt% matplotlib inline # load titanic datasettitanic_dataset = pd.read_csv('tested.csv.xls')titanic_dataset.head()# Drop some unimportant columns in the dataset.titanic_dataset.drop(['Name', 'Ticket','Cabin','PassengerId'],axis=1, inplace=True) # check for different data typestitanic_dataset.dtypes # print unique values of datasettitanic_dataset['Embarked'].unique()titanic_dataset['Sex'].unique() # Replace NAs with meantitanic_dataset.fillna(titanic_dataset.mean(), inplace=True) # convert some column into integer for representation in# scatter matrixtitanic_dataset["Sex"] = titanic_dataset["Sex"].cat.codestitanic_dataset["Embarked"] = titanic_dataset["Embarked"].cat.codes titanic_dataset.head() # plot scatter matrix using pandas and matplotlibsurvive_colors = {0:'orange', 1:'blue'}pd.plotting.scatter_matrix(titanic_dataset,figsize=(20,20),grid=True, marker='o', c= titanic_dataset['Survived'].map(colors)) # plot scatter matrix using seabornsns.set_theme(style="ticks")sns.pairplot(titanic_dataset, hue='Survived')
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 892 0 3 Kelly, Mr. James male 34.5 0 0 330911 7.8292 NaN Q
1 893 1 3 Wilkes, Mrs. James (Ellen Needs) female 47.0 1 0 363272 7.0000 NaN S
2 894 0 2 Myles, Mr. Thomas Francis male 62.0 0 0 240276 9.6875 NaN Q
3 895 0 3 Wirz, Mr. Albert male 27.0 0 0 315154 8.6625 NaN S
4 896 1 3 Hirvonen, Mrs. Alexander (Helga E Lindqvist) female 22.0 1 1 3101298 12.2875 NaN S
PassengerId int64
Survived int64
Pclass int64
Sex object
Age float64
SibSp int64
Parch int64
Fare float64
Embarked object
dtype: object
Survived Pclass Sex Age SibSp Parch Fare Embarked
0 0 3 1 34.5 0 0 7.8292 1
1 1 3 0 47.0 1 0 7.0000 2
2 0 2 1 62.0 0 0 9.6875 1
3 0 3 1 27.0 0 0 8.6625 2
4 1 3 0 22.0 1 1 12.2875 2
Matplotlib Scatter matrix
Seaborn Scatter matrix
NIST handbook
prachisoda1234
Data Visualization
ML-EDA
ML-plots
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree Introduction with example
Search Algorithms in AI
Getting started with Machine Learning
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Nov, 2021"
},
{
"code": null,
"e": 200,
"s": 28,
"text": "In a dataset, for k set of variables/columns (X1, X2, ....Xk), the scatter plot matrix plot all the pairwise scatter between different variables in the form of a matrix. "
},
{
"code": null,
"e": 252,
"s": 200,
"text": "Scatter plot matrix answer the following questions:"
},
{
"code": null,
"e": 394,
"s": 252,
"text": "Are there any pair-wise relationships between different variables? And if there are relationships, what is the nature of these relationships?"
},
{
"code": null,
"e": 433,
"s": 394,
"text": "Are there any outliers in the dataset?"
},
{
"code": null,
"e": 529,
"s": 433,
"text": "Is there any clustering by groups present in the dataset on the basis of a particular variable?"
},
{
"code": null,
"e": 720,
"s": 529,
"text": "For k variables in the dataset, the scatter plot matrix contains k rows and k columns. Each row and column represents as a single scatter plot. Each individual plot (i, j) can be defined as:"
},
{
"code": null,
"e": 747,
"s": 720,
"text": "Vertical Axis: Variable Xj"
},
{
"code": null,
"e": 776,
"s": 747,
"text": "Horizontal Axis: Variable Xi"
},
{
"code": null,
"e": 860,
"s": 776,
"text": "Below are some important factors we consider when plotting the Scatter plot matrix:"
},
{
"code": null,
"e": 1034,
"s": 860,
"text": "The plot lies on the diagonal is just a 45 line because we are plotting here Xi vs Xi. However, we can plot the histogram for the Xi in the diagonals or just leave it blank."
},
{
"code": null,
"e": 1146,
"s": 1034,
"text": "Since Xi vs Xj is equivalent to Xj vs Xi with the axes reversed, we can also omit the plots below the diagonal."
},
{
"code": null,
"e": 1275,
"s": 1146,
"text": "It can be more helpful if we overlay some line plot on the scattered points in the plots to give more understanding of the plot."
},
{
"code": null,
"e": 1400,
"s": 1275,
"text": "The idea of the pair-wise plot can also be extended to different other plots such as qunatile-quantile plots or bihistogram."
},
{
"code": null,
"e": 1648,
"s": 1400,
"text": "For this implementation, we will be using the Titanic dataset. This dataset can be downloaded from Kaggle. Before plotting the scatter matrix, we will be performing some preprocessing operations on the dataframe to obtain it into the desired form."
},
{
"code": null,
"e": 1656,
"s": 1648,
"text": "Python3"
},
{
"code": "import pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt% matplotlib inline # load titanic datasettitanic_dataset = pd.read_csv('tested.csv.xls')titanic_dataset.head()# Drop some unimportant columns in the dataset.titanic_dataset.drop(['Name', 'Ticket','Cabin','PassengerId'],axis=1, inplace=True) # check for different data typestitanic_dataset.dtypes # print unique values of datasettitanic_dataset['Embarked'].unique()titanic_dataset['Sex'].unique() # Replace NAs with meantitanic_dataset.fillna(titanic_dataset.mean(), inplace=True) # convert some column into integer for representation in# scatter matrixtitanic_dataset[\"Sex\"] = titanic_dataset[\"Sex\"].cat.codestitanic_dataset[\"Embarked\"] = titanic_dataset[\"Embarked\"].cat.codes titanic_dataset.head() # plot scatter matrix using pandas and matplotlibsurvive_colors = {0:'orange', 1:'blue'}pd.plotting.scatter_matrix(titanic_dataset,figsize=(20,20),grid=True, marker='o', c= titanic_dataset['Survived'].map(colors)) # plot scatter matrix using seabornsns.set_theme(style=\"ticks\")sns.pairplot(titanic_dataset, hue='Survived')",
"e": 2796,
"s": 1656,
"text": null
},
{
"code": null,
"e": 3453,
"s": 2796,
"text": "PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked\n0 892 0 3 Kelly, Mr. James male 34.5 0 0 330911 7.8292 NaN Q\n1 893 1 3 Wilkes, Mrs. James (Ellen Needs) female 47.0 1 0 363272 7.0000 NaN S\n2 894 0 2 Myles, Mr. Thomas Francis male 62.0 0 0 240276 9.6875 NaN Q\n3 895 0 3 Wirz, Mr. Albert male 27.0 0 0 315154 8.6625 NaN S\n4 896 1 3 Hirvonen, Mrs. Alexander (Helga E Lindqvist) female 22.0 1 1 3101298 12.2875 NaN S"
},
{
"code": null,
"e": 3674,
"s": 3453,
"text": "PassengerId int64\nSurvived int64\nPclass int64\nSex object\nAge float64\nSibSp int64\nParch int64\nFare float64\nEmbarked object\ndtype: object"
},
{
"code": null,
"e": 3996,
"s": 3674,
"text": "Survived Pclass Sex Age SibSp Parch Fare Embarked\n0 0 3 1 34.5 0 0 7.8292 1\n1 1 3 0 47.0 1 0 7.0000 2\n2 0 2 1 62.0 0 0 9.6875 1\n3 0 3 1 27.0 0 0 8.6625 2\n4 1 3 0 22.0 1 1 12.2875 2"
},
{
"code": null,
"e": 4022,
"s": 3996,
"text": "Matplotlib Scatter matrix"
},
{
"code": null,
"e": 4045,
"s": 4022,
"text": "Seaborn Scatter matrix"
},
{
"code": null,
"e": 4059,
"s": 4045,
"text": "NIST handbook"
},
{
"code": null,
"e": 4074,
"s": 4059,
"text": "prachisoda1234"
},
{
"code": null,
"e": 4093,
"s": 4074,
"text": "Data Visualization"
},
{
"code": null,
"e": 4100,
"s": 4093,
"text": "ML-EDA"
},
{
"code": null,
"e": 4109,
"s": 4100,
"text": "ML-plots"
},
{
"code": null,
"e": 4126,
"s": 4109,
"text": "Machine Learning"
},
{
"code": null,
"e": 4133,
"s": 4126,
"text": "Python"
},
{
"code": null,
"e": 4150,
"s": 4133,
"text": "Machine Learning"
},
{
"code": null,
"e": 4248,
"s": 4150,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4288,
"s": 4248,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 4312,
"s": 4288,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 4350,
"s": 4312,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 4391,
"s": 4350,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 4424,
"s": 4391,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 4452,
"s": 4424,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 4502,
"s": 4452,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 4524,
"s": 4502,
"text": "Python map() function"
},
{
"code": null,
"e": 4542,
"s": 4524,
"text": "Python Dictionary"
}
] |
How to use links on card-img-overlay class in Bootstrap 4 ?
|
15 Apr, 2020
When we put any link inside of a bootstrap card it performs well until we used card-img-overlay to put an image as a background of that card.
Bootstrap Card: A card in BootStrap 4 is a flexible and extensible content container. It includes options for headers, footers, content, colors, links etc.
Card Image Overlays: card-img-overlay is used to set the image as background image of the card and add text over the image.Syntax: For card overlay<div class="card">
<img src="..."/>
<div class="card-img-overlay">
<p class="text">....</p>
</div>
</div>
<div class="card">
<img src="..."/>
<div class="card-img-overlay">
<p class="text">....</p>
</div>
</div>
Approach: All the links placed inside class card-img-overlay works but links placed outside this class do not work. To make these links work, set the position of these links ‘relative’.
CSS Code: Place this inside the <style> tag.
.card-link
{
position:relative;
}
Below example illustrates the approach:
Example 1: This example illustrates card card-img-overlay, in the 1st card we are not using the card-img-overlay but when we use the card-img-overlay the links are not working even text is not responding as a text. It totally behaves likes a picture.
Program:<!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> .card { width: 250px; height: 300px; border: 2px solid black; padding: 5px; } h1 { color: green; text-align: center; } img { height: 120px; } .left { float: left; } .right { float: right; } .container { margin-top: 50px; width: 600px; height: auto; } </style></head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <div class="card left"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/uploads/20200109151258/672.png" /> <div class="card-inverse"> <h3 class="text-stroke">GeeksforGeeks</h3> </div> <div class="card-block"> <a href="#" class="card-link">Card link</a> <p class="card-text">A Computer Science Portal</p> </div> <div class="card-footer"> <small class="text-muted">Card link is working</small> </div> </div> <div class="card right"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/uploads/20200109151258/672.png" /> <div class="card-img-overlay card-inverse"> <h3 class="text-stroke">GeeksforGeeks</h3> </div> <div class="card-block"> <a href="#" class="card-link">Card link</a> <p class="card-text">A Computer Science Portal</p> </div> <div class="card-footer"> <small class="text-muted">Card link is not working</small> </div> </div> </div></body> </html>
<!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> .card { width: 250px; height: 300px; border: 2px solid black; padding: 5px; } h1 { color: green; text-align: center; } img { height: 120px; } .left { float: left; } .right { float: right; } .container { margin-top: 50px; width: 600px; height: auto; } </style></head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <div class="card left"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/uploads/20200109151258/672.png" /> <div class="card-inverse"> <h3 class="text-stroke">GeeksforGeeks</h3> </div> <div class="card-block"> <a href="#" class="card-link">Card link</a> <p class="card-text">A Computer Science Portal</p> </div> <div class="card-footer"> <small class="text-muted">Card link is working</small> </div> </div> <div class="card right"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/uploads/20200109151258/672.png" /> <div class="card-img-overlay card-inverse"> <h3 class="text-stroke">GeeksforGeeks</h3> </div> <div class="card-block"> <a href="#" class="card-link">Card link</a> <p class="card-text">A Computer Science Portal</p> </div> <div class="card-footer"> <small class="text-muted">Card link is not working</small> </div> </div> </div></body> </html>
Output:
Example 2: This example illustrates card card-img-overlay, in the 1st card we are not using the card-img-overlay but when we use the card-img-overlay the links are working and text are also behaving as text.
Program:<!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> .card-link{ position:relative; } .card { width: 250px; height: 300px; border: 2px solid black; padding: 5px; } h1 { color: green; text-align: center; } img { height: 120px; } .left { float: left; } .right { float: right; } .container { margin-top: 50px; width: 600px; height: auto; } </style></head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <div class="card left"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/uploads/20200109151258/672.png" /> <div class="card-inverse"> <h3 class="text-stroke">GeeksforGeeks</h3> </div> <div class="card-block"> <a href="#" class="card-link">Card link</a> <p class="card-text">A Computer Science Portal</p> </div> <div class="card-footer"> <small class="text-muted">Card link is working</small> </div> </div> <div class="card right"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/uploads/20200109151258/672.png" /> <div class="card-img-overlay card-inverse"> <h3 class="text-stroke">GeeksforGeeks</h3> <div class="card-block"> <a href="#" class="card-link text-white" >Card link</a> <p class="card-text">A Computer Science Portal</p> </div> </div> <a href="#" class="card-link " >Card link</a> <div class="card-footer"> <small>Card link is working</small> </div> </div> </div></body> </html>
<!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Card</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> .card-link{ position:relative; } .card { width: 250px; height: 300px; border: 2px solid black; padding: 5px; } h1 { color: green; text-align: center; } img { height: 120px; } .left { float: left; } .right { float: right; } .container { margin-top: 50px; width: 600px; height: auto; } </style></head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <div class="card left"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/uploads/20200109151258/672.png" /> <div class="card-inverse"> <h3 class="text-stroke">GeeksforGeeks</h3> </div> <div class="card-block"> <a href="#" class="card-link">Card link</a> <p class="card-text">A Computer Science Portal</p> </div> <div class="card-footer"> <small class="text-muted">Card link is working</small> </div> </div> <div class="card right"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/uploads/20200109151258/672.png" /> <div class="card-img-overlay card-inverse"> <h3 class="text-stroke">GeeksforGeeks</h3> <div class="card-block"> <a href="#" class="card-link text-white" >Card link</a> <p class="card-text">A Computer Science Portal</p> </div> </div> <a href="#" class="card-link " >Card link</a> <div class="card-footer"> <small>Card link is working</small> </div> </div> </div></body> </html>
Output:
Note: In the second example the muted text not behaving like text because it is out of the card-link div.
g_ragini
Bootstrap-4
Picked
Bootstrap
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to Use Bootstrap with React?
Tailwind CSS vs Bootstrap
How to set vertical alignment in Bootstrap ?
How to toggle password visibility in forms using Bootstrap-icons ?
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": "\n15 Apr, 2020"
},
{
"code": null,
"e": 170,
"s": 28,
"text": "When we put any link inside of a bootstrap card it performs well until we used card-img-overlay to put an image as a background of that card."
},
{
"code": null,
"e": 326,
"s": 170,
"text": "Bootstrap Card: A card in BootStrap 4 is a flexible and extensible content container. It includes options for headers, footers, content, colors, links etc."
},
{
"code": null,
"e": 584,
"s": 326,
"text": "Card Image Overlays: card-img-overlay is used to set the image as background image of the card and add text over the image.Syntax: For card overlay<div class=\"card\">\n <img src=\"...\"/>\n <div class=\"card-img-overlay\">\n <p class=\"text\">....</p>\n </div>\n</div>"
},
{
"code": null,
"e": 695,
"s": 584,
"text": "<div class=\"card\">\n <img src=\"...\"/>\n <div class=\"card-img-overlay\">\n <p class=\"text\">....</p>\n </div>\n</div>"
},
{
"code": null,
"e": 881,
"s": 695,
"text": "Approach: All the links placed inside class card-img-overlay works but links placed outside this class do not work. To make these links work, set the position of these links ‘relative’."
},
{
"code": null,
"e": 926,
"s": 881,
"text": "CSS Code: Place this inside the <style> tag."
},
{
"code": null,
"e": 976,
"s": 926,
"text": ".card-link \n { \n position:relative; \n }\n"
},
{
"code": null,
"e": 1016,
"s": 976,
"text": "Below example illustrates the approach:"
},
{
"code": null,
"e": 1267,
"s": 1016,
"text": "Example 1: This example illustrates card card-img-overlay, in the 1st card we are not using the card-img-overlay but when we use the card-img-overlay the links are not working even text is not responding as a text. It totally behaves likes a picture."
},
{
"code": null,
"e": 3697,
"s": 1267,
"text": "Program:<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> .card { width: 250px; height: 300px; border: 2px solid black; padding: 5px; } h1 { color: green; text-align: center; } img { height: 120px; } .left { float: left; } .right { float: right; } .container { margin-top: 50px; width: 600px; height: auto; } </style></head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <div class=\"card left\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200109151258/672.png\" /> <div class=\"card-inverse\"> <h3 class=\"text-stroke\">GeeksforGeeks</h3> </div> <div class=\"card-block\"> <a href=\"#\" class=\"card-link\">Card link</a> <p class=\"card-text\">A Computer Science Portal</p> </div> <div class=\"card-footer\"> <small class=\"text-muted\">Card link is working</small> </div> </div> <div class=\"card right\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200109151258/672.png\" /> <div class=\"card-img-overlay card-inverse\"> <h3 class=\"text-stroke\">GeeksforGeeks</h3> </div> <div class=\"card-block\"> <a href=\"#\" class=\"card-link\">Card link</a> <p class=\"card-text\">A Computer Science Portal</p> </div> <div class=\"card-footer\"> <small class=\"text-muted\">Card link is not working</small> </div> </div> </div></body> </html>"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> .card { width: 250px; height: 300px; border: 2px solid black; padding: 5px; } h1 { color: green; text-align: center; } img { height: 120px; } .left { float: left; } .right { float: right; } .container { margin-top: 50px; width: 600px; height: auto; } </style></head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <div class=\"card left\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200109151258/672.png\" /> <div class=\"card-inverse\"> <h3 class=\"text-stroke\">GeeksforGeeks</h3> </div> <div class=\"card-block\"> <a href=\"#\" class=\"card-link\">Card link</a> <p class=\"card-text\">A Computer Science Portal</p> </div> <div class=\"card-footer\"> <small class=\"text-muted\">Card link is working</small> </div> </div> <div class=\"card right\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200109151258/672.png\" /> <div class=\"card-img-overlay card-inverse\"> <h3 class=\"text-stroke\">GeeksforGeeks</h3> </div> <div class=\"card-block\"> <a href=\"#\" class=\"card-link\">Card link</a> <p class=\"card-text\">A Computer Science Portal</p> </div> <div class=\"card-footer\"> <small class=\"text-muted\">Card link is not working</small> </div> </div> </div></body> </html>",
"e": 6119,
"s": 3697,
"text": null
},
{
"code": null,
"e": 6127,
"s": 6119,
"text": "Output:"
},
{
"code": null,
"e": 6335,
"s": 6127,
"text": "Example 2: This example illustrates card card-img-overlay, in the 1st card we are not using the card-img-overlay but when we use the card-img-overlay the links are working and text are also behaving as text."
},
{
"code": null,
"e": 8910,
"s": 6335,
"text": "Program:<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> .card-link{ position:relative; } .card { width: 250px; height: 300px; border: 2px solid black; padding: 5px; } h1 { color: green; text-align: center; } img { height: 120px; } .left { float: left; } .right { float: right; } .container { margin-top: 50px; width: 600px; height: auto; } </style></head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <div class=\"card left\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200109151258/672.png\" /> <div class=\"card-inverse\"> <h3 class=\"text-stroke\">GeeksforGeeks</h3> </div> <div class=\"card-block\"> <a href=\"#\" class=\"card-link\">Card link</a> <p class=\"card-text\">A Computer Science Portal</p> </div> <div class=\"card-footer\"> <small class=\"text-muted\">Card link is working</small> </div> </div> <div class=\"card right\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200109151258/672.png\" /> <div class=\"card-img-overlay card-inverse\"> <h3 class=\"text-stroke\">GeeksforGeeks</h3> <div class=\"card-block\"> <a href=\"#\" class=\"card-link text-white\" >Card link</a> <p class=\"card-text\">A Computer Science Portal</p> </div> </div> <a href=\"#\" class=\"card-link \" >Card link</a> <div class=\"card-footer\"> <small>Card link is working</small> </div> </div> </div></body> </html> "
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Card</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> .card-link{ position:relative; } .card { width: 250px; height: 300px; border: 2px solid black; padding: 5px; } h1 { color: green; text-align: center; } img { height: 120px; } .left { float: left; } .right { float: right; } .container { margin-top: 50px; width: 600px; height: auto; } </style></head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <div class=\"card left\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200109151258/672.png\" /> <div class=\"card-inverse\"> <h3 class=\"text-stroke\">GeeksforGeeks</h3> </div> <div class=\"card-block\"> <a href=\"#\" class=\"card-link\">Card link</a> <p class=\"card-text\">A Computer Science Portal</p> </div> <div class=\"card-footer\"> <small class=\"text-muted\">Card link is working</small> </div> </div> <div class=\"card right\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200109151258/672.png\" /> <div class=\"card-img-overlay card-inverse\"> <h3 class=\"text-stroke\">GeeksforGeeks</h3> <div class=\"card-block\"> <a href=\"#\" class=\"card-link text-white\" >Card link</a> <p class=\"card-text\">A Computer Science Portal</p> </div> </div> <a href=\"#\" class=\"card-link \" >Card link</a> <div class=\"card-footer\"> <small>Card link is working</small> </div> </div> </div></body> </html> ",
"e": 11477,
"s": 8910,
"text": null
},
{
"code": null,
"e": 11485,
"s": 11477,
"text": "Output:"
},
{
"code": null,
"e": 11591,
"s": 11485,
"text": "Note: In the second example the muted text not behaving like text because it is out of the card-link div."
},
{
"code": null,
"e": 11600,
"s": 11591,
"text": "g_ragini"
},
{
"code": null,
"e": 11612,
"s": 11600,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 11619,
"s": 11612,
"text": "Picked"
},
{
"code": null,
"e": 11629,
"s": 11619,
"text": "Bootstrap"
},
{
"code": null,
"e": 11646,
"s": 11629,
"text": "Web Technologies"
},
{
"code": null,
"e": 11673,
"s": 11646,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 11771,
"s": 11673,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11812,
"s": 11771,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 11845,
"s": 11812,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 11871,
"s": 11845,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 11916,
"s": 11871,
"text": "How to set vertical alignment in Bootstrap ?"
},
{
"code": null,
"e": 11983,
"s": 11916,
"text": "How to toggle password visibility in forms using Bootstrap-icons ?"
},
{
"code": null,
"e": 12016,
"s": 11983,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 12078,
"s": 12016,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 12139,
"s": 12078,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 12189,
"s": 12139,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python | Find maximum value in each sublist
|
14 Feb, 2019
Given list of lists in Python, write a Python program to find maximum value of list each sub-list.
Examples:
Input : [[10, 13, 454, 66, 44], [10, 8, 7, 23]]
Output : [454, 23]
Input : [[15, 12, 27, 1, 33], [101, 58, 77, 23]]
Output : [33, 101]
Method #1: Using list comprehension.
# Python code to Find maximum of list in nested list # Initialising Lista = [[10, 13, 454, 66, 44], [10, 8, 7, 23]] # find max in listb = [max(p) for p in a] # Printing maxprint(b)
[454, 23]
Method #2: Using map
# Python code to Find maximum of list in nested list # Initialising Lista = [[10, 13, 454, 66, 44], [10, 8, 7, 23]] # find max in listans = list(map(max, a)) # Printing maxprint(ans)
[454, 23]
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Feb, 2019"
},
{
"code": null,
"e": 127,
"s": 28,
"text": "Given list of lists in Python, write a Python program to find maximum value of list each sub-list."
},
{
"code": null,
"e": 137,
"s": 127,
"text": "Examples:"
},
{
"code": null,
"e": 275,
"s": 137,
"text": "Input : [[10, 13, 454, 66, 44], [10, 8, 7, 23]]\nOutput : [454, 23]\n\nInput : [[15, 12, 27, 1, 33], [101, 58, 77, 23]]\nOutput : [33, 101]"
},
{
"code": null,
"e": 313,
"s": 275,
"text": " Method #1: Using list comprehension."
},
{
"code": "# Python code to Find maximum of list in nested list # Initialising Lista = [[10, 13, 454, 66, 44], [10, 8, 7, 23]] # find max in listb = [max(p) for p in a] # Printing maxprint(b)",
"e": 497,
"s": 313,
"text": null
},
{
"code": null,
"e": 508,
"s": 497,
"text": "[454, 23]\n"
},
{
"code": null,
"e": 530,
"s": 508,
"text": " Method #2: Using map"
},
{
"code": "# Python code to Find maximum of list in nested list # Initialising Lista = [[10, 13, 454, 66, 44], [10, 8, 7, 23]] # find max in listans = list(map(max, a)) # Printing maxprint(ans)",
"e": 716,
"s": 530,
"text": null
},
{
"code": null,
"e": 727,
"s": 716,
"text": "[454, 23]\n"
},
{
"code": null,
"e": 748,
"s": 727,
"text": "Python list-programs"
},
{
"code": null,
"e": 760,
"s": 748,
"text": "python-list"
},
{
"code": null,
"e": 767,
"s": 760,
"text": "Python"
},
{
"code": null,
"e": 779,
"s": 767,
"text": "python-list"
},
{
"code": null,
"e": 877,
"s": 779,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 895,
"s": 877,
"text": "Python Dictionary"
},
{
"code": null,
"e": 937,
"s": 895,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 959,
"s": 937,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 994,
"s": 959,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1020,
"s": 994,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1052,
"s": 1020,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1081,
"s": 1052,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1108,
"s": 1081,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1138,
"s": 1108,
"text": "Iterate over a list in Python"
}
] |
Program for FCFS CPU Scheduling | Set 1
|
19 Apr, 2021
Given n processes with their burst times, the task is to find average waiting time and average turn around time using FCFS scheduling algorithm. First in, first out (FIFO), also known as first come, first served (FCFS), is the simplest scheduling algorithm. FIFO simply queues processes in the order that they arrive in the ready queue. In this, the process that comes first will be executed first and next process starts only after the previous gets fully executed. Here we are considering that arrival time for all processes is 0.How to compute below times in Round Robin using a program?
Completion Time: Time at which process completes its execution.Turn Around Time: Time Difference between completion time and arrival time. Turn Around Time = Completion Time – Arrival TimeWaiting Time(W.T): Time Difference between turn around time and burst time. Waiting Time = Turn Around Time – Burst Time
Completion Time: Time at which process completes its execution.
Turn Around Time: Time Difference between completion time and arrival time. Turn Around Time = Completion Time – Arrival Time
Waiting Time(W.T): Time Difference between turn around time and burst time. Waiting Time = Turn Around Time – Burst Time
In this post, we have assumed arrival times as 0, so turn around and completion times are same.
Implementation:
1- Input the processes along with their burst time (bt).
2- Find waiting time (wt) for all processes.
3- As first process that comes need not to wait so
waiting time for process 1 will be 0 i.e. wt[0] = 0.
4- Find waiting time for all other processes i.e. for
process i ->
wt[i] = bt[i-1] + wt[i-1] .
5- Find turnaround time = waiting_time + burst_time
for all processes.
6- Find average waiting time =
total_waiting_time / no_of_processes.
7- Similarly, find average turnaround time =
total_turn_around_time / no_of_processes.
C++
C
Java
Python 3
C#
Javascript
// C++ program for implementation of FCFS// scheduling#include<iostream>using namespace std; // Function to find the waiting time for all// processesvoid findWaitingTime(int processes[], int n, int bt[], int wt[]){ // waiting time for first process is 0 wt[0] = 0; // calculating waiting time for (int i = 1; i < n ; i++ ) wt[i] = bt[i-1] + wt[i-1] ;} // Function to calculate turn around timevoid findTurnAroundTime( int processes[], int n, int bt[], int wt[], int tat[]){ // calculating turnaround time by adding // bt[i] + wt[i] for (int i = 0; i < n ; i++) tat[i] = bt[i] + wt[i];} //Function to calculate average timevoid findavgTime( int processes[], int n, int bt[]){ int wt[n], tat[n], total_wt = 0, total_tat = 0; //Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt); //Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); //Display processes along with all details cout << "Processes "<< " Burst time " << " Waiting time " << " Turn around time\n"; // Calculate total waiting time and total turn // around time for (int i=0; i<n; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; cout << " " << i+1 << "\t\t" << bt[i] <<"\t " << wt[i] <<"\t\t " << tat[i] <<endl; } cout << "Average waiting time = " << (float)total_wt / (float)n; cout << "\nAverage turn around time = " << (float)total_tat / (float)n;} // Driver codeint main(){ //process id's int processes[] = { 1, 2, 3}; int n = sizeof processes / sizeof processes[0]; //Burst time of all processes int burst_time[] = {10, 5, 8}; findavgTime(processes, n, burst_time); return 0;}
// C program for implementation of FCFS // scheduling#include<stdio.h>// Function to find the waiting time for all // processesvoid findWaitingTime(int processes[], int n, int bt[], int wt[]){ // waiting time for first process is 0 wt[0] = 0; // calculating waiting time for (int i = 1; i < n ; i++ ) wt[i] = bt[i-1] + wt[i-1] ;} // Function to calculate turn around timevoid findTurnAroundTime( int processes[], int n, int bt[], int wt[], int tat[]){ // calculating turnaround time by adding // bt[i] + wt[i] for (int i = 0; i < n ; i++) tat[i] = bt[i] + wt[i];} //Function to calculate average timevoid findavgTime( int processes[], int n, int bt[]){ int wt[n], tat[n], total_wt = 0, total_tat = 0; //Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt); //Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); //Display processes along with all details printf("Processes Burst time Waiting time Turn around time\n"); // Calculate total waiting time and total turn // around time for (int i=0; i<n; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; printf(" %d ",(i+1)); printf(" %d ", bt[i] ); printf(" %d",wt[i] ); printf(" %d\n",tat[i] ); } int s=(float)total_wt / (float)n; int t=(float)total_tat / (float)n; printf("Average waiting time = %d",s); printf("\n"); printf("Average turn around time = %d ",t);} // Driver codeint main(){ //process id's int processes[] = { 1, 2, 3}; int n = sizeof processes / sizeof processes[0]; //Burst time of all processes int burst_time[] = {10, 5, 8}; findavgTime(processes, n, burst_time); return 0;}// This code is contributed by Shivi_Aggarwal
// Java program for implementation of FCFS// scheduling import java.text.ParseException; class GFG { // Function to find the waiting time for all // processes static void findWaitingTime(int processes[], int n, int bt[], int wt[]) { // waiting time for first process is 0 wt[0] = 0; // calculating waiting time for (int i = 1; i < n; i++) { wt[i] = bt[i - 1] + wt[i - 1]; } } // Function to calculate turn around time static void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[]) { // calculating turnaround time by adding // bt[i] + wt[i] for (int i = 0; i < n; i++) { tat[i] = bt[i] + wt[i]; } } //Function to calculate average time static void findavgTime(int processes[], int n, int bt[]) { int wt[] = new int[n], tat[] = new int[n]; int total_wt = 0, total_tat = 0; //Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt); //Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); //Display processes along with all details System.out.printf("Processes Burst time Waiting" +" time Turn around time\n"); // Calculate total waiting time and total turn // around time for (int i = 0; i < n; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; System.out.printf(" %d ", (i + 1)); System.out.printf(" %d ", bt[i]); System.out.printf(" %d", wt[i]); System.out.printf(" %d\n", tat[i]); } float s = (float)total_wt /(float) n; int t = total_tat / n; System.out.printf("Average waiting time = %f", s); System.out.printf("\n"); System.out.printf("Average turn around time = %d ", t); } // Driver code public static void main(String[] args) throws ParseException { //process id's int processes[] = {1, 2, 3}; int n = processes.length; //Burst time of all processes int burst_time[] = {10, 5, 8}; findavgTime(processes, n, burst_time); }}// This code is contributed by 29ajaykumar
# Python3 program for implementation# of FCFS scheduling # Function to find the waiting# time for all processesdef findWaitingTime(processes, n, bt, wt): # waiting time for # first process is 0 wt[0] = 0 # calculating waiting time for i in range(1, n ): wt[i] = bt[i - 1] + wt[i - 1] # Function to calculate turn# around timedef findTurnAroundTime(processes, n, bt, wt, tat): # calculating turnaround # time by adding bt[i] + wt[i] for i in range(n): tat[i] = bt[i] + wt[i] # Function to calculate# average timedef findavgTime( processes, n, bt): wt = [0] * n tat = [0] * n total_wt = 0 total_tat = 0 # Function to find waiting # time of all processes findWaitingTime(processes, n, bt, wt) # Function to find turn around # time for all processes findTurnAroundTime(processes, n, bt, wt, tat) # Display processes along # with all details print( "Processes Burst time " + " Waiting time " + " Turn around time") # Calculate total waiting time # and total turn around time for i in range(n): total_wt = total_wt + wt[i] total_tat = total_tat + tat[i] print(" " + str(i + 1) + "\t\t" + str(bt[i]) + "\t " + str(wt[i]) + "\t\t " + str(tat[i])) print( "Average waiting time = "+ str(total_wt / n)) print("Average turn around time = "+ str(total_tat / n)) # Driver codeif __name__ =="__main__": # process id's processes = [ 1, 2, 3] n = len(processes) # Burst time of all processes burst_time = [10, 5, 8] findavgTime(processes, n, burst_time) # This code is contributed# by ChitraNayal
// C# program for implementation of FCFS// schedulingusing System; class GFG{ // Function to find the waiting time for all // processes static void findWaitingTime(int []processes, int n, int []bt, int[] wt) { // waiting time for first process is 0 wt[0] = 0; // calculating waiting time for (int i = 1; i < n; i++) { wt[i] = bt[i - 1] + wt[i - 1]; } } // Function to calculate turn around time static void findTurnAroundTime(int []processes, int n, int []bt, int []wt, int []tat) { // calculating turnaround time by adding // bt[i] + wt[i] for (int i = 0; i < n; i++) { tat[i] = bt[i] + wt[i]; } } // Function to calculate average time static void findavgTime(int []processes, int n, int []bt) { int []wt = new int[n]; int []tat = new int[n]; int total_wt = 0, total_tat = 0; //Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt); //Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); //Display processes along with all details Console.Write("Processes Burst time Waiting" +" time Turn around time\n"); // Calculate total waiting time and total turn // around time for (int i = 0; i < n; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; Console.Write(" {0} ", (i + 1)); Console.Write(" {0} ", bt[i]); Console.Write(" {0}", wt[i]); Console.Write(" {0}\n", tat[i]); } float s = (float)total_wt /(float) n; int t = total_tat / n; Console.Write("Average waiting time = {0}", s); Console.Write("\n"); Console.Write("Average turn around time = {0} ", t); } // Driver code public static void Main(String[] args) { // process id's int []processes = {1, 2, 3}; int n = processes.Length; // Burst time of all processes int []burst_time = {10, 5, 8}; findavgTime(processes, n, burst_time); }} // This code contributed by Rajput-Ji
<script> // JavaScript program for implementation of FCFS // scheduling // Function to find the waiting time for all // processes function findWaitingTime(processes,n,bt,wt) { // waiting time for first process is 0 wt[0] = 0; // calculating waiting time for (let i = 1; i < n; i++) { wt[i] = bt[i - 1] + wt[i - 1]; } } function findTurnAroundTime(processes,n,bt,wt,tat) { // calculating turnaround time by adding // bt[i] + wt[i] for (let i = 0; i < n; i++) { tat[i] = bt[i] + wt[i]; } } function findavgTime(processes,n,bt) { let wt = new Array(n), tat = new Array(n); for(let i=0;i<n;i++) { wt[i]=0; tat[i]=0; } let total_wt = 0, total_tat = 0; //Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt); //Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); //Display processes along with all details document.write("Processes Burst time Waiting" +" time Turn around time<br>"); // Calculate total waiting time and total turn // around time for (let i = 0; i < n; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; document.write(" ", (i + 1)+" "); document.write(" "+ bt[i]+" "); document.write(" "+ wt[i]); document.write(" "+ tat[i]+"<br>"); } let s = total_wt / n; let t = Math.floor(total_tat / n); document.write("Average waiting time = "+ s); document.write("<br>"); document.write("Average turn around time = ", t+" "); } let processes=[1,2,3]; let n = processes.length; let burst_time=[10,5,8]; findavgTime(processes, n, burst_time); // This code is contributed by rag2127 </script>
Output:
Processes Burst time Waiting time Turn around time
1 10 0 10
2 5 10 15
3 8 15 23
Average waiting time = 8.33333
Average turn around time = 16
Important Points:
Non-preemptiveAverage Waiting Time is not optimalCannot utilize resources in parallel : Results in Convoy effect (Consider a situation when many IO bound processes are there and one CPU bound process. The IO bound processes have to wait for CPU bound process when CPU bound process acquires CPU. The IO bound process could have better taken CPU for some time, then used IO devices).
Non-preemptive
Average Waiting Time is not optimal
Cannot utilize resources in parallel : Results in Convoy effect (Consider a situation when many IO bound processes are there and one CPU bound process. The IO bound processes have to wait for CPU bound process when CPU bound process acquires CPU. The IO bound process could have better taken CPU for some time, then used IO devices).
Shivi_Aggarwal
ukasp
29AjayKumar
Rajput-Ji
rag2127
cpu-scheduling
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Cache Memory in Computer Organization
LRU Cache Implementation
'crontab' in Linux with Examples
Cd cmd command
Memory Management in Operating System
Last Minute Notes – Operating Systems
Commonly Asked Operating Systems Interview Questions
Preemptive and Non-Preemptive Scheduling
Difference between Internal and External fragmentation
File Access Methods in Operating System
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Apr, 2021"
},
{
"code": null,
"e": 645,
"s": 52,
"text": "Given n processes with their burst times, the task is to find average waiting time and average turn around time using FCFS scheduling algorithm. First in, first out (FIFO), also known as first come, first served (FCFS), is the simplest scheduling algorithm. FIFO simply queues processes in the order that they arrive in the ready queue. In this, the process that comes first will be executed first and next process starts only after the previous gets fully executed. Here we are considering that arrival time for all processes is 0.How to compute below times in Round Robin using a program? "
},
{
"code": null,
"e": 954,
"s": 645,
"text": "Completion Time: Time at which process completes its execution.Turn Around Time: Time Difference between completion time and arrival time. Turn Around Time = Completion Time – Arrival TimeWaiting Time(W.T): Time Difference between turn around time and burst time. Waiting Time = Turn Around Time – Burst Time"
},
{
"code": null,
"e": 1018,
"s": 954,
"text": "Completion Time: Time at which process completes its execution."
},
{
"code": null,
"e": 1144,
"s": 1018,
"text": "Turn Around Time: Time Difference between completion time and arrival time. Turn Around Time = Completion Time – Arrival Time"
},
{
"code": null,
"e": 1265,
"s": 1144,
"text": "Waiting Time(W.T): Time Difference between turn around time and burst time. Waiting Time = Turn Around Time – Burst Time"
},
{
"code": null,
"e": 1364,
"s": 1267,
"text": "In this post, we have assumed arrival times as 0, so turn around and completion times are same. "
},
{
"code": null,
"e": 1382,
"s": 1364,
"text": "Implementation: "
},
{
"code": null,
"e": 1976,
"s": 1382,
"text": "1- Input the processes along with their burst time (bt).\n2- Find waiting time (wt) for all processes.\n3- As first process that comes need not to wait so \n waiting time for process 1 will be 0 i.e. wt[0] = 0.\n4- Find waiting time for all other processes i.e. for\n process i -> \n wt[i] = bt[i-1] + wt[i-1] .\n5- Find turnaround time = waiting_time + burst_time \n for all processes.\n6- Find average waiting time = \n total_waiting_time / no_of_processes.\n7- Similarly, find average turnaround time = \n total_turn_around_time / no_of_processes."
},
{
"code": null,
"e": 1984,
"s": 1980,
"text": "C++"
},
{
"code": null,
"e": 1986,
"s": 1984,
"text": "C"
},
{
"code": null,
"e": 1991,
"s": 1986,
"text": "Java"
},
{
"code": null,
"e": 2000,
"s": 1991,
"text": "Python 3"
},
{
"code": null,
"e": 2003,
"s": 2000,
"text": "C#"
},
{
"code": null,
"e": 2014,
"s": 2003,
"text": "Javascript"
},
{
"code": "// C++ program for implementation of FCFS// scheduling#include<iostream>using namespace std; // Function to find the waiting time for all// processesvoid findWaitingTime(int processes[], int n, int bt[], int wt[]){ // waiting time for first process is 0 wt[0] = 0; // calculating waiting time for (int i = 1; i < n ; i++ ) wt[i] = bt[i-1] + wt[i-1] ;} // Function to calculate turn around timevoid findTurnAroundTime( int processes[], int n, int bt[], int wt[], int tat[]){ // calculating turnaround time by adding // bt[i] + wt[i] for (int i = 0; i < n ; i++) tat[i] = bt[i] + wt[i];} //Function to calculate average timevoid findavgTime( int processes[], int n, int bt[]){ int wt[n], tat[n], total_wt = 0, total_tat = 0; //Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt); //Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); //Display processes along with all details cout << \"Processes \"<< \" Burst time \" << \" Waiting time \" << \" Turn around time\\n\"; // Calculate total waiting time and total turn // around time for (int i=0; i<n; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; cout << \" \" << i+1 << \"\\t\\t\" << bt[i] <<\"\\t \" << wt[i] <<\"\\t\\t \" << tat[i] <<endl; } cout << \"Average waiting time = \" << (float)total_wt / (float)n; cout << \"\\nAverage turn around time = \" << (float)total_tat / (float)n;} // Driver codeint main(){ //process id's int processes[] = { 1, 2, 3}; int n = sizeof processes / sizeof processes[0]; //Burst time of all processes int burst_time[] = {10, 5, 8}; findavgTime(processes, n, burst_time); return 0;}",
"e": 3874,
"s": 2014,
"text": null
},
{
"code": "// C program for implementation of FCFS // scheduling#include<stdio.h>// Function to find the waiting time for all // processesvoid findWaitingTime(int processes[], int n, int bt[], int wt[]){ // waiting time for first process is 0 wt[0] = 0; // calculating waiting time for (int i = 1; i < n ; i++ ) wt[i] = bt[i-1] + wt[i-1] ;} // Function to calculate turn around timevoid findTurnAroundTime( int processes[], int n, int bt[], int wt[], int tat[]){ // calculating turnaround time by adding // bt[i] + wt[i] for (int i = 0; i < n ; i++) tat[i] = bt[i] + wt[i];} //Function to calculate average timevoid findavgTime( int processes[], int n, int bt[]){ int wt[n], tat[n], total_wt = 0, total_tat = 0; //Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt); //Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); //Display processes along with all details printf(\"Processes Burst time Waiting time Turn around time\\n\"); // Calculate total waiting time and total turn // around time for (int i=0; i<n; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; printf(\" %d \",(i+1)); printf(\" %d \", bt[i] ); printf(\" %d\",wt[i] ); printf(\" %d\\n\",tat[i] ); } int s=(float)total_wt / (float)n; int t=(float)total_tat / (float)n; printf(\"Average waiting time = %d\",s); printf(\"\\n\"); printf(\"Average turn around time = %d \",t);} // Driver codeint main(){ //process id's int processes[] = { 1, 2, 3}; int n = sizeof processes / sizeof processes[0]; //Burst time of all processes int burst_time[] = {10, 5, 8}; findavgTime(processes, n, burst_time); return 0;}// This code is contributed by Shivi_Aggarwal",
"e": 5810,
"s": 3874,
"text": null
},
{
"code": "// Java program for implementation of FCFS// scheduling import java.text.ParseException; class GFG { // Function to find the waiting time for all // processes static void findWaitingTime(int processes[], int n, int bt[], int wt[]) { // waiting time for first process is 0 wt[0] = 0; // calculating waiting time for (int i = 1; i < n; i++) { wt[i] = bt[i - 1] + wt[i - 1]; } } // Function to calculate turn around time static void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[]) { // calculating turnaround time by adding // bt[i] + wt[i] for (int i = 0; i < n; i++) { tat[i] = bt[i] + wt[i]; } } //Function to calculate average time static void findavgTime(int processes[], int n, int bt[]) { int wt[] = new int[n], tat[] = new int[n]; int total_wt = 0, total_tat = 0; //Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt); //Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); //Display processes along with all details System.out.printf(\"Processes Burst time Waiting\" +\" time Turn around time\\n\"); // Calculate total waiting time and total turn // around time for (int i = 0; i < n; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; System.out.printf(\" %d \", (i + 1)); System.out.printf(\" %d \", bt[i]); System.out.printf(\" %d\", wt[i]); System.out.printf(\" %d\\n\", tat[i]); } float s = (float)total_wt /(float) n; int t = total_tat / n; System.out.printf(\"Average waiting time = %f\", s); System.out.printf(\"\\n\"); System.out.printf(\"Average turn around time = %d \", t); } // Driver code public static void main(String[] args) throws ParseException { //process id's int processes[] = {1, 2, 3}; int n = processes.length; //Burst time of all processes int burst_time[] = {10, 5, 8}; findavgTime(processes, n, burst_time); }}// This code is contributed by 29ajaykumar",
"e": 8117,
"s": 5810,
"text": null
},
{
"code": "# Python3 program for implementation# of FCFS scheduling # Function to find the waiting# time for all processesdef findWaitingTime(processes, n, bt, wt): # waiting time for # first process is 0 wt[0] = 0 # calculating waiting time for i in range(1, n ): wt[i] = bt[i - 1] + wt[i - 1] # Function to calculate turn# around timedef findTurnAroundTime(processes, n, bt, wt, tat): # calculating turnaround # time by adding bt[i] + wt[i] for i in range(n): tat[i] = bt[i] + wt[i] # Function to calculate# average timedef findavgTime( processes, n, bt): wt = [0] * n tat = [0] * n total_wt = 0 total_tat = 0 # Function to find waiting # time of all processes findWaitingTime(processes, n, bt, wt) # Function to find turn around # time for all processes findTurnAroundTime(processes, n, bt, wt, tat) # Display processes along # with all details print( \"Processes Burst time \" + \" Waiting time \" + \" Turn around time\") # Calculate total waiting time # and total turn around time for i in range(n): total_wt = total_wt + wt[i] total_tat = total_tat + tat[i] print(\" \" + str(i + 1) + \"\\t\\t\" + str(bt[i]) + \"\\t \" + str(wt[i]) + \"\\t\\t \" + str(tat[i])) print( \"Average waiting time = \"+ str(total_wt / n)) print(\"Average turn around time = \"+ str(total_tat / n)) # Driver codeif __name__ ==\"__main__\": # process id's processes = [ 1, 2, 3] n = len(processes) # Burst time of all processes burst_time = [10, 5, 8] findavgTime(processes, n, burst_time) # This code is contributed# by ChitraNayal",
"e": 9939,
"s": 8117,
"text": null
},
{
"code": "// C# program for implementation of FCFS// schedulingusing System; class GFG{ // Function to find the waiting time for all // processes static void findWaitingTime(int []processes, int n, int []bt, int[] wt) { // waiting time for first process is 0 wt[0] = 0; // calculating waiting time for (int i = 1; i < n; i++) { wt[i] = bt[i - 1] + wt[i - 1]; } } // Function to calculate turn around time static void findTurnAroundTime(int []processes, int n, int []bt, int []wt, int []tat) { // calculating turnaround time by adding // bt[i] + wt[i] for (int i = 0; i < n; i++) { tat[i] = bt[i] + wt[i]; } } // Function to calculate average time static void findavgTime(int []processes, int n, int []bt) { int []wt = new int[n]; int []tat = new int[n]; int total_wt = 0, total_tat = 0; //Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt); //Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); //Display processes along with all details Console.Write(\"Processes Burst time Waiting\" +\" time Turn around time\\n\"); // Calculate total waiting time and total turn // around time for (int i = 0; i < n; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; Console.Write(\" {0} \", (i + 1)); Console.Write(\" {0} \", bt[i]); Console.Write(\" {0}\", wt[i]); Console.Write(\" {0}\\n\", tat[i]); } float s = (float)total_wt /(float) n; int t = total_tat / n; Console.Write(\"Average waiting time = {0}\", s); Console.Write(\"\\n\"); Console.Write(\"Average turn around time = {0} \", t); } // Driver code public static void Main(String[] args) { // process id's int []processes = {1, 2, 3}; int n = processes.Length; // Burst time of all processes int []burst_time = {10, 5, 8}; findavgTime(processes, n, burst_time); }} // This code contributed by Rajput-Ji",
"e": 12235,
"s": 9939,
"text": null
},
{
"code": "<script> // JavaScript program for implementation of FCFS // scheduling // Function to find the waiting time for all // processes function findWaitingTime(processes,n,bt,wt) { // waiting time for first process is 0 wt[0] = 0; // calculating waiting time for (let i = 1; i < n; i++) { wt[i] = bt[i - 1] + wt[i - 1]; } } function findTurnAroundTime(processes,n,bt,wt,tat) { // calculating turnaround time by adding // bt[i] + wt[i] for (let i = 0; i < n; i++) { tat[i] = bt[i] + wt[i]; } } function findavgTime(processes,n,bt) { let wt = new Array(n), tat = new Array(n); for(let i=0;i<n;i++) { wt[i]=0; tat[i]=0; } let total_wt = 0, total_tat = 0; //Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt); //Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); //Display processes along with all details document.write(\"Processes Burst time Waiting\" +\" time Turn around time<br>\"); // Calculate total waiting time and total turn // around time for (let i = 0; i < n; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; document.write(\" \", (i + 1)+\" \"); document.write(\" \"+ bt[i]+\" \"); document.write(\" \"+ wt[i]); document.write(\" \"+ tat[i]+\"<br>\"); } let s = total_wt / n; let t = Math.floor(total_tat / n); document.write(\"Average waiting time = \"+ s); document.write(\"<br>\"); document.write(\"Average turn around time = \", t+\" \"); } let processes=[1,2,3]; let n = processes.length; let burst_time=[10,5,8]; findavgTime(processes, n, burst_time); // This code is contributed by rag2127 </script>",
"e": 14277,
"s": 12235,
"text": null
},
{
"code": null,
"e": 14286,
"s": 14277,
"text": "Output: "
},
{
"code": null,
"e": 14491,
"s": 14286,
"text": "Processes Burst time Waiting time Turn around time\n 1 10 0 10\n 2 5 10 15\n 3 8 15 23\nAverage waiting time = 8.33333\nAverage turn around time = 16"
},
{
"code": null,
"e": 14511,
"s": 14491,
"text": "Important Points: "
},
{
"code": null,
"e": 14894,
"s": 14511,
"text": "Non-preemptiveAverage Waiting Time is not optimalCannot utilize resources in parallel : Results in Convoy effect (Consider a situation when many IO bound processes are there and one CPU bound process. The IO bound processes have to wait for CPU bound process when CPU bound process acquires CPU. The IO bound process could have better taken CPU for some time, then used IO devices)."
},
{
"code": null,
"e": 14909,
"s": 14894,
"text": "Non-preemptive"
},
{
"code": null,
"e": 14945,
"s": 14909,
"text": "Average Waiting Time is not optimal"
},
{
"code": null,
"e": 15279,
"s": 14945,
"text": "Cannot utilize resources in parallel : Results in Convoy effect (Consider a situation when many IO bound processes are there and one CPU bound process. The IO bound processes have to wait for CPU bound process when CPU bound process acquires CPU. The IO bound process could have better taken CPU for some time, then used IO devices)."
},
{
"code": null,
"e": 15294,
"s": 15279,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 15300,
"s": 15294,
"text": "ukasp"
},
{
"code": null,
"e": 15312,
"s": 15300,
"text": "29AjayKumar"
},
{
"code": null,
"e": 15322,
"s": 15312,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 15330,
"s": 15322,
"text": "rag2127"
},
{
"code": null,
"e": 15345,
"s": 15330,
"text": "cpu-scheduling"
},
{
"code": null,
"e": 15363,
"s": 15345,
"text": "Operating Systems"
},
{
"code": null,
"e": 15381,
"s": 15363,
"text": "Operating Systems"
},
{
"code": null,
"e": 15479,
"s": 15381,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15517,
"s": 15479,
"text": "Cache Memory in Computer Organization"
},
{
"code": null,
"e": 15542,
"s": 15517,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 15575,
"s": 15542,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 15590,
"s": 15575,
"text": "Cd cmd command"
},
{
"code": null,
"e": 15628,
"s": 15590,
"text": "Memory Management in Operating System"
},
{
"code": null,
"e": 15666,
"s": 15628,
"text": "Last Minute Notes – Operating Systems"
},
{
"code": null,
"e": 15719,
"s": 15666,
"text": "Commonly Asked Operating Systems Interview Questions"
},
{
"code": null,
"e": 15760,
"s": 15719,
"text": "Preemptive and Non-Preemptive Scheduling"
},
{
"code": null,
"e": 15815,
"s": 15760,
"text": "Difference between Internal and External fragmentation"
}
] |
Convert class object to JSON in Python
|
29 Dec, 2020
Conversion of the class object to JSON is done using json package in Python. json.dumps() converts Python object into a json string. Every Python object has an attribute which is denoted by __dict__ and this stores the object’s attributes.
Object is first converted into dictionary format using __dict__ attribute.This newly created dictionary is passed as a parameter to json.dumps() which then yields a JSON string.
Object is first converted into dictionary format using __dict__ attribute.
This newly created dictionary is passed as a parameter to json.dumps() which then yields a JSON string.
Syntax: json.dumps(Object obj)
Parameter: Expects a dictionary object.
Return: json string
Following python code converts a python class Student object to JSON.
Python3
# import required packagesimport json # custom classclass Student: def __init__(self, roll_no, name, batch): self.roll_no = roll_no self.name = name self.batch = batch class Car: def __init__(self, brand, name, batch): self.brand = brand self.name = name self.batch = batch # main functionif __name__ == "__main__": # create two new student objects s1 = Student("85", "Swapnil", "IMT") s2 = Student("124", "Akash", "IMT") # create two new car objects c1 = Car("Honda", "city", "2005") c2 = Car("Honda", "Amaze", "2011") # convert to JSON format jsonstr1 = json.dumps(s1.__dict__) jsonstr2 = json.dumps(s2.__dict__) jsonstr3 = json.dumps(c1.__dict__) jsonstr4 = json.dumps(c2.__dict__) # print created JSON objects print(jsonstr1) print(jsonstr2) print(jsonstr3) print(jsonstr4)
Output:
{"roll_no": "85", "name": "Swapnil", "batch": "IMT"}
{"roll_no": "124", "name": "Akash", "batch": "IMT"}
{"brand": "Honda", "name": "city", "batch": "2005"}
{"brand": "Honda", "name": "Amaze", "batch": "2011"}
Python json-programs
Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 269,
"s": 28,
"text": "Conversion of the class object to JSON is done using json package in Python. json.dumps() converts Python object into a json string. Every Python object has an attribute which is denoted by __dict__ and this stores the object’s attributes. "
},
{
"code": null,
"e": 447,
"s": 269,
"text": "Object is first converted into dictionary format using __dict__ attribute.This newly created dictionary is passed as a parameter to json.dumps() which then yields a JSON string."
},
{
"code": null,
"e": 522,
"s": 447,
"text": "Object is first converted into dictionary format using __dict__ attribute."
},
{
"code": null,
"e": 626,
"s": 522,
"text": "This newly created dictionary is passed as a parameter to json.dumps() which then yields a JSON string."
},
{
"code": null,
"e": 657,
"s": 626,
"text": "Syntax: json.dumps(Object obj)"
},
{
"code": null,
"e": 697,
"s": 657,
"text": "Parameter: Expects a dictionary object."
},
{
"code": null,
"e": 717,
"s": 697,
"text": "Return: json string"
},
{
"code": null,
"e": 787,
"s": 717,
"text": "Following python code converts a python class Student object to JSON."
},
{
"code": null,
"e": 795,
"s": 787,
"text": "Python3"
},
{
"code": "# import required packagesimport json # custom classclass Student: def __init__(self, roll_no, name, batch): self.roll_no = roll_no self.name = name self.batch = batch class Car: def __init__(self, brand, name, batch): self.brand = brand self.name = name self.batch = batch # main functionif __name__ == \"__main__\": # create two new student objects s1 = Student(\"85\", \"Swapnil\", \"IMT\") s2 = Student(\"124\", \"Akash\", \"IMT\") # create two new car objects c1 = Car(\"Honda\", \"city\", \"2005\") c2 = Car(\"Honda\", \"Amaze\", \"2011\") # convert to JSON format jsonstr1 = json.dumps(s1.__dict__) jsonstr2 = json.dumps(s2.__dict__) jsonstr3 = json.dumps(c1.__dict__) jsonstr4 = json.dumps(c2.__dict__) # print created JSON objects print(jsonstr1) print(jsonstr2) print(jsonstr3) print(jsonstr4)",
"e": 1686,
"s": 795,
"text": null
},
{
"code": null,
"e": 1694,
"s": 1686,
"text": "Output:"
},
{
"code": null,
"e": 1904,
"s": 1694,
"text": "{\"roll_no\": \"85\", \"name\": \"Swapnil\", \"batch\": \"IMT\"}\n{\"roll_no\": \"124\", \"name\": \"Akash\", \"batch\": \"IMT\"}\n{\"brand\": \"Honda\", \"name\": \"city\", \"batch\": \"2005\"}\n{\"brand\": \"Honda\", \"name\": \"Amaze\", \"batch\": \"2011\"}"
},
{
"code": null,
"e": 1925,
"s": 1904,
"text": "Python json-programs"
},
{
"code": null,
"e": 1937,
"s": 1925,
"text": "Python-json"
},
{
"code": null,
"e": 1944,
"s": 1937,
"text": "Python"
},
{
"code": null,
"e": 2042,
"s": 1944,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2074,
"s": 2042,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2101,
"s": 2074,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2132,
"s": 2101,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2155,
"s": 2132,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2176,
"s": 2155,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2232,
"s": 2176,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2274,
"s": 2232,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2316,
"s": 2274,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2355,
"s": 2316,
"text": "Python | Get unique values from a list"
}
] |
Namespaces and Scope in Python
|
09 Feb, 2021
A namespace is a system that has a unique name for each and every object in Python. An object might be a variable or a method. Python itself maintains a namespace in the form of a Python dictionary. Let’s go through an example, a directory-file system structure in computers. Needless to say, that one can have multiple directories having a file with the same name inside every directory. But one can get directed to the file, one wishes, just by specifying the absolute path to the file. Real-time example, the role of a namespace is like a surname. One might not find a single “Alice” in the class there might be multiple “Alice” but when you particularly ask for “Alice Lee” or “Alice Clark” (with a surname), there will be only one (time being don’t think of both first name and surname are same for multiple students).On similar lines, the Python interpreter understands what exact method or variable one is trying to point to in the code, depending upon the namespace. So, the division of the word itself gives a little more information. Its Name (which means name, a unique identifier) + Space(which talks something related to scope). Here, a name might be of any Python method or variable and space depends upon the location from where is trying to access a variable or a method.
When Python interpreter runs solely without any user-defined modules, methods, classes, etc. Some functions like print(), id() are always present, these are built-in namespaces. When a user creates a module, a global namespace gets created, later the creation of local functions creates the local namespace. The built-in namespace encompasses the global namespace and the global namespace encompasses the local namespace.
A lifetime of a namespace depends upon the scope of objects, if the scope of an object ends, the lifetime of that namespace comes to an end. Hence, it is not possible to access the inner namespace’s objects from an outer namespace.
Example:
Python3
# var1 is in the global namespacevar1 = 5def some_func(): # var2 is in the local namespace var2 = 6 def some_inner_func(): # var3 is in the nested local # namespace var3 = 7
As shown in the following figure, the same object name can be present in multiple namespaces as isolation between the same name is maintained by their namespace.
But in some cases, one might be interested in updating or processing global variables only, as shown in the following example, one should mark it explicitly as global and the update or process. Note that the line “count = count +1” references the global variable and therefore uses the global variable, but compare this to the same line written “count = 1”. Then the line “global count” is absolutely needed according to scope rules.
Python3
# Python program processing# global variable count = 5def some_method(): global count count = count + 1 print(count)some_method()
Output:
6
Scope refers to the coding region from which a particular Python object is accessible. Hence one cannot access any particular object from anywhere from the code, the accessing has to be allowed by the scope of the object.Let’s take an example to have a detailed understanding of the same:
Example 1:
Python3
# Python program showing# a scope of object def some_func(): print("Inside some_func") def some_inner_func(): var = 10 print("Inside inner function, value of var:",var) some_inner_func() print("Try printing var from outer function: ",var)some_func()
Output:
Inside some_func
Inside inner function, value of var: 10
Traceback (most recent call last):
File "/home/1eb47bb3eac2fa36d6bfe5d349dfcb84.py", line 8, in
some_func()
File "/home/1eb47bb3eac2fa36d6bfe5d349dfcb84.py", line 7, in some_func
print("Try printing var from outer function: ",var)
NameError: name 'var' is not defined
wwwchetanranecr7
jamesxxyzzy
vaibhavviva93
python-basics
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
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 ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Feb, 2021"
},
{
"code": null,
"e": 1341,
"s": 52,
"text": "A namespace is a system that has a unique name for each and every object in Python. An object might be a variable or a method. Python itself maintains a namespace in the form of a Python dictionary. Let’s go through an example, a directory-file system structure in computers. Needless to say, that one can have multiple directories having a file with the same name inside every directory. But one can get directed to the file, one wishes, just by specifying the absolute path to the file. Real-time example, the role of a namespace is like a surname. One might not find a single “Alice” in the class there might be multiple “Alice” but when you particularly ask for “Alice Lee” or “Alice Clark” (with a surname), there will be only one (time being don’t think of both first name and surname are same for multiple students).On similar lines, the Python interpreter understands what exact method or variable one is trying to point to in the code, depending upon the namespace. So, the division of the word itself gives a little more information. Its Name (which means name, a unique identifier) + Space(which talks something related to scope). Here, a name might be of any Python method or variable and space depends upon the location from where is trying to access a variable or a method. "
},
{
"code": null,
"e": 1764,
"s": 1341,
"text": "When Python interpreter runs solely without any user-defined modules, methods, classes, etc. Some functions like print(), id() are always present, these are built-in namespaces. When a user creates a module, a global namespace gets created, later the creation of local functions creates the local namespace. The built-in namespace encompasses the global namespace and the global namespace encompasses the local namespace. "
},
{
"code": null,
"e": 1997,
"s": 1764,
"text": "A lifetime of a namespace depends upon the scope of objects, if the scope of an object ends, the lifetime of that namespace comes to an end. Hence, it is not possible to access the inner namespace’s objects from an outer namespace. "
},
{
"code": null,
"e": 2007,
"s": 1997,
"text": "Example: "
},
{
"code": null,
"e": 2015,
"s": 2007,
"text": "Python3"
},
{
"code": "# var1 is in the global namespacevar1 = 5def some_func(): # var2 is in the local namespace var2 = 6 def some_inner_func(): # var3 is in the nested local # namespace var3 = 7",
"e": 2221,
"s": 2015,
"text": null
},
{
"code": null,
"e": 2383,
"s": 2221,
"text": "As shown in the following figure, the same object name can be present in multiple namespaces as isolation between the same name is maintained by their namespace."
},
{
"code": null,
"e": 2820,
"s": 2383,
"text": "But in some cases, one might be interested in updating or processing global variables only, as shown in the following example, one should mark it explicitly as global and the update or process. Note that the line “count = count +1” references the global variable and therefore uses the global variable, but compare this to the same line written “count = 1”. Then the line “global count” is absolutely needed according to scope rules."
},
{
"code": null,
"e": 2828,
"s": 2820,
"text": "Python3"
},
{
"code": "# Python program processing# global variable count = 5def some_method(): global count count = count + 1 print(count)some_method()",
"e": 2967,
"s": 2828,
"text": null
},
{
"code": null,
"e": 2976,
"s": 2967,
"text": "Output: "
},
{
"code": null,
"e": 2978,
"s": 2976,
"text": "6"
},
{
"code": null,
"e": 3269,
"s": 2978,
"text": "Scope refers to the coding region from which a particular Python object is accessible. Hence one cannot access any particular object from anywhere from the code, the accessing has to be allowed by the scope of the object.Let’s take an example to have a detailed understanding of the same: "
},
{
"code": null,
"e": 3281,
"s": 3269,
"text": "Example 1: "
},
{
"code": null,
"e": 3289,
"s": 3281,
"text": "Python3"
},
{
"code": "# Python program showing# a scope of object def some_func(): print(\"Inside some_func\") def some_inner_func(): var = 10 print(\"Inside inner function, value of var:\",var) some_inner_func() print(\"Try printing var from outer function: \",var)some_func()",
"e": 3565,
"s": 3289,
"text": null
},
{
"code": null,
"e": 3574,
"s": 3565,
"text": "Output: "
},
{
"code": null,
"e": 3913,
"s": 3574,
"text": "Inside some_func\nInside inner function, value of var: 10\n\nTraceback (most recent call last):\n File \"/home/1eb47bb3eac2fa36d6bfe5d349dfcb84.py\", line 8, in \n some_func()\n File \"/home/1eb47bb3eac2fa36d6bfe5d349dfcb84.py\", line 7, in some_func\n print(\"Try printing var from outer function: \",var)\nNameError: name 'var' is not defined"
},
{
"code": null,
"e": 3930,
"s": 3913,
"text": "wwwchetanranecr7"
},
{
"code": null,
"e": 3942,
"s": 3930,
"text": "jamesxxyzzy"
},
{
"code": null,
"e": 3956,
"s": 3942,
"text": "vaibhavviva93"
},
{
"code": null,
"e": 3970,
"s": 3956,
"text": "python-basics"
},
{
"code": null,
"e": 3994,
"s": 3970,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 4001,
"s": 3994,
"text": "Python"
},
{
"code": null,
"e": 4020,
"s": 4001,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4118,
"s": 4020,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4146,
"s": 4118,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 4196,
"s": 4146,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 4218,
"s": 4196,
"text": "Python map() function"
},
{
"code": null,
"e": 4262,
"s": 4218,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 4304,
"s": 4262,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4326,
"s": 4304,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4361,
"s": 4326,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4387,
"s": 4361,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4419,
"s": 4387,
"text": "How to Install PIP on Windows ?"
}
] |
Kotlin Nested class and Inner class
|
05 Oct, 2021
A class is declared within another class then it is called a nested class. By default nested class is static so we can access the nested class property or variables using dot(.) notation without creating an object of the class.Syntax of declaration:
class outerClass {
............
// outer class properties or member function
class nestedClass {
..........
// inner class properties or member function
}
}
Note: Nested class can’t access the members of the outer class, but we can access the property of nested class from the outer class without creating an object for nested class.
Kotlin program of accessing nested class properties:
Kotlin
// outer class declarationclass outerClass { var str = "Outer class" // nested class declaration class nestedClass { val firstName = "Praveen" val lastName = "Ruhil" }}fun main(args: Array<String>) { // accessing member of Nested class print(outerClass.nestedClass().firstName) print(" ") println(outerClass.nestedClass().lastName)}
Output:
Praveen Ruhil
In Kotlin, to access the member function of nested class, we need to create the object for nested class and call the member function using it.
Kotlin program of accessing nested class member function:
Kotlin
// outer class declarationclass outerClass { var str = "Outer class" // nested class declaration class nestedClass { var s1 = "Nested class" // nested class member function fun nestfunc(str2: String): String { var s2 = s1.plus(str2) return s2 } }}fun main(args: Array<String>) { // creating object of Nested class val nested = outerClass.nestedClass() // invoking the nested member function by passing string var result = nested.nestfunc(" member function call successful") println(result)}
Output:
Nested class member function call successful
Kotlin classes are much similar to Java classes when we think about the capabilities and use cases, but not identical. Nested in Kotlin is similar to a static nested class in Java and the Inner class is similar to a non-static nested class in Java.
When we can declare a class inside another class using the keyword inner then it is called inner class. With the help of the inner class, we can access the outer class property inside the inner class.
class outerClass {
............
// outer class properties or member function
inner class innerClass {
..........
// inner class properties or member function
}
}
In the below program we are trying to access str from the inner class member function. But it does not work and gives a compile-time error. Kotlin program of inner class:
Kotlin
// outer class declarationclass outerClass { var str = "Outer class" // innerClass declaration without using inner keyword class innerClass { var s1 = "Inner class" fun nestfunc(): String { // can not access the outer class property str var s2 = str return s2 } }}// main functionfun main(args: Array<String>) { // creating object for inner class val inner= outerClass().innerClass() // inner function call using object println(inner.nestfunc())}
Output:
Error:(9, 22) Kotlin: Unresolved reference: str
First, use the inner keyword in front of the inner class. Then, create an instance of the outer class else we can’t use inner classes.
Kotlin
// outer class declarationclass outerClass { var str = "Outer class" // innerClass declaration with using inner keyword inner class innerClass { var s1 = "Inner class" fun nestfunc(): String { // can access the outer class property str var s2 = str return s2 } }}// main functionfun main(args: Array<String>) { // creating object for inner class val inner= outerClass().innerClass() // inner function call using object println(inner.nestfunc()+" property accessed successfully from inner class ")}
Output:
Outer class property accessed successfully from inner class
mohdqasim89mq
abhishek0719kadiyan
varshagumber28
Kotlin OOPs
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 303,
"s": 52,
"text": "A class is declared within another class then it is called a nested class. By default nested class is static so we can access the nested class property or variables using dot(.) notation without creating an object of the class.Syntax of declaration: "
},
{
"code": null,
"e": 517,
"s": 303,
"text": "class outerClass {\n ............\n // outer class properties or member function\n \n class nestedClass { \n ..........\n // inner class properties or member function\n }\n}"
},
{
"code": null,
"e": 694,
"s": 517,
"text": "Note: Nested class can’t access the members of the outer class, but we can access the property of nested class from the outer class without creating an object for nested class."
},
{
"code": null,
"e": 748,
"s": 694,
"text": "Kotlin program of accessing nested class properties: "
},
{
"code": null,
"e": 755,
"s": 748,
"text": "Kotlin"
},
{
"code": "// outer class declarationclass outerClass { var str = \"Outer class\" // nested class declaration class nestedClass { val firstName = \"Praveen\" val lastName = \"Ruhil\" }}fun main(args: Array<String>) { // accessing member of Nested class print(outerClass.nestedClass().firstName) print(\" \") println(outerClass.nestedClass().lastName)}",
"e": 1127,
"s": 755,
"text": null
},
{
"code": null,
"e": 1136,
"s": 1127,
"text": "Output: "
},
{
"code": null,
"e": 1150,
"s": 1136,
"text": "Praveen Ruhil"
},
{
"code": null,
"e": 1293,
"s": 1150,
"text": "In Kotlin, to access the member function of nested class, we need to create the object for nested class and call the member function using it."
},
{
"code": null,
"e": 1351,
"s": 1293,
"text": "Kotlin program of accessing nested class member function:"
},
{
"code": null,
"e": 1358,
"s": 1351,
"text": "Kotlin"
},
{
"code": "// outer class declarationclass outerClass { var str = \"Outer class\" // nested class declaration class nestedClass { var s1 = \"Nested class\" // nested class member function fun nestfunc(str2: String): String { var s2 = s1.plus(str2) return s2 } }}fun main(args: Array<String>) { // creating object of Nested class val nested = outerClass.nestedClass() // invoking the nested member function by passing string var result = nested.nestfunc(\" member function call successful\") println(result)}",
"e": 1926,
"s": 1358,
"text": null
},
{
"code": null,
"e": 1936,
"s": 1926,
"text": "Output: "
},
{
"code": null,
"e": 1981,
"s": 1936,
"text": "Nested class member function call successful"
},
{
"code": null,
"e": 2232,
"s": 1981,
"text": "Kotlin classes are much similar to Java classes when we think about the capabilities and use cases, but not identical. Nested in Kotlin is similar to a static nested class in Java and the Inner class is similar to a non-static nested class in Java. "
},
{
"code": null,
"e": 2434,
"s": 2232,
"text": "When we can declare a class inside another class using the keyword inner then it is called inner class. With the help of the inner class, we can access the outer class property inside the inner class. "
},
{
"code": null,
"e": 2653,
"s": 2434,
"text": "class outerClass {\n ............\n // outer class properties or member function\n \n inner class innerClass { \n ..........\n // inner class properties or member function\n }\n}"
},
{
"code": null,
"e": 2824,
"s": 2653,
"text": "In the below program we are trying to access str from the inner class member function. But it does not work and gives a compile-time error. Kotlin program of inner class:"
},
{
"code": null,
"e": 2831,
"s": 2824,
"text": "Kotlin"
},
{
"code": "// outer class declarationclass outerClass { var str = \"Outer class\" // innerClass declaration without using inner keyword class innerClass { var s1 = \"Inner class\" fun nestfunc(): String { // can not access the outer class property str var s2 = str return s2 } }}// main functionfun main(args: Array<String>) { // creating object for inner class val inner= outerClass().innerClass() // inner function call using object println(inner.nestfunc())}",
"e": 3356,
"s": 2831,
"text": null
},
{
"code": null,
"e": 3365,
"s": 3356,
"text": "Output: "
},
{
"code": null,
"e": 3413,
"s": 3365,
"text": "Error:(9, 22) Kotlin: Unresolved reference: str"
},
{
"code": null,
"e": 3548,
"s": 3413,
"text": "First, use the inner keyword in front of the inner class. Then, create an instance of the outer class else we can’t use inner classes."
},
{
"code": null,
"e": 3555,
"s": 3548,
"text": "Kotlin"
},
{
"code": "// outer class declarationclass outerClass { var str = \"Outer class\" // innerClass declaration with using inner keyword inner class innerClass { var s1 = \"Inner class\" fun nestfunc(): String { // can access the outer class property str var s2 = str return s2 } }}// main functionfun main(args: Array<String>) { // creating object for inner class val inner= outerClass().innerClass() // inner function call using object println(inner.nestfunc()+\" property accessed successfully from inner class \")}",
"e": 4131,
"s": 3555,
"text": null
},
{
"code": null,
"e": 4141,
"s": 4131,
"text": "Output: "
},
{
"code": null,
"e": 4201,
"s": 4141,
"text": "Outer class property accessed successfully from inner class"
},
{
"code": null,
"e": 4215,
"s": 4201,
"text": "mohdqasim89mq"
},
{
"code": null,
"e": 4235,
"s": 4215,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 4250,
"s": 4235,
"text": "varshagumber28"
},
{
"code": null,
"e": 4262,
"s": 4250,
"text": "Kotlin OOPs"
},
{
"code": null,
"e": 4269,
"s": 4262,
"text": "Kotlin"
}
] |
Python – Find text using beautifulSoup then replace in original soup variable
|
29 Nov, 2021
Python provides a library called BeautifulSoap to easily allow web scraping. BeautifulSoup object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The BeautifulSoup object represents the parsed document as a whole. In this article, we’ll be scrapping a simple website and replacing the content in the parsed “soup” variable.
For the purpose of this article, let’s create a virtual environment (venv) as it helps us to manage separate package installations for different projects and to avoid messing up with dependencies and interpreters!
More about, how to create a virtual environment can be read from here: Create a virtual environment
Navigate to your project directory and run this command to create a virtual environment named “env” in your project directory.
python3 -m venv env
Activate the “env” by typing.
source env/bin/activate
Having interpreter activated, we can see the name of an interpreter in our command line before :~$ symbol
BeautifulSoup: A library to scrape the web pages.
pip install bs4
requests: This makes the process of sending HTTP requests.
pip install requests
Let’s start by importing libraries and storing “GET” requests response in a variable.
Python3
import bs4from bs4 import BeautifulSoupimport requests # sending a GET req.response = requests.get("https://isitchristmas.today/")print(response.status_code)
Output:
200
A status of 200 implies a successful request.
Now let’s parse the content as a BeautifulSoup object to extract the title and header tags of the website (as for this article) and to replace it in the original soup variable. The find() method returns the first matching case from the soup object.
Python3
# create objectsoup = BeautifulSoup(r.text, "html.parser") # find titletitle = soup.find("title") # find headingheading = soup.find("h1") print(title)
Output:
Replacing the content of the parsed soup obj with the “.string” method.
Python3
# replacetitle.string = "Is GFG day today?"heading.string = "Welcome to GFG"
Output:
Thus, the title tag and heading tags have been replaced in the original soup variable.
Note: We can’t push the modified page back to the website as those pages are rendered from servers where they are hosted.
Below is the complete program:
Python3
import bs4from bs4 import BeautifulSoupimport requests # sending a GET requestsresponse = requests.get("https://isitchristmas.today/") # a status 200 implies a successful requests#print(response.status_code) soup = BeautifulSoup(response.text, "html.parser")#print(soup) title = soup.find("title")heading = soup.find("h1") # replacdetitle.string = "Is GFG day today?"heading.string = "Welcome to GFG" # display replaced contentprint(soup)# The title and the heading tag contents# get changed in the parsed soup obj.
Output:
surindertarika1234
kapoorsagar226
Picked
Python BeautifulSoup
Python bs4-Exercises
Technical Scripter 2020
Python
Technical Scripter
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": "\n29 Nov, 2021"
},
{
"code": null,
"e": 494,
"s": 28,
"text": "Python provides a library called BeautifulSoap to easily allow web scraping. BeautifulSoup object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The BeautifulSoup object represents the parsed document as a whole. In this article, we’ll be scrapping a simple website and replacing the content in the parsed “soup” variable."
},
{
"code": null,
"e": 708,
"s": 494,
"text": "For the purpose of this article, let’s create a virtual environment (venv) as it helps us to manage separate package installations for different projects and to avoid messing up with dependencies and interpreters!"
},
{
"code": null,
"e": 808,
"s": 708,
"text": "More about, how to create a virtual environment can be read from here: Create a virtual environment"
},
{
"code": null,
"e": 936,
"s": 808,
"text": "Navigate to your project directory and run this command to create a virtual environment named “env” in your project directory. "
},
{
"code": null,
"e": 956,
"s": 936,
"text": "python3 -m venv env"
},
{
"code": null,
"e": 986,
"s": 956,
"text": "Activate the “env” by typing."
},
{
"code": null,
"e": 1011,
"s": 986,
"text": " source env/bin/activate"
},
{
"code": null,
"e": 1117,
"s": 1011,
"text": "Having interpreter activated, we can see the name of an interpreter in our command line before :~$ symbol"
},
{
"code": null,
"e": 1167,
"s": 1117,
"text": "BeautifulSoup: A library to scrape the web pages."
},
{
"code": null,
"e": 1183,
"s": 1167,
"text": "pip install bs4"
},
{
"code": null,
"e": 1242,
"s": 1183,
"text": "requests: This makes the process of sending HTTP requests."
},
{
"code": null,
"e": 1263,
"s": 1242,
"text": "pip install requests"
},
{
"code": null,
"e": 1349,
"s": 1263,
"text": "Let’s start by importing libraries and storing “GET” requests response in a variable."
},
{
"code": null,
"e": 1357,
"s": 1349,
"text": "Python3"
},
{
"code": "import bs4from bs4 import BeautifulSoupimport requests # sending a GET req.response = requests.get(\"https://isitchristmas.today/\")print(response.status_code)",
"e": 1515,
"s": 1357,
"text": null
},
{
"code": null,
"e": 1523,
"s": 1515,
"text": "Output:"
},
{
"code": null,
"e": 1527,
"s": 1523,
"text": "200"
},
{
"code": null,
"e": 1573,
"s": 1527,
"text": "A status of 200 implies a successful request."
},
{
"code": null,
"e": 1822,
"s": 1573,
"text": "Now let’s parse the content as a BeautifulSoup object to extract the title and header tags of the website (as for this article) and to replace it in the original soup variable. The find() method returns the first matching case from the soup object."
},
{
"code": null,
"e": 1830,
"s": 1822,
"text": "Python3"
},
{
"code": "# create objectsoup = BeautifulSoup(r.text, \"html.parser\") # find titletitle = soup.find(\"title\") # find headingheading = soup.find(\"h1\") print(title)",
"e": 1981,
"s": 1830,
"text": null
},
{
"code": null,
"e": 1989,
"s": 1981,
"text": "Output:"
},
{
"code": null,
"e": 2062,
"s": 1989,
"text": "Replacing the content of the parsed soup obj with the “.string” method. "
},
{
"code": null,
"e": 2070,
"s": 2062,
"text": "Python3"
},
{
"code": "# replacetitle.string = \"Is GFG day today?\"heading.string = \"Welcome to GFG\"",
"e": 2147,
"s": 2070,
"text": null
},
{
"code": null,
"e": 2155,
"s": 2147,
"text": "Output:"
},
{
"code": null,
"e": 2242,
"s": 2155,
"text": "Thus, the title tag and heading tags have been replaced in the original soup variable."
},
{
"code": null,
"e": 2364,
"s": 2242,
"text": "Note: We can’t push the modified page back to the website as those pages are rendered from servers where they are hosted."
},
{
"code": null,
"e": 2395,
"s": 2364,
"text": "Below is the complete program:"
},
{
"code": null,
"e": 2403,
"s": 2395,
"text": "Python3"
},
{
"code": "import bs4from bs4 import BeautifulSoupimport requests # sending a GET requestsresponse = requests.get(\"https://isitchristmas.today/\") # a status 200 implies a successful requests#print(response.status_code) soup = BeautifulSoup(response.text, \"html.parser\")#print(soup) title = soup.find(\"title\")heading = soup.find(\"h1\") # replacdetitle.string = \"Is GFG day today?\"heading.string = \"Welcome to GFG\" # display replaced contentprint(soup)# The title and the heading tag contents# get changed in the parsed soup obj.",
"e": 2920,
"s": 2403,
"text": null
},
{
"code": null,
"e": 2928,
"s": 2920,
"text": "Output:"
},
{
"code": null,
"e": 2949,
"s": 2930,
"text": "surindertarika1234"
},
{
"code": null,
"e": 2964,
"s": 2949,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 2971,
"s": 2964,
"text": "Picked"
},
{
"code": null,
"e": 2992,
"s": 2971,
"text": "Python BeautifulSoup"
},
{
"code": null,
"e": 3013,
"s": 2992,
"text": "Python bs4-Exercises"
},
{
"code": null,
"e": 3037,
"s": 3013,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3044,
"s": 3037,
"text": "Python"
},
{
"code": null,
"e": 3063,
"s": 3044,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3161,
"s": 3063,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3193,
"s": 3161,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3220,
"s": 3193,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3241,
"s": 3220,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3264,
"s": 3241,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3320,
"s": 3264,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3351,
"s": 3320,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3393,
"s": 3351,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3435,
"s": 3393,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3474,
"s": 3435,
"text": "Python | Get unique values from a list"
}
] |
Java Program to check Armstrong Number
|
27 Sep, 2021
Problem Statement – Given a number x. Write a Java Program to determine whether the given number is Armstrong’s number or not.
Examples –
Input : 153
Output : Yes
153 is an Armstrong number.
1*1*1 + 5*5*5 + 3*3*3 = 153
Input : 120
Output : No
120 is not a Armstrong number.
1*1*1 + 2*2*2 + 0*0*0 = 9
Input : 1253
Output : No
1253 is not a Armstrong Number
1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723
Input : 1634
Output : Yes
1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634
In a mathematical number system, the Armstrong number is the number in any given number base, which makes the total of the same number when each of its digits is raised to the power of the total number of digits in the number. In simple words, we can say that a positive integer of n digits is called an Armstrong number of order n (order is the total number of digits present in a number) if,
abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....
For example, using a simple number 153 and the decimal system, we see 3 digits in it. If we do a simple mathematical operation of raising each of its digits to the power of 3, and then totaling the sum obtained, we get 153.
13 + 53 + 33=153. The number 153 is an example of the Armstrong number.
Java
// Java program to determine whether the number is// Armstrong number or notpublic class Armstrong { /* Function to calculate x raised to the power y */ int power(int x, long y) { if (y == 0) return 1; if (y % 2 == 0) return power(x, y / 2) * power(x, y / 2); return x * power(x, y / 2) * power(x, y / 2); } /* Function to calculate order of the number */ int order(int x) { int n = 0; while (x != 0) { n++; x = x / 10; } return n; } // Function to check whether the given number is // Armstrong number or not boolean isArmstrong(int x) { // Calling order function int n = order(x); int temp = x, sum = 0; while (temp != 0) { int r = temp % 10; sum = sum + power(r, n); temp = temp / 10; } // If satisfies Armstrong condition return (sum == x); } // Driver Program public static void main(String[] args) { Armstrong ob = new Armstrong(); int x = 153; System.out.println(x + " : " + ob.isArmstrong(x)); x = 1253; System.out.println(x + " : " + ob.isArmstrong(x)); }}
153 : true
1253 : false
nishkarshgandhi
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 180,
"s": 52,
"text": "Problem Statement – Given a number x. Write a Java Program to determine whether the given number is Armstrong’s number or not. "
},
{
"code": null,
"e": 192,
"s": 180,
"text": "Examples – "
},
{
"code": null,
"e": 528,
"s": 192,
"text": "Input : 153\nOutput : Yes\n153 is an Armstrong number.\n1*1*1 + 5*5*5 + 3*3*3 = 153\n\nInput : 120\nOutput : No\n120 is not a Armstrong number.\n1*1*1 + 2*2*2 + 0*0*0 = 9\n\nInput : 1253\nOutput : No\n1253 is not a Armstrong Number\n1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723\n\nInput : 1634\nOutput : Yes\n1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634"
},
{
"code": null,
"e": 923,
"s": 528,
"text": "In a mathematical number system, the Armstrong number is the number in any given number base, which makes the total of the same number when each of its digits is raised to the power of the total number of digits in the number. In simple words, we can say that a positive integer of n digits is called an Armstrong number of order n (order is the total number of digits present in a number) if, "
},
{
"code": null,
"e": 983,
"s": 923,
"text": "abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + .... "
},
{
"code": null,
"e": 1208,
"s": 983,
"text": "For example, using a simple number 153 and the decimal system, we see 3 digits in it. If we do a simple mathematical operation of raising each of its digits to the power of 3, and then totaling the sum obtained, we get 153. "
},
{
"code": null,
"e": 1281,
"s": 1208,
"text": "13 + 53 + 33=153. The number 153 is an example of the Armstrong number. "
},
{
"code": null,
"e": 1286,
"s": 1281,
"text": "Java"
},
{
"code": "// Java program to determine whether the number is// Armstrong number or notpublic class Armstrong { /* Function to calculate x raised to the power y */ int power(int x, long y) { if (y == 0) return 1; if (y % 2 == 0) return power(x, y / 2) * power(x, y / 2); return x * power(x, y / 2) * power(x, y / 2); } /* Function to calculate order of the number */ int order(int x) { int n = 0; while (x != 0) { n++; x = x / 10; } return n; } // Function to check whether the given number is // Armstrong number or not boolean isArmstrong(int x) { // Calling order function int n = order(x); int temp = x, sum = 0; while (temp != 0) { int r = temp % 10; sum = sum + power(r, n); temp = temp / 10; } // If satisfies Armstrong condition return (sum == x); } // Driver Program public static void main(String[] args) { Armstrong ob = new Armstrong(); int x = 153; System.out.println(x + \" : \" + ob.isArmstrong(x)); x = 1253; System.out.println(x + \" : \" + ob.isArmstrong(x)); }}",
"e": 2527,
"s": 1286,
"text": null
},
{
"code": null,
"e": 2551,
"s": 2527,
"text": "153 : true\n1253 : false"
},
{
"code": null,
"e": 2567,
"s": 2551,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 2572,
"s": 2567,
"text": "Java"
},
{
"code": null,
"e": 2586,
"s": 2572,
"text": "Java Programs"
},
{
"code": null,
"e": 2591,
"s": 2586,
"text": "Java"
}
] |
Set isEmpty() method in Java with Examples
|
31 Dec, 2018
The java.util.Set.isEmpty() method is used to check if a Set is empty or not. It returns True if the Set is empty otherwise it returns False.
Syntax:
boolean isEmpty()
Parameters: This method does not take any parameter
Return Value: The method returns True if the set is empty else returns False.
Below program illustrate the java.util.Set.isEmpty() method:
// Java code to illustrate isEmpty()import java.io.*;import java.util.*; public class SetDemo { public static void main(String args[]) { // Creating an empty Set Set<String> set = new HashSet<String>(); // Use add() method to add elements into the Set set.add("Welcome"); set.add("To"); set.add("Geeks"); set.add("4"); set.add("Geeks"); // Displaying the Set System.out.println("Set: " + set); // Check for the empty set System.out.println("Is the set empty? " + set.isEmpty()); // Clearing the set using clear() method set.clear(); // Again Checking for the empty set System.out.println("Is the set empty? " + set.isEmpty()); }}
Set: [4, Geeks, Welcome, To]
Is the set empty? false
Is the set empty? true
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#isEmpty()
Java-Collections
Java-Functions
java-set
Java
Java
Java-Collections
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
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Dec, 2018"
},
{
"code": null,
"e": 170,
"s": 28,
"text": "The java.util.Set.isEmpty() method is used to check if a Set is empty or not. It returns True if the Set is empty otherwise it returns False."
},
{
"code": null,
"e": 178,
"s": 170,
"text": "Syntax:"
},
{
"code": null,
"e": 196,
"s": 178,
"text": "boolean isEmpty()"
},
{
"code": null,
"e": 248,
"s": 196,
"text": "Parameters: This method does not take any parameter"
},
{
"code": null,
"e": 326,
"s": 248,
"text": "Return Value: The method returns True if the set is empty else returns False."
},
{
"code": null,
"e": 387,
"s": 326,
"text": "Below program illustrate the java.util.Set.isEmpty() method:"
},
{
"code": "// Java code to illustrate isEmpty()import java.io.*;import java.util.*; public class SetDemo { public static void main(String args[]) { // Creating an empty Set Set<String> set = new HashSet<String>(); // Use add() method to add elements into the Set set.add(\"Welcome\"); set.add(\"To\"); set.add(\"Geeks\"); set.add(\"4\"); set.add(\"Geeks\"); // Displaying the Set System.out.println(\"Set: \" + set); // Check for the empty set System.out.println(\"Is the set empty? \" + set.isEmpty()); // Clearing the set using clear() method set.clear(); // Again Checking for the empty set System.out.println(\"Is the set empty? \" + set.isEmpty()); }}",
"e": 1149,
"s": 387,
"text": null
},
{
"code": null,
"e": 1226,
"s": 1149,
"text": "Set: [4, Geeks, Welcome, To]\nIs the set empty? false\nIs the set empty? true\n"
},
{
"code": null,
"e": 1308,
"s": 1226,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#isEmpty()"
},
{
"code": null,
"e": 1325,
"s": 1308,
"text": "Java-Collections"
},
{
"code": null,
"e": 1340,
"s": 1325,
"text": "Java-Functions"
},
{
"code": null,
"e": 1349,
"s": 1340,
"text": "java-set"
},
{
"code": null,
"e": 1354,
"s": 1349,
"text": "Java"
},
{
"code": null,
"e": 1359,
"s": 1354,
"text": "Java"
},
{
"code": null,
"e": 1376,
"s": 1359,
"text": "Java-Collections"
},
{
"code": null,
"e": 1474,
"s": 1376,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1489,
"s": 1474,
"text": "Stream In Java"
},
{
"code": null,
"e": 1510,
"s": 1489,
"text": "Introduction to Java"
},
{
"code": null,
"e": 1531,
"s": 1510,
"text": "Constructors in Java"
},
{
"code": null,
"e": 1550,
"s": 1531,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 1567,
"s": 1550,
"text": "Generics in Java"
},
{
"code": null,
"e": 1597,
"s": 1567,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 1623,
"s": 1597,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 1639,
"s": 1623,
"text": "Strings in Java"
},
{
"code": null,
"e": 1676,
"s": 1639,
"text": "Differences between JDK, JRE and JVM"
}
] |
Firebase - Data
|
The Firebase data is representing JSON objects. If you open your app from Firebase dashboard, you can add data manually by clicking on the + sign.
We will create a simple data structure. You can check the image below.
In the previous chapter, we connected Firebase to our app. Now, we can log Firebase to the console.
console.log(firebase)
We can create a reference to our player’s collection.
var ref = firebase.database().ref('players');
console.log(ref);
We can see the following result in the console.
60 Lectures
5 hours
University Code
28 Lectures
2.5 hours
Appeteria
85 Lectures
14.5 hours
Appeteria
46 Lectures
2.5 hours
Gautham Vijayan
13 Lectures
1.5 hours
Nishant Kumar
85 Lectures
16.5 hours
Rahul Agarwal
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2313,
"s": 2166,
"text": "The Firebase data is representing JSON objects. If you open your app from Firebase dashboard, you can add data manually by clicking on the + sign."
},
{
"code": null,
"e": 2384,
"s": 2313,
"text": "We will create a simple data structure. You can check the image below."
},
{
"code": null,
"e": 2484,
"s": 2384,
"text": "In the previous chapter, we connected Firebase to our app. Now, we can log Firebase to the console."
},
{
"code": null,
"e": 2506,
"s": 2484,
"text": "console.log(firebase)"
},
{
"code": null,
"e": 2560,
"s": 2506,
"text": "We can create a reference to our player’s collection."
},
{
"code": null,
"e": 2628,
"s": 2560,
"text": " \nvar ref = firebase.database().ref('players');\n\nconsole.log(ref);"
},
{
"code": null,
"e": 2676,
"s": 2628,
"text": "We can see the following result in the console."
},
{
"code": null,
"e": 2709,
"s": 2676,
"text": "\n 60 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 2726,
"s": 2709,
"text": " University Code"
},
{
"code": null,
"e": 2761,
"s": 2726,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2772,
"s": 2761,
"text": " Appeteria"
},
{
"code": null,
"e": 2808,
"s": 2772,
"text": "\n 85 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 2819,
"s": 2808,
"text": " Appeteria"
},
{
"code": null,
"e": 2854,
"s": 2819,
"text": "\n 46 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2871,
"s": 2854,
"text": " Gautham Vijayan"
},
{
"code": null,
"e": 2906,
"s": 2871,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2921,
"s": 2906,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 2957,
"s": 2921,
"text": "\n 85 Lectures \n 16.5 hours \n"
},
{
"code": null,
"e": 2972,
"s": 2957,
"text": " Rahul Agarwal"
},
{
"code": null,
"e": 2979,
"s": 2972,
"text": " Print"
},
{
"code": null,
"e": 2990,
"s": 2979,
"text": " Add Notes"
}
] |
How to get the number of days between two Dates in JavaScript?
|
To get the number of days between two dates, use the Maths.floor() method.
You can try to run the following code to get days between two dates −
Live Demo
<html>
<head>
<title>JavaScript Get Days</title>
</head>
<body>
<script>
var date1, date2;
date1 = new Date();
document.write(""+date1);
date2 = new Date( "Dec 10, 2015 20:15:10" );
document.write("<br>"+date2);
// get total seconds between two dates
var res = Math.abs(date1 - date2) / 1000;
var days = Math.floor(res / 86400);
document.write("<br>Difference: "+days);
</script>
</body>
</html>
Mon May 28 2018 09:32:56 GMT+0530 (India Standard Time)
Thu Dec 10 2015 20:15:10 GMT+0530 (India Standard Time)
Difference: 899
|
[
{
"code": null,
"e": 1137,
"s": 1062,
"text": "To get the number of days between two dates, use the Maths.floor() method."
},
{
"code": null,
"e": 1207,
"s": 1137,
"text": "You can try to run the following code to get days between two dates −"
},
{
"code": null,
"e": 1217,
"s": 1207,
"text": "Live Demo"
},
{
"code": null,
"e": 1724,
"s": 1217,
"text": "<html>\n <head>\n <title>JavaScript Get Days</title>\n </head>\n <body>\n <script>\n var date1, date2;\n date1 = new Date();\n document.write(\"\"+date1);\n date2 = new Date( \"Dec 10, 2015 20:15:10\" );\n document.write(\"<br>\"+date2);\n // get total seconds between two dates\n var res = Math.abs(date1 - date2) / 1000;\n var days = Math.floor(res / 86400);\n document.write(\"<br>Difference: \"+days);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 1852,
"s": 1724,
"text": "Mon May 28 2018 09:32:56 GMT+0530 (India Standard Time)\nThu Dec 10 2015 20:15:10 GMT+0530 (India Standard Time)\nDifference: 899"
}
] |
Logistic Regression. A simpler intuitive explanation. | by Abhishek Kumar | Towards Data Science
|
Contrary to its name logistic regression is a classification algorithm. Given an input example, a logistic regression model assigns the example to a relevant class.
A note on the notation. x_{i} means x subscript i and x_{^th} means x superscript th.
Linear Regression is used to predict a real-valued output anywhere between +∞ and -∞.
Each example used to train a linear regression model is defined by its properties or features which are collectively called as the feature vector. Your name, age, contact number, gender, et-cetera correspond to a feature vector describing you.
A linear regression model f(x), is a linear combination of the features of the input examples x, and is represented by f(x) = wx+b.
Transforming the original features (consider a 1-dimensional feature vector x) by squaring or cubing them results in polynomial models (such as f(x) = wx2+b or f(x) = wx3+b).
Generally for a data set with R-dimensional feature vector x, and 1-dimensional output y, linear regression models a hyper plane as the decision boundary. Hyper plane is a line in case of a 2D region, a plane in case of a 3D space, a 3 dimensional shape such as a sphere in case of 4D space and so on. Hyper planes have one less dimension than their surrounding space.
The mean squared error cost function is used to find the optimal set of values w* and b* for a linear regression model.
For the sake of understanding let’s assume John, has been assigned the job of predicting whether a given email is spam or not spam. He collects a dataset represented in the table below. The data set consists of n examples, where each example x_{i} is represented by a 2-dimensional feature vector, comprising of the number of words and the number of links in that email. The target variable y, is equal to 1 if the corresponding example is a spam and is 0 otherwise.
Y takes value 0 for a negative class which corresponds to absence of something (like not spam) whereas, Y takes value 1 for a positive class which corresponds to presence of something (like spam).
John first decides to build a linear regression model to solve this problem. However having built the linear regression model he is quite unhappy with his results.
Remember, that linear regression is used to predict a real-valued output where the output may vary between +∞ to -∞ whereas in this case y, the target variable takes only two discrete values, 0 and 1.
John’s decides to extend the concepts of linear regression to fulfil his requirement. One approach is to take the output of linear regression and map it between 0 and 1, if the resultant output is below a certain threshold, classify the example as a negative class whereas if the resultant output is above a certain threshold, classify the example as a positive class. In fact, this is the logistic regression learning algorithm.
We will crunch the real-valued output obtained from a linear regression model between 0 and 1 and classify a new example based on a threshold value. The function used to perform this mapping is the sigmoid function.
The graph shows that the sigmoid function has successfully mapped values from +∞ to -∞ between 0 and 1.
Note that the value of sigmoid function is 0.5 at x=0. Also, if x>0 then the value of sigmoid function is >0.5, on the other hand if x<0 then the value of sigmoid function is <0.5.
Following the above discussion, the model of logistic regression is represented as —
In above equation, the output wx+b, from the linear regression model has been passed as an input to the sigmoid function, thereby crunching values ranging from +∞ to -∞ between 0 and 1 and, giving us the model for logistic regression. The output of the model is interpreted as the probability of an example x falling into the positive class. Concretely, if for an unseen x the model outputs 0.8, then it implies that, the probability of x being classified as positive is 0.8.
It is apparent that different values of w and b correspond to different models of logistic regression. But, we want an optimal set of values, w* and b* which will minimize the error between the predictions made by the model f(x) and the actual results y for the training set.
The cost function for a logistic regression model, called the log-likelihood function is given by —
The goal is to find values of w and b for the model f(x) which will minimise the above cost function. On observing the cost function we notice that there are two terms inside summation where, the first term will be 0 for all the examples where y=0, and the second term will be zero for all the examples where y=1. So, for any given example one of the summation terms is always zero. Also, the range of f(x) is [0,1], which implies that -log(f(x)) ranges from (+∞,0].
Let’s try to understand the cost function better by considering an arbitrary example x_{^i} for which y=1. The second term will evaluate to zero as (1-y_{^i}) becomes zero. As far as the first term is concerned, if our model f(x) predicts 1, then the first term will also become zero because log(1) is equal to 0, therefore both the first and the second term become zero, subsequently the cost also becomes zero, which makes sense as our model has predicted the correct value for the target variable, y. Had our model predicted 0, the value of -log(0) would have approached +∞, signifying the high penalty imposed by the cost function on our model.
Try out an example where the target variable y equals to zero.
The average over summation signifies that we want to the minimise the overall error for all the training examples.
Having developed this intuition John now decides to build a logistic regression model for the spam classifier problem. He starts by plotting his data set.
It is apparent that a linear decision boundary is unlikely to fit the data set. Just like linear regression we may transform features to higher order comprising of quadratic or cubic terms to fit a non-linear decision boundary to our dataset.
Let’s say, John decides to fit a quadratic decision boundary to his data set, therefore he includes the second degree terms such as (number of links)2, (number of words)2 and (number of links)*(number of words). He finally ends up with the following decision boundary.
The above decision boundary corresponds to the circle with the centre at (55,5) and a radius of 4 unit —
Which gives John the following logistic regression model —
For an unseen example falling inside the circle (decision boundary) the equation of circle returns a negative value therefore the above model returns a value less than 0.5, implying the probability of that example being spam is less than 0.5. If the threshold is also 0.5, the target variable, y takes the value 0, implying the example to be a regular email.
Consider a case where example falls outside the decision boundary.
Choosing a threshold value is in itself a topic for discussion — one interpretation is that, the threshold value signifies how tolerant the model is. Take an example of a model which classifies patients as being affected with a heart disease — in such a scenario it is preferred to have a lower value of threshold which captures the idea that— whenever in doubt, classify the patient as being effected by the disease and have him/her checked just to be sure — it means your are willing to accept more false positives (classifying a healthy patient as unhealthy or classifying a not spam email as a spam email).
Technically, sensitivity is the ability to correctly identify patients with the disease (true positive), whereas specificity is the ability to correctly identify patients without the disease (true negative). Ideally, one would want a threshold value that balances sensitivity and specificity however, the value of threshold is problem specific and depending on how tolerant you want the model to be, the value has to tuned.
Consider a classification problem with three arbitrary classes represented in the plot below —
Now the goal is to extend the ideas of binary classification to multi-class classification. The following plots illustrate how to convert our original problem of multi-class classification to a binary classification problem.
Each plot considers only one class at a time and predicts the probability of an example falling into that class, finally the class with the highest probability is assigned to a new example. This method is called as one versus all classification.
In general, to solve a multi-class classification problem with n classes, n logistic regression models are trained each considering only a single class. Whenever a new example has to be classified, all the n models predict the probability of the example falling into its respective class. Finally, the example is assigned to the class with the highest probability as predicted by one of the n models.
|
[
{
"code": null,
"e": 337,
"s": 172,
"text": "Contrary to its name logistic regression is a classification algorithm. Given an input example, a logistic regression model assigns the example to a relevant class."
},
{
"code": null,
"e": 423,
"s": 337,
"text": "A note on the notation. x_{i} means x subscript i and x_{^th} means x superscript th."
},
{
"code": null,
"e": 509,
"s": 423,
"text": "Linear Regression is used to predict a real-valued output anywhere between +∞ and -∞."
},
{
"code": null,
"e": 753,
"s": 509,
"text": "Each example used to train a linear regression model is defined by its properties or features which are collectively called as the feature vector. Your name, age, contact number, gender, et-cetera correspond to a feature vector describing you."
},
{
"code": null,
"e": 885,
"s": 753,
"text": "A linear regression model f(x), is a linear combination of the features of the input examples x, and is represented by f(x) = wx+b."
},
{
"code": null,
"e": 1060,
"s": 885,
"text": "Transforming the original features (consider a 1-dimensional feature vector x) by squaring or cubing them results in polynomial models (such as f(x) = wx2+b or f(x) = wx3+b)."
},
{
"code": null,
"e": 1429,
"s": 1060,
"text": "Generally for a data set with R-dimensional feature vector x, and 1-dimensional output y, linear regression models a hyper plane as the decision boundary. Hyper plane is a line in case of a 2D region, a plane in case of a 3D space, a 3 dimensional shape such as a sphere in case of 4D space and so on. Hyper planes have one less dimension than their surrounding space."
},
{
"code": null,
"e": 1549,
"s": 1429,
"text": "The mean squared error cost function is used to find the optimal set of values w* and b* for a linear regression model."
},
{
"code": null,
"e": 2016,
"s": 1549,
"text": "For the sake of understanding let’s assume John, has been assigned the job of predicting whether a given email is spam or not spam. He collects a dataset represented in the table below. The data set consists of n examples, where each example x_{i} is represented by a 2-dimensional feature vector, comprising of the number of words and the number of links in that email. The target variable y, is equal to 1 if the corresponding example is a spam and is 0 otherwise."
},
{
"code": null,
"e": 2213,
"s": 2016,
"text": "Y takes value 0 for a negative class which corresponds to absence of something (like not spam) whereas, Y takes value 1 for a positive class which corresponds to presence of something (like spam)."
},
{
"code": null,
"e": 2377,
"s": 2213,
"text": "John first decides to build a linear regression model to solve this problem. However having built the linear regression model he is quite unhappy with his results."
},
{
"code": null,
"e": 2578,
"s": 2377,
"text": "Remember, that linear regression is used to predict a real-valued output where the output may vary between +∞ to -∞ whereas in this case y, the target variable takes only two discrete values, 0 and 1."
},
{
"code": null,
"e": 3008,
"s": 2578,
"text": "John’s decides to extend the concepts of linear regression to fulfil his requirement. One approach is to take the output of linear regression and map it between 0 and 1, if the resultant output is below a certain threshold, classify the example as a negative class whereas if the resultant output is above a certain threshold, classify the example as a positive class. In fact, this is the logistic regression learning algorithm."
},
{
"code": null,
"e": 3224,
"s": 3008,
"text": "We will crunch the real-valued output obtained from a linear regression model between 0 and 1 and classify a new example based on a threshold value. The function used to perform this mapping is the sigmoid function."
},
{
"code": null,
"e": 3328,
"s": 3224,
"text": "The graph shows that the sigmoid function has successfully mapped values from +∞ to -∞ between 0 and 1."
},
{
"code": null,
"e": 3509,
"s": 3328,
"text": "Note that the value of sigmoid function is 0.5 at x=0. Also, if x>0 then the value of sigmoid function is >0.5, on the other hand if x<0 then the value of sigmoid function is <0.5."
},
{
"code": null,
"e": 3594,
"s": 3509,
"text": "Following the above discussion, the model of logistic regression is represented as —"
},
{
"code": null,
"e": 4070,
"s": 3594,
"text": "In above equation, the output wx+b, from the linear regression model has been passed as an input to the sigmoid function, thereby crunching values ranging from +∞ to -∞ between 0 and 1 and, giving us the model for logistic regression. The output of the model is interpreted as the probability of an example x falling into the positive class. Concretely, if for an unseen x the model outputs 0.8, then it implies that, the probability of x being classified as positive is 0.8."
},
{
"code": null,
"e": 4346,
"s": 4070,
"text": "It is apparent that different values of w and b correspond to different models of logistic regression. But, we want an optimal set of values, w* and b* which will minimize the error between the predictions made by the model f(x) and the actual results y for the training set."
},
{
"code": null,
"e": 4446,
"s": 4346,
"text": "The cost function for a logistic regression model, called the log-likelihood function is given by —"
},
{
"code": null,
"e": 4913,
"s": 4446,
"text": "The goal is to find values of w and b for the model f(x) which will minimise the above cost function. On observing the cost function we notice that there are two terms inside summation where, the first term will be 0 for all the examples where y=0, and the second term will be zero for all the examples where y=1. So, for any given example one of the summation terms is always zero. Also, the range of f(x) is [0,1], which implies that -log(f(x)) ranges from (+∞,0]."
},
{
"code": null,
"e": 5562,
"s": 4913,
"text": "Let’s try to understand the cost function better by considering an arbitrary example x_{^i} for which y=1. The second term will evaluate to zero as (1-y_{^i}) becomes zero. As far as the first term is concerned, if our model f(x) predicts 1, then the first term will also become zero because log(1) is equal to 0, therefore both the first and the second term become zero, subsequently the cost also becomes zero, which makes sense as our model has predicted the correct value for the target variable, y. Had our model predicted 0, the value of -log(0) would have approached +∞, signifying the high penalty imposed by the cost function on our model."
},
{
"code": null,
"e": 5625,
"s": 5562,
"text": "Try out an example where the target variable y equals to zero."
},
{
"code": null,
"e": 5740,
"s": 5625,
"text": "The average over summation signifies that we want to the minimise the overall error for all the training examples."
},
{
"code": null,
"e": 5895,
"s": 5740,
"text": "Having developed this intuition John now decides to build a logistic regression model for the spam classifier problem. He starts by plotting his data set."
},
{
"code": null,
"e": 6138,
"s": 5895,
"text": "It is apparent that a linear decision boundary is unlikely to fit the data set. Just like linear regression we may transform features to higher order comprising of quadratic or cubic terms to fit a non-linear decision boundary to our dataset."
},
{
"code": null,
"e": 6407,
"s": 6138,
"text": "Let’s say, John decides to fit a quadratic decision boundary to his data set, therefore he includes the second degree terms such as (number of links)2, (number of words)2 and (number of links)*(number of words). He finally ends up with the following decision boundary."
},
{
"code": null,
"e": 6512,
"s": 6407,
"text": "The above decision boundary corresponds to the circle with the centre at (55,5) and a radius of 4 unit —"
},
{
"code": null,
"e": 6571,
"s": 6512,
"text": "Which gives John the following logistic regression model —"
},
{
"code": null,
"e": 6930,
"s": 6571,
"text": "For an unseen example falling inside the circle (decision boundary) the equation of circle returns a negative value therefore the above model returns a value less than 0.5, implying the probability of that example being spam is less than 0.5. If the threshold is also 0.5, the target variable, y takes the value 0, implying the example to be a regular email."
},
{
"code": null,
"e": 6997,
"s": 6930,
"text": "Consider a case where example falls outside the decision boundary."
},
{
"code": null,
"e": 7608,
"s": 6997,
"text": "Choosing a threshold value is in itself a topic for discussion — one interpretation is that, the threshold value signifies how tolerant the model is. Take an example of a model which classifies patients as being affected with a heart disease — in such a scenario it is preferred to have a lower value of threshold which captures the idea that— whenever in doubt, classify the patient as being effected by the disease and have him/her checked just to be sure — it means your are willing to accept more false positives (classifying a healthy patient as unhealthy or classifying a not spam email as a spam email)."
},
{
"code": null,
"e": 8032,
"s": 7608,
"text": "Technically, sensitivity is the ability to correctly identify patients with the disease (true positive), whereas specificity is the ability to correctly identify patients without the disease (true negative). Ideally, one would want a threshold value that balances sensitivity and specificity however, the value of threshold is problem specific and depending on how tolerant you want the model to be, the value has to tuned."
},
{
"code": null,
"e": 8127,
"s": 8032,
"text": "Consider a classification problem with three arbitrary classes represented in the plot below —"
},
{
"code": null,
"e": 8352,
"s": 8127,
"text": "Now the goal is to extend the ideas of binary classification to multi-class classification. The following plots illustrate how to convert our original problem of multi-class classification to a binary classification problem."
},
{
"code": null,
"e": 8598,
"s": 8352,
"text": "Each plot considers only one class at a time and predicts the probability of an example falling into that class, finally the class with the highest probability is assigned to a new example. This method is called as one versus all classification."
}
] |
Reproducible model training: deep dive | by Vladislav Grozin | Towards Data Science
|
Reproducible research is easy. Just log your parameters and metrics somewhere, fix seeds, and you are good to go
— me, about two weeks ago.
Oh boy, I was wrong.
There are a lot of workshops, tutorials, and conferences on reproducible research.
A plethora of utilities, tools, and frameworks are made to help us make nice reproducible solutions.
However, there are still problems. These pitfalls are not apparent in a simple tutorial project but bound to happen in any real research. Very few people talk about them, so I’d like to share my knowledge about these topics.
In this post, I’ll tell a story about my quest towards being able to consistently train models (so it gives the same weights every run).
Once upon a time, I had a project related to computer vision (handwriting author identification).
At some point, I decided to spend time refactoring code and tidying up the project. I split my large Keras model into several stages, designed test sets for each, and used ML Flow to track results of and performance of each stage (it was quite hard — but that’s a story for another day).
After a week or so of refactoring, I have built a nice pipeline, caught a few bugs, managed to fiddle a bit with hyperparameters and slightly improved performance.
However, I noticed one strange thing. I fixed all random seeds, as numerous guides suggested:
def fix_seeds(seed): random.seed(seed) np.random.seed(seed) tf.set_random_seed(seed) session_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1) sess = tf.Session(graph=tf.get_default_graph(), config=session_conf) K.set_session(sess)
But for some reason, two consecutive runs with identical hyperparameters gave different results.
Being unable to track the issue down in the project, I decided to make a script with a small model that reproduces the issue.
I defined a simple neural network:
def create_mlp(dim): model = Sequential() model.add(Dense(8, input_dim=dim)) model.add(Dense(1)) return model
Because data does not matter much here, I generated some random data to work with. After that we are ready to train our model:
model = create_mlp(10)init_weights = np.array(model.get_weights()[0]).sum()model.compile(optimizer=keras.optimizers.RMSprop(lr=1e-2), loss=keras.losses.MSE)model.fit(Xs, Ys, batch_size=10, epochs=10)
After training, we can check reproducibility. assert_same_across_runs is a simple function that checks whether the passed value is the same between runs (it does so by writing the value to a file):
assert_same_across_runs("dense model data", Ys.sum())assert_same_across_runs("dense model weight after training", init_weights)assert_same_across_runs("dense model weight after training", np.array(model.get_weights()[0]).sum())
Full script
I ran it several times. Model weights were exactly the same each execution.
Strange! I added a bit of complexity into the model by plugging in convolution layers:
def create_nnet(dim): input = Input(shape=dim) conv = Conv2D(5, (3, 3), activation="relu")(input) flat = Flatten()(conv) output = Dense(1)(flat) return Model([input], [output])
Full script
Training procedure quite is similar: we create the model, generate some data, train our model, and then check metrics.
And, voila, it broke. Every time the script is run, a different number is printed.
This issue does not happen to machines without GPU. If your machine has GPU, you can hide it from the script by setting CUDA_VISIBLE_DEVICES environment variable to “” from the console.
A quick investigation discovered ugly truth: there are issues with reproducibility, and some layers make model irreproducible, at least by default(to all “you suffer because you use Keras”, Pytorch has a similar problem)
Some complex operations do not have a well-defined order of sub-operations.For example, convolution is just a bunch of additions, but the order of these additions is not defined.
So, each execution results in different order of summations. Because we operate with floating-point with finite precision, convolution yields slightly different results.
Yep, order of summation matters, (a+b)+c != a+(b+c)! You can even check it yourself:
import numpy as npnp.random.seed(42)xs = np.random.normal(size=10000)a = 0.0for x in xs: a += xb = 0for x in reversed(xs): b += xprint(a, b)print("Difference: ", a - b)
Should print
-21.359833684261957 -21.359833684262377Difference: 4.192202140984591e-13
Yes, it is “just 4e-13”. But because this imprecision happens at each level of the deep neural network, and for each batch, this error accumulates over layers and time, and model weights diverge significantly. As a result, losses of two consecutive runs can look like this:
One might argue that these small discrepancies between runs should not affect the model performance, and in fact, fixing random seed and exact reproducibility is not that important.
Well, there are merits to this argument. Randomness affects weights; so, model performance technically depends on the random seed. Changing the seed should have a lesser impact on accuracy than adding new featuresor changing architecture. Moreover, because the random seed is not an essential part of the model, it might be useful to evaluate model several times for different seeds (or let GPU randomize), and report averaged values along with confidence intervals.
However, in practice, very few papers do that. Instead, models are compared with a baseline based on point estimates. Moreover, there are concerns that improvements that papers report are less than this randomness, and improper aggregation can skew results.
What’s even worse is that results in irreducible stochasticity in the code. You cannot write unit tests. It usually does not bother data scientists much, so instead imagine a situation.
You have found a paper that describes a fancy model — and it has cleanly organized open-source implementation. You download the code and the model, start training it. After a couple of days (it’s a very fancy model)you test the model. It does not work. Is it a problem with the hyperparameters? With your hardware or driver versions? Dataset? Maybe, repo authors are frauds, and the problem is in the repository itself? You’ll never know.
Until experiments are completely reproducible, troubleshooting is extremely cumbersome, as you do not know which part of the pipeline contains the problem.
So, it seems that having the ability to reproduce model can be extremely handy.
Order of summations is not defined? Okay. We can define it ourselves, i.e. rewrite convolution as a bunch of summations. Yes, it comes with some overhead, but it would solve our problem.
Happily, CuDNN already has “reproducible” implementation of most operations (and it is, indeed, slower). First of all, you do not have to write anything yourself, you just have to tell CuDNN to use it. Secondly, CuDNN ispretty low in the stack — so, you won’t get much overhead:
There is a layered pipe between your code and your hardware
Because we do not interact with CuDNN directly, we have to tell our library of choice to use specific implementations. In other words, we have to turn on the “I’m ok with slower training, give me consistent results every run” flag.
Unfortunately, Keras does not have that functionality (yet), as described in these issues.
Looks like it’s time for PyTorch to shine. It has settings that will enable the use of CuDNN deterministic implementations:
Let’s write a simple network with a single convolution, and train it on random data. The exact architecture or data do not matter much, as we are just testing reproducibility.
class Net(nn.Module): def __init__(self, in_shape: int): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 5, 3) self.hidden_size = int((in_shape — 2) * (in_shape — 2) / 4) * 5 self.fc1 = nn.Linear(self.hidden_size, 1)def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = x.view(-1, self.hidden_size) x = F.relu(self.fc1(x)) return x
the fix_seeds function also gets changed to include
def fix_seeds(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(42) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False
Again, we’ll use synthetic data to train the network.
After initialization, we ensure that the sum of weights is equal to a specific value. Similarly, after training the network we check the model weights. If there is any discrepancies or randomness, the script will tell us.
Full script
python3 reproducibility_cnn_torch.py
gives consistent results, which means training neural network in PyTorch gives exactly the same weights.
There are caveats. First of all, these settings can impact training time, but tests show a negligible difference (1.14 +- 0.07 seconds for non-deterministic version; 1.17 +- 0.08 seconds for deterministic one). Secondly, CuDNN documentation warns us that there are several algorithms without reproducibility guarantees. These algorithms are usually faster than their deterministic variations, but PyTorch does not use them if flags are set. At last, some modules are non-deterministic (I was unable to reproduce the issue myself).
Anyways, these issues are rarely an obstruction. So, Torch has built-in reproducibility support, and Keras does not have such functionality right now.
But wait! There are some speculations that because Keras and Torch share back-end, setting these variables in PyTorch will affect Keras. It could be the case if the variables affected some process-wide parameters. This way, we can make use of these flags AND use Keras to write models painlessly.First of all, let’s check out how these flags work.
Let’s go deeper! Setting deterministic / benchmark flags from Python sidecalls functions defined in the C sources. Here, the state is stored internally.After that, this flag affects the choice of the algorithm during convolution. In other words, setting this flag does not affect the global state (environment variables, for example).
So, it seems that PyTorch settings do not affect Keras internals (and actual tests confirm that).
Added: some users report that for some layers (CuDNNLSTM is a notable example) and for some hardware and software combinations this hack MAY work. This is definitely an interesting effect, but I would discourage using this in practice. Using a technique that sometimes works and sometimes doesn’t undermines the whole idea of reproducible learning.
Fixing random seeds is extremely useful, as it helps with model debugging. Moreover, the decreased metric variance between runs helps to make decisions about whether some feature increases the performance of the model.
But sometimes it is not enough. Some models (convolutional, recurrent) require additional CuDNN settings to be set. Keras has no such functionality yet, while PyTorch does:
torch.backends.cudnn.deterministic = Truetorch.backends.cudnn.benchmark = False
|
[
{
"code": null,
"e": 285,
"s": 172,
"text": "Reproducible research is easy. Just log your parameters and metrics somewhere, fix seeds, and you are good to go"
},
{
"code": null,
"e": 312,
"s": 285,
"text": "— me, about two weeks ago."
},
{
"code": null,
"e": 333,
"s": 312,
"text": "Oh boy, I was wrong."
},
{
"code": null,
"e": 416,
"s": 333,
"text": "There are a lot of workshops, tutorials, and conferences on reproducible research."
},
{
"code": null,
"e": 517,
"s": 416,
"text": "A plethora of utilities, tools, and frameworks are made to help us make nice reproducible solutions."
},
{
"code": null,
"e": 742,
"s": 517,
"text": "However, there are still problems. These pitfalls are not apparent in a simple tutorial project but bound to happen in any real research. Very few people talk about them, so I’d like to share my knowledge about these topics."
},
{
"code": null,
"e": 879,
"s": 742,
"text": "In this post, I’ll tell a story about my quest towards being able to consistently train models (so it gives the same weights every run)."
},
{
"code": null,
"e": 977,
"s": 879,
"text": "Once upon a time, I had a project related to computer vision (handwriting author identification)."
},
{
"code": null,
"e": 1265,
"s": 977,
"text": "At some point, I decided to spend time refactoring code and tidying up the project. I split my large Keras model into several stages, designed test sets for each, and used ML Flow to track results of and performance of each stage (it was quite hard — but that’s a story for another day)."
},
{
"code": null,
"e": 1429,
"s": 1265,
"text": "After a week or so of refactoring, I have built a nice pipeline, caught a few bugs, managed to fiddle a bit with hyperparameters and slightly improved performance."
},
{
"code": null,
"e": 1523,
"s": 1429,
"text": "However, I noticed one strange thing. I fixed all random seeds, as numerous guides suggested:"
},
{
"code": null,
"e": 1809,
"s": 1523,
"text": "def fix_seeds(seed): random.seed(seed) np.random.seed(seed) tf.set_random_seed(seed) session_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1) sess = tf.Session(graph=tf.get_default_graph(), config=session_conf) K.set_session(sess)"
},
{
"code": null,
"e": 1906,
"s": 1809,
"text": "But for some reason, two consecutive runs with identical hyperparameters gave different results."
},
{
"code": null,
"e": 2032,
"s": 1906,
"text": "Being unable to track the issue down in the project, I decided to make a script with a small model that reproduces the issue."
},
{
"code": null,
"e": 2067,
"s": 2032,
"text": "I defined a simple neural network:"
},
{
"code": null,
"e": 2189,
"s": 2067,
"text": "def create_mlp(dim): model = Sequential() model.add(Dense(8, input_dim=dim)) model.add(Dense(1)) return model"
},
{
"code": null,
"e": 2316,
"s": 2189,
"text": "Because data does not matter much here, I generated some random data to work with. After that we are ready to train our model:"
},
{
"code": null,
"e": 2529,
"s": 2316,
"text": "model = create_mlp(10)init_weights = np.array(model.get_weights()[0]).sum()model.compile(optimizer=keras.optimizers.RMSprop(lr=1e-2), loss=keras.losses.MSE)model.fit(Xs, Ys, batch_size=10, epochs=10)"
},
{
"code": null,
"e": 2727,
"s": 2529,
"text": "After training, we can check reproducibility. assert_same_across_runs is a simple function that checks whether the passed value is the same between runs (it does so by writing the value to a file):"
},
{
"code": null,
"e": 2963,
"s": 2727,
"text": "assert_same_across_runs(\"dense model data\", Ys.sum())assert_same_across_runs(\"dense model weight after training\", init_weights)assert_same_across_runs(\"dense model weight after training\", np.array(model.get_weights()[0]).sum())"
},
{
"code": null,
"e": 2975,
"s": 2963,
"text": "Full script"
},
{
"code": null,
"e": 3051,
"s": 2975,
"text": "I ran it several times. Model weights were exactly the same each execution."
},
{
"code": null,
"e": 3138,
"s": 3051,
"text": "Strange! I added a bit of complexity into the model by plugging in convolution layers:"
},
{
"code": null,
"e": 3330,
"s": 3138,
"text": "def create_nnet(dim): input = Input(shape=dim) conv = Conv2D(5, (3, 3), activation=\"relu\")(input) flat = Flatten()(conv) output = Dense(1)(flat) return Model([input], [output])"
},
{
"code": null,
"e": 3342,
"s": 3330,
"text": "Full script"
},
{
"code": null,
"e": 3461,
"s": 3342,
"text": "Training procedure quite is similar: we create the model, generate some data, train our model, and then check metrics."
},
{
"code": null,
"e": 3544,
"s": 3461,
"text": "And, voila, it broke. Every time the script is run, a different number is printed."
},
{
"code": null,
"e": 3730,
"s": 3544,
"text": "This issue does not happen to machines without GPU. If your machine has GPU, you can hide it from the script by setting CUDA_VISIBLE_DEVICES environment variable to “” from the console."
},
{
"code": null,
"e": 3951,
"s": 3730,
"text": "A quick investigation discovered ugly truth: there are issues with reproducibility, and some layers make model irreproducible, at least by default(to all “you suffer because you use Keras”, Pytorch has a similar problem)"
},
{
"code": null,
"e": 4130,
"s": 3951,
"text": "Some complex operations do not have a well-defined order of sub-operations.For example, convolution is just a bunch of additions, but the order of these additions is not defined."
},
{
"code": null,
"e": 4300,
"s": 4130,
"text": "So, each execution results in different order of summations. Because we operate with floating-point with finite precision, convolution yields slightly different results."
},
{
"code": null,
"e": 4385,
"s": 4300,
"text": "Yep, order of summation matters, (a+b)+c != a+(b+c)! You can even check it yourself:"
},
{
"code": null,
"e": 4560,
"s": 4385,
"text": "import numpy as npnp.random.seed(42)xs = np.random.normal(size=10000)a = 0.0for x in xs: a += xb = 0for x in reversed(xs): b += xprint(a, b)print(\"Difference: \", a - b)"
},
{
"code": null,
"e": 4573,
"s": 4560,
"text": "Should print"
},
{
"code": null,
"e": 4646,
"s": 4573,
"text": "-21.359833684261957 -21.359833684262377Difference: 4.192202140984591e-13"
},
{
"code": null,
"e": 4920,
"s": 4646,
"text": "Yes, it is “just 4e-13”. But because this imprecision happens at each level of the deep neural network, and for each batch, this error accumulates over layers and time, and model weights diverge significantly. As a result, losses of two consecutive runs can look like this:"
},
{
"code": null,
"e": 5102,
"s": 4920,
"text": "One might argue that these small discrepancies between runs should not affect the model performance, and in fact, fixing random seed and exact reproducibility is not that important."
},
{
"code": null,
"e": 5569,
"s": 5102,
"text": "Well, there are merits to this argument. Randomness affects weights; so, model performance technically depends on the random seed. Changing the seed should have a lesser impact on accuracy than adding new featuresor changing architecture. Moreover, because the random seed is not an essential part of the model, it might be useful to evaluate model several times for different seeds (or let GPU randomize), and report averaged values along with confidence intervals."
},
{
"code": null,
"e": 5827,
"s": 5569,
"text": "However, in practice, very few papers do that. Instead, models are compared with a baseline based on point estimates. Moreover, there are concerns that improvements that papers report are less than this randomness, and improper aggregation can skew results."
},
{
"code": null,
"e": 6013,
"s": 5827,
"text": "What’s even worse is that results in irreducible stochasticity in the code. You cannot write unit tests. It usually does not bother data scientists much, so instead imagine a situation."
},
{
"code": null,
"e": 6452,
"s": 6013,
"text": "You have found a paper that describes a fancy model — and it has cleanly organized open-source implementation. You download the code and the model, start training it. After a couple of days (it’s a very fancy model)you test the model. It does not work. Is it a problem with the hyperparameters? With your hardware or driver versions? Dataset? Maybe, repo authors are frauds, and the problem is in the repository itself? You’ll never know."
},
{
"code": null,
"e": 6608,
"s": 6452,
"text": "Until experiments are completely reproducible, troubleshooting is extremely cumbersome, as you do not know which part of the pipeline contains the problem."
},
{
"code": null,
"e": 6688,
"s": 6608,
"text": "So, it seems that having the ability to reproduce model can be extremely handy."
},
{
"code": null,
"e": 6875,
"s": 6688,
"text": "Order of summations is not defined? Okay. We can define it ourselves, i.e. rewrite convolution as a bunch of summations. Yes, it comes with some overhead, but it would solve our problem."
},
{
"code": null,
"e": 7154,
"s": 6875,
"text": "Happily, CuDNN already has “reproducible” implementation of most operations (and it is, indeed, slower). First of all, you do not have to write anything yourself, you just have to tell CuDNN to use it. Secondly, CuDNN ispretty low in the stack — so, you won’t get much overhead:"
},
{
"code": null,
"e": 7214,
"s": 7154,
"text": "There is a layered pipe between your code and your hardware"
},
{
"code": null,
"e": 7446,
"s": 7214,
"text": "Because we do not interact with CuDNN directly, we have to tell our library of choice to use specific implementations. In other words, we have to turn on the “I’m ok with slower training, give me consistent results every run” flag."
},
{
"code": null,
"e": 7537,
"s": 7446,
"text": "Unfortunately, Keras does not have that functionality (yet), as described in these issues."
},
{
"code": null,
"e": 7661,
"s": 7537,
"text": "Looks like it’s time for PyTorch to shine. It has settings that will enable the use of CuDNN deterministic implementations:"
},
{
"code": null,
"e": 7837,
"s": 7661,
"text": "Let’s write a simple network with a single convolution, and train it on random data. The exact architecture or data do not matter much, as we are just testing reproducibility."
},
{
"code": null,
"e": 8262,
"s": 7837,
"text": "class Net(nn.Module): def __init__(self, in_shape: int): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 5, 3) self.hidden_size = int((in_shape — 2) * (in_shape — 2) / 4) * 5 self.fc1 = nn.Linear(self.hidden_size, 1)def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = x.view(-1, self.hidden_size) x = F.relu(self.fc1(x)) return x"
},
{
"code": null,
"e": 8314,
"s": 8262,
"text": "the fix_seeds function also gets changed to include"
},
{
"code": null,
"e": 8492,
"s": 8314,
"text": "def fix_seeds(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(42) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False"
},
{
"code": null,
"e": 8546,
"s": 8492,
"text": "Again, we’ll use synthetic data to train the network."
},
{
"code": null,
"e": 8768,
"s": 8546,
"text": "After initialization, we ensure that the sum of weights is equal to a specific value. Similarly, after training the network we check the model weights. If there is any discrepancies or randomness, the script will tell us."
},
{
"code": null,
"e": 8780,
"s": 8768,
"text": "Full script"
},
{
"code": null,
"e": 8817,
"s": 8780,
"text": "python3 reproducibility_cnn_torch.py"
},
{
"code": null,
"e": 8922,
"s": 8817,
"text": "gives consistent results, which means training neural network in PyTorch gives exactly the same weights."
},
{
"code": null,
"e": 9453,
"s": 8922,
"text": "There are caveats. First of all, these settings can impact training time, but tests show a negligible difference (1.14 +- 0.07 seconds for non-deterministic version; 1.17 +- 0.08 seconds for deterministic one). Secondly, CuDNN documentation warns us that there are several algorithms without reproducibility guarantees. These algorithms are usually faster than their deterministic variations, but PyTorch does not use them if flags are set. At last, some modules are non-deterministic (I was unable to reproduce the issue myself)."
},
{
"code": null,
"e": 9604,
"s": 9453,
"text": "Anyways, these issues are rarely an obstruction. So, Torch has built-in reproducibility support, and Keras does not have such functionality right now."
},
{
"code": null,
"e": 9952,
"s": 9604,
"text": "But wait! There are some speculations that because Keras and Torch share back-end, setting these variables in PyTorch will affect Keras. It could be the case if the variables affected some process-wide parameters. This way, we can make use of these flags AND use Keras to write models painlessly.First of all, let’s check out how these flags work."
},
{
"code": null,
"e": 10287,
"s": 9952,
"text": "Let’s go deeper! Setting deterministic / benchmark flags from Python sidecalls functions defined in the C sources. Here, the state is stored internally.After that, this flag affects the choice of the algorithm during convolution. In other words, setting this flag does not affect the global state (environment variables, for example)."
},
{
"code": null,
"e": 10385,
"s": 10287,
"text": "So, it seems that PyTorch settings do not affect Keras internals (and actual tests confirm that)."
},
{
"code": null,
"e": 10734,
"s": 10385,
"text": "Added: some users report that for some layers (CuDNNLSTM is a notable example) and for some hardware and software combinations this hack MAY work. This is definitely an interesting effect, but I would discourage using this in practice. Using a technique that sometimes works and sometimes doesn’t undermines the whole idea of reproducible learning."
},
{
"code": null,
"e": 10953,
"s": 10734,
"text": "Fixing random seeds is extremely useful, as it helps with model debugging. Moreover, the decreased metric variance between runs helps to make decisions about whether some feature increases the performance of the model."
},
{
"code": null,
"e": 11126,
"s": 10953,
"text": "But sometimes it is not enough. Some models (convolutional, recurrent) require additional CuDNN settings to be set. Keras has no such functionality yet, while PyTorch does:"
}
] |
How to Copy Files in Python | Towards Data Science
|
Copying files programmatically, is one of the most common tasks in day-to-day software development. In today’s short guide we will explore a few different ways for copying files in Python using a library called shutil.
The shutil module is part of the Python’s Standard Library and offers a wide range of high level file operations. Now with respect to file copying, the library offers numerous methods that can be used depending on whether you want to copy metadata or file permissions and whether the desired destination will be a directory.
In this article, we will discuss about all available methods for doing so, namely
shutil.copy
shutil.copyfile
shutil.copy2
shutil.copyfileobj
At the end of the guide you can find a table that summarises the features of each individual methods mentioned above.
shutil.copy() method is used to copy specified source (without the metadata) to the destination file or directory and it will return the path to the newly created file. The src can either be a path-like object or a string.
shutil.copy(src, dst, *, follow_symlinks=True)
Preserves file permissions
Destination can be a directory
Does not copy metadata
Does not work with File objects
Example
import shutil# Copy file example.txt into a new file called example_copy.txtshutil.copy('example.txt', 'example_copy.txt')# Copy file example.txt into directory test/shutil.copy('example.txt', 'test/')
The shutil.copyfile() method is used to copy the source file (without the metadata) to the specified destination file. Again, the src can either be a path-like object or a string.
shutil.copyfile(src, dst, *, follow_symlinks=True)
Does not preserve file permissions
Destination cannot be a directory
Does not copy metadata
Does not work with File objects
Example
import shutil# Copy file example.txt into a new file called example_copy.txtshutil.copyfile('source.txt', 'destination.txt')
The shutil.copy2() method is identical to shutil.copy() except that copy2() attempts to preserve file metadata as well.
shutil.copy2(src, dst, *, follow_symlinks=True)
Preserves file permissions
Destination can be a directory
Copies metadata
Does not work with File objects
Example
import shutil# Copy file example.txt into a new file called example_copy.txtshutil.copy2('example.txt', 'example_copy.txt')# Copy file example.txt into directory test/shutil.copy2('example.txt', 'test/')
Now if you have to work with File Objects then shutil.copyfileobj is the way to go. Essentially, the method will copy the contents of the source file object to the specified destination file-like object. You can also set the length that corresponds to the buffer size used to copy the contents.
shutil.copyfileobj(fsrc, fdst[, length])
Does not preserve file permissions
Destination cannot be a directory
Does not copy metadata
Can work with File objects
Example
import shutilsource_file = open('example.txt', 'rb')dest_file = open('example_copy.txt', 'wb')shutil.copyfileobj(source_file, dest_file)
In today’s short guide we explore a few different ways for programmatically copying files using Python. More precisely, we introduced a few relevant methods offered by shutil module that comes as part of the Standard Library of the language.
Depending on whether you want to copy file permissions, metadata and whether you want to copy a file to a directory (or even use a method which in accepts file objects) you need to choose the one that will do the trick for your specific use-case.
The table below summarises the capabilities of each of the methods discussed in this article. Note that the only method that accepts File Objects is shutil.copyfileobj.
+--------------------+----------------+--------------+-------------+| Method | Preserves File | Destination | Copies || | Permissions | can be a dir | Metadata |+--------------------+----------------+--------------+-------------+| shutil.copy | ✔ | ✔ | ✗ || shutil.copyfile | ✗ | ✗ | ✗ || shutil.copy2 | ✔ | ✔ | ✔ || shutil.copyfileobj | ✗ | ✗ | ✗ |+--------------------+----------------+--------------+-------------+
Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.
gmyrianthous.medium.com
You may also like
|
[
{
"code": null,
"e": 390,
"s": 171,
"text": "Copying files programmatically, is one of the most common tasks in day-to-day software development. In today’s short guide we will explore a few different ways for copying files in Python using a library called shutil."
},
{
"code": null,
"e": 715,
"s": 390,
"text": "The shutil module is part of the Python’s Standard Library and offers a wide range of high level file operations. Now with respect to file copying, the library offers numerous methods that can be used depending on whether you want to copy metadata or file permissions and whether the desired destination will be a directory."
},
{
"code": null,
"e": 797,
"s": 715,
"text": "In this article, we will discuss about all available methods for doing so, namely"
},
{
"code": null,
"e": 809,
"s": 797,
"text": "shutil.copy"
},
{
"code": null,
"e": 825,
"s": 809,
"text": "shutil.copyfile"
},
{
"code": null,
"e": 838,
"s": 825,
"text": "shutil.copy2"
},
{
"code": null,
"e": 857,
"s": 838,
"text": "shutil.copyfileobj"
},
{
"code": null,
"e": 975,
"s": 857,
"text": "At the end of the guide you can find a table that summarises the features of each individual methods mentioned above."
},
{
"code": null,
"e": 1198,
"s": 975,
"text": "shutil.copy() method is used to copy specified source (without the metadata) to the destination file or directory and it will return the path to the newly created file. The src can either be a path-like object or a string."
},
{
"code": null,
"e": 1245,
"s": 1198,
"text": "shutil.copy(src, dst, *, follow_symlinks=True)"
},
{
"code": null,
"e": 1272,
"s": 1245,
"text": "Preserves file permissions"
},
{
"code": null,
"e": 1303,
"s": 1272,
"text": "Destination can be a directory"
},
{
"code": null,
"e": 1326,
"s": 1303,
"text": "Does not copy metadata"
},
{
"code": null,
"e": 1358,
"s": 1326,
"text": "Does not work with File objects"
},
{
"code": null,
"e": 1366,
"s": 1358,
"text": "Example"
},
{
"code": null,
"e": 1568,
"s": 1366,
"text": "import shutil# Copy file example.txt into a new file called example_copy.txtshutil.copy('example.txt', 'example_copy.txt')# Copy file example.txt into directory test/shutil.copy('example.txt', 'test/')"
},
{
"code": null,
"e": 1748,
"s": 1568,
"text": "The shutil.copyfile() method is used to copy the source file (without the metadata) to the specified destination file. Again, the src can either be a path-like object or a string."
},
{
"code": null,
"e": 1799,
"s": 1748,
"text": "shutil.copyfile(src, dst, *, follow_symlinks=True)"
},
{
"code": null,
"e": 1834,
"s": 1799,
"text": "Does not preserve file permissions"
},
{
"code": null,
"e": 1868,
"s": 1834,
"text": "Destination cannot be a directory"
},
{
"code": null,
"e": 1891,
"s": 1868,
"text": "Does not copy metadata"
},
{
"code": null,
"e": 1923,
"s": 1891,
"text": "Does not work with File objects"
},
{
"code": null,
"e": 1931,
"s": 1923,
"text": "Example"
},
{
"code": null,
"e": 2056,
"s": 1931,
"text": "import shutil# Copy file example.txt into a new file called example_copy.txtshutil.copyfile('source.txt', 'destination.txt')"
},
{
"code": null,
"e": 2176,
"s": 2056,
"text": "The shutil.copy2() method is identical to shutil.copy() except that copy2() attempts to preserve file metadata as well."
},
{
"code": null,
"e": 2224,
"s": 2176,
"text": "shutil.copy2(src, dst, *, follow_symlinks=True)"
},
{
"code": null,
"e": 2251,
"s": 2224,
"text": "Preserves file permissions"
},
{
"code": null,
"e": 2282,
"s": 2251,
"text": "Destination can be a directory"
},
{
"code": null,
"e": 2298,
"s": 2282,
"text": "Copies metadata"
},
{
"code": null,
"e": 2330,
"s": 2298,
"text": "Does not work with File objects"
},
{
"code": null,
"e": 2338,
"s": 2330,
"text": "Example"
},
{
"code": null,
"e": 2542,
"s": 2338,
"text": "import shutil# Copy file example.txt into a new file called example_copy.txtshutil.copy2('example.txt', 'example_copy.txt')# Copy file example.txt into directory test/shutil.copy2('example.txt', 'test/')"
},
{
"code": null,
"e": 2837,
"s": 2542,
"text": "Now if you have to work with File Objects then shutil.copyfileobj is the way to go. Essentially, the method will copy the contents of the source file object to the specified destination file-like object. You can also set the length that corresponds to the buffer size used to copy the contents."
},
{
"code": null,
"e": 2878,
"s": 2837,
"text": "shutil.copyfileobj(fsrc, fdst[, length])"
},
{
"code": null,
"e": 2913,
"s": 2878,
"text": "Does not preserve file permissions"
},
{
"code": null,
"e": 2947,
"s": 2913,
"text": "Destination cannot be a directory"
},
{
"code": null,
"e": 2970,
"s": 2947,
"text": "Does not copy metadata"
},
{
"code": null,
"e": 2997,
"s": 2970,
"text": "Can work with File objects"
},
{
"code": null,
"e": 3005,
"s": 2997,
"text": "Example"
},
{
"code": null,
"e": 3142,
"s": 3005,
"text": "import shutilsource_file = open('example.txt', 'rb')dest_file = open('example_copy.txt', 'wb')shutil.copyfileobj(source_file, dest_file)"
},
{
"code": null,
"e": 3384,
"s": 3142,
"text": "In today’s short guide we explore a few different ways for programmatically copying files using Python. More precisely, we introduced a few relevant methods offered by shutil module that comes as part of the Standard Library of the language."
},
{
"code": null,
"e": 3631,
"s": 3384,
"text": "Depending on whether you want to copy file permissions, metadata and whether you want to copy a file to a directory (or even use a method which in accepts file objects) you need to choose the one that will do the trick for your specific use-case."
},
{
"code": null,
"e": 3800,
"s": 3631,
"text": "The table below summarises the capabilities of each of the methods discussed in this article. Note that the only method that accepts File Objects is shutil.copyfileobj."
},
{
"code": null,
"e": 4413,
"s": 3800,
"text": "+--------------------+----------------+--------------+-------------+| Method | Preserves File | Destination | Copies || | Permissions | can be a dir | Metadata |+--------------------+----------------+--------------+-------------+| shutil.copy | ✔ | ✔ | ✗ || shutil.copyfile | ✗ | ✗ | ✗ || shutil.copy2 | ✔ | ✔ | ✔ || shutil.copyfileobj | ✗ | ✗ | ✗ |+--------------------+----------------+--------------+-------------+"
},
{
"code": null,
"e": 4584,
"s": 4413,
"text": "Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium."
},
{
"code": null,
"e": 4608,
"s": 4584,
"text": "gmyrianthous.medium.com"
}
] |
How to choose stocks to invest in with Python | by Khuyen Tran | Towards Data Science
|
You plan to invest in several stocks in the coming 3 years, each with a different expected return for each dollar invested and a specific amount of investment, as shown in the table below (all in thousands of dollars). Given that the amount you can invest in stock purchases is limited each year, you want to decide which stocks to invest in each year so as to maximize the total returns.
Everybody wants to receive the most returns with the least investment but not everybody takes the time to analyze the stocks because this is not an easy task. You decided to use your data science skills to help you with this problem but found it challenging to solve with machine learning techniques. Why is this the case?
While Machine Learning is great in learning from data and making predictions, it has a limitation in making the optimal decision. But with Python MIP (Mixed-Integer Linear Programming) tool, the stocks chosen for each year could be determined with ease. When your problems involve multiple constraints and allow for many possible solutions, only MIP has the power to find the optimal solution. You can find more information about MIP here. This blog will show you how to use this tool for your benefit.
Input parameters:
Number of stocks (I)
Budget requirement of each stock for each year (a[t][i])
Budget requirement each year (b[t])
Annual return of each stock (c[i])
Decision variables: Whether or not to select a stock each year x[t][i]. This is a binary variable with x[t][i] = 1 when selected and x[t][i]=0 otherwise
Constraints: The sum of the budget requirement for all invested stocks each year cannot exceed the budget requirement for that year
Objective: Maximize total return in investment
c = [90, 120, 100, 80, 130]b = [45, 60, 50]a = [[10, 15, 12, 9, 13],[20, 15, 25, 15, 10],[15, 20, 20, 15, 10]]T, I = range(len(b)),range(len(c))
Install MIP
pip install mip==1.4.2 from mip.model import *
m = Model(sense = MAXIMIZE,solver_name=CBC)
Create variables with add_var()
Create a vector of variables with n binary decision variables (n = 5) indicating whether a stock is selected or not
x = [[m.add_var(name = names[i], var_type=BINARY) for i in I] for t in T]
Use *xsum()* for summation expressions
m.objective = maximize(xsum(c[i] * x[t][i] for i in I for t in T))
Add constraint in money available each year
for t in range(3): m += xsum(a[t][i] * x[t][i] for i in I) <= b[t]
Optimize() method executes the optimization of a formulation. Optimize method returns the status (OptimizationStatus) of the search. OPTIMAL if the search was concluded and the optimal solution was found.
status = m.optimize() if status == OptimizationStatus.OPTIMAL: print('optimal solution cost {} found'.format(m.objective_value))
results = {}for i in range(3): results[i+1] = [m.vars[j].x for j in range(5*i,5*i+5)]
import pandas as pd result = pd.DataFrame(data = results, index = ['A','B','C','D','E'])
Based on the results obtained, this is what you should do to maximize the total return in investment with different limitation in the budget each year:
In year 1, invest in stock A, C, D, and E
In year 2, invest in stock A, B, and D
In year 3, invest in stock B, C, and E
Even though stocks E and B give the highest return on investment, they are not always chosen because of their high budget requirements in that respective year. (i.e Stock B is not chosen in year 1 because it has the highest budget requirement compared to other stocks)
Some stocks are not chosen in one year not because of their budget requirement but because of their low return in investment (i.e Stock A is not chosen in year 3 even though the budget requirement is relatively low)
Congratulations! You learned how which stocks to choose for each given year to achieve the optimal return in value using MIP. I hope you have fun choosing your stock and observing the optimal results after just a few lines of code.
Feel free to fork and play with the code for this article in this Github repo.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
medium.com
[1]Gurobi. Retrieved from: https://www.gurobi.com/machine-learning-and-mathematical-optimization/
|
[
{
"code": null,
"e": 561,
"s": 172,
"text": "You plan to invest in several stocks in the coming 3 years, each with a different expected return for each dollar invested and a specific amount of investment, as shown in the table below (all in thousands of dollars). Given that the amount you can invest in stock purchases is limited each year, you want to decide which stocks to invest in each year so as to maximize the total returns."
},
{
"code": null,
"e": 884,
"s": 561,
"text": "Everybody wants to receive the most returns with the least investment but not everybody takes the time to analyze the stocks because this is not an easy task. You decided to use your data science skills to help you with this problem but found it challenging to solve with machine learning techniques. Why is this the case?"
},
{
"code": null,
"e": 1387,
"s": 884,
"text": "While Machine Learning is great in learning from data and making predictions, it has a limitation in making the optimal decision. But with Python MIP (Mixed-Integer Linear Programming) tool, the stocks chosen for each year could be determined with ease. When your problems involve multiple constraints and allow for many possible solutions, only MIP has the power to find the optimal solution. You can find more information about MIP here. This blog will show you how to use this tool for your benefit."
},
{
"code": null,
"e": 1405,
"s": 1387,
"text": "Input parameters:"
},
{
"code": null,
"e": 1426,
"s": 1405,
"text": "Number of stocks (I)"
},
{
"code": null,
"e": 1483,
"s": 1426,
"text": "Budget requirement of each stock for each year (a[t][i])"
},
{
"code": null,
"e": 1519,
"s": 1483,
"text": "Budget requirement each year (b[t])"
},
{
"code": null,
"e": 1554,
"s": 1519,
"text": "Annual return of each stock (c[i])"
},
{
"code": null,
"e": 1707,
"s": 1554,
"text": "Decision variables: Whether or not to select a stock each year x[t][i]. This is a binary variable with x[t][i] = 1 when selected and x[t][i]=0 otherwise"
},
{
"code": null,
"e": 1839,
"s": 1707,
"text": "Constraints: The sum of the budget requirement for all invested stocks each year cannot exceed the budget requirement for that year"
},
{
"code": null,
"e": 1886,
"s": 1839,
"text": "Objective: Maximize total return in investment"
},
{
"code": null,
"e": 2031,
"s": 1886,
"text": "c = [90, 120, 100, 80, 130]b = [45, 60, 50]a = [[10, 15, 12, 9, 13],[20, 15, 25, 15, 10],[15, 20, 20, 15, 10]]T, I = range(len(b)),range(len(c))"
},
{
"code": null,
"e": 2043,
"s": 2031,
"text": "Install MIP"
},
{
"code": null,
"e": 2090,
"s": 2043,
"text": "pip install mip==1.4.2 from mip.model import *"
},
{
"code": null,
"e": 2134,
"s": 2090,
"text": "m = Model(sense = MAXIMIZE,solver_name=CBC)"
},
{
"code": null,
"e": 2166,
"s": 2134,
"text": "Create variables with add_var()"
},
{
"code": null,
"e": 2282,
"s": 2166,
"text": "Create a vector of variables with n binary decision variables (n = 5) indicating whether a stock is selected or not"
},
{
"code": null,
"e": 2356,
"s": 2282,
"text": "x = [[m.add_var(name = names[i], var_type=BINARY) for i in I] for t in T]"
},
{
"code": null,
"e": 2395,
"s": 2356,
"text": "Use *xsum()* for summation expressions"
},
{
"code": null,
"e": 2462,
"s": 2395,
"text": "m.objective = maximize(xsum(c[i] * x[t][i] for i in I for t in T))"
},
{
"code": null,
"e": 2506,
"s": 2462,
"text": "Add constraint in money available each year"
},
{
"code": null,
"e": 2575,
"s": 2506,
"text": "for t in range(3): m += xsum(a[t][i] * x[t][i] for i in I) <= b[t]"
},
{
"code": null,
"e": 2780,
"s": 2575,
"text": "Optimize() method executes the optimization of a formulation. Optimize method returns the status (OptimizationStatus) of the search. OPTIMAL if the search was concluded and the optimal solution was found."
},
{
"code": null,
"e": 2912,
"s": 2780,
"text": "status = m.optimize() if status == OptimizationStatus.OPTIMAL: print('optimal solution cost {} found'.format(m.objective_value)) "
},
{
"code": null,
"e": 3000,
"s": 2912,
"text": "results = {}for i in range(3): results[i+1] = [m.vars[j].x for j in range(5*i,5*i+5)]"
},
{
"code": null,
"e": 3089,
"s": 3000,
"text": "import pandas as pd result = pd.DataFrame(data = results, index = ['A','B','C','D','E'])"
},
{
"code": null,
"e": 3241,
"s": 3089,
"text": "Based on the results obtained, this is what you should do to maximize the total return in investment with different limitation in the budget each year:"
},
{
"code": null,
"e": 3283,
"s": 3241,
"text": "In year 1, invest in stock A, C, D, and E"
},
{
"code": null,
"e": 3322,
"s": 3283,
"text": "In year 2, invest in stock A, B, and D"
},
{
"code": null,
"e": 3361,
"s": 3322,
"text": "In year 3, invest in stock B, C, and E"
},
{
"code": null,
"e": 3630,
"s": 3361,
"text": "Even though stocks E and B give the highest return on investment, they are not always chosen because of their high budget requirements in that respective year. (i.e Stock B is not chosen in year 1 because it has the highest budget requirement compared to other stocks)"
},
{
"code": null,
"e": 3846,
"s": 3630,
"text": "Some stocks are not chosen in one year not because of their budget requirement but because of their low return in investment (i.e Stock A is not chosen in year 3 even though the budget requirement is relatively low)"
},
{
"code": null,
"e": 4078,
"s": 3846,
"text": "Congratulations! You learned how which stocks to choose for each given year to achieve the optimal return in value using MIP. I hope you have fun choosing your stock and observing the optimal results after just a few lines of code."
},
{
"code": null,
"e": 4157,
"s": 4078,
"text": "Feel free to fork and play with the code for this article in this Github repo."
},
{
"code": null,
"e": 4317,
"s": 4157,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
},
{
"code": null,
"e": 4493,
"s": 4317,
"text": "Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:"
},
{
"code": null,
"e": 4516,
"s": 4493,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4539,
"s": 4516,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4562,
"s": 4539,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4573,
"s": 4562,
"text": "medium.com"
}
] |
MATLAB - Quick Guide
|
MATLAB (matrix laboratory) is a fourth-generation high-level programming language and interactive environment for numerical computation, visualization and programming.
It allows matrix manipulations; plotting of functions and data; implementation of algorithms; creation of user interfaces; interfacing with programs written in other languages, including C, C++, Java, and FORTRAN; analyze data; develop algorithms; and create models and applications.
It has numerous built-in commands and math functions that help you in mathematical calculations, generating plots, and performing numerical methods.
MATLAB is used in every facet of computational mathematics. Following are some commonly used mathematical calculations where it is used most commonly −
Dealing with Matrices and Arrays
2-D and 3-D Plotting and graphics
Linear Algebra
Algebraic Equations
Non-linear Functions
Statistics
Data Analysis
Calculus and Differential Equations
Numerical Calculations
Integration
Transforms
Curve Fitting
Various other special functions
Following are the basic features of MATLAB −
It is a high-level language for numerical computation, visualization and application development.
It is a high-level language for numerical computation, visualization and application development.
It also provides an interactive environment for iterative exploration, design and problem solving.
It also provides an interactive environment for iterative exploration, design and problem solving.
It provides vast library of mathematical functions for linear algebra, statistics, Fourier analysis, filtering, optimization, numerical integration and solving ordinary differential equations.
It provides vast library of mathematical functions for linear algebra, statistics, Fourier analysis, filtering, optimization, numerical integration and solving ordinary differential equations.
It provides built-in graphics for visualizing data and tools for creating custom plots.
It provides built-in graphics for visualizing data and tools for creating custom plots.
MATLAB's programming interface gives development tools for improving code quality maintainability and maximizing performance.
MATLAB's programming interface gives development tools for improving code quality maintainability and maximizing performance.
It provides tools for building applications with custom graphical interfaces.
It provides tools for building applications with custom graphical interfaces.
It provides functions for integrating MATLAB based algorithms with external applications and languages such as C, Java, .NET and Microsoft Excel.
It provides functions for integrating MATLAB based algorithms with external applications and languages such as C, Java, .NET and Microsoft Excel.
MATLAB is widely used as a computational tool in science and engineering encompassing the fields of physics, chemistry, math and all engineering streams. It is used in a range of applications including −
Signal Processing and Communications
Image and Video Processing
Control Systems
Test and Measurement
Computational Finance
Computational Biology
Setting up MATLAB environment is a matter of few clicks. The installer can be downloaded from here.
MathWorks provides the licensed product, a trial version and a student version as well. You need to log into the site and wait a little for their approval.
After downloading the installer the software can be installed through few clicks.
MATLAB development IDE can be launched from the icon created on the desktop. The main working window in MATLAB is called the desktop. When MATLAB is started, the desktop appears in its default layout −
The desktop has the following panels −
Current Folder − This panel allows you to access the project folders and files.
Current Folder − This panel allows you to access the project folders and files.
Command Window − This is the main area where commands can be entered at the command line. It is indicated by the command prompt (>>).
Command Window − This is the main area where commands can be entered at the command line. It is indicated by the command prompt (>>).
Workspace − The workspace shows all the variables created and/or imported from files.
Workspace − The workspace shows all the variables created and/or imported from files.
Command History − This panel shows or return commands that are entered at the command line.
Command History − This panel shows or return commands that are entered at the command line.
If you are willing to use Octave on your machine ( Linux, BSD, OS X or Windows ), then kindly download latest version from Download GNU Octave. You can check the given installation instructions for your machine.
MATLAB environment behaves like a super-complex calculator. You can enter commands at the >> command prompt.
MATLAB is an interpreted environment. In other words, you give a command and MATLAB executes it right away.
Type a valid expression, for example,
5 + 5
And press ENTER
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans = 10
Let us take up few more examples −
3 ^ 2 % 3 raised to the power of 2
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans = 9
Another example,
sin(pi /2) % sine of angle 90o
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans = 1
Another example,
7/0 % Divide by zero
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans = Inf
warning: division by zero
Another example,
732 * 20.3
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
ans = 1.4860e+04
MATLAB provides some special expressions for some mathematical symbols, like pi for π, Inf for ∞, i (and j) for √-1 etc. Nan stands for 'not a number'.
Semicolon (;) indicates end of statement. However, if you want to suppress and hide the MATLAB output for an expression, add a semicolon after the expression.
For example,
x = 3;
y = x + 5
When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −
y = 8
The percent symbol (%) is used for indicating a comment line. For example,
x = 9 % assign the value 9 to x
You can also write a block of comments using the block comment operators % { and % }.
The MATLAB editor includes tools and context menu items to help you add, remove, or change the format of comments.
MATLAB supports the following commonly used operators and special characters −
MATLAB supports the following special variables and constants −
Variable names consist of a letter followed by any number of letters, digits or underscore.
MATLAB is case-sensitive.
Variable names can be of any length, however, MATLAB uses only first N characters, where N is given by the function namelengthmax.
The save command is used for saving all the variables in the workspace, as a file with .mat extension, in the current directory.
For example,
save myfile
You can reload the file anytime later using the load command.
load myfile
In MATLAB environment, every variable is an array or matrix.
You can assign variables in a simple way. For example,
x = 3 % defining x and initializing it with a value
MATLAB will execute the above statement and return the following result −
x = 3
It creates a 1-by-1 matrix named x and stores the value 3 in its element. Let us check another example,
x = sqrt(16) % defining x and initializing it with an expression
MATLAB will execute the above statement and return the following result −
x = 4
Please note that −
Once a variable is entered into the system, you can refer to it later.
Once a variable is entered into the system, you can refer to it later.
Variables must have values before they are used.
Variables must have values before they are used.
When an expression returns a result that is not assigned to any variable, the system assigns it to a variable named ans, which can be used later.
When an expression returns a result that is not assigned to any variable, the system assigns it to a variable named ans, which can be used later.
For example,
sqrt(78)
MATLAB will execute the above statement and return the following result −
ans = 8.8318
You can use this variable ans −
sqrt(78);
9876/ans
MATLAB will execute the above statement and return the following result −
ans = 1118.2
Let's look at another example −
x = 7 * 8;
y = x * 7.89
MATLAB will execute the above statement and return the following result −
y = 441.84
You can have multiple assignments on the same line. For example,
a = 2; b = 7; c = a * b
MATLAB will execute the above statement and return the following result −
c = 14
The who command displays all the variable names you have used.
who
MATLAB will execute the above statement and return the following result −
Your variables are:
a ans b c
The whos command displays little more about the variables −
Variables currently in memory
Type of each variables
Memory allocated to each variable
Whether they are complex variables or not
whos
MATLAB will execute the above statement and return the following result −
Attr Name Size Bytes Class
==== ==== ==== ==== =====
a 1x1 8 double
ans 1x70 757 cell
b 1x1 8 double
c 1x1 8 double
Total is 73 elements using 781 bytes
The clear command deletes all (or the specified) variable(s) from the memory.
clear x % it will delete x, won't display anything
clear % it will delete all variables in the workspace
% peacefully and unobtrusively
Long assignments can be extended to another line by using an ellipses (...). For example,
initial_velocity = 0;
acceleration = 9.8;
time = 20;
final_velocity = initial_velocity + acceleration * time
MATLAB will execute the above statement and return the following result −
final_velocity = 196
By default, MATLAB displays numbers with four decimal place values. This is known as short format.
However, if you want more precision, you need to use the format command.
The format long command displays 16 digits after decimal.
For example −
format long
x = 7 + 10/3 + 5 ^ 1.2
MATLAB will execute the above statement and return the following result−
x = 17.2319816406394
Another example,
format short
x = 7 + 10/3 + 5 ^ 1.2
MATLAB will execute the above statement and return the following result −
x = 17.232
The format bank command rounds numbers to two decimal places. For example,
format bank
daily_wage = 177.45;
weekly_wage = daily_wage * 6
MATLAB will execute the above statement and return the following result −
weekly_wage = 1064.70
MATLAB displays large numbers using exponential notation.
The format short e command allows displaying in exponential form with four decimal places plus the exponent.
For example,
format short e
4.678 * 4.9
MATLAB will execute the above statement and return the following result −
ans = 2.2922e+01
The format long e command allows displaying in exponential form with four decimal places plus the exponent. For example,
format long e
x = pi
MATLAB will execute the above statement and return the following result −
x = 3.141592653589793e+00
The format rat command gives the closest rational expression resulting from a calculation. For example,
format rat
4.678 * 4.9
MATLAB will execute the above statement and return the following result −
ans = 34177/1491
A vector is a one-dimensional array of numbers. MATLAB allows creating two types of vectors −
Row vectors
Column vectors
Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit the elements.
For example,
r = [7 8 9 10 11]
MATLAB will execute the above statement and return the following result −
r =
7 8 9 10 11
Another example,
r = [7 8 9 10 11];
t = [2, 3, 4, 5, 6];
res = r + t
MATLAB will execute the above statement and return the following result −
res =
9 11 13 15 17
Column vectors are created by enclosing the set of elements in square brackets, using semicolon(;) to delimit the elements.
c = [7; 8; 9; 10; 11]
MATLAB will execute the above statement and return the following result −
c =
7
8
9
10
11
A matrix is a two-dimensional array of numbers.
In MATLAB, a matrix is created by entering each row as a sequence of space or comma separated elements, and end of a row is demarcated by a semicolon. For example, let us create a 3-by-3 matrix as −
m = [1 2 3; 4 5 6; 7 8 9]
MATLAB will execute the above statement and return the following result −
m =
1 2 3
4 5 6
7 8 9
MATLAB is an interactive program for numerical computation and data visualization. You can enter a command by typing it at the MATLAB prompt '>>' on the Command Window.
In this section, we will provide lists of commonly used general MATLAB commands.
MATLAB provides various commands for managing a session. The following table provides all such commands −
MATLAB provides various useful commands for working with the system, like saving the current work in the workspace as a file and loading the file later.
It also provides various commands for other system-related activities like, displaying date, listing files in the directory, displaying current directory, etc.
The following table displays some commonly used system-related commands −
MATLAB provides the following input and output related commands −
The fscanf and fprintf commands behave like C scanf and printf functions. They support the following format codes −
The format function has the following forms used for numeric display −
The following table shows various commands used for working with arrays, matrices and vectors −
MATLAB provides numerous commands for plotting graphs. The following table shows some of the commonly used commands for plotting −
So far, we have used MATLAB environment as a calculator. However, MATLAB is also a powerful programming language, as well as an interactive computational environment.
In previous chapters, you have learned how to enter commands from the MATLAB command prompt. MATLAB also allows you to write series of commands into a file and execute the file as complete unit, like writing a function and calling it.
MATLAB allows writing two kinds of program files −
Scripts − script files are program files with .m extension. In these files, you write series of commands, which you want to execute together. Scripts do not accept inputs and do not return any outputs. They operate on data in the workspace.
Scripts − script files are program files with .m extension. In these files, you write series of commands, which you want to execute together. Scripts do not accept inputs and do not return any outputs. They operate on data in the workspace.
Functions − functions files are also program files with .m extension. Functions can accept inputs and return outputs. Internal variables are local to the function.
Functions − functions files are also program files with .m extension. Functions can accept inputs and return outputs. Internal variables are local to the function.
You can use the MATLAB editor or any other text editor to create your .mfiles. In this section, we will discuss the script files. A script file contains multiple sequential lines of MATLAB commands and function calls. You can run a script by typing its name at the command line.
To create scripts files, you need to use a text editor. You can open the MATLAB editor in two ways −
Using the command prompt
Using the IDE
If you are using the command prompt, type edit in the command prompt. This will open the editor. You can directly type edit and then the filename (with .m extension)
edit
Or
edit <filename>
The above command will create the file in default MATLAB directory. If you want to store all program files in a specific folder, then you will have to provide the entire path.
Let us create a folder named progs. Type the following commands at the command prompt (>>) −
mkdir progs % create directory progs under default directory
chdir progs % changing the current directory to progs
edit prog1.m % creating an m file named prog1.m
If you are creating the file for first time, MATLAB prompts you to confirm it. Click Yes.
Alternatively, if you are using the IDE, choose NEW -> Script. This also opens the editor and creates a file named Untitled. You can name and save the file after typing the code.
Type the following code in the editor −
NoOfStudents = 6000;
TeachingStaff = 150;
NonTeachingStaff = 20;
Total = NoOfStudents + TeachingStaff ...
+ NonTeachingStaff;
disp(Total);
After creating and saving the file, you can run it in two ways −
Clicking the Run button on the editor window or
Clicking the Run button on the editor window or
Just typing the filename (without extension) in the command prompt: >> prog1
Just typing the filename (without extension) in the command prompt: >> prog1
The command window prompt displays the result −
6170
Create a script file, and type the following code −
a = 5; b = 7;
c = a + b
d = c + sin(b)
e = 5 * d
f = exp(-d)
When the above code is compiled and executed, it produces the following result −
c = 12
d = 12.657
e = 63.285
f = 3.1852e-06
MATLAB does not require any type declaration or dimension statements. Whenever MATLAB encounters a new variable name, it creates the variable and allocates appropriate memory space.
If the variable already exists, then MATLAB replaces the original content with new content and allocates new storage space, where necessary.
For example,
Total = 42
The above statement creates a 1-by-1 matrix named 'Total' and stores the value 42 in it.
MATLAB provides 15 fundamental data types. Every data type stores data that is in the form of a matrix or array. The size of this matrix or array is a minimum of 0-by-0 and this can grow up to a matrix or array of any size.
The following table shows the most commonly used data types in MATLAB −
int8
8-bit signed integer
uint8
8-bit unsigned integer
int16
16-bit signed integer
uint16
16-bit unsigned integer
int32
32-bit signed integer
uint32
32-bit unsigned integer
int64
64-bit signed integer
uint64
64-bit unsigned integer
single
single precision numerical data
double
double precision numerical data
logical
logical values of 1 or 0, represent true and false respectively
char
character data (strings are stored as vector of characters)
cell array
array of indexed cells, each capable of storing an array of a different dimension and data type
structure
C-like structures, each structure having named fields capable of storing an array of a different dimension and data type
function handle
pointer to a function
user classes
objects constructed from a user-defined class
java classes
objects constructed from a Java class
Create a script file with the following code −
str = 'Hello World!'
n = 2345
d = double(n)
un = uint32(789.50)
rn = 5678.92347
c = int32(rn)
When the above code is compiled and executed, it produces the following result −
str = Hello World!
n = 2345
d = 2345
un = 790
rn = 5678.9
c = 5679
MATLAB provides various functions for converting, a value from one data type to another. The following table shows the data type conversion functions −
MATLAB provides various functions for identifying data type of a variable.
Following table provides the functions for determining the data type of a variable −
Create a script file with the following code −
x = 3
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
x = 23.54
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
x = [1 2 3]
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
x = 'Hello'
isinteger(x)
isfloat(x)
isvector(x)
isscalar(x)
isnumeric(x)
When you run the file, it produces the following result −
x = 3
ans = 0
ans = 1
ans = 1
ans = 1
ans = 1
x = 23.540
ans = 0
ans = 1
ans = 1
ans = 1
ans = 1
x =
1 2 3
ans = 0
ans = 1
ans = 1
ans = 0
x = Hello
ans = 0
ans = 0
ans = 1
ans = 0
ans = 0
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. MATLAB is designed to operate primarily on whole matrices and arrays. Therefore, operators in MATLAB work both on scalar and non-scalar data. MATLAB allows the following types of elementary operations −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operations
Set Operations
MATLAB allows two different types of arithmetic operations −
Matrix arithmetic operations
Array arithmetic operations
Matrix arithmetic operations are same as defined in linear algebra. Array operations are executed element by element, both on one-dimensional and multidimensional array.
The matrix operators and array operators are differentiated by the period (.) symbol. However, as the addition and subtraction operation is same for matrices and arrays, the operator is same for both cases. The following table gives brief description of the operators −
Show Examples
+
Addition or unary plus. A+B adds the values stored in variables A and B. A and B must have the same size, unless one is a scalar. A scalar can be added to a matrix of any size.
-
Subtraction or unary minus. A-B subtracts the value of B from A. A and B must have the same size, unless one is a scalar. A scalar can be subtracted from a matrix of any size.
*
Matrix multiplication. C = A*B is the linear algebraic product of the matrices A and B. More precisely,
For non-scalar A and B, the number of columns of A must be equal to the number of rows of B. A scalar can multiply a matrix of any size.
.*
Array multiplication. A.*B is the element-by-element product of the arrays A and B. A and B must have the same size, unless one of them is a scalar.
/
Slash or matrix right division. B/A is roughly the same as B*inv(A). More precisely, B/A = (A'\B')'.
./
Array right division. A./B is the matrix with elements A(i,j)/B(i,j). A and B must have the same size, unless one of them is a scalar.
\
Backslash or matrix left division. If A is a square matrix, A\B is roughly the same as inv(A)*B, except it is computed in a different way. If A is an n-by-n matrix and B is a column vector with n components, or a matrix with several such columns, then X = A\B is the solution to the equation AX = B. A warning message is displayed if A is badly scaled or nearly singular.
.\
Array left division. A.\B is the matrix with elements B(i,j)/A(i,j). A and B must have the same size, unless one of them is a scalar.
^
Matrix power. X^p is X to the power p, if p is a scalar. If p is an integer, the power is computed by repeated squaring. If the integer is negative, X is inverted first. For other values of p, the calculation involves eigenvalues and eigenvectors, such that if [V,D] = eig(X), then X^p = V*D.^p/V.
.^
Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. A and B must have the same size, unless one of them is a scalar.
'
Matrix transpose. A' is the linear algebraic transpose of A. For complex matrices, this is the complex conjugate transpose.
.'
Array transpose. A.' is the array transpose of A. For complex matrices, this does not involve conjugation.
Relational operators can also work on both scalar and non-scalar data. Relational operators for arrays perform element-by-element comparisons between two arrays and return a logical array of the same size, with elements set to logical 1 (true) where the relation is true and elements set to logical 0 (false) where it is not.
The following table shows the relational operators available in MATLAB −
Show Examples
<
Less than
<=
Less than or equal to
>
Greater than
>=
Greater than or equal to
==
Equal to
~=
Not equal to
MATLAB offers two types of logical operators and functions −
Element-wise − These operators operate on corresponding elements of logical arrays.
Element-wise − These operators operate on corresponding elements of logical arrays.
Short-circuit − These operators operate on scalar and, logical expressions.
Short-circuit − These operators operate on scalar and, logical expressions.
Element-wise logical operators operate element-by-element on logical arrays. The symbols &, |, and ~ are the logical array operators AND, OR, and NOT.
Short-circuit logical operators allow short-circuiting on logical operations. The symbols && and || are the logical short-circuit operators AND and OR.
Show Examples
Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows −
Assume if A = 60; and B = 13; Now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
MATLAB provides various functions for bit-wise operations like 'bitwise and', 'bitwise or' and 'bitwise not' operations, shift operation, etc.
The following table shows the commonly used bitwise operations −
Show Examples
MATLAB provides various functions for set operations, like union, intersection and testing for set membership, etc.
The following table shows some commonly used set operations −
Show Examples
intersect(A,B)
Set intersection of two arrays; returns the values common to both A and B. The values returned are in sorted order.
intersect(A,B,'rows')
Treats each row of A and each row of B as single entities and returns the rows common to both A and B. The rows of the returned matrix are in sorted order.
ismember(A,B)
Returns an array the same size as A, containing 1 (true) where the elements of A are found in B. Elsewhere, it returns 0 (false).
ismember(A,B,'rows')
Treats each row of A and each row of B as single entities and returns a vector containing 1 (true) where the rows of matrix A are also rows of B. Elsewhere, it returns 0 (false).
issorted(A)
Returns logical 1 (true) if the elements of A are in sorted order and logical 0 (false) otherwise. Input A can be a vector or an N-by-1 or 1-by-N cell array of strings. A is considered to be sorted if A and the output of sort(A) are equal.
issorted(A, 'rows')
Returns logical 1 (true) if the rows of two-dimensional matrix A is in sorted order, and logical 0 (false) otherwise. Matrix A is considered to be sorted if A and the output of sortrows(A) are equal.
setdiff(A,B)
Sets difference of two arrays; returns the values in A that are not in B. The values in the returned array are in sorted order.
setdiff(A,B,'rows')
Treats each row of A and each row of B as single entities and returns the rows from A that are not in B. The rows of the returned matrix are in sorted order.
The 'rows' option does not support cell arrays.
setxor
Sets exclusive OR of two arrays
union
Sets union of two arrays
unique
Unique values in array
Decision making structures require that the programmer should specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the programming languages −
MATLAB provides following types of decision making statements. Click the following links to check their detail −
An if ... end statement consists of a boolean expression followed by one or more statements.
An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
An if statement can be followed by one (or more) optional elseif... and an else statement, which is very useful to test various conditions.
You can use one if or elseif statement inside another if or elseif statement(s).
A switch statement allows a variable to be tested for equality against a list of values.
You can use one switch statement inside another switch statement(s).
There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially. The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −
MATLAB provides following types of loops to handle looping requirements. Click the following links to check their detail −
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
You can use one or more loops inside any another loop.
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
MATLAB supports the following control statements. Click the following links to check their detail.
Terminates the loop statement and transfers execution to the statement immediately following the loop.
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
A vector is a one-dimensional array of numbers. MATLAB allows creating two types of vectors −
Row vectors
Column vectors
Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit the elements.
r = [7 8 9 10 11]
MATLAB will execute the above statement and return the following result −
r =
7 8 9 10 11
Column vectors are created by enclosing the set of elements in square brackets, using semicolon to delimit the elements.
c = [7; 8; 9; 10; 11]
MATLAB will execute the above statement and return the following result −
c =
7
8
9
10
11
You can reference one or more of the elements of a vector in several ways. The ith component of a vector v is referred as v(i). For example −
v = [ 1; 2; 3; 4; 5; 6]; % creating a column vector of 6 elements
v(3)
MATLAB will execute the above statement and return the following result −
ans = 3
When you reference a vector with a colon, such as v(:), all the components of the vector are listed.
v = [ 1; 2; 3; 4; 5; 6]; % creating a column vector of 6 elements
v(:)
MATLAB will execute the above statement and return the following result −
ans =
1
2
3
4
5
6
MATLAB allows you to select a range of elements from a vector.
For example, let us create a row vector rv of 9 elements, then we will reference the elements 3 to 7 by writing rv(3:7) and create a new vector named sub_rv.
rv = [1 2 3 4 5 6 7 8 9];
sub_rv = rv(3:7)
MATLAB will execute the above statement and return the following result −
sub_rv =
3 4 5 6 7
In this section, let us discuss the following vector operations −
Addition and Subtraction of Vectors
Addition and Subtraction of Vectors
Scalar Multiplication of Vectors
Scalar Multiplication of Vectors
Transpose of a Vector
Transpose of a Vector
Appending Vectors
Appending Vectors
Magnitude of a Vector
Magnitude of a Vector
Vector Dot Product
Vector Dot Product
Vectors with Uniformly Spaced Elements
Vectors with Uniformly Spaced Elements
A matrix is a two-dimensional array of numbers.
In MATLAB, you create a matrix by entering elements in each row as comma or space delimited numbers and using semicolons to mark the end of each row.
For example, let us create a 4-by-5 matrix a −
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]
MATLAB will execute the above statement and return the following result −
a =
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
To reference an element in the mth row and nth column, of a matrix mx, we write −
mx(m, n);
For example, to refer to the element in the 2nd row and 5th column, of the matrix a, as created in the last section, we type −
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a(2,5)
MATLAB will execute the above statement and return the following result −
ans = 6
To reference all the elements in the mth column we type A(:,m).
Let us create a column vector v, from the elements of the 4th row of the matrix a −
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
v = a(:,4)
MATLAB will execute the above statement and return the following result −
v =
4
5
6
7
You can also select the elements in the mth through nth columns, for this we write −
a(:,m:n)
Let us create a smaller matrix taking the elements from the second and third columns −
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a(:, 2:3)
MATLAB will execute the above statement and return the following result −
ans =
2 3
3 4
4 5
5 6
In the same way, you can create a sub-matrix taking a sub-part of a matrix.
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a(:, 2:3)
MATLAB will execute the above statement and return the following result −
ans =
2 3
3 4
4 5
5 6
In the same way, you can create a sub-matrix taking a sub-part of a matrix.
For example, let us create a sub-matrix sa taking the inner subpart of a −
3 4 5
4 5 6
To do this, write −
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
sa = a(2:3,2:4)
MATLAB will execute the above statement and return the following result −
sa =
3 4 5
4 5 6
You can delete an entire row or column of a matrix by assigning an empty set of square braces [] to that row or column. Basically, [] denotes an empty array.
For example, let us delete the fourth row of a −
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a( 4 , : ) = []
MATLAB will execute the above statement and return the following result −
a =
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
Next, let us delete the fifth column of a −
a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a(: , 5)=[]
MATLAB will execute the above statement and return the following result −
a =
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
In this example, let us create a 3-by-3 matrix m, then we will copy the second and third rows of this matrix twice to create a 4-by-3 matrix.
Create a script file with the following code −
a = [ 1 2 3 ; 4 5 6; 7 8 9];
new_mat = a([2,3,2,3],:)
When you run the file, it displays the following result −
new_mat =
4 5 6
7 8 9
4 5 6
7 8 9
In this section, let us discuss the following basic and commonly used matrix operations −
Addition and Subtraction of Matrices
Addition and Subtraction of Matrices
Division of Matrices
Division of Matrices
Scalar Operations of Matrices
Scalar Operations of Matrices
Transpose of a Matrix
Transpose of a Matrix
Concatenating Matrices
Concatenating Matrices
Matrix Multiplication
Matrix Multiplication
Determinant of a Matrix
Determinant of a Matrix
Inverse of a Matrix
Inverse of a Matrix
All variables of all data types in MATLAB are multidimensional arrays. A vector is a one-dimensional array and a matrix is a two-dimensional array.
We have already discussed vectors and matrices. In this chapter, we will discuss multidimensional arrays. However, before that, let us discuss some special types of arrays.
In this section, we will discuss some functions that create some special arrays. For all these functions, a single argument creates a square array, double arguments create rectangular array.
The zeros() function creates an array of all zeros −
For example −
zeros(5)
MATLAB will execute the above statement and return the following result −
ans =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
The ones() function creates an array of all ones −
For example −
ones(4,3)
MATLAB will execute the above statement and return the following result −
ans =
1 1 1
1 1 1
1 1 1
1 1 1
The eye() function creates an identity matrix.
For example −
eye(4)
MATLAB will execute the above statement and return the following result −
ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
The rand() function creates an array of uniformly distributed random numbers on (0,1) −
For example −
rand(3, 5)
MATLAB will execute the above statement and return the following result −
ans =
0.8147 0.9134 0.2785 0.9649 0.9572
0.9058 0.6324 0.5469 0.1576 0.4854
0.1270 0.0975 0.9575 0.9706 0.8003
A magic square is a square that produces the same sum, when its elements are added row-wise, column-wise or diagonally.
The magic() function creates a magic square array. It takes a singular argument that gives the size of the square. The argument must be a scalar greater than or equal to 3.
magic(4)
MATLAB will execute the above statement and return the following result −
ans =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
An array having more than two dimensions is called a multidimensional array in MATLAB. Multidimensional arrays in MATLAB are an extension of the normal two-dimensional matrix.
Generally to generate a multidimensional array, we first create a two-dimensional array and extend it.
For example, let's create a two-dimensional array a.
a = [7 9 5; 6 1 9; 4 3 2]
MATLAB will execute the above statement and return the following result −
a =
7 9 5
6 1 9
4 3 2
The array a is a 3-by-3 array; we can add a third dimension to a, by providing the values like −
a(:, :, 2)= [ 1 2 3; 4 5 6; 7 8 9]
MATLAB will execute the above statement and return the following result −
a =
ans(:,:,1) =
0 0 0
0 0 0
0 0 0
ans(:,:,2) =
1 2 3
4 5 6
7 8 9
We can also create multidimensional arrays using the ones(), zeros() or the rand() functions.
For example,
b = rand(4,3,2)
MATLAB will execute the above statement and return the following result −
b(:,:,1) =
0.0344 0.7952 0.6463
0.4387 0.1869 0.7094
0.3816 0.4898 0.7547
0.7655 0.4456 0.2760
b(:,:,2) =
0.6797 0.4984 0.2238
0.6551 0.9597 0.7513
0.1626 0.3404 0.2551
0.1190 0.5853 0.5060
We can also use the cat() function to build multidimensional arrays. It concatenates a list of arrays along a specified dimension −
Syntax for the cat() function is −
B = cat(dim, A1, A2...)
Where,
B is the new array created
B is the new array created
A1, A2, ... are the arrays to be concatenated
A1, A2, ... are the arrays to be concatenated
dim is the dimension along which to concatenate the arrays
dim is the dimension along which to concatenate the arrays
Create a script file and type the following code into it −
a = [9 8 7; 6 5 4; 3 2 1];
b = [1 2 3; 4 5 6; 7 8 9];
c = cat(3, a, b, [ 2 3 1; 4 7 8; 3 9 0])
When you run the file, it displays −
c(:,:,1) =
9 8 7
6 5 4
3 2 1
c(:,:,2) =
1 2 3
4 5 6
7 8 9
c(:,:,3) =
2 3 1
4 7 8
3 9 0
MATLAB provides the following functions to sort, rotate, permute, reshape, or shift array contents.
The following examples illustrate some of the functions mentioned above.
Length, Dimension and Number of elements −
Create a script file and type the following code into it −
x = [7.1, 3.4, 7.2, 28/4, 3.6, 17, 9.4, 8.9];
length(x) % length of x vector
y = rand(3, 4, 5, 2);
ndims(y) % no of dimensions in array y
s = ['Zara', 'Nuha', 'Shamim', 'Riz', 'Shadab'];
numel(s) % no of elements in s
When you run the file, it displays the following result −
ans = 8
ans = 4
ans = 23
Circular Shifting of the Array Elements −
Create a script file and type the following code into it −
a = [1 2 3; 4 5 6; 7 8 9] % the original array a
b = circshift(a,1) % circular shift first dimension values down by 1.
c = circshift(a,[1 -1]) % circular shift first dimension values % down by 1
% and second dimension values to the left % by 1.
When you run the file, it displays the following result −
a =
1 2 3
4 5 6
7 8 9
b =
7 8 9
1 2 3
4 5 6
c =
8 9 7
2 3 1
5 6 4
Create a script file and type the following code into it −
v = [ 23 45 12 9 5 0 19 17] % horizontal vector
sort(v) % sorting v
m = [2 6 4; 5 3 9; 2 0 1] % two dimensional array
sort(m, 1) % sorting m along the row
sort(m, 2) % sorting m along the column
When you run the file, it displays the following result −
v =
23 45 12 9 5 0 19 17
ans =
0 5 9 12 17 19 23 45
m =
2 6 4
5 3 9
2 0 1
ans =
2 0 1
2 3 4
5 6 9
ans =
2 4 6
3 5 9
0 1 2
Cell arrays are arrays of indexed cells where each cell can store an array of a different dimensions and data types.
The cell function is used for creating a cell array. Syntax for the cell function is −
C = cell(dim)
C = cell(dim1,...,dimN)
D = cell(obj)
C is the cell array;
C is the cell array;
dim is a scalar integer or vector of integers that specifies the dimensions of cell array C;
dim is a scalar integer or vector of integers that specifies the dimensions of cell array C;
dim1, ... , dimN are scalar integers that specify the dimensions of C;
dim1, ... , dimN are scalar integers that specify the dimensions of C;
obj is One of the following −
Java array or object
.NET array of type System.String or System.Object
obj is One of the following −
Java array or object
.NET array of type System.String or System.Object
Create a script file and type the following code into it −
c = cell(2, 5);
c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5}
When you run the file, it displays the following result −
c =
{
[1,1] = Red
[2,1] = 1
[1,2] = Blue
[2,2] = 2
[1,3] = Green
[2,3] = 3
[1,4] = Yellow
[2,4] = 4
[1,5] = White
[2,5] = 5
}
There are two ways to refer to the elements of a cell array −
Enclosing the indices in first bracket (), to refer to sets of cells
Enclosing the indices in braces {}, to refer to the data within individual cells
When you enclose the indices in first bracket, it refers to the set of cells.
Cell array indices in smooth parentheses refer to sets of cells.
For example −
c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5};
c(1:2,1:2)
MATLAB will execute the above statement and return the following result −
ans =
{
[1,1] = Red
[2,1] = 1
[1,2] = Blue
[2,2] = 2
}
You can also access the contents of cells by indexing with curly braces.
For example −
c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5};
c{1, 2:4}
MATLAB will execute the above statement and return the following result −
ans = Blue
ans = Green
ans = Yellow
The colon(:) is one of the most useful operator in MATLAB. It is used to create vectors, subscript arrays, and specify for iterations.
If you want to create a row vector, containing integers from 1 to 10, you write −
1:10
MATLAB executes the statement and returns a row vector containing the integers from 1 to 10 −
ans =
1 2 3 4 5 6 7 8 9 10
If you want to specify an increment value other than one, for example −
100: -5: 50
MATLAB executes the statement and returns the following result −
ans =
100 95 90 85 80 75 70 65 60 55 50
Let us take another example −
0:pi/8:pi
MATLAB executes the statement and returns the following result −
ans =
Columns 1 through 7
0 0.3927 0.7854 1.1781 1.5708 1.9635 2.3562
Columns 8 through 9
2.7489 3.1416
You can use the colon operator to create a vector of indices to select rows, columns or elements of arrays.
The following table describes its use for this purpose (let us have a matrix A) −
Create a script file and type the following code in it −
A = [1 2 3 4; 4 5 6 7; 7 8 9 10]
A(:,2) % second column of A
A(:,2:3) % second and third column of A
A(2:3,2:3) % second and third rows and second and third columns
When you run the file, it displays the following result −
A =
1 2 3 4
4 5 6 7
7 8 9 10
ans =
2
5
8
ans =
2 3
5 6
8 9
ans =
5 6
8 9
MATLAB supports various numeric classes that include signed and unsigned integers and single-precision and double-precision floating-point numbers. By default, MATLAB stores all numeric values as double-precision floating point numbers.
You can choose to store any number or array of numbers as integers or as single-precision numbers.
All numeric types support basic array operations and mathematical operations.
MATLAB provides the following functions to convert to various numeric data types −
Create a script file and type the following code −
x = single([5.32 3.47 6.28]) .* 7.5
x = double([5.32 3.47 6.28]) .* 7.5
x = int8([5.32 3.47 6.28]) .* 7.5
x = int16([5.32 3.47 6.28]) .* 7.5
x = int32([5.32 3.47 6.28]) .* 7.5
x = int64([5.32 3.47 6.28]) .* 7.5
When you run the file, it shows the following result −
x =
39.900 26.025 47.100
x =
39.900 26.025 47.100
x =
38 23 45
x =
38 23 45
x =
38 23 45
x =
38 23 45
Let us extend the previous example a little more. Create a script file and type the following code −
x = int32([5.32 3.47 6.28]) .* 7.5
x = int64([5.32 3.47 6.28]) .* 7.5
x = num2cell(x)
When you run the file, it shows the following result −
x =
38 23 45
x =
38 23 45
x =
{
[1,1] = 38
[1,2] = 23
[1,3] = 45
}
The functions intmax() and intmin() return the maximum and minimum values that can be represented with all types of integer numbers.
Both the functions take the integer data type as the argument, for example, intmax(int8) or intmin(int64) and return the maximum and minimum values that you can represent with the integer data type.
The following example illustrates how to obtain the smallest and largest values of integers. Create a script file and write the following code in it −
% displaying the smallest and largest signed integer data
str = 'The range for int8 is:\n\t%d to %d ';
sprintf(str, intmin('int8'), intmax('int8'))
str = 'The range for int16 is:\n\t%d to %d ';
sprintf(str, intmin('int16'), intmax('int16'))
str = 'The range for int32 is:\n\t%d to %d ';
sprintf(str, intmin('int32'), intmax('int32'))
str = 'The range for int64 is:\n\t%d to %d ';
sprintf(str, intmin('int64'), intmax('int64'))
% displaying the smallest and largest unsigned integer data
str = 'The range for uint8 is:\n\t%d to %d ';
sprintf(str, intmin('uint8'), intmax('uint8'))
str = 'The range for uint16 is:\n\t%d to %d ';
sprintf(str, intmin('uint16'), intmax('uint16'))
str = 'The range for uint32 is:\n\t%d to %d ';
sprintf(str, intmin('uint32'), intmax('uint32'))
str = 'The range for uint64 is:\n\t%d to %d ';
sprintf(str, intmin('uint64'), intmax('uint64'))
When you run the file, it shows the following result −
ans = The range for int8 is:
-128 to 127
ans = The range for int16 is:
-32768 to 32767
ans = The range for int32 is:
-2147483648 to 2147483647
ans = The range for int64 is:
0 to 0
ans = The range for uint8 is:
0 to 255
ans = The range for uint16 is:
0 to 65535
ans = The range for uint32 is:
0 to -1
ans = The range for uint64 is:
0 to 18446744073709551616
The functions realmax() and realmin() return the maximum and minimum values that can be represented with floating point numbers.
Both the functions when called with the argument 'single', return the maximum and minimum values that you can represent with the single-precision data type and when called with the argument 'double', return the maximum and minimum values that you can represent with the double-precision data type.
The following example illustrates how to obtain the smallest and largest floating point numbers. Create a script file and write the following code in it −
% displaying the smallest and largest single-precision
% floating point number
str = 'The range for single is:\n\t%g to %g and\n\t %g to %g';
sprintf(str, -realmax('single'), -realmin('single'), ...
realmin('single'), realmax('single'))
% displaying the smallest and largest double-precision
% floating point number
str = 'The range for double is:\n\t%g to %g and\n\t %g to %g';
sprintf(str, -realmax('double'), -realmin('double'), ...
realmin('double'), realmax('double'))
When you run the file, it displays the following result −
ans = The range for single is:
-3.40282e+38 to -1.17549e-38 and
1.17549e-38 to 3.40282e+38
ans = The range for double is:
-1.79769e+308 to -2.22507e-308 and
2.22507e-308 to 1.79769e+308
Creating a character string is quite simple in MATLAB. In fact, we have used it many times. For example, you type the following in the command prompt −
my_string = 'Tutorials Point'
MATLAB will execute the above statement and return the following result −
my_string = Tutorials Point
MATLAB considers all variables as arrays, and strings are considered as character arrays. Let us use the whos command to check the variable created above −
whos
MATLAB will execute the above statement and return the following result −
Name Size Bytes Class Attributes
my_string 1x16 32 char
Interestingly, you can use numeric conversion functions like uint8 or uint16 to convert the characters in the string to their numeric codes. The char function converts the integer vector back to characters −
Create a script file and type the following code into it −
my_string = 'Tutorial''s Point';
str_ascii = uint8(my_string) % 8-bit ascii values
str_back_to_char= char(str_ascii)
str_16bit = uint16(my_string) % 16-bit ascii values
str_back_to_char = char(str_16bit)
When you run the file, it displays the following result −
str_ascii =
84 117 116 111 114 105 97 108 39 115 32 80 111 105 110 116
str_back_to_char = Tutorial's Point
str_16bit =
84 117 116 111 114 105 97 108 39 115 32 80 111 105 110 116
str_back_to_char = Tutorial's Point
The strings we have discussed so far are one-dimensional character arrays; however, we need to store more than that. We need to store more dimensional textual data in our program. This is achieved by creating rectangular character arrays.
Simplest way of creating a rectangular character array is by concatenating two or more one-dimensional character arrays, either vertically or horizontally as required.
You can combine strings vertically in either of the following ways −
Using the MATLAB concatenation operator [] and separating each row with a semicolon (;). Please note that in this method each row must contain the same number of characters. For strings with different lengths, you should pad with space characters as needed.
Using the MATLAB concatenation operator [] and separating each row with a semicolon (;). Please note that in this method each row must contain the same number of characters. For strings with different lengths, you should pad with space characters as needed.
Using the char function. If the strings are of different lengths, char pads the shorter strings with trailing blanks so that each row has the same number of characters.
Using the char function. If the strings are of different lengths, char pads the shorter strings with trailing blanks so that each row has the same number of characters.
Create a script file and type the following code into it −
doc_profile = ['Zara Ali '; ...
'Sr. Surgeon '; ...
'R N Tagore Cardiology Research Center']
doc_profile = char('Zara Ali', 'Sr. Surgeon', ...
'RN Tagore Cardiology Research Center')
When you run the file, it displays the following result −
doc_profile =
Zara Ali
Sr. Surgeon
R N Tagore Cardiology Research Center
doc_profile =
Zara Ali
Sr. Surgeon
RN Tagore Cardiology Research Center
You can combine strings horizontally in either of the following ways −
Using the MATLAB concatenation operator, [] and separating the input strings with a comma or a space. This method preserves any trailing spaces in the input arrays.
Using the MATLAB concatenation operator, [] and separating the input strings with a comma or a space. This method preserves any trailing spaces in the input arrays.
Using the string concatenation function, strcat. This method removes trailing spaces in the inputs.
Using the string concatenation function, strcat. This method removes trailing spaces in the inputs.
Create a script file and type the following code into it −
name = 'Zara Ali ';
position = 'Sr. Surgeon ';
worksAt = 'R N Tagore Cardiology Research Center';
profile = [name ', ' position ', ' worksAt]
profile = strcat(name, ', ', position, ', ', worksAt)
When you run the file, it displays the following result −
profile = Zara Ali , Sr. Surgeon , R N Tagore Cardiology Research Center
profile = Zara Ali,Sr. Surgeon,R N Tagore Cardiology Research Center
From our previous discussion, it is clear that combining strings with different lengths could be a pain as all strings in the array has to be of the same length. We have used blank spaces at the end of strings to equalize their length.
However, a more efficient way to combine the strings is to convert the resulting array into a cell array.
MATLAB cell array can hold different sizes and types of data in an array. Cell arrays provide a more flexible way to store strings of varying length.
The cellstr function converts a character array into a cell array of strings.
Create a script file and type the following code into it −
name = 'Zara Ali ';
position = 'Sr. Surgeon ';
worksAt = 'R N Tagore Cardiology Research Center';
profile = char(name, position, worksAt);
profile = cellstr(profile);
disp(profile)
When you run the file, it displays the following result −
{
[1,1] = Zara Ali
[2,1] = Sr. Surgeon
[3,1] = R N Tagore Cardiology Research Center
}
MATLAB provides numerous string functions creating, combining, parsing, comparing and manipulating strings.
Following table provides brief description of the string functions in MATLAB −
The following examples illustrate some of the above-mentioned string functions −
Create a script file and type the following code into it −
A = pi*1000*ones(1,5);
sprintf(' %f \n %.2f \n %+.2f \n %12.2f \n %012.2f \n', A)
When you run the file, it displays the following result −
ans = 3141.592654
3141.59
+3141.59
3141.59
000003141.59
Create a script file and type the following code into it −
%cell array of strings
str_array = {'red','blue','green', 'yellow', 'orange'};
% Join strings in cell array into single string
str1 = strjoin(str_array, "-")
str2 = strjoin(str_array, ",")
When you run the file, it displays the following result −
str1 = red-blue-green-yellow-orange
str2 = red,blue,green,yellow,orange
Create a script file and type the following code into it −
students = {'Zara Ali', 'Neha Bhatnagar', ...
'Monica Malik', 'Madhu Gautam', ...
'Madhu Sharma', 'Bhawna Sharma',...
'Nuha Ali', 'Reva Dutta', ...
'Sunaina Ali', 'Sofia Kabir'};
% The strrep function searches and replaces sub-string.
new_student = strrep(students(8), 'Reva', 'Poulomi')
% Display first names
first_names = strtok(students)
When you run the file, it displays the following result −
new_student =
{
[1,1] = Poulomi Dutta
}
first_names =
{
[1,1] = Zara
[1,2] = Neha
[1,3] = Monica
[1,4] = Madhu
[1,5] = Madhu
[1,6] = Bhawna
[1,7] = Nuha
[1,8] = Reva
[1,9] = Sunaina
[1,10] = Sofia
}
Create a script file and type the following code into it −
str1 = 'This is test'
str2 = 'This is text'
if (strcmp(str1, str2))
sprintf('%s and %s are equal', str1, str2)
else
sprintf('%s and %s are not equal', str1, str2)
end
When you run the file, it displays the following result −
str1 = This is test
str2 = This is text
ans = This is test and This is text are not equal
A function is a group of statements that together perform a task. In MATLAB, functions are defined in separate files. The name of the file and of the function should be the same.
Functions operate on variables within their own workspace, which is also called the local workspace, separate from the workspace you access at the MATLAB command prompt which is called the base workspace.
Functions can accept more than one input arguments and may return more than one output arguments.
Syntax of a function statement is −
function [out1,out2, ..., outN] = myfun(in1,in2,in3, ..., inN)
The following function named mymax should be written in a file named mymax.m. It takes five numbers as argument and returns the maximum of the numbers.
Create a function file, named mymax.m and type the following code in it −
function max = mymax(n1, n2, n3, n4, n5)
%This function calculates the maximum of the
% five numbers given as input
max = n1;
if(n2 > max)
max = n2;
end
if(n3 > max)
max = n3;
end
if(n4 > max)
max = n4;
end
if(n5 > max)
max = n5;
end
The first line of a function starts with the keyword function. It gives the name of the function and order of arguments. In our example, the mymax function has five input arguments and one output argument.
The comment lines that come right after the function statement provide the help text. These lines are printed when you type −
help mymax
MATLAB will execute the above statement and return the following result −
This function calculates the maximum of the
five numbers given as input
You can call the function as −
mymax(34, 78, 89, 23, 11)
MATLAB will execute the above statement and return the following result −
ans = 89
An anonymous function is like an inline function in traditional programming languages, defined within a single MATLAB statement. It consists of a single MATLAB expression and any number of input and output arguments.
You can define an anonymous function right at the MATLAB command line or within a function or script.
This way you can create simple functions without having to create a file for them.
The syntax for creating an anonymous function from an expression is
f = @(arglist)expression
In this example, we will write an anonymous function named power, which will take two numbers as input and return first number raised to the power of the second number.
Create a script file and type the following code in it −
power = @(x, n) x.^n;
result1 = power(7, 3)
result2 = power(49, 0.5)
result3 = power(10, -10)
result4 = power (4.5, 1.5)
When you run the file, it displays −
result1 = 343
result2 = 7
result3 = 1.0000e-10
result4 = 9.5459
Any function other than an anonymous function must be defined within a file. Each function file contains a required primary function that appears first and any number of optional sub-functions that comes after the primary function and used by it.
Primary functions can be called from outside of the file that defines them, either from command line or from other functions, but sub-functions cannot be called from command line or other functions, outside the function file.
Sub-functions are visible only to the primary function and other sub-functions within the function file that defines them.
Let us write a function named quadratic that would calculate the roots of a quadratic equation. The function would take three inputs, the quadratic co-efficient, the linear co-efficient and the constant term. It would return the roots.
The function file quadratic.m will contain the primary function quadratic and the sub-function disc, which calculates the discriminant.
Create a function file quadratic.m and type the following code in it −
function [x1,x2] = quadratic(a,b,c)
%this function returns the roots of
% a quadratic equation.
% It takes 3 input arguments
% which are the co-efficients of x2, x and the
%constant term
% It returns the roots
d = disc(a,b,c);
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of quadratic
function dis = disc(a,b,c)
%function calculates the discriminant
dis = sqrt(b^2 - 4*a*c);
end % end of sub-function
You can call the above function from command prompt as −
quadratic(2,4,-4)
MATLAB will execute the above statement and return the following result −
ans = 0.7321
You can define functions within the body of another function. These are called nested functions. A nested function contains any or all of the components of any other function.
Nested functions are defined within the scope of another function and they share access to the containing function's workspace.
A nested function follows the following syntax −
function x = A(p1, p2)
...
B(p2)
function y = B(p3)
...
end
...
end
Let us rewrite the function quadratic, from previous example, however, this time the disc function will be a nested function.
Create a function file quadratic2.m and type the following code in it −
function [x1,x2] = quadratic2(a,b,c)
function disc % nested function
d = sqrt(b^2 - 4*a*c);
end % end of function disc
disc;
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of function quadratic2
You can call the above function from command prompt as −
quadratic2(2,4,-4)
MATLAB will execute the above statement and return the following result −
ans = 0.73205
A private function is a primary function that is visible only to a limited group of other functions. If you do not want to expose the implementation of a function(s), you can create them as private functions.
Private functions reside in subfolders with the special name private.
They are visible only to functions in the parent folder.
Let us rewrite the quadratic function. This time, however, the disc function calculating the discriminant, will be a private function.
Create a subfolder named private in working directory. Store the following function file disc.m in it −
function dis = disc(a,b,c)
%function calculates the discriminant
dis = sqrt(b^2 - 4*a*c);
end % end of sub-function
Create a function quadratic3.m in your working directory and type the following code in it −
function [x1,x2] = quadratic3(a,b,c)
%this function returns the roots of
% a quadratic equation.
% It takes 3 input arguments
% which are the co-efficient of x2, x and the
%constant term
% It returns the roots
d = disc(a,b,c);
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end % end of quadratic3
You can call the above function from command prompt as −
quadratic3(2,4,-4)
MATLAB will execute the above statement and return the following result −
ans = 0.73205
Global variables can be shared by more than one function. For this, you need to declare the variable as global in all the functions.
If you want to access that variable from the base workspace, then declare the variable at the command line.
The global declaration must occur before the variable is actually used in a function. It is a good practice to use capital letters for the names of global variables to distinguish them from other variables.
Let us create a function file named average.m and type the following code in it −
function avg = average(nums)
global TOTAL
avg = sum(nums)/TOTAL;
end
Create a script file and type the following code in it −
global TOTAL;
TOTAL = 10;
n = [34, 45, 25, 45, 33, 19, 40, 34, 38, 42];
av = average(n)
When you run the file, it will display the following result −
av = 35.500
Importing data in MATLAB means loading data from an external file. The importdata function allows loading various data files of different formats. It has the following five forms −
A = importdata(filename)
Loads data into array A from the file denoted by filename.
A = importdata('-pastespecial')
Loads data from the system clipboard rather than from a file.
A = importdata(___, delimiterIn)
Interprets delimiterIn as the column separator in ASCII file, filename, or the clipboard data. You can use delimiterIn with any of the input arguments in the above syntaxes.
A = importdata(___, delimiterIn, headerlinesIn)
Loads data from ASCII file, filename, or the clipboard, reading numeric data starting from line headerlinesIn+1.
[A, delimiterOut, headerlinesOut] = importdata(___)
Returns the detected delimiter character for the input ASCII file in delimiterOut and the detected number of header lines in headerlinesOut, using any of the input arguments in the previous syntaxes.
Let us load and display an image file. Create a script file and type the following code in it −
filename = 'smile.jpg';
A = importdata(filename);
image(A);
When you run the file, MATLAB displays the image file. However, you must store it in the current directory.
In this example, we import a text file and specify Delimiter and Column Header. Let us create a space-delimited ASCII file with column headers, named weeklydata.txt.
Our text file weeklydata.txt looks like this −
SunDay MonDay TuesDay WednesDay ThursDay FriDay SaturDay
95.01 76.21 61.54 40.57 55.79 70.28 81.53
73.11 45.65 79.19 93.55 75.29 69.87 74.68
60.68 41.85 92.18 91.69 81.32 90.38 74.51
48.60 82.14 73.82 41.03 0.99 67.22 93.18
89.13 44.47 57.63 89.36 13.89 19.88 46.60
Create a script file and type the following code in it −
filename = 'weeklydata.txt';
delimiterIn = ' ';
headerlinesIn = 1;
A = importdata(filename,delimiterIn,headerlinesIn);
% View data
for k = [1:7]
disp(A.colheaders{1, k})
disp(A.data(:, k))
disp(' ')
end
When you run the file, it displays the following result −
SunDay
95.0100
73.1100
60.6800
48.6000
89.1300
MonDay
76.2100
45.6500
41.8500
82.1400
44.4700
TuesDay
61.5400
79.1900
92.1800
73.8200
57.6300
WednesDay
40.5700
93.5500
91.6900
41.0300
89.3600
ThursDay
55.7900
75.2900
81.3200
0.9900
13.8900
FriDay
70.2800
69.8700
90.3800
67.2200
19.8800
SaturDay
81.5300
74.6800
74.5100
93.1800
46.6000
In this example, let us import data from clipboard.
Copy the following lines to the clipboard −
Mathematics is simple
Create a script file and type the following code −
A = importdata('-pastespecial')
When you run the file, it displays the following result −
A =
'Mathematics is simple'
The importdata function is a high-level function. The low-level file I/O functions in MATLAB allow the most control over reading or writing data to a file. However, these functions need more detailed information about your file to work efficiently.
MATLAB provides the following functions for read and write operations at the byte or character level −
MATLAB provides the following functions for low-level import of text data files −
The fscanf function reads formatted data in a text or ASCII file.
The fscanf function reads formatted data in a text or ASCII file.
The fgetl and fgets functions read one line of a file at a time, where a newline character separates each line.
The fgetl and fgets functions read one line of a file at a time, where a newline character separates each line.
The fread function reads a stream of data at the byte or bit level.
The fread function reads a stream of data at the byte or bit level.
We have a text data file 'myfile.txt' saved in our working directory. The file stores rainfall data for three months; June, July and August for the year 2012.
The data in myfile.txt contains repeated sets of time, month and rainfall measurements at five places. The header data stores the number of months M; so we have M sets of measurements.
The file looks like this −
Rainfall Data
Months: June, July, August
M = 3
12:00:00
June-2012
17.21 28.52 39.78 16.55 23.67
19.15 0.35 17.57 NaN 12.01
17.92 28.49 17.40 17.06 11.09
9.59 9.33 NaN 0.31 0.23
10.46 13.17 NaN 14.89 19.33
20.97 19.50 17.65 14.45 14.00
18.23 10.34 17.95 16.46 19.34
09:10:02
July-2012
12.76 16.94 14.38 11.86 16.89
20.46 23.17 NaN 24.89 19.33
30.97 49.50 47.65 24.45 34.00
18.23 30.34 27.95 16.46 19.34
30.46 33.17 NaN 34.89 29.33
30.97 49.50 47.65 24.45 34.00
28.67 30.34 27.95 36.46 29.34
15:03:40
August-2012
17.09 16.55 19.59 17.25 19.22
17.54 11.45 13.48 22.55 24.01
NaN 21.19 25.85 25.05 27.21
26.79 24.98 12.23 16.99 18.67
17.54 11.45 13.48 22.55 24.01
NaN 21.19 25.85 25.05 27.21
26.79 24.98 12.23 16.99 18.67
We will import data from this file and display this data. Take the following steps −
Open the file with fopen function and get the file identifier.
Open the file with fopen function and get the file identifier.
Describe the data in the file with format specifiers, such as '%s' for a string, '%d' for an integer, or '%f' for a floating-point number.
Describe the data in the file with format specifiers, such as '%s' for a string, '%d' for an integer, or '%f' for a floating-point number.
To skip literal characters in the file, include them in the format description. To skip a data field, use an asterisk ('*') in the specifier.
For example, to read the headers and return the single value for M, we write −
M = fscanf(fid, '%*s %*s\n%*s %*s %*s %*s\nM=%d\n\n', 1);
To skip literal characters in the file, include them in the format description. To skip a data field, use an asterisk ('*') in the specifier.
For example, to read the headers and return the single value for M, we write −
M = fscanf(fid, '%*s %*s\n%*s %*s %*s %*s\nM=%d\n\n', 1);
By default, fscanf reads data according to our format description until it does not find any match for the data, or it reaches the end of the file. Here we will use for loop for reading 3 sets of data and each time, it will read 7 rows and 5 columns.
By default, fscanf reads data according to our format description until it does not find any match for the data, or it reaches the end of the file. Here we will use for loop for reading 3 sets of data and each time, it will read 7 rows and 5 columns.
We will create a structure named mydata in the workspace to store data read from the file. This structure has three fields - time, month, and raindata array.
We will create a structure named mydata in the workspace to store data read from the file. This structure has three fields - time, month, and raindata array.
Create a script file and type the following code in it −
filename = '/data/myfile.txt';
rows = 7;
cols = 5;
% open the file
fid = fopen(filename);
% read the file headers, find M (number of months)
M = fscanf(fid, '%*s %*s\n%*s %*s %*s %*s\nM=%d\n\n', 1);
% read each set of measurements
for n = 1:M
mydata(n).time = fscanf(fid, '%s', 1);
mydata(n).month = fscanf(fid, '%s', 1);
% fscanf fills the array in column order,
% so transpose the results
mydata(n).raindata = ...
fscanf(fid, '%f', [rows, cols]);
end
for n = 1:M
disp(mydata(n).time), disp(mydata(n).month)
disp(mydata(n).raindata)
end
% close the file
fclose(fid);
When you run the file, it displays the following result −
12:00:00
June-2012
17.2100 17.5700 11.0900 13.1700 14.4500
28.5200 NaN 9.5900 NaN 14.0000
39.7800 12.0100 9.3300 14.8900 18.2300
16.5500 17.9200 NaN 19.3300 10.3400
23.6700 28.4900 0.3100 20.9700 17.9500
19.1500 17.4000 0.2300 19.5000 16.4600
0.3500 17.0600 10.4600 17.6500 19.3400
09:10:02
July-2012
12.7600 NaN 34.0000 33.1700 24.4500
16.9400 24.8900 18.2300 NaN 34.0000
14.3800 19.3300 30.3400 34.8900 28.6700
11.8600 30.9700 27.9500 29.3300 30.3400
16.8900 49.5000 16.4600 30.9700 27.9500
20.4600 47.6500 19.3400 49.5000 36.4600
23.1700 24.4500 30.4600 47.6500 29.3400
15:03:40
August-2012
17.0900 13.4800 27.2100 11.4500 25.0500
16.5500 22.5500 26.7900 13.4800 27.2100
19.5900 24.0100 24.9800 22.5500 26.7900
17.2500 NaN 12.2300 24.0100 24.9800
19.2200 21.1900 16.9900 NaN 12.2300
17.5400 25.8500 18.6700 21.1900 16.9900
11.4500 25.0500 17.5400 25.8500 18.6700
Data export (or output) in MATLAB means to write into files. MATLAB allows you to use your data in another application that reads ASCII files. For this, MATLAB provides several data export options.
You can create the following type of files −
Rectangular, delimited ASCII data file from an array.
Rectangular, delimited ASCII data file from an array.
Diary (or log) file of keystrokes and the resulting text output.
Diary (or log) file of keystrokes and the resulting text output.
Specialized ASCII file using low-level functions such as fprintf.
Specialized ASCII file using low-level functions such as fprintf.
MEX-file to access your C/C++ or Fortran routine that writes to a particular text file format.
MEX-file to access your C/C++ or Fortran routine that writes to a particular text file format.
Apart from this, you can also export data to spreadsheets.
There are two ways to export a numeric array as a delimited ASCII data file −
Using the save function and specifying the -ascii qualifier
Using the save function and specifying the -ascii qualifier
Using the dlmwrite function
Using the dlmwrite function
Syntax for using the save function is −
save my_data.out num_array -ascii
where, my_data.out is the delimited ASCII data file created, num_array is a numeric array and −ascii is the specifier.
Syntax for using the dlmwrite function is −
dlmwrite('my_data.out', num_array, 'dlm_char')
where, my_data.out is the delimited ASCII data file created, num_array is a numeric array and dlm_char is the delimiter character.
The following example demonstrates the concept. Create a script file and type the following code −
num_array = [ 1 2 3 4 ; 4 5 6 7; 7 8 9 0];
save array_data1.out num_array -ascii;
type array_data1.out
dlmwrite('array_data2.out', num_array, ' ');
type array_data2.out
When you run the file, it displays the following result −
1.0000000e+00 2.0000000e+00 3.0000000e+00 4.0000000e+00
4.0000000e+00 5.0000000e+00 6.0000000e+00 7.0000000e+00
7.0000000e+00 8.0000000e+00 9.0000000e+00 0.0000000e+00
1 2 3 4
4 5 6 7
7 8 9 0
Please note that the save -ascii command and the dlmwrite function does not work with cell arrays as input. To create a delimited ASCII file from the contents of a cell array, you can
Either, convert the cell array to a matrix using the cell2mat function
Either, convert the cell array to a matrix using the cell2mat function
Or export the cell array using low-level file I/O functions.
Or export the cell array using low-level file I/O functions.
If you use the save function to write a character array to an ASCII file, it writes the ASCII equivalent of the characters to the file.
For example, let us write the word 'hello' to a file −
h = 'hello';
save textdata.out h -ascii
type textdata.out
MATLAB executes the above statements and displays the following result. which is the characters of the string 'hello' in 8-digit ASCII format.
1.0400000e+02 1.0100000e+02 1.0800000e+02 1.0800000e+02 1.1100000e+02
Diary files are activity logs of your MATLAB session. The diary function creates an exact copy of your session in a disk file, excluding graphics.
To turn on the diary function, type −
diary
Optionally, you can give the name of the log file, say −
diary logdata.out
To turn off the diary function −
diary off
You can open the diary file in a text editor.
So far, we have exported numeric arrays. However, you may need to create other text files, including combinations of numeric and character data, nonrectangular output files, or files with non-ASCII encoding schemes. For these purposes, MATLAB provides the low-level fprintf function.
As in low-level I/O file activities, before exporting, you need to open or create a file with the fopen function and get the file identifier. By default, fopen opens a file for read-only access. You should specify the permission to write or append, such as 'w' or 'a'.
After processing the file, you need to close it with fclose(fid) function.
The following example demonstrates the concept −
Create a script file and type the following code in it −
% create a matrix y, with two rows
x = 0:10:100;
y = [x; log(x)];
% open a file for writing
fid = fopen('logtable.txt', 'w');
% Table Header
fprintf(fid, 'Log Function\n\n');
% print values in column order
% two values appear on each row of the file
fprintf(fid, '%f %f\n', y);
fclose(fid);
% display the file created
type logtable.txt
When you run the file, it displays the following result −
Log Function
0.000000 -Inf
10.000000 2.302585
20.000000 2.995732
30.000000 3.401197
40.000000 3.688879
50.000000 3.912023
60.000000 4.094345
70.000000 4.248495
80.000000 4.382027
90.000000 4.499810
100.000000 4.605170
To plot the graph of a function, you need to take the following steps −
Define x, by specifying the range of values for the variable x, for which the function is to be plotted
Define x, by specifying the range of values for the variable x, for which the function is to be plotted
Define the function, y = f(x)
Define the function, y = f(x)
Call the plot command, as plot(x, y)
Call the plot command, as plot(x, y)
Following example would demonstrate the concept. Let us plot the simple function y = x for the range of values for x from 0 to 100, with an increment of 5.
Create a script file and type the following code −
x = [0:5:100];
y = x;
plot(x, y)
When you run the file, MATLAB displays the following plot −
Let us take one more example to plot the function y = x2. In this example, we will draw two graphs with the same function, but in second time, we will reduce the value of increment. Please note that as we decrease the increment, the graph becomes smoother.
Create a script file and type the following code −
x = [1 2 3 4 5 6 7 8 9 10];
x = [-100:20:100];
y = x.^2;
plot(x, y)
When you run the file, MATLAB displays the following plot −
Change the code file a little, reduce the increment to 5 −
x = [-100:5:100];
y = x.^2;
plot(x, y)
MATLAB draws a smoother graph −
MATLAB allows you to add title, labels along the x-axis and y-axis, grid lines and also to adjust the axes to spruce up the graph.
The xlabel and ylabel commands generate labels along x-axis and y-axis.
The xlabel and ylabel commands generate labels along x-axis and y-axis.
The title command allows you to put a title on the graph.
The title command allows you to put a title on the graph.
The grid on command allows you to put the grid lines on the graph.
The grid on command allows you to put the grid lines on the graph.
The axis equal command allows generating the plot with the same scale factors and the spaces on both axes.
The axis equal command allows generating the plot with the same scale factors and the spaces on both axes.
The axis square command generates a square plot.
The axis square command generates a square plot.
Create a script file and type the following code −
x = [0:0.01:10];
y = sin(x);
plot(x, y), xlabel('x'), ylabel('Sin(x)'), title('Sin(x) Graph'),
grid on, axis equal
MATLAB generates the following graph −
You can draw multiple graphs on the same plot. The following example demonstrates the concept −
Create a script file and type the following code −
x = [0 : 0.01: 10];
y = sin(x);
g = cos(x);
plot(x, y, x, g, '.-'), legend('Sin(x)', 'Cos(x)')
MATLAB generates the following graph −
MATLAB provides eight basic color options for drawing graphs. The following table shows the colors and their codes −
Let us draw the graph of two polynomials
f(x) = 3x4 + 2x3+ 7x2 + 2x + 9 and
f(x) = 3x4 + 2x3+ 7x2 + 2x + 9 and
g(x) = 5x3 + 9x + 2
g(x) = 5x3 + 9x + 2
Create a script file and type the following code −
x = [-10 : 0.01: 10];
y = 3*x.^4 + 2 * x.^3 + 7 * x.^2 + 2 * x + 9;
g = 5 * x.^3 + 9 * x + 2;
plot(x, y, 'r', x, g, 'g')
When you run the file, MATLAB generates the following graph −
The axis command allows you to set the axis scales. You can provide minimum and maximum values for x and y axes using the axis command in the following way −
axis ( [xmin xmax ymin ymax] )
The following example shows this −
Create a script file and type the following code −
x = [0 : 0.01: 10];
y = exp(-x).* sin(2*x + 3);
plot(x, y), axis([0 10 -1 1])
When you run the file, MATLAB generates the following graph −
When you create an array of plots in the same figure, each of these plots is called a subplot. The subplot command is used for creating subplots.
Syntax for the command is −
subplot(m, n, p)
where, m and n are the number of rows and columns of the plot array and p specifies where to put a particular plot.
Each plot created with the subplot command can have its own characteristics. Following example demonstrates the concept −
Let us generate two plots −
y = e−1.5xsin(10x)
y = e−2xsin(10x)
Create a script file and type the following code −
x = [0:0.01:5];
y = exp(-1.5*x).*sin(10*x);
subplot(1,2,1)
plot(x,y), xlabel('x'),ylabel('exp(–1.5x)*sin(10x)'),axis([0 5 -1 1])
y = exp(-2*x).*sin(10*x);
subplot(1,2,2)
plot(x,y),xlabel('x'),ylabel('exp(–2x)*sin(10x)'),axis([0 5 -1 1])
When you run the file, MATLAB generates the following graph −
This chapter will continue exploring the plotting and graphics capabilities of MATLAB. We will discuss −
Drawing bar charts
Drawing contours
Three dimensional plots
The bar command draws a two dimensional bar chart. Let us take up an example to demonstrate the idea.
Let us have an imaginary classroom with 10 students. We know the percent of marks obtained by these students are 75, 58, 90, 87, 50, 85, 92, 75, 60 and 95. We will draw the bar chart for this data.
Create a script file and type the following code −
x = [1:10];
y = [75, 58, 90, 87, 50, 85, 92, 75, 60, 95];
bar(x,y), xlabel('Student'),ylabel('Score'),
title('First Sem:')
print -deps graph.eps
When you run the file, MATLAB displays the following bar chart −
A contour line of a function of two variables is a curve along which the function has a constant value. Contour lines are used for creating contour maps by joining points of equal elevation above a given level, such as mean sea level.
MATLAB provides a contour function for drawing contour maps.
Let us generate a contour map that shows the contour lines for a given function g = f(x, y). This function has two variables. So, we will have to generate two independent variables, i.e., two data sets x and y. This is done by calling the meshgrid command.
The meshgrid command is used for generating a matrix of elements that give the range over x and y along with the specification of increment in each case.
Let us plot our function g = f(x, y), where −5 ≤ x ≤ 5, −3 ≤ y ≤ 3. Let us take an increment of 0.1 for both the values. The variables are set as −
[x,y] = meshgrid(–5:0.1:5, –3:0.1:3);
Lastly, we need to assign the function. Let our function be: x2 + y2
Create a script file and type the following code −
[x,y] = meshgrid(-5:0.1:5,-3:0.1:3); %independent variables
g = x.^2 + y.^2; % our function
contour(x,y,g) % call the contour function
print -deps graph.eps
When you run the file, MATLAB displays the following contour map −
Let us modify the code a little to spruce up the map
[x,y] = meshgrid(-5:0.1:5,-3:0.1:3); %independent variables
g = x.^2 + y.^2; % our function
[C, h] = contour(x,y,g); % call the contour function
set(h,'ShowText','on','TextStep',get(h,'LevelStep')*2)
print -deps graph.eps
When you run the file, MATLAB displays the following contour map −
Three-dimensional plots basically display a surface defined by a function in two variables, g = f (x,y).
As before, to define g, we first create a set of (x,y) points over the domain of the function using the meshgrid command. Next, we assign the function itself. Finally, we use the surf command to create a surface plot.
The following example demonstrates the concept −
Let us create a 3D surface map for the function g = xe-(x2 + y2)
Create a script file and type the following code −
[x,y] = meshgrid(-2:.2:2);
g = x .* exp(-x.^2 - y.^2);
surf(x, y, g)
print -deps graph.eps
When you run the file, MATLAB displays the following 3-D map −
You can also use the mesh command to generate a three-dimensional surface. However, the surf command displays both the connecting lines and the faces of the surface in color, whereas, the mesh command creates a wireframe surface with colored lines connecting the defining points.
So far, we have seen that all the examples work in MATLAB as well as its GNU, alternatively called Octave. But for solving basic algebraic equations, both MATLAB and Octave are little different, so we will try to cover MATLAB and Octave in separate sections.
We will also discuss factorizing and simplification of algebraic expressions.
The solve function is used for solving algebraic equations. In its simplest form, the solve function takes the equation enclosed in quotes as an argument.
For example, let us solve for x in the equation x-5 = 0
solve('x-5=0')
MATLAB will execute the above statement and return the following result −
ans =
5
You can also call the solve function as −
y = solve('x-5 = 0')
MATLAB will execute the above statement and return the following result −
y =
5
You may even not include the right hand side of the equation −
solve('x-5')
MATLAB will execute the above statement and return the following result −
ans =
5
If the equation involves multiple symbols, then MATLAB by default assumes that you are solving for x, however, the solve function has another form −
solve(equation, variable)
where, you can also mention the variable.
For example, let us solve the equation v – u – 3t2 = 0, for v. In this case, we should write −
solve('v-u-3*t^2=0', 'v')
MATLAB will execute the above statement and return the following result −
ans =
3*t^2 + u
The roots function is used for solving algebraic equations in Octave and you can write above examples as follows −
For example, let us solve for x in the equation x-5 = 0
roots([1, -5])
Octave will execute the above statement and return the following result −
ans = 5
You can also call the solve function as −
y = roots([1, -5])
Octave will execute the above statement and return the following result −
y = 5
The solve function can also solve higher order equations. It is often used to solve quadratic equations. The function returns the roots of the equation in an array.
The following example solves the quadratic equation x2 -7x +12 = 0. Create a script file and type the following code −
eq = 'x^2 -7*x + 12 = 0';
s = solve(eq);
disp('The first root is: '), disp(s(1));
disp('The second root is: '), disp(s(2));
When you run the file, it displays the following result −
The first root is:
3
The second root is:
4
The following example solves the quadratic equation x2 -7x +12 = 0 in Octave. Create a script file and type the following code −
s = roots([1, -7, 12]);
disp('The first root is: '), disp(s(1));
disp('The second root is: '), disp(s(2));
When you run the file, it displays the following result −
The first root is:
4
The second root is:
3
The solve function can also solve higher order equations. For example, let us solve a cubic equation as (x-3)2(x-7) = 0
solve('(x-3)^2*(x-7)=0')
MATLAB will execute the above statement and return the following result −
ans =
3
3
7
In case of higher order equations, roots are long containing many terms. You can get the numerical value of such roots by converting them to double. The following example solves the fourth order equation x4 − 7x3 + 3x2 − 5x + 9 = 0.
Create a script file and type the following code −
eq = 'x^4 - 7*x^3 + 3*x^2 - 5*x + 9 = 0';
s = solve(eq);
disp('The first root is: '), disp(s(1));
disp('The second root is: '), disp(s(2));
disp('The third root is: '), disp(s(3));
disp('The fourth root is: '), disp(s(4));
% converting the roots to double type
disp('Numeric value of first root'), disp(double(s(1)));
disp('Numeric value of second root'), disp(double(s(2)));
disp('Numeric value of third root'), disp(double(s(3)));
disp('Numeric value of fourth root'), disp(double(s(4)));
When you run the file, it returns the following result −
The first root is:
6.630396332390718431485053218985
The second root is:
1.0597804633025896291682772499885
The third root is:
- 0.34508839784665403032666523448675 - 1.0778362954630176596831109269793*i
The fourth root is:
- 0.34508839784665403032666523448675 + 1.0778362954630176596831109269793*i
Numeric value of first root
6.6304
Numeric value of second root
1.0598
Numeric value of third root
-0.3451 - 1.0778i
Numeric value of fourth root
-0.3451 + 1.0778i
Please note that the last two roots are complex numbers.
The following example solves the fourth order equation x4 − 7x3 + 3x2 − 5x + 9 = 0.
Create a script file and type the following code −
v = [1, -7, 3, -5, 9];
s = roots(v);
% converting the roots to double type
disp('Numeric value of first root'), disp(double(s(1)));
disp('Numeric value of second root'), disp(double(s(2)));
disp('Numeric value of third root'), disp(double(s(3)));
disp('Numeric value of fourth root'), disp(double(s(4)));
When you run the file, it returns the following result −
Numeric value of first root
6.6304
Numeric value of second root
-0.34509 + 1.07784i
Numeric value of third root
-0.34509 - 1.07784i
Numeric value of fourth root
1.0598
The solve function can also be used to generate solutions of systems of equations involving more than one variables. Let us take up a simple example to demonstrate this use.
Let us solve the equations −
5x + 9y = 5
3x – 6y = 4
Create a script file and type the following code −
s = solve('5*x + 9*y = 5','3*x - 6*y = 4');
s.x
s.y
When you run the file, it displays the following result −
ans =
22/19
ans =
-5/57
In same way, you can solve larger linear systems. Consider the following set of equations −
x + 3y -2z = 5
3x + 5y + 6z = 7
2x + 4y + 3z = 8
We have a little different approach to solve a system of 'n' linear equations in 'n' unknowns. Let us take up a simple example to demonstrate this use.
Let us solve the equations −
5x + 9y = 5
3x – 6y = 4
Such a system of linear equations can be written as the single matrix equation Ax = b, where A is the coefficient matrix, b is the column vector containing the right-hand side of the linear equations and x is the column vector representing the solution as shown in the below program −
Create a script file and type the following code −
A = [5, 9; 3, -6];
b = [5;4];
A \ b
When you run the file, it displays the following result −
ans =
1.157895
-0.087719
In same way, you can solve larger linear systems as given below −
x + 3y -2z = 5
3x + 5y + 6z = 7
2x + 4y + 3z = 8
The expand and the collect function expands and collects an equation respectively. The following example demonstrates the concepts −
When you work with many symbolic functions, you should declare that your variables are symbolic.
Create a script file and type the following code −
syms x %symbolic variable x
syms y %symbolic variable x
% expanding equations
expand((x-5)*(x+9))
expand((x+2)*(x-3)*(x-5)*(x+7))
expand(sin(2*x))
expand(cos(x+y))
% collecting equations
collect(x^3 *(x-7))
collect(x^4*(x-3)*(x-5))
When you run the file, it displays the following result −
ans =
x^2 + 4*x - 45
ans =
x^4 + x^3 - 43*x^2 + 23*x + 210
ans =
2*cos(x)*sin(x)
ans =
cos(x)*cos(y) - sin(x)*sin(y)
ans =
x^4 - 7*x^3
ans =
x^6 - 8*x^5 + 15*x^4
You need to have symbolic package, which provides expand and the collect function to expand and collect an equation, respectively. The following example demonstrates the concepts −
When you work with many symbolic functions, you should declare that your variables are symbolic but Octave has different approach to define symbolic variables. Notice the use of Sin and Cos, which are also defined in symbolic package.
Create a script file and type the following code −
% first of all load the package, make sure its installed.
pkg load symbolic
% make symbols module available
symbols
% define symbolic variables
x = sym ('x');
y = sym ('y');
z = sym ('z');
% expanding equations
expand((x-5)*(x+9))
expand((x+2)*(x-3)*(x-5)*(x+7))
expand(Sin(2*x))
expand(Cos(x+y))
% collecting equations
collect(x^3 *(x-7), z)
collect(x^4*(x-3)*(x-5), z)
When you run the file, it displays the following result −
ans =
-45.0+x^2+(4.0)*x
ans =
210.0+x^4-(43.0)*x^2+x^3+(23.0)*x
ans =
sin((2.0)*x)
ans =
cos(y+x)
ans =
x^(3.0)*(-7.0+x)
ans =
(-3.0+x)*x^(4.0)*(-5.0+x)
The factor function factorizes an expression and the simplify function simplifies an expression. The following example demonstrates the concept −
Create a script file and type the following code −
syms x
syms y
factor(x^3 - y^3)
factor([x^2-y^2,x^3+y^3])
simplify((x^4-16)/(x^2-4))
When you run the file, it displays the following result −
ans =
(x - y)*(x^2 + x*y + y^2)
ans =
[ (x - y)*(x + y), (x + y)*(x^2 - x*y + y^2)]
ans =
x^2 + 4
MATLAB provides various ways for solving problems of differential and integral calculus, solving differential equations of any degree and calculation of limits. Best of all, you can easily plot the graphs of complex functions and check maxima, minima and other stationery points on a graph by solving the original function, as well as its derivative.
This chapter will deal with problems of calculus. In this chapter, we will discuss pre-calculus concepts i.e., calculating limits of functions and verifying the properties of limits.
In the next chapter Differential, we will compute derivative of an expression and find the local maxima and minima on a graph. We will also discuss solving differential equations.
Finally, in the Integration chapter, we will discuss integral calculus.
MATLAB provides the limit function for calculating limits. In its most basic form, the limit function takes expression as an argument and finds the limit of the expression as the independent variable goes to zero.
For example, let us calculate the limit of a function f(x) = (x3 + 5)/(x4 + 7), as x tends to zero.
syms x
limit((x^3 + 5)/(x^4 + 7))
MATLAB will execute the above statement and return the following result −
ans =
5/7
The limit function falls in the realm of symbolic computing; you need to use the syms function to tell MATLAB which symbolic variables you are using. You can also compute limit of a function, as the variable tends to some number other than zero. To calculate lim x->a(f(x)), we use the limit command with arguments. The first being the expression and the second is the number, that x approaches, here it is a.
For example, let us calculate limit of a function f(x) = (x-3)/(x-1), as x tends to 1.
limit((x - 3)/(x-1),1)
MATLAB will execute the above statement and return the following result −
ans =
NaN
Let's take another example,
limit(x^2 + 5, 3)
MATLAB will execute the above statement and return the following result −
ans =
14
Following is Octave version of the above example using symbolic package, try to execute and compare the result −
pkg load symbolic
symbols
x = sym("x");
subs((x^3+5)/(x^4+7),x,0)
Octave will execute the above statement and return the following result −
ans =
0.7142857142857142857
Algebraic Limit Theorem provides some basic properties of limits. These are as follows −
Let us consider two functions −
f(x) = (3x + 5)/(x - 3)
g(x) = x2 + 1.
Let us calculate the limits of the functions as x tends to 5, of both functions and verify the basic properties of limits using these two functions and MATLAB.
Create a script file and type the following code into it −
syms x
f = (3*x + 5)/(x-3);
g = x^2 + 1;
l1 = limit(f, 4)
l2 = limit (g, 4)
lAdd = limit(f + g, 4)
lSub = limit(f - g, 4)
lMult = limit(f*g, 4)
lDiv = limit (f/g, 4)
When you run the file, it displays −
l1 =
17
l2 =
17
lAdd =
34
lSub =
0
lMult =
289
lDiv =
1
Following is Octave version of the above example using symbolic package, try to execute and compare the result −
pkg load symbolic
symbols
x = sym("x");
f = (3*x + 5)/(x-3);
g = x^2 + 1;
l1 = subs(f, x, 4)
l2 = subs (g, x, 4)
lAdd = subs (f+g, x, 4)
lSub = subs (f-g, x, 4)
lMult = subs (f*g, x, 4)
lDiv = subs (f/g, x, 4)
Octave will execute the above statement and return the following result −
l1 =
17.0
l2 =
17.0
lAdd =
34.0
lSub =
0.0
lMult =
289.0
lDiv =
1.0
When a function has a discontinuity for some particular value of the variable, the limit does not exist at that point. In other words, limits of a function f(x) has discontinuity at x = a, when the value of limit, as x approaches x from left side, does not equal the value of the limit as x approaches from right side.
This leads to the concept of left-handed and right-handed limits. A left-handed limit is defined as the limit as x -> a, from the left, i.e., x approaches a, for values of x < a. A right-handed limit is defined as the limit as x -> a, from the right, i.e., x approaches a, for values of x > a. When the left-handed limit and right-handed limit are not equal, the limit does not exist.
Let us consider a function −
f(x) = (x - 3)/|x - 3|
We will show that limx->3 f(x) does not exist. MATLAB helps us to establish this fact in two ways −
By plotting the graph of the function and showing the discontinuity.
By computing the limits and showing that both are different.
The left-handed and right-handed limits are computed by passing the character strings 'left' and 'right' to the limit command as the last argument.
Create a script file and type the following code into it −
f = (x - 3)/abs(x-3);
ezplot(f,[-1,5])
l = limit(f,x,3,'left')
r = limit(f,x,3,'right')
When you run the file, MATLAB draws the following plot
After this following output is displayed −
l =
-1
r =
1
MATLAB provides the diff command for computing symbolic derivatives. In its simplest form, you pass the function you want to differentiate to diff command as an argument.
For example, let us compute the derivative of the function f(t) = 3t2 + 2t-2
Create a script file and type the following code into it −
syms t
f = 3*t^2 + 2*t^(-2);
diff(f)
When the above code is compiled and executed, it produces the following result −
ans =
6*t - 4/t^3
Following is Octave equivalent of the above calculation −
pkg load symbolic
symbols
t = sym("t");
f = 3*t^2 + 2*t^(-2);
differentiate(f,t)
Octave executes the code and returns the following result −
ans =
-(4.0)*t^(-3.0)+(6.0)*t
Let us briefly state various equations or rules for differentiation of functions and verify these rules. For this purpose, we will write f'(x) for a first order derivative and f"(x) for a second order derivative.
Following are the rules for differentiation −
For any functions f and g and any real numbers a and b are the derivative of the function −
h(x) = af(x) + bg(x) with respect to x is given by −
h'(x) = af'(x) + bg'(x)
The sum and subtraction rules state that if f and g are two functions, f' and g' are their derivatives respectively, then,
(f + g)' = f' + g'
(f - g)' = f' - g'
The product rule states that if f and g are two functions, f' and g' are their derivatives respectively, then,
(f.g)' = f'.g + g'.f
The quotient rule states that if f and g are two functions, f' and g' are their derivatives respectively, then,
(f/g)' = (f'.g - g'.f)/g2
The polynomial or elementary power rule states that, if y = f(x) = xn, then f' = n. x(n-1)
A direct outcome of this rule is that the derivative of any constant is zero, i.e., if y = k, any constant, then
f' = 0
The chain rule states that, derivative of the function of a function h(x) = f(g(x)) with respect to x is,
h'(x)= f'(g(x)).g'(x)
Create a script file and type the following code into it −
syms x
syms t
f = (x + 2)*(x^2 + 3)
der1 = diff(f)
f = (t^2 + 3)*(sqrt(t) + t^3)
der2 = diff(f)
f = (x^2 - 2*x + 1)*(3*x^3 - 5*x^2 + 2)
der3 = diff(f)
f = (2*x^2 + 3*x)/(x^3 + 1)
der4 = diff(f)
f = (x^2 + 1)^17
der5 = diff(f)
f = (t^3 + 3* t^2 + 5*t -9)^(-6)
der6 = diff(f)
When you run the file, MATLAB displays the following result −
f =
(x^2 + 3)*(x + 2)
der1 =
2*x*(x + 2) + x^2 + 3
f =
(t^(1/2) + t^3)*(t^2 + 3)
der2 =
(t^2 + 3)*(3*t^2 + 1/(2*t^(1/2))) + 2*t*(t^(1/2) + t^3)
f =
(x^2 - 2*x + 1)*(3*x^3 - 5*x^2 + 2)
der3 =
(2*x - 2)*(3*x^3 - 5*x^2 + 2) - (- 9*x^2 + 10*x)*(x^2 - 2*x + 1)
f =
(2*x^2 + 3*x)/(x^3 + 1)
der4 =
(4*x + 3)/(x^3 + 1) - (3*x^2*(2*x^2 + 3*x))/(x^3 + 1)^2
f =
(x^2 + 1)^17
der5 =
34*x*(x^2 + 1)^16
f =
1/(t^3 + 3*t^2 + 5*t - 9)^6
der6 =
-(6*(3*t^2 + 6*t + 5))/(t^3 + 3*t^2 + 5*t - 9)^7
Following is Octave equivalent of the above calculation −
pkg load symbolic
symbols
x = sym("x");
t = sym("t");
f = (x + 2)*(x^2 + 3)
der1 = differentiate(f,x)
f = (t^2 + 3)*(t^(1/2) + t^3)
der2 = differentiate(f,t)
f = (x^2 - 2*x + 1)*(3*x^3 - 5*x^2 + 2)
der3 = differentiate(f,x)
f = (2*x^2 + 3*x)/(x^3 + 1)
der4 = differentiate(f,x)
f = (x^2 + 1)^17
der5 = differentiate(f,x)
f = (t^3 + 3* t^2 + 5*t -9)^(-6)
der6 = differentiate(f,t)
Octave executes the code and returns the following result −
f =
(2.0+x)*(3.0+x^(2.0))
der1 =
3.0+x^(2.0)+(2.0)*(2.0+x)*x
f =
(t^(3.0)+sqrt(t))*(3.0+t^(2.0))
der2 =
(2.0)*(t^(3.0)+sqrt(t))*t+((3.0)*t^(2.0)+(0.5)*t^(-0.5))*(3.0+t^(2.0))
f =
(1.0+x^(2.0)-(2.0)*x)*(2.0-(5.0)*x^(2.0)+(3.0)*x^(3.0))
der3 =
(-2.0+(2.0)*x)*(2.0-(5.0)*x^(2.0)+(3.0)*x^(3.0))+((9.0)*x^(2.0)-(10.0)*x)*(1.0+x^(2.0)-(2.0)*x)
f =
(1.0+x^(3.0))^(-1)*((2.0)*x^(2.0)+(3.0)*x)
der4 =
(1.0+x^(3.0))^(-1)*(3.0+(4.0)*x)-(3.0)*(1.0+x^(3.0))^(-2)*x^(2.0)*((2.0)*x^(2.0)+(3.0)*x)
f =
(1.0+x^(2.0))^(17.0)
der5 =
(34.0)*(1.0+x^(2.0))^(16.0)*x
f =
(-9.0+(3.0)*t^(2.0)+t^(3.0)+(5.0)*t)^(-6.0)
der6 =
-(6.0)*(-9.0+(3.0)*t^(2.0)+t^(3.0)+(5.0)*t)^(-7.0)*(5.0+(3.0)*t^(2.0)+(6.0)*t)
The following table provides the derivatives of commonly used exponential, logarithmic and trigonometric functions −
Create a script file and type the following code into it −
syms x
y = exp(x)
diff(y)
y = x^9
diff(y)
y = sin(x)
diff(y)
y = tan(x)
diff(y)
y = cos(x)
diff(y)
y = log(x)
diff(y)
y = log10(x)
diff(y)
y = sin(x)^2
diff(y)
y = cos(3*x^2 + 2*x + 1)
diff(y)
y = exp(x)/sin(x)
diff(y)
When you run the file, MATLAB displays the following result −
y =
exp(x)
ans =
exp(x)
y =
x^9
ans =
9*x^8
y =
sin(x)
ans =
cos(x)
y =
tan(x)
ans =
tan(x)^2 + 1
y =
cos(x)
ans =
-sin(x)
y =
log(x)
ans =
1/x
y =
log(x)/log(10)
ans =
1/(x*log(10))
y =
sin(x)^2
ans =
2*cos(x)*sin(x)
y =
cos(3*x^2 + 2*x + 1)
ans =
-sin(3*x^2 + 2*x + 1)*(6*x + 2)
y =
exp(x)/sin(x)
ans =
exp(x)/sin(x) - (exp(x)*cos(x))/sin(x)^2
Following is Octave equivalent of the above calculation −
pkg load symbolic
symbols
x = sym("x");
y = Exp(x)
differentiate(y,x)
y = x^9
differentiate(y,x)
y = Sin(x)
differentiate(y,x)
y = Tan(x)
differentiate(y,x)
y = Cos(x)
differentiate(y,x)
y = Log(x)
differentiate(y,x)
% symbolic packages does not have this support
%y = Log10(x)
%differentiate(y,x)
y = Sin(x)^2
differentiate(y,x)
y = Cos(3*x^2 + 2*x + 1)
differentiate(y,x)
y = Exp(x)/Sin(x)
differentiate(y,x)
Octave executes the code and returns the following result −
y =
exp(x)
ans =
exp(x)
y =
x^(9.0)
ans =
(9.0)*x^(8.0)
y =
sin(x)
ans =
cos(x)
y =
tan(x)
ans =
1+tan(x)^2
y =
cos(x)
ans =
-sin(x)
y =
log(x)
ans =
x^(-1)
y =
sin(x)^(2.0)
ans =
(2.0)*sin(x)*cos(x)
y =
cos(1.0+(2.0)*x+(3.0)*x^(2.0))
ans =
-(2.0+(6.0)*x)*sin(1.0+(2.0)*x+(3.0)*x^(2.0))
y =
sin(x)^(-1)*exp(x)
ans =
sin(x)^(-1)*exp(x)-sin(x)^(-2)*cos(x)*exp(x)
To compute higher derivatives of a function f, we use the syntax diff(f,n).
Let us compute the second derivative of the function y = f(x) = x .e-3x
f = x*exp(-3*x);
diff(f, 2)
MATLAB executes the code and returns the following result −
ans =
9*x*exp(-3*x) - 6*exp(-3*x)
Following is Octave equivalent of the above calculation −
pkg load symbolic
symbols
x = sym("x");
f = x*Exp(-3*x);
differentiate(f, x, 2)
Octave executes the code and returns the following result −
ans =
(9.0)*exp(-(3.0)*x)*x-(6.0)*exp(-(3.0)*x)
In this example, let us solve a problem. Given that a function y = f(x) = 3 sin(x) + 7 cos(5x). We will have to find out whether the equation f" + f = -5cos(2x) holds true.
Create a script file and type the following code into it −
syms x
y = 3*sin(x)+7*cos(5*x); % defining the function
lhs = diff(y,2)+y; %evaluting the lhs of the equation
rhs = -5*cos(2*x); %rhs of the equation
if(isequal(lhs,rhs))
disp('Yes, the equation holds true');
else
disp('No, the equation does not hold true');
end
disp('Value of LHS is: '), disp(lhs);
When you run the file, it displays the following result −
No, the equation does not hold true
Value of LHS is:
-168*cos(5*x)
Following is Octave equivalent of the above calculation −
pkg load symbolic
symbols
x = sym("x");
y = 3*Sin(x)+7*Cos(5*x); % defining the function
lhs = differentiate(y, x, 2) + y; %evaluting the lhs of the equation
rhs = -5*Cos(2*x); %rhs of the equation
if(lhs == rhs)
disp('Yes, the equation holds true');
else
disp('No, the equation does not hold true');
end
disp('Value of LHS is: '), disp(lhs);
Octave executes the code and returns the following result −
No, the equation does not hold true
Value of LHS is:
-(168.0)*cos((5.0)*x)
If we are searching for the local maxima and minima for a graph, we are basically looking for the highest or lowest points on the graph of the function at a particular locality, or for a particular range of values of the symbolic variable.
For a function y = f(x) the points on the graph where the graph has zero slope are called stationary points. In other words stationary points are where f'(x) = 0.
To find the stationary points of a function we differentiate, we need to set the derivative equal to zero and solve the equation.
Let us find the stationary points of the function f(x) = 2x3 + 3x2 − 12x + 17
Take the following steps −
First let us enter the function and plot its graph.
syms x
y = 2*x^3 + 3*x^2 - 12*x + 17; % defining the function
ezplot(y)
MATLAB executes the code and returns the following plot −
Here is Octave equivalent code for the above example −
pkg load symbolic
symbols
x = sym('x');
y = inline("2*x^3 + 3*x^2 - 12*x + 17");
ezplot(y)
print -deps graph.eps
Our aim is to find some local maxima and minima on the graph, so let us find the local maxima and minima for the interval [-2, 2] on the graph.
syms x
y = 2*x^3 + 3*x^2 - 12*x + 17; % defining the function
ezplot(y, [-2, 2])
MATLAB executes the code and returns the following plot −
Here is Octave equivalent code for the above example −
pkg load symbolic
symbols
x = sym('x');
y = inline("2*x^3 + 3*x^2 - 12*x + 17");
ezplot(y, [-2, 2])
print -deps graph.eps
Next, let us compute the derivative.
g = diff(y)
MATLAB executes the code and returns the following result −
g =
6*x^2 + 6*x - 12
Here is Octave equivalent of the above calculation −
pkg load symbolic
symbols
x = sym("x");
y = 2*x^3 + 3*x^2 - 12*x + 17;
g = differentiate(y,x)
Octave executes the code and returns the following result −
g =
-12.0+(6.0)*x+(6.0)*x^(2.0)
Let us solve the derivative function, g, to get the values where it becomes zero.
s = solve(g)
MATLAB executes the code and returns the following result −
s =
1
-2
Following is Octave equivalent of the above calculation −
pkg load symbolic
symbols
x = sym("x");
y = 2*x^3 + 3*x^2 - 12*x + 17;
g = differentiate(y,x)
roots([6, 6, -12])
Octave executes the code and returns the following result −
g =
-12.0+(6.0)*x^(2.0)+(6.0)*x
ans =
-2
1
This agrees with our plot. So let us evaluate the function f at the critical points x = 1, -2. We can substitute a value in a symbolic function by using the subs command.
subs(y, 1), subs(y, -2)
MATLAB executes the code and returns the following result −
ans =
10
ans =
37
Following is Octave equivalent of the above calculation −
pkg load symbolic
symbols
x = sym("x");
y = 2*x^3 + 3*x^2 - 12*x + 17;
g = differentiate(y,x)
roots([6, 6, -12])
subs(y, x, 1), subs(y, x, -2)
ans =
10.0
ans =
37.0-4.6734207789940138748E-18*I
Therefore, The minimum and maximum values on the function f(x) = 2x3 + 3x2 − 12x + 17, in the interval [-2,2] are 10 and 37.
MATLAB provides the dsolve command for solving differential equations symbolically.
The most basic form of the dsolve command for finding the solution to a single equation is
dsolve('eqn')
where eqn is a text string used to enter the equation.
It returns a symbolic solution with a set of arbitrary constants that MATLAB labels C1, C2, and so on.
You can also specify initial and boundary conditions for the problem, as comma-delimited list following the equation as −
dsolve('eqn','cond1', 'cond2',...)
For the purpose of using dsolve command, derivatives are indicated with a D. For example, an equation like f'(t) = -2*f + cost(t) is entered as −
'Df = -2*f + cos(t)'
Higher derivatives are indicated by following D by the order of the derivative.
For example the equation f"(x) + 2f'(x) = 5sin3x should be entered as −
'D2y + 2Dy = 5*sin(3*x)'
Let us take up a simple example of a first order differential equation: y' = 5y.
s = dsolve('Dy = 5*y')
MATLAB executes the code and returns the following result −
s =
C2*exp(5*t)
Let us take up another example of a second order differential equation as: y" - y = 0, y(0) = -1, y'(0) = 2.
dsolve('D2y - y = 0','y(0) = -1','Dy(0) = 2')
MATLAB executes the code and returns the following result −
ans =
exp(t)/2 - (3*exp(-t))/2
Integration deals with two essentially different types of problems.
In the first type, derivative of a function is given and we want to find the function. Therefore, we basically reverse the process of differentiation. This reverse process is known as anti-differentiation, or finding the primitive function, or finding an indefinite integral.
In the first type, derivative of a function is given and we want to find the function. Therefore, we basically reverse the process of differentiation. This reverse process is known as anti-differentiation, or finding the primitive function, or finding an indefinite integral.
The second type of problems involve adding up a very large number of very small quantities and then taking a limit as the size of the quantities approaches zero, while the number of terms tend to infinity. This process leads to the definition of the definite integral.
The second type of problems involve adding up a very large number of very small quantities and then taking a limit as the size of the quantities approaches zero, while the number of terms tend to infinity. This process leads to the definition of the definite integral.
Definite integrals are used for finding area, volume, center of gravity, moment of inertia, work done by a force, and in numerous other applications.
By definition, if the derivative of a function f(x) is f'(x), then we say that an indefinite integral of f'(x) with respect to x is f(x). For example, since the derivative (with respect to x) of x2 is 2x, we can say that an indefinite integral of 2x is x2.
In symbols −
f'(x2) = 2x, therefore,
∫ 2xdx = x2.
Indefinite integral is not unique, because derivative of x2 + c, for any value of a constant c, will also be 2x.
This is expressed in symbols as −
∫ 2xdx = x2 + c.
Where, c is called an 'arbitrary constant'.
MATLAB provides an int command for calculating integral of an expression. To derive an expression for the indefinite integral of a function, we write −
int(f);
For example, from our previous example −
syms x
int(2*x)
MATLAB executes the above statement and returns the following result −
ans =
x^2
In this example, let us find the integral of some commonly used expressions. Create a script file and type the following code in it −
syms x n
int(sym(x^n))
f = 'sin(n*t)'
int(sym(f))
syms a t
int(a*cos(pi*t))
int(a^x)
When you run the file, it displays the following result −
ans =
piecewise([n == -1, log(x)], [n ~= -1, x^(n + 1)/(n + 1)])
f =
sin(n*t)
ans =
-cos(n*t)/n
ans =
(a*sin(pi*t))/pi
ans =
a^x/log(a)
Create a script file and type the following code in it −
syms x n
int(cos(x))
int(exp(x))
int(log(x))
int(x^-1)
int(x^5*cos(5*x))
pretty(int(x^5*cos(5*x)))
int(x^-5)
int(sec(x)^2)
pretty(int(1 - 10*x + 9 * x^2))
int((3 + 5*x -6*x^2 - 7*x^3)/2*x^2)
pretty(int((3 + 5*x -6*x^2 - 7*x^3)/2*x^2))
Note that the pretty function returns an expression in a more readable format.
When you run the file, it displays the following result −
ans =
sin(x)
ans =
exp(x)
ans =
x*(log(x) - 1)
ans =
log(x)
ans =
(24*cos(5*x))/3125 + (24*x*sin(5*x))/625 - (12*x^2*cos(5*x))/125 + (x^4*cos(5*x))/5 - (4*x^3*sin(5*x))/25 + (x^5*sin(5*x))/5
2 4
24 cos(5 x) 24 x sin(5 x) 12 x cos(5 x) x cos(5 x)
----------- + ------------- - -------------- + ------------
3125 625 125 5
3 5
4 x sin(5 x) x sin(5 x)
------------- + -----------
25 5
ans =
-1/(4*x^4)
ans =
tan(x)
2
x (3 x - 5 x + 1)
ans =
- (7*x^6)/12 - (3*x^5)/5 + (5*x^4)/8 + x^3/2
6 5 4 3
7 x 3 x 5 x x
- ---- - ---- + ---- + --
12 5 8 2
By definition, definite integral is basically the limit of a sum. We use definite integrals to find areas such as the area between a curve and the x-axis and the area between two curves. Definite integrals can also be used in other situations, where the quantity required can be expressed as the limit of a sum.
The int function can be used for definite integration by passing the limits over which you want to calculate the integral.
To calculate
we write,
int(x, a, b)
For example, to calculate the value of we write −
int(x, 4, 9)
MATLAB executes the above statement and returns the following result −
ans =
65/2
Following is Octave equivalent of the above calculation −
pkg load symbolic
symbols
x = sym("x");
f = x;
c = [1, 0];
integral = polyint(c);
a = polyval(integral, 9) - polyval(integral, 4);
display('Area: '), disp(double(a));
Octave executes the code and returns the following result −
Area:
32.500
An alternative solution can be given using quad() function provided by Octave as follows −
pkg load symbolic
symbols
f = inline("x");
[a, ierror, nfneval] = quad(f, 4, 9);
display('Area: '), disp(double(a));
Octave executes the code and returns the following result −
Area:
32.500
Let us calculate the area enclosed between the x-axis, and the curve y = x3−2x+5 and the ordinates x = 1 and x = 2.
The required area is given by −
Create a script file and type the following code −
f = x^3 - 2*x +5;
a = int(f, 1, 2)
display('Area: '), disp(double(a));
When you run the file, it displays the following result −
a =
23/4
Area:
5.7500
Following is Octave equivalent of the above calculation −
pkg load symbolic
symbols
x = sym("x");
f = x^3 - 2*x +5;
c = [1, 0, -2, 5];
integral = polyint(c);
a = polyval(integral, 2) - polyval(integral, 1);
display('Area: '), disp(double(a));
Octave executes the code and returns the following result −
Area:
5.7500
An alternative solution can be given using quad() function provided by Octave as follows −
pkg load symbolic
symbols
x = sym("x");
f = inline("x^3 - 2*x +5");
[a, ierror, nfneval] = quad(f, 1, 2);
display('Area: '), disp(double(a));
Octave executes the code and returns the following result −
Area:
5.7500
Find the area under the curve: f(x) = x2 cos(x) for −4 ≤ x ≤ 9.
Create a script file and write the following code −
f = x^2*cos(x);
ezplot(f, [-4,9])
a = int(f, -4, 9)
disp('Area: '), disp(double(a));
When you run the file, MATLAB plots the graph −
The output is given below −
a =
8*cos(4) + 18*cos(9) + 14*sin(4) + 79*sin(9)
Area:
0.3326
Following is Octave equivalent of the above calculation −
pkg load symbolic
symbols
x = sym("x");
f = inline("x^2*cos(x)");
ezplot(f, [-4,9])
print -deps graph.eps
[a, ierror, nfneval] = quad(f, -4, 9);
display('Area: '), disp(double(a));
MATLAB represents polynomials as row vectors containing coefficients ordered by descending powers. For example, the equation P(x) = x4 + 7x3 - 5x + 9 could be represented as −
p = [1 7 0 -5 9];
The polyval function is used for evaluating a polynomial at a specified value. For example, to evaluate our previous polynomial p, at x = 4, type −
p = [1 7 0 -5 9];
polyval(p,4)
MATLAB executes the above statements and returns the following result −
ans = 693
MATLAB also provides the polyvalm function for evaluating a matrix polynomial. A matrix polynomial is a polynomial with matrices as variables.
For example, let us create a square matrix X and evaluate the polynomial p, at X −
p = [1 7 0 -5 9];
X = [1 2 -3 4; 2 -5 6 3; 3 1 0 2; 5 -7 3 8];
polyvalm(p, X)
MATLAB executes the above statements and returns the following result −
ans =
2307 -1769 -939 4499
2314 -2376 -249 4695
2256 -1892 -549 4310
4570 -4532 -1062 9269
The roots function calculates the roots of a polynomial. For example, to calculate the roots of our polynomial p, type −
p = [1 7 0 -5 9];
r = roots(p)
MATLAB executes the above statements and returns the following result −
r =
-6.8661 + 0.0000i
-1.4247 + 0.0000i
0.6454 + 0.7095i
0.6454 - 0.7095i
The function poly is an inverse of the roots function and returns to the polynomial coefficients. For example −
p2 = poly(r)
MATLAB executes the above statements and returns the following result −
p2 =
Columns 1 through 3:
1.00000 + 0.00000i 7.00000 + 0.00000i 0.00000 + 0.00000i
Columns 4 and 5:
-5.00000 - 0.00000i 9.00000 + 0.00000i
The polyfit function finds the coefficients of a polynomial that fits a set of data in a least-squares sense. If x and y are two vectors containing the x and y data to be fitted to a n-degree polynomial, then we get the polynomial fitting the data by writing −
p = polyfit(x,y,n)
Create a script file and type the following code −
x = [1 2 3 4 5 6]; y = [5.5 43.1 128 290.7 498.4 978.67]; %data
p = polyfit(x,y,4) %get the polynomial
% Compute the values of the polyfit estimate over a finer range,
% and plot the estimate over the real data values for comparison:
x2 = 1:.1:6;
y2 = polyval(p,x2);
plot(x,y,'o',x2,y2)
grid on
When you run the file, MATLAB displays the following result −
p =
4.1056 -47.9607 222.2598 -362.7453 191.1250
And plots the following graph −
MATLAB provides command for working with transforms, such as the Laplace and Fourier transforms. Transforms are used in science and engineering as a tool for simplifying analysis and look at data from another angle.
For example, the Fourier transform allows us to convert a signal represented as a function of time to a function of frequency. Laplace transform allows us to convert a differential equation to an algebraic equation.
MATLAB provides the laplace, fourier and fft commands to work with Laplace, Fourier and Fast Fourier transforms.
The Laplace transform of a function of time f(t) is given by the following integral −
Laplace transform is also denoted as transform of f(t) to F(s). You can see this transform or integration process converts f(t), a function of the symbolic variable t, into another function F(s), with another variable s.
Laplace transform turns differential equations into algebraic ones. To compute a Laplace transform of a function f(t), write −
laplace(f(t))
In this example, we will compute the Laplace transform of some commonly used functions.
Create a script file and type the following code −
syms s t a b w
laplace(a)
laplace(t^2)
laplace(t^9)
laplace(exp(-b*t))
laplace(sin(w*t))
laplace(cos(w*t))
When you run the file, it displays the following result −
ans =
1/s^2
ans =
2/s^3
ans =
362880/s^10
ans =
1/(b + s)
ans =
w/(s^2 + w^2)
ans =
s/(s^2 + w^2)
MATLAB allows us to compute the inverse Laplace transform using the command ilaplace.
For example,
ilaplace(1/s^3)
MATLAB will execute the above statement and display the result −
ans =
t^2/2
Create a script file and type the following code −
syms s t a b w
ilaplace(1/s^7)
ilaplace(2/(w+s))
ilaplace(s/(s^2+4))
ilaplace(exp(-b*t))
ilaplace(w/(s^2 + w^2))
ilaplace(s/(s^2 + w^2))
When you run the file, it displays the following result −
ans =
t^6/720
ans =
2*exp(-t*w)
ans =
cos(2*t)
ans =
ilaplace(exp(-b*t), t, x)
ans =
sin(t*w)
ans =
cos(t*w)
Fourier transforms commonly transforms a mathematical function of time, f(t), into a new function, sometimes denoted by or F, whose argument is frequency with units of cycles/s (hertz) or radians per second. The new function is then known as the Fourier transform and/or the frequency spectrum of the function f.
Create a script file and type the following code in it −
syms x
f = exp(-2*x^2); %our function
ezplot(f,[-2,2]) % plot of our function
FT = fourier(f) % Fourier transform
When you run the file, MATLAB plots the following graph −
The following result is displayed −
FT =
(2^(1/2)*pi^(1/2)*exp(-w^2/8))/2
Plotting the Fourier transform as −
ezplot(FT)
Gives the following graph −
MATLAB provides the ifourier command for computing the inverse Fourier transform of a function. For example,
f = ifourier(-2*exp(-abs(w)))
MATLAB will execute the above statement and display the result −
f =
-2/(pi*(x^2 + 1))
GNU Octave is a high-level programming language like MATLAB and it is mostly compatible with MATLAB. It is also used for numerical computations.
Octave has the following common features with MATLAB −
matrices are fundamental data type
it has built-in support for complex numbers
it has built-in math functions and libraries
it supports user-defined functions
GNU Octave is also freely redistributable software. You may redistribute it and/or modify it under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation.
Most MATLAB programs run in Octave, but some of the Octave programs may not run in MATLAB because, Octave allows some syntax that MATLAB does not.
For example, MATLAB supports single quotes only, but Octave supports both single and double quotes for defining strings. If you are looking for a tutorial on Octave, then kindly go through this tutorial from beginning which covers both MATLAB as well as Octave.
Almost all the examples covered in this tutorial are compatible with MATLAB as well as Octave. Let's try following example in MATLAB and Octave which produces same result without any syntax changes −
This example creates a 3D surface map for the function g = xe-(x2 + y2). Create a script file and type the following code −
[x,y] = meshgrid(-2:.2:2);
g = x .* exp(-x.^2 - y.^2);
surf(x, y, g)
print -deps graph.eps
When you run the file, MATLAB displays the following 3-D map −
Though all the core functionality of MATLAB is available in Octave, there are some functionality for example, Differential & Integration Calculus, which does not match exactly in both the languages. This tutorial has tried to give both type of examples where they differed in their syntax.
Consider following example where MATLAB and Octave make use of different functions to get the area of a curve: f(x) = x2 cos(x) for −4 ≤ x ≤ 9. Following is MATLAB version of the code −
f = x^2*cos(x);
ezplot(f, [-4,9])
a = int(f, -4, 9)
disp('Area: '), disp(double(a));
When you run the file, MATLAB plots the graph −
The following result is displayed
a =
8*cos(4) + 18*cos(9) + 14*sin(4) + 79*sin(9)
Area:
0.3326
But to give area of the same curve in Octave, you will have to make use of symbolic package as follows −
pkg load symbolic
symbols
x = sym("x");
f = inline("x^2*cos(x)");
ezplot(f, [-4,9])
print -deps graph.eps
[a, ierror, nfneval] = quad(f, -4, 9);
display('Area: '), disp(double(a));
Simulink is a simulation and model-based design environment for dynamic and embedded systems, integrated with MATLAB. Simulink, also developed by MathWorks, is a data flow graphical programming language tool for modelling, simulating and analyzing multi-domain dynamic systems. It is basically a graphical block diagramming tool with customizable set of block libraries.
It allows you to incorporate MATLAB algorithms into models as well as export the simulation results into MATLAB for further analysis.
Simulink supports −
system-level design
simulation
automatic code generation
testing and verification of embedded systems
There are several other add-on products provided by MathWorks and third-party hardware and software products that are available for use with Simulink.
The following list gives brief description of some of them −
Stateflow allows developing state machines and flow charts.
Stateflow allows developing state machines and flow charts.
Simulink Coder allows the generation of C source code for real-time implementation of systems automatically.
Simulink Coder allows the generation of C source code for real-time implementation of systems automatically.
xPC Target together with x86-based real-time systems provide an environment to simulate and test Simulink and Stateflow models in real-time on the physical system.
xPC Target together with x86-based real-time systems provide an environment to simulate and test Simulink and Stateflow models in real-time on the physical system.
Embedded Coder supports specific embedded targets.
Embedded Coder supports specific embedded targets.
HDL Coder allows to automatically generate synthesizable VHDL and Verilog.
HDL Coder allows to automatically generate synthesizable VHDL and Verilog.
SimEvents provides a library of graphical building blocks for modelling queuing systems.
SimEvents provides a library of graphical building blocks for modelling queuing systems.
Simulink is capable of systematic verification and validation of models through modelling style checking, requirements traceability and model coverage analysis.
Simulink Design Verifier allows you to identify design errors and to generate test case scenarios for model checking.
To open Simulink, type in the MATLAB work space −
simulink
Simulink opens with the Library Browser. The Library Browser is used for building simulation models.
On the left side window pane, you will find several libraries categorized on the basis of various systems, clicking on each one will display the design blocks on the right window pane.
To create a new model, click the New button on the Library Browser's toolbar. This opens a new untitled model window.
A Simulink model is a block diagram.
Model elements are added by selecting the appropriate elements from the Library Browser and dragging them into the Model window.
Alternately, you can copy the model elements and paste them into the model window.
Drag and drop items from the Simulink library to make your project.
For the purpose of this example, two blocks will be used for the simulation - A Source (a signal) and a Sink (a scope). A signal generator (the source) generates an analog signal, which will then be graphically visualized by the scope(the sink).
Begin by dragging the required blocks from the library to the project window. Then, connect the blocks together which can be done by dragging connectors from connection points on one block to those of another.
Let us drag a 'Sine Wave' block into the model.
Select 'Sinks' from the library and drag a 'Scope' block into the model.
Drag a signal line from the output of the Sine Wave block to the input of the Scope block.
Run the simulation by pressing the 'Run' button, keeping all parameters default (you can change them from the Simulation menu)
You should get the below graph from the scope.
30 Lectures
4 hours
Nouman Azam
127 Lectures
12 hours
Nouman Azam
17 Lectures
3 hours
Sanjeev
37 Lectures
5 hours
TELCOMA Global
22 Lectures
4 hours
TELCOMA Global
18 Lectures
3 hours
Phinite Academy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2309,
"s": 2141,
"text": "MATLAB (matrix laboratory) is a fourth-generation high-level programming language and interactive environment for numerical computation, visualization and programming."
},
{
"code": null,
"e": 2593,
"s": 2309,
"text": "It allows matrix manipulations; plotting of functions and data; implementation of algorithms; creation of user interfaces; interfacing with programs written in other languages, including C, C++, Java, and FORTRAN; analyze data; develop algorithms; and create models and applications."
},
{
"code": null,
"e": 2742,
"s": 2593,
"text": "It has numerous built-in commands and math functions that help you in mathematical calculations, generating plots, and performing numerical methods."
},
{
"code": null,
"e": 2894,
"s": 2742,
"text": "MATLAB is used in every facet of computational mathematics. Following are some commonly used mathematical calculations where it is used most commonly −"
},
{
"code": null,
"e": 2927,
"s": 2894,
"text": "Dealing with Matrices and Arrays"
},
{
"code": null,
"e": 2961,
"s": 2927,
"text": "2-D and 3-D Plotting and graphics"
},
{
"code": null,
"e": 2976,
"s": 2961,
"text": "Linear Algebra"
},
{
"code": null,
"e": 2996,
"s": 2976,
"text": "Algebraic Equations"
},
{
"code": null,
"e": 3017,
"s": 2996,
"text": "Non-linear Functions"
},
{
"code": null,
"e": 3028,
"s": 3017,
"text": "Statistics"
},
{
"code": null,
"e": 3042,
"s": 3028,
"text": "Data Analysis"
},
{
"code": null,
"e": 3078,
"s": 3042,
"text": "Calculus and Differential Equations"
},
{
"code": null,
"e": 3101,
"s": 3078,
"text": "Numerical Calculations"
},
{
"code": null,
"e": 3113,
"s": 3101,
"text": "Integration"
},
{
"code": null,
"e": 3124,
"s": 3113,
"text": "Transforms"
},
{
"code": null,
"e": 3138,
"s": 3124,
"text": "Curve Fitting"
},
{
"code": null,
"e": 3170,
"s": 3138,
"text": "Various other special functions"
},
{
"code": null,
"e": 3215,
"s": 3170,
"text": "Following are the basic features of MATLAB −"
},
{
"code": null,
"e": 3313,
"s": 3215,
"text": "It is a high-level language for numerical computation, visualization and application development."
},
{
"code": null,
"e": 3411,
"s": 3313,
"text": "It is a high-level language for numerical computation, visualization and application development."
},
{
"code": null,
"e": 3510,
"s": 3411,
"text": "It also provides an interactive environment for iterative exploration, design and problem solving."
},
{
"code": null,
"e": 3609,
"s": 3510,
"text": "It also provides an interactive environment for iterative exploration, design and problem solving."
},
{
"code": null,
"e": 3802,
"s": 3609,
"text": "It provides vast library of mathematical functions for linear algebra, statistics, Fourier analysis, filtering, optimization, numerical integration and solving ordinary differential equations."
},
{
"code": null,
"e": 3995,
"s": 3802,
"text": "It provides vast library of mathematical functions for linear algebra, statistics, Fourier analysis, filtering, optimization, numerical integration and solving ordinary differential equations."
},
{
"code": null,
"e": 4083,
"s": 3995,
"text": "It provides built-in graphics for visualizing data and tools for creating custom plots."
},
{
"code": null,
"e": 4171,
"s": 4083,
"text": "It provides built-in graphics for visualizing data and tools for creating custom plots."
},
{
"code": null,
"e": 4297,
"s": 4171,
"text": "MATLAB's programming interface gives development tools for improving code quality maintainability and maximizing performance."
},
{
"code": null,
"e": 4423,
"s": 4297,
"text": "MATLAB's programming interface gives development tools for improving code quality maintainability and maximizing performance."
},
{
"code": null,
"e": 4501,
"s": 4423,
"text": "It provides tools for building applications with custom graphical interfaces."
},
{
"code": null,
"e": 4579,
"s": 4501,
"text": "It provides tools for building applications with custom graphical interfaces."
},
{
"code": null,
"e": 4725,
"s": 4579,
"text": "It provides functions for integrating MATLAB based algorithms with external applications and languages such as C, Java, .NET and Microsoft Excel."
},
{
"code": null,
"e": 4871,
"s": 4725,
"text": "It provides functions for integrating MATLAB based algorithms with external applications and languages such as C, Java, .NET and Microsoft Excel."
},
{
"code": null,
"e": 5075,
"s": 4871,
"text": "MATLAB is widely used as a computational tool in science and engineering encompassing the fields of physics, chemistry, math and all engineering streams. It is used in a range of applications including −"
},
{
"code": null,
"e": 5112,
"s": 5075,
"text": "Signal Processing and Communications"
},
{
"code": null,
"e": 5139,
"s": 5112,
"text": "Image and Video Processing"
},
{
"code": null,
"e": 5155,
"s": 5139,
"text": "Control Systems"
},
{
"code": null,
"e": 5176,
"s": 5155,
"text": "Test and Measurement"
},
{
"code": null,
"e": 5198,
"s": 5176,
"text": "Computational Finance"
},
{
"code": null,
"e": 5220,
"s": 5198,
"text": "Computational Biology"
},
{
"code": null,
"e": 5320,
"s": 5220,
"text": "Setting up MATLAB environment is a matter of few clicks. The installer can be downloaded from here."
},
{
"code": null,
"e": 5476,
"s": 5320,
"text": "MathWorks provides the licensed product, a trial version and a student version as well. You need to log into the site and wait a little for their approval."
},
{
"code": null,
"e": 5558,
"s": 5476,
"text": "After downloading the installer the software can be installed through few clicks."
},
{
"code": null,
"e": 5760,
"s": 5558,
"text": "MATLAB development IDE can be launched from the icon created on the desktop. The main working window in MATLAB is called the desktop. When MATLAB is started, the desktop appears in its default layout −"
},
{
"code": null,
"e": 5799,
"s": 5760,
"text": "The desktop has the following panels −"
},
{
"code": null,
"e": 5879,
"s": 5799,
"text": "Current Folder − This panel allows you to access the project folders and files."
},
{
"code": null,
"e": 5959,
"s": 5879,
"text": "Current Folder − This panel allows you to access the project folders and files."
},
{
"code": null,
"e": 6093,
"s": 5959,
"text": "Command Window − This is the main area where commands can be entered at the command line. It is indicated by the command prompt (>>)."
},
{
"code": null,
"e": 6227,
"s": 6093,
"text": "Command Window − This is the main area where commands can be entered at the command line. It is indicated by the command prompt (>>)."
},
{
"code": null,
"e": 6313,
"s": 6227,
"text": "Workspace − The workspace shows all the variables created and/or imported from files."
},
{
"code": null,
"e": 6399,
"s": 6313,
"text": "Workspace − The workspace shows all the variables created and/or imported from files."
},
{
"code": null,
"e": 6491,
"s": 6399,
"text": "Command History − This panel shows or return commands that are entered at the command line."
},
{
"code": null,
"e": 6583,
"s": 6491,
"text": "Command History − This panel shows or return commands that are entered at the command line."
},
{
"code": null,
"e": 6795,
"s": 6583,
"text": "If you are willing to use Octave on your machine ( Linux, BSD, OS X or Windows ), then kindly download latest version from Download GNU Octave. You can check the given installation instructions for your machine."
},
{
"code": null,
"e": 6904,
"s": 6795,
"text": "MATLAB environment behaves like a super-complex calculator. You can enter commands at the >> command prompt."
},
{
"code": null,
"e": 7012,
"s": 6904,
"text": "MATLAB is an interpreted environment. In other words, you give a command and MATLAB executes it right away."
},
{
"code": null,
"e": 7050,
"s": 7012,
"text": "Type a valid expression, for example,"
},
{
"code": null,
"e": 7056,
"s": 7050,
"text": "5 + 5"
},
{
"code": null,
"e": 7072,
"s": 7056,
"text": "And press ENTER"
},
{
"code": null,
"e": 7183,
"s": 7072,
"text": "When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −"
},
{
"code": null,
"e": 7193,
"s": 7183,
"text": "ans = 10\n"
},
{
"code": null,
"e": 7228,
"s": 7193,
"text": "Let us take up few more examples −"
},
{
"code": null,
"e": 7270,
"s": 7228,
"text": "3 ^ 2\t % 3 raised to the power of 2"
},
{
"code": null,
"e": 7381,
"s": 7270,
"text": "When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −"
},
{
"code": null,
"e": 7390,
"s": 7381,
"text": "ans = 9\n"
},
{
"code": null,
"e": 7407,
"s": 7390,
"text": "Another example,"
},
{
"code": null,
"e": 7441,
"s": 7407,
"text": "sin(pi /2)\t % sine of angle 90o\n"
},
{
"code": null,
"e": 7552,
"s": 7441,
"text": "When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −"
},
{
"code": null,
"e": 7561,
"s": 7552,
"text": "ans = 1\n"
},
{
"code": null,
"e": 7578,
"s": 7561,
"text": "Another example,"
},
{
"code": null,
"e": 7606,
"s": 7578,
"text": "7/0\t\t % Divide by zero"
},
{
"code": null,
"e": 7717,
"s": 7606,
"text": "When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −"
},
{
"code": null,
"e": 7754,
"s": 7717,
"text": "ans = Inf\nwarning: division by zero\n"
},
{
"code": null,
"e": 7771,
"s": 7754,
"text": "Another example,"
},
{
"code": null,
"e": 7783,
"s": 7771,
"text": "732 * 20.3\t"
},
{
"code": null,
"e": 7894,
"s": 7783,
"text": "When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −"
},
{
"code": null,
"e": 7913,
"s": 7894,
"text": "ans = 1.4860e+04\n"
},
{
"code": null,
"e": 8065,
"s": 7913,
"text": "MATLAB provides some special expressions for some mathematical symbols, like pi for π, Inf for ∞, i (and j) for √-1 etc. Nan stands for 'not a number'."
},
{
"code": null,
"e": 8224,
"s": 8065,
"text": "Semicolon (;) indicates end of statement. However, if you want to suppress and hide the MATLAB output for an expression, add a semicolon after the expression."
},
{
"code": null,
"e": 8237,
"s": 8224,
"text": "For example,"
},
{
"code": null,
"e": 8254,
"s": 8237,
"text": "x = 3;\ny = x + 5"
},
{
"code": null,
"e": 8365,
"s": 8254,
"text": "When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is −"
},
{
"code": null,
"e": 8373,
"s": 8365,
"text": "y = 8\n"
},
{
"code": null,
"e": 8448,
"s": 8373,
"text": "The percent symbol (%) is used for indicating a comment line. For example,"
},
{
"code": null,
"e": 8485,
"s": 8448,
"text": "x = 9\t % assign the value 9 to x"
},
{
"code": null,
"e": 8572,
"s": 8485,
"text": "You can also write a block of comments using the block comment operators % { and % }."
},
{
"code": null,
"e": 8687,
"s": 8572,
"text": "The MATLAB editor includes tools and context menu items to help you add, remove, or change the format of comments."
},
{
"code": null,
"e": 8766,
"s": 8687,
"text": "MATLAB supports the following commonly used operators and special characters −"
},
{
"code": null,
"e": 8830,
"s": 8766,
"text": "MATLAB supports the following special variables and constants −"
},
{
"code": null,
"e": 8922,
"s": 8830,
"text": "Variable names consist of a letter followed by any number of letters, digits or underscore."
},
{
"code": null,
"e": 8948,
"s": 8922,
"text": "MATLAB is case-sensitive."
},
{
"code": null,
"e": 9079,
"s": 8948,
"text": "Variable names can be of any length, however, MATLAB uses only first N characters, where N is given by the function namelengthmax."
},
{
"code": null,
"e": 9208,
"s": 9079,
"text": "The save command is used for saving all the variables in the workspace, as a file with .mat extension, in the current directory."
},
{
"code": null,
"e": 9221,
"s": 9208,
"text": "For example,"
},
{
"code": null,
"e": 9234,
"s": 9221,
"text": "save myfile\n"
},
{
"code": null,
"e": 9296,
"s": 9234,
"text": "You can reload the file anytime later using the load command."
},
{
"code": null,
"e": 9309,
"s": 9296,
"text": "load myfile\n"
},
{
"code": null,
"e": 9370,
"s": 9309,
"text": "In MATLAB environment, every variable is an array or matrix."
},
{
"code": null,
"e": 9425,
"s": 9370,
"text": "You can assign variables in a simple way. For example,"
},
{
"code": null,
"e": 9484,
"s": 9425,
"text": "x = 3\t % defining x and initializing it with a value"
},
{
"code": null,
"e": 9558,
"s": 9484,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 9565,
"s": 9558,
"text": "x = 3\n"
},
{
"code": null,
"e": 9669,
"s": 9565,
"text": "It creates a 1-by-1 matrix named x and stores the value 3 in its element. Let us check another example,"
},
{
"code": null,
"e": 9735,
"s": 9669,
"text": "x = sqrt(16) \t% defining x and initializing it with an expression"
},
{
"code": null,
"e": 9809,
"s": 9735,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 9816,
"s": 9809,
"text": "x = 4\n"
},
{
"code": null,
"e": 9835,
"s": 9816,
"text": "Please note that −"
},
{
"code": null,
"e": 9906,
"s": 9835,
"text": "Once a variable is entered into the system, you can refer to it later."
},
{
"code": null,
"e": 9977,
"s": 9906,
"text": "Once a variable is entered into the system, you can refer to it later."
},
{
"code": null,
"e": 10026,
"s": 9977,
"text": "Variables must have values before they are used."
},
{
"code": null,
"e": 10075,
"s": 10026,
"text": "Variables must have values before they are used."
},
{
"code": null,
"e": 10221,
"s": 10075,
"text": "When an expression returns a result that is not assigned to any variable, the system assigns it to a variable named ans, which can be used later."
},
{
"code": null,
"e": 10367,
"s": 10221,
"text": "When an expression returns a result that is not assigned to any variable, the system assigns it to a variable named ans, which can be used later."
},
{
"code": null,
"e": 10380,
"s": 10367,
"text": "For example,"
},
{
"code": null,
"e": 10389,
"s": 10380,
"text": "sqrt(78)"
},
{
"code": null,
"e": 10463,
"s": 10389,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 10478,
"s": 10463,
"text": "ans = 8.8318\n"
},
{
"code": null,
"e": 10510,
"s": 10478,
"text": "You can use this variable ans −"
},
{
"code": null,
"e": 10529,
"s": 10510,
"text": "sqrt(78);\n9876/ans"
},
{
"code": null,
"e": 10603,
"s": 10529,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 10618,
"s": 10603,
"text": "ans = 1118.2\n"
},
{
"code": null,
"e": 10650,
"s": 10618,
"text": "Let's look at another example −"
},
{
"code": null,
"e": 10674,
"s": 10650,
"text": "x = 7 * 8;\ny = x * 7.89"
},
{
"code": null,
"e": 10748,
"s": 10674,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 10761,
"s": 10748,
"text": "y = 441.84\n"
},
{
"code": null,
"e": 10826,
"s": 10761,
"text": "You can have multiple assignments on the same line. For example,"
},
{
"code": null,
"e": 10850,
"s": 10826,
"text": "a = 2; b = 7; c = a * b"
},
{
"code": null,
"e": 10924,
"s": 10850,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 10932,
"s": 10924,
"text": "c = 14\n"
},
{
"code": null,
"e": 10995,
"s": 10932,
"text": "The who command displays all the variable names you have used."
},
{
"code": null,
"e": 11000,
"s": 10995,
"text": "who\n"
},
{
"code": null,
"e": 11074,
"s": 11000,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 11115,
"s": 11074,
"text": "Your variables are:\na ans b c \n"
},
{
"code": null,
"e": 11175,
"s": 11115,
"text": "The whos command displays little more about the variables −"
},
{
"code": null,
"e": 11205,
"s": 11175,
"text": "Variables currently in memory"
},
{
"code": null,
"e": 11228,
"s": 11205,
"text": "Type of each variables"
},
{
"code": null,
"e": 11262,
"s": 11228,
"text": "Memory allocated to each variable"
},
{
"code": null,
"e": 11304,
"s": 11262,
"text": "Whether they are complex variables or not"
},
{
"code": null,
"e": 11310,
"s": 11304,
"text": "whos\n"
},
{
"code": null,
"e": 11384,
"s": 11310,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 11708,
"s": 11384,
"text": "Attr Name Size Bytes Class\n==== ==== ==== ==== ===== \n a 1x1 8 double\n ans 1x70 757 cell\n b 1x1 8 double\n c 1x1 8 double\n\nTotal is 73 elements using 781 bytes \n"
},
{
"code": null,
"e": 11786,
"s": 11708,
"text": "The clear command deletes all (or the specified) variable(s) from the memory."
},
{
"code": null,
"e": 11947,
"s": 11786,
"text": "clear x % it will delete x, won't display anything\nclear % it will delete all variables in the workspace\n % peacefully and unobtrusively \n"
},
{
"code": null,
"e": 12037,
"s": 11947,
"text": "Long assignments can be extended to another line by using an ellipses (...). For example,"
},
{
"code": null,
"e": 12146,
"s": 12037,
"text": "initial_velocity = 0;\nacceleration = 9.8;\ntime = 20;\nfinal_velocity = initial_velocity + acceleration * time"
},
{
"code": null,
"e": 12220,
"s": 12146,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 12242,
"s": 12220,
"text": "final_velocity = 196\n"
},
{
"code": null,
"e": 12341,
"s": 12242,
"text": "By default, MATLAB displays numbers with four decimal place values. This is known as short format."
},
{
"code": null,
"e": 12414,
"s": 12341,
"text": "However, if you want more precision, you need to use the format command."
},
{
"code": null,
"e": 12472,
"s": 12414,
"text": "The format long command displays 16 digits after decimal."
},
{
"code": null,
"e": 12486,
"s": 12472,
"text": "For example −"
},
{
"code": null,
"e": 12521,
"s": 12486,
"text": "format long\nx = 7 + 10/3 + 5 ^ 1.2"
},
{
"code": null,
"e": 12594,
"s": 12521,
"text": "MATLAB will execute the above statement and return the following result−"
},
{
"code": null,
"e": 12616,
"s": 12594,
"text": "x = 17.2319816406394\n"
},
{
"code": null,
"e": 12633,
"s": 12616,
"text": "Another example,"
},
{
"code": null,
"e": 12669,
"s": 12633,
"text": "format short\nx = 7 + 10/3 + 5 ^ 1.2"
},
{
"code": null,
"e": 12743,
"s": 12669,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 12755,
"s": 12743,
"text": "x = 17.232\n"
},
{
"code": null,
"e": 12830,
"s": 12755,
"text": "The format bank command rounds numbers to two decimal places. For example,"
},
{
"code": null,
"e": 12892,
"s": 12830,
"text": "format bank\ndaily_wage = 177.45;\nweekly_wage = daily_wage * 6"
},
{
"code": null,
"e": 12966,
"s": 12892,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 12989,
"s": 12966,
"text": "weekly_wage = 1064.70\n"
},
{
"code": null,
"e": 13047,
"s": 12989,
"text": "MATLAB displays large numbers using exponential notation."
},
{
"code": null,
"e": 13156,
"s": 13047,
"text": "The format short e command allows displaying in exponential form with four decimal places plus the exponent."
},
{
"code": null,
"e": 13169,
"s": 13156,
"text": "For example,"
},
{
"code": null,
"e": 13196,
"s": 13169,
"text": "format short e\n4.678 * 4.9"
},
{
"code": null,
"e": 13270,
"s": 13196,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 13288,
"s": 13270,
"text": "ans = 2.2922e+01\n"
},
{
"code": null,
"e": 13409,
"s": 13288,
"text": "The format long e command allows displaying in exponential form with four decimal places plus the exponent. For example,"
},
{
"code": null,
"e": 13430,
"s": 13409,
"text": "format long e\nx = pi"
},
{
"code": null,
"e": 13504,
"s": 13430,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 13531,
"s": 13504,
"text": "x = 3.141592653589793e+00\n"
},
{
"code": null,
"e": 13635,
"s": 13531,
"text": "The format rat command gives the closest rational expression resulting from a calculation. For example,"
},
{
"code": null,
"e": 13658,
"s": 13635,
"text": "format rat\n4.678 * 4.9"
},
{
"code": null,
"e": 13732,
"s": 13658,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 13751,
"s": 13732,
"text": "ans = 34177/1491 \n"
},
{
"code": null,
"e": 13845,
"s": 13751,
"text": "A vector is a one-dimensional array of numbers. MATLAB allows creating two types of vectors −"
},
{
"code": null,
"e": 13857,
"s": 13845,
"text": "Row vectors"
},
{
"code": null,
"e": 13872,
"s": 13857,
"text": "Column vectors"
},
{
"code": null,
"e": 13995,
"s": 13872,
"text": "Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit the elements."
},
{
"code": null,
"e": 14008,
"s": 13995,
"text": "For example,"
},
{
"code": null,
"e": 14026,
"s": 14008,
"text": "r = [7 8 9 10 11]"
},
{
"code": null,
"e": 14100,
"s": 14026,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 14132,
"s": 14100,
"text": "r =\n\n 7 8 9 10 11 \n"
},
{
"code": null,
"e": 14149,
"s": 14132,
"text": "Another example,"
},
{
"code": null,
"e": 14201,
"s": 14149,
"text": "r = [7 8 9 10 11];\nt = [2, 3, 4, 5, 6];\nres = r + t"
},
{
"code": null,
"e": 14275,
"s": 14201,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 14338,
"s": 14275,
"text": "res =\n\n 9 11 13 15 17\n"
},
{
"code": null,
"e": 14462,
"s": 14338,
"text": "Column vectors are created by enclosing the set of elements in square brackets, using semicolon(;) to delimit the elements."
},
{
"code": null,
"e": 14487,
"s": 14462,
"text": "c = [7; 8; 9; 10; 11]"
},
{
"code": null,
"e": 14561,
"s": 14487,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 14641,
"s": 14561,
"text": "c =\n 7 \n 8 \n 9 \n 10 \n 11 \n"
},
{
"code": null,
"e": 14689,
"s": 14641,
"text": "A matrix is a two-dimensional array of numbers."
},
{
"code": null,
"e": 14888,
"s": 14689,
"text": "In MATLAB, a matrix is created by entering each row as a sequence of space or comma separated elements, and end of a row is demarcated by a semicolon. For example, let us create a 3-by-3 matrix as −"
},
{
"code": null,
"e": 14914,
"s": 14888,
"text": "m = [1 2 3; 4 5 6; 7 8 9]"
},
{
"code": null,
"e": 14988,
"s": 14914,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 15131,
"s": 14988,
"text": "m =\n 1 2 3 \n 4 5 6 \n 7 8 9 \n"
},
{
"code": null,
"e": 15300,
"s": 15131,
"text": "MATLAB is an interactive program for numerical computation and data visualization. You can enter a command by typing it at the MATLAB prompt '>>' on the Command Window."
},
{
"code": null,
"e": 15381,
"s": 15300,
"text": "In this section, we will provide lists of commonly used general MATLAB commands."
},
{
"code": null,
"e": 15487,
"s": 15381,
"text": "MATLAB provides various commands for managing a session. The following table provides all such commands −"
},
{
"code": null,
"e": 15640,
"s": 15487,
"text": "MATLAB provides various useful commands for working with the system, like saving the current work in the workspace as a file and loading the file later."
},
{
"code": null,
"e": 15800,
"s": 15640,
"text": "It also provides various commands for other system-related activities like, displaying date, listing files in the directory, displaying current directory, etc."
},
{
"code": null,
"e": 15874,
"s": 15800,
"text": "The following table displays some commonly used system-related commands −"
},
{
"code": null,
"e": 15940,
"s": 15874,
"text": "MATLAB provides the following input and output related commands −"
},
{
"code": null,
"e": 16056,
"s": 15940,
"text": "The fscanf and fprintf commands behave like C scanf and printf functions. They support the following format codes −"
},
{
"code": null,
"e": 16127,
"s": 16056,
"text": "The format function has the following forms used for numeric display −"
},
{
"code": null,
"e": 16223,
"s": 16127,
"text": "The following table shows various commands used for working with arrays, matrices and vectors −"
},
{
"code": null,
"e": 16354,
"s": 16223,
"text": "MATLAB provides numerous commands for plotting graphs. The following table shows some of the commonly used commands for plotting −"
},
{
"code": null,
"e": 16521,
"s": 16354,
"text": "So far, we have used MATLAB environment as a calculator. However, MATLAB is also a powerful programming language, as well as an interactive computational environment."
},
{
"code": null,
"e": 16756,
"s": 16521,
"text": "In previous chapters, you have learned how to enter commands from the MATLAB command prompt. MATLAB also allows you to write series of commands into a file and execute the file as complete unit, like writing a function and calling it."
},
{
"code": null,
"e": 16807,
"s": 16756,
"text": "MATLAB allows writing two kinds of program files −"
},
{
"code": null,
"e": 17048,
"s": 16807,
"text": "Scripts − script files are program files with .m extension. In these files, you write series of commands, which you want to execute together. Scripts do not accept inputs and do not return any outputs. They operate on data in the workspace."
},
{
"code": null,
"e": 17289,
"s": 17048,
"text": "Scripts − script files are program files with .m extension. In these files, you write series of commands, which you want to execute together. Scripts do not accept inputs and do not return any outputs. They operate on data in the workspace."
},
{
"code": null,
"e": 17453,
"s": 17289,
"text": "Functions − functions files are also program files with .m extension. Functions can accept inputs and return outputs. Internal variables are local to the function."
},
{
"code": null,
"e": 17617,
"s": 17453,
"text": "Functions − functions files are also program files with .m extension. Functions can accept inputs and return outputs. Internal variables are local to the function."
},
{
"code": null,
"e": 17896,
"s": 17617,
"text": "You can use the MATLAB editor or any other text editor to create your .mfiles. In this section, we will discuss the script files. A script file contains multiple sequential lines of MATLAB commands and function calls. You can run a script by typing its name at the command line."
},
{
"code": null,
"e": 17997,
"s": 17896,
"text": "To create scripts files, you need to use a text editor. You can open the MATLAB editor in two ways −"
},
{
"code": null,
"e": 18022,
"s": 17997,
"text": "Using the command prompt"
},
{
"code": null,
"e": 18036,
"s": 18022,
"text": "Using the IDE"
},
{
"code": null,
"e": 18202,
"s": 18036,
"text": "If you are using the command prompt, type edit in the command prompt. This will open the editor. You can directly type edit and then the filename (with .m extension)"
},
{
"code": null,
"e": 18227,
"s": 18202,
"text": "edit \nOr\nedit <filename>"
},
{
"code": null,
"e": 18403,
"s": 18227,
"text": "The above command will create the file in default MATLAB directory. If you want to store all program files in a specific folder, then you will have to provide the entire path."
},
{
"code": null,
"e": 18496,
"s": 18403,
"text": "Let us create a folder named progs. Type the following commands at the command prompt (>>) −"
},
{
"code": null,
"e": 18667,
"s": 18496,
"text": "mkdir progs % create directory progs under default directory\nchdir progs % changing the current directory to progs\nedit prog1.m % creating an m file named prog1.m"
},
{
"code": null,
"e": 18757,
"s": 18667,
"text": "If you are creating the file for first time, MATLAB prompts you to confirm it. Click Yes."
},
{
"code": null,
"e": 18936,
"s": 18757,
"text": "Alternatively, if you are using the IDE, choose NEW -> Script. This also opens the editor and creates a file named Untitled. You can name and save the file after typing the code."
},
{
"code": null,
"e": 18976,
"s": 18936,
"text": "Type the following code in the editor −"
},
{
"code": null,
"e": 19118,
"s": 18976,
"text": "NoOfStudents = 6000;\nTeachingStaff = 150;\nNonTeachingStaff = 20;\nTotal = NoOfStudents + TeachingStaff ...\n + NonTeachingStaff;\ndisp(Total);"
},
{
"code": null,
"e": 19183,
"s": 19118,
"text": "After creating and saving the file, you can run it in two ways −"
},
{
"code": null,
"e": 19231,
"s": 19183,
"text": "Clicking the Run button on the editor window or"
},
{
"code": null,
"e": 19279,
"s": 19231,
"text": "Clicking the Run button on the editor window or"
},
{
"code": null,
"e": 19356,
"s": 19279,
"text": "Just typing the filename (without extension) in the command prompt: >> prog1"
},
{
"code": null,
"e": 19433,
"s": 19356,
"text": "Just typing the filename (without extension) in the command prompt: >> prog1"
},
{
"code": null,
"e": 19481,
"s": 19433,
"text": "The command window prompt displays the result −"
},
{
"code": null,
"e": 19487,
"s": 19481,
"text": "6170\n"
},
{
"code": null,
"e": 19539,
"s": 19487,
"text": "Create a script file, and type the following code −"
},
{
"code": null,
"e": 19600,
"s": 19539,
"text": "a = 5; b = 7;\nc = a + b\nd = c + sin(b)\ne = 5 * d\nf = exp(-d)"
},
{
"code": null,
"e": 19681,
"s": 19600,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 19732,
"s": 19681,
"text": "c = 12\nd = 12.657\ne = 63.285\nf = 3.1852e-06\n"
},
{
"code": null,
"e": 19914,
"s": 19732,
"text": "MATLAB does not require any type declaration or dimension statements. Whenever MATLAB encounters a new variable name, it creates the variable and allocates appropriate memory space."
},
{
"code": null,
"e": 20055,
"s": 19914,
"text": "If the variable already exists, then MATLAB replaces the original content with new content and allocates new storage space, where necessary."
},
{
"code": null,
"e": 20068,
"s": 20055,
"text": "For example,"
},
{
"code": null,
"e": 20080,
"s": 20068,
"text": "Total = 42\n"
},
{
"code": null,
"e": 20169,
"s": 20080,
"text": "The above statement creates a 1-by-1 matrix named 'Total' and stores the value 42 in it."
},
{
"code": null,
"e": 20393,
"s": 20169,
"text": "MATLAB provides 15 fundamental data types. Every data type stores data that is in the form of a matrix or array. The size of this matrix or array is a minimum of 0-by-0 and this can grow up to a matrix or array of any size."
},
{
"code": null,
"e": 20465,
"s": 20393,
"text": "The following table shows the most commonly used data types in MATLAB −"
},
{
"code": null,
"e": 20470,
"s": 20465,
"text": "int8"
},
{
"code": null,
"e": 20491,
"s": 20470,
"text": "8-bit signed integer"
},
{
"code": null,
"e": 20497,
"s": 20491,
"text": "uint8"
},
{
"code": null,
"e": 20520,
"s": 20497,
"text": "8-bit unsigned integer"
},
{
"code": null,
"e": 20526,
"s": 20520,
"text": "int16"
},
{
"code": null,
"e": 20548,
"s": 20526,
"text": "16-bit signed integer"
},
{
"code": null,
"e": 20555,
"s": 20548,
"text": "uint16"
},
{
"code": null,
"e": 20579,
"s": 20555,
"text": "16-bit unsigned integer"
},
{
"code": null,
"e": 20585,
"s": 20579,
"text": "int32"
},
{
"code": null,
"e": 20607,
"s": 20585,
"text": "32-bit signed integer"
},
{
"code": null,
"e": 20614,
"s": 20607,
"text": "uint32"
},
{
"code": null,
"e": 20638,
"s": 20614,
"text": "32-bit unsigned integer"
},
{
"code": null,
"e": 20644,
"s": 20638,
"text": "int64"
},
{
"code": null,
"e": 20666,
"s": 20644,
"text": "64-bit signed integer"
},
{
"code": null,
"e": 20673,
"s": 20666,
"text": "uint64"
},
{
"code": null,
"e": 20697,
"s": 20673,
"text": "64-bit unsigned integer"
},
{
"code": null,
"e": 20704,
"s": 20697,
"text": "single"
},
{
"code": null,
"e": 20736,
"s": 20704,
"text": "single precision numerical data"
},
{
"code": null,
"e": 20743,
"s": 20736,
"text": "double"
},
{
"code": null,
"e": 20775,
"s": 20743,
"text": "double precision numerical data"
},
{
"code": null,
"e": 20783,
"s": 20775,
"text": "logical"
},
{
"code": null,
"e": 20847,
"s": 20783,
"text": "logical values of 1 or 0, represent true and false respectively"
},
{
"code": null,
"e": 20852,
"s": 20847,
"text": "char"
},
{
"code": null,
"e": 20912,
"s": 20852,
"text": "character data (strings are stored as vector of characters)"
},
{
"code": null,
"e": 20923,
"s": 20912,
"text": "cell array"
},
{
"code": null,
"e": 21019,
"s": 20923,
"text": "array of indexed cells, each capable of storing an array of a different dimension and data type"
},
{
"code": null,
"e": 21029,
"s": 21019,
"text": "structure"
},
{
"code": null,
"e": 21150,
"s": 21029,
"text": "C-like structures, each structure having named fields capable of storing an array of a different dimension and data type"
},
{
"code": null,
"e": 21166,
"s": 21150,
"text": "function handle"
},
{
"code": null,
"e": 21188,
"s": 21166,
"text": "pointer to a function"
},
{
"code": null,
"e": 21201,
"s": 21188,
"text": "user classes"
},
{
"code": null,
"e": 21247,
"s": 21201,
"text": "objects constructed from a user-defined class"
},
{
"code": null,
"e": 21260,
"s": 21247,
"text": "java classes"
},
{
"code": null,
"e": 21298,
"s": 21260,
"text": "objects constructed from a Java class"
},
{
"code": null,
"e": 21345,
"s": 21298,
"text": "Create a script file with the following code −"
},
{
"code": null,
"e": 21439,
"s": 21345,
"text": "str = 'Hello World!'\nn = 2345\nd = double(n)\nun = uint32(789.50)\nrn = 5678.92347\nc = int32(rn)"
},
{
"code": null,
"e": 21520,
"s": 21439,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 21591,
"s": 21520,
"text": "str = Hello World!\nn = 2345\nd = 2345\nun = 790\nrn = 5678.9\nc = 5679\n"
},
{
"code": null,
"e": 21743,
"s": 21591,
"text": "MATLAB provides various functions for converting, a value from one data type to another. The following table shows the data type conversion functions −"
},
{
"code": null,
"e": 21819,
"s": 21743,
"text": "MATLAB provides various functions for identifying data type of a variable. "
},
{
"code": null,
"e": 21904,
"s": 21819,
"text": "Following table provides the functions for determining the data type of a variable −"
},
{
"code": null,
"e": 21951,
"s": 21904,
"text": "Create a script file with the following code −"
},
{
"code": null,
"e": 22228,
"s": 21951,
"text": "x = 3\nisinteger(x)\nisfloat(x)\nisvector(x)\nisscalar(x)\nisnumeric(x)\n \nx = 23.54\nisinteger(x)\nisfloat(x)\nisvector(x)\nisscalar(x)\nisnumeric(x)\n \nx = [1 2 3]\nisinteger(x)\nisfloat(x)\nisvector(x)\nisscalar(x)\n \nx = 'Hello'\nisinteger(x)\nisfloat(x)\nisvector(x)\nisscalar(x)\nisnumeric(x)"
},
{
"code": null,
"e": 22286,
"s": 22228,
"text": "When you run the file, it produces the following result −"
},
{
"code": null,
"e": 22506,
"s": 22286,
"text": "x = 3\nans = 0\nans = 1\nans = 1\nans = 1\nans = 1\nx = 23.540\nans = 0\nans = 1\nans = 1\nans = 1\nans = 1\nx =\n\n 1 2 3\n\nans = 0\nans = 1\nans = 1\nans = 0\nx = Hello\nans = 0\nans = 0\nans = 1\nans = 0\nans = 0\n"
},
{
"code": null,
"e": 22816,
"s": 22506,
"text": "An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. MATLAB is designed to operate primarily on whole matrices and arrays. Therefore, operators in MATLAB work both on scalar and non-scalar data. MATLAB allows the following types of elementary operations −"
},
{
"code": null,
"e": 22837,
"s": 22816,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 22858,
"s": 22837,
"text": "Relational Operators"
},
{
"code": null,
"e": 22876,
"s": 22858,
"text": "Logical Operators"
},
{
"code": null,
"e": 22895,
"s": 22876,
"text": "Bitwise Operations"
},
{
"code": null,
"e": 22910,
"s": 22895,
"text": "Set Operations"
},
{
"code": null,
"e": 22971,
"s": 22910,
"text": "MATLAB allows two different types of arithmetic operations −"
},
{
"code": null,
"e": 23000,
"s": 22971,
"text": "Matrix arithmetic operations"
},
{
"code": null,
"e": 23028,
"s": 23000,
"text": "Array arithmetic operations"
},
{
"code": null,
"e": 23198,
"s": 23028,
"text": "Matrix arithmetic operations are same as defined in linear algebra. Array operations are executed element by element, both on one-dimensional and multidimensional array."
},
{
"code": null,
"e": 23468,
"s": 23198,
"text": "The matrix operators and array operators are differentiated by the period (.) symbol. However, as the addition and subtraction operation is same for matrices and arrays, the operator is same for both cases. The following table gives brief description of the operators −"
},
{
"code": null,
"e": 23482,
"s": 23468,
"text": "Show Examples"
},
{
"code": null,
"e": 23484,
"s": 23482,
"text": "+"
},
{
"code": null,
"e": 23661,
"s": 23484,
"text": "Addition or unary plus. A+B adds the values stored in variables A and B. A and B must have the same size, unless one is a scalar. A scalar can be added to a matrix of any size."
},
{
"code": null,
"e": 23663,
"s": 23661,
"text": "-"
},
{
"code": null,
"e": 23839,
"s": 23663,
"text": "Subtraction or unary minus. A-B subtracts the value of B from A. A and B must have the same size, unless one is a scalar. A scalar can be subtracted from a matrix of any size."
},
{
"code": null,
"e": 23841,
"s": 23839,
"text": "*"
},
{
"code": null,
"e": 23945,
"s": 23841,
"text": "Matrix multiplication. C = A*B is the linear algebraic product of the matrices A and B. More precisely,"
},
{
"code": null,
"e": 24082,
"s": 23945,
"text": "For non-scalar A and B, the number of columns of A must be equal to the number of rows of B. A scalar can multiply a matrix of any size."
},
{
"code": null,
"e": 24085,
"s": 24082,
"text": ".*"
},
{
"code": null,
"e": 24234,
"s": 24085,
"text": "Array multiplication. A.*B is the element-by-element product of the arrays A and B. A and B must have the same size, unless one of them is a scalar."
},
{
"code": null,
"e": 24236,
"s": 24234,
"text": "/"
},
{
"code": null,
"e": 24337,
"s": 24236,
"text": "Slash or matrix right division. B/A is roughly the same as B*inv(A). More precisely, B/A = (A'\\B')'."
},
{
"code": null,
"e": 24340,
"s": 24337,
"text": "./"
},
{
"code": null,
"e": 24475,
"s": 24340,
"text": "Array right division. A./B is the matrix with elements A(i,j)/B(i,j). A and B must have the same size, unless one of them is a scalar."
},
{
"code": null,
"e": 24477,
"s": 24475,
"text": "\\"
},
{
"code": null,
"e": 24849,
"s": 24477,
"text": "Backslash or matrix left division. If A is a square matrix, A\\B is roughly the same as inv(A)*B, except it is computed in a different way. If A is an n-by-n matrix and B is a column vector with n components, or a matrix with several such columns, then X = A\\B is the solution to the equation AX = B. A warning message is displayed if A is badly scaled or nearly singular."
},
{
"code": null,
"e": 24852,
"s": 24849,
"text": ".\\"
},
{
"code": null,
"e": 24986,
"s": 24852,
"text": "Array left division. A.\\B is the matrix with elements B(i,j)/A(i,j). A and B must have the same size, unless one of them is a scalar."
},
{
"code": null,
"e": 24988,
"s": 24986,
"text": "^"
},
{
"code": null,
"e": 25286,
"s": 24988,
"text": "Matrix power. X^p is X to the power p, if p is a scalar. If p is an integer, the power is computed by repeated squaring. If the integer is negative, X is inverted first. For other values of p, the calculation involves eigenvalues and eigenvectors, such that if [V,D] = eig(X), then X^p = V*D.^p/V."
},
{
"code": null,
"e": 25289,
"s": 25286,
"text": ".^"
},
{
"code": null,
"e": 25428,
"s": 25289,
"text": "Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. A and B must have the same size, unless one of them is a scalar."
},
{
"code": null,
"e": 25430,
"s": 25428,
"text": "'"
},
{
"code": null,
"e": 25554,
"s": 25430,
"text": "Matrix transpose. A' is the linear algebraic transpose of A. For complex matrices, this is the complex conjugate transpose."
},
{
"code": null,
"e": 25557,
"s": 25554,
"text": ".'"
},
{
"code": null,
"e": 25664,
"s": 25557,
"text": "Array transpose. A.' is the array transpose of A. For complex matrices, this does not involve conjugation."
},
{
"code": null,
"e": 25990,
"s": 25664,
"text": "Relational operators can also work on both scalar and non-scalar data. Relational operators for arrays perform element-by-element comparisons between two arrays and return a logical array of the same size, with elements set to logical 1 (true) where the relation is true and elements set to logical 0 (false) where it is not."
},
{
"code": null,
"e": 26063,
"s": 25990,
"text": "The following table shows the relational operators available in MATLAB −"
},
{
"code": null,
"e": 26077,
"s": 26063,
"text": "Show Examples"
},
{
"code": null,
"e": 26079,
"s": 26077,
"text": "<"
},
{
"code": null,
"e": 26089,
"s": 26079,
"text": "Less than"
},
{
"code": null,
"e": 26092,
"s": 26089,
"text": "<="
},
{
"code": null,
"e": 26114,
"s": 26092,
"text": "Less than or equal to"
},
{
"code": null,
"e": 26116,
"s": 26114,
"text": ">"
},
{
"code": null,
"e": 26129,
"s": 26116,
"text": "Greater than"
},
{
"code": null,
"e": 26132,
"s": 26129,
"text": ">="
},
{
"code": null,
"e": 26157,
"s": 26132,
"text": "Greater than or equal to"
},
{
"code": null,
"e": 26160,
"s": 26157,
"text": "=="
},
{
"code": null,
"e": 26169,
"s": 26160,
"text": "Equal to"
},
{
"code": null,
"e": 26172,
"s": 26169,
"text": "~="
},
{
"code": null,
"e": 26185,
"s": 26172,
"text": "Not equal to"
},
{
"code": null,
"e": 26246,
"s": 26185,
"text": "MATLAB offers two types of logical operators and functions −"
},
{
"code": null,
"e": 26330,
"s": 26246,
"text": "Element-wise − These operators operate on corresponding elements of logical arrays."
},
{
"code": null,
"e": 26414,
"s": 26330,
"text": "Element-wise − These operators operate on corresponding elements of logical arrays."
},
{
"code": null,
"e": 26490,
"s": 26414,
"text": "Short-circuit − These operators operate on scalar and, logical expressions."
},
{
"code": null,
"e": 26566,
"s": 26490,
"text": "Short-circuit − These operators operate on scalar and, logical expressions."
},
{
"code": null,
"e": 26717,
"s": 26566,
"text": "Element-wise logical operators operate element-by-element on logical arrays. The symbols &, |, and ~ are the logical array operators AND, OR, and NOT."
},
{
"code": null,
"e": 26869,
"s": 26717,
"text": "Short-circuit logical operators allow short-circuiting on logical operations. The symbols && and || are the logical short-circuit operators AND and OR."
},
{
"code": null,
"e": 26883,
"s": 26869,
"text": "Show Examples"
},
{
"code": null,
"e": 26998,
"s": 26883,
"text": "Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows −"
},
{
"code": null,
"e": 27075,
"s": 26998,
"text": "Assume if A = 60; and B = 13; Now in binary format they will be as follows −"
},
{
"code": null,
"e": 27089,
"s": 27075,
"text": "A = 0011 1100"
},
{
"code": null,
"e": 27103,
"s": 27089,
"text": "B = 0000 1101"
},
{
"code": null,
"e": 27121,
"s": 27103,
"text": "-----------------"
},
{
"code": null,
"e": 27137,
"s": 27121,
"text": "A&B = 0000 1100"
},
{
"code": null,
"e": 27153,
"s": 27137,
"text": "A|B = 0011 1101"
},
{
"code": null,
"e": 27169,
"s": 27153,
"text": "A^B = 0011 0001"
},
{
"code": null,
"e": 27185,
"s": 27169,
"text": "~A = 1100 0011"
},
{
"code": null,
"e": 27328,
"s": 27185,
"text": "MATLAB provides various functions for bit-wise operations like 'bitwise and', 'bitwise or' and 'bitwise not' operations, shift operation, etc."
},
{
"code": null,
"e": 27393,
"s": 27328,
"text": "The following table shows the commonly used bitwise operations −"
},
{
"code": null,
"e": 27407,
"s": 27393,
"text": "Show Examples"
},
{
"code": null,
"e": 27523,
"s": 27407,
"text": "MATLAB provides various functions for set operations, like union, intersection and testing for set membership, etc."
},
{
"code": null,
"e": 27585,
"s": 27523,
"text": "The following table shows some commonly used set operations −"
},
{
"code": null,
"e": 27599,
"s": 27585,
"text": "Show Examples"
},
{
"code": null,
"e": 27614,
"s": 27599,
"text": "intersect(A,B)"
},
{
"code": null,
"e": 27730,
"s": 27614,
"text": "Set intersection of two arrays; returns the values common to both A and B. The values returned are in sorted order."
},
{
"code": null,
"e": 27752,
"s": 27730,
"text": "intersect(A,B,'rows')"
},
{
"code": null,
"e": 27908,
"s": 27752,
"text": "Treats each row of A and each row of B as single entities and returns the rows common to both A and B. The rows of the returned matrix are in sorted order."
},
{
"code": null,
"e": 27922,
"s": 27908,
"text": "ismember(A,B)"
},
{
"code": null,
"e": 28052,
"s": 27922,
"text": "Returns an array the same size as A, containing 1 (true) where the elements of A are found in B. Elsewhere, it returns 0 (false)."
},
{
"code": null,
"e": 28073,
"s": 28052,
"text": "ismember(A,B,'rows')"
},
{
"code": null,
"e": 28252,
"s": 28073,
"text": "Treats each row of A and each row of B as single entities and returns a vector containing 1 (true) where the rows of matrix A are also rows of B. Elsewhere, it returns 0 (false)."
},
{
"code": null,
"e": 28264,
"s": 28252,
"text": "issorted(A)"
},
{
"code": null,
"e": 28504,
"s": 28264,
"text": "Returns logical 1 (true) if the elements of A are in sorted order and logical 0 (false) otherwise. Input A can be a vector or an N-by-1 or 1-by-N cell array of strings. A is considered to be sorted if A and the output of sort(A) are equal."
},
{
"code": null,
"e": 28524,
"s": 28504,
"text": "issorted(A, 'rows')"
},
{
"code": null,
"e": 28724,
"s": 28524,
"text": "Returns logical 1 (true) if the rows of two-dimensional matrix A is in sorted order, and logical 0 (false) otherwise. Matrix A is considered to be sorted if A and the output of sortrows(A) are equal."
},
{
"code": null,
"e": 28737,
"s": 28724,
"text": "setdiff(A,B)"
},
{
"code": null,
"e": 28865,
"s": 28737,
"text": "Sets difference of two arrays; returns the values in A that are not in B. The values in the returned array are in sorted order."
},
{
"code": null,
"e": 28885,
"s": 28865,
"text": "setdiff(A,B,'rows')"
},
{
"code": null,
"e": 29043,
"s": 28885,
"text": "Treats each row of A and each row of B as single entities and returns the rows from A that are not in B. The rows of the returned matrix are in sorted order."
},
{
"code": null,
"e": 29091,
"s": 29043,
"text": "The 'rows' option does not support cell arrays."
},
{
"code": null,
"e": 29098,
"s": 29091,
"text": "setxor"
},
{
"code": null,
"e": 29130,
"s": 29098,
"text": "Sets exclusive OR of two arrays"
},
{
"code": null,
"e": 29136,
"s": 29130,
"text": "union"
},
{
"code": null,
"e": 29161,
"s": 29136,
"text": "Sets union of two arrays"
},
{
"code": null,
"e": 29168,
"s": 29161,
"text": "unique"
},
{
"code": null,
"e": 29191,
"s": 29168,
"text": "Unique values in array"
},
{
"code": null,
"e": 29513,
"s": 29191,
"text": "Decision making structures require that the programmer should specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false."
},
{
"code": null,
"e": 29627,
"s": 29513,
"text": "Following is the general form of a typical decision making structure found in most of the programming languages −"
},
{
"code": null,
"e": 29740,
"s": 29627,
"text": "MATLAB provides following types of decision making statements. Click the following links to check their detail −"
},
{
"code": null,
"e": 29833,
"s": 29740,
"text": "An if ... end statement consists of a boolean expression followed by one or more statements."
},
{
"code": null,
"e": 29949,
"s": 29833,
"text": "An if statement can be followed by an optional else statement, which executes when the boolean expression is false."
},
{
"code": null,
"e": 30089,
"s": 29949,
"text": "An if statement can be followed by one (or more) optional elseif... and an else statement, which is very useful to test various conditions."
},
{
"code": null,
"e": 30170,
"s": 30089,
"text": "You can use one if or elseif statement inside another if or elseif statement(s)."
},
{
"code": null,
"e": 30259,
"s": 30170,
"text": "A switch statement allows a variable to be tested for equality against a list of values."
},
{
"code": null,
"e": 30328,
"s": 30259,
"text": "You can use one switch statement inside another switch statement(s)."
},
{
"code": null,
"e": 30557,
"s": 30328,
"text": "There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially. The first statement in a function is executed first, followed by the second, and so on."
},
{
"code": null,
"e": 30663,
"s": 30557,
"text": "Programming languages provide various control structures that allow for more complicated execution paths."
},
{
"code": null,
"e": 30844,
"s": 30663,
"text": "A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −"
},
{
"code": null,
"e": 30967,
"s": 30844,
"text": "MATLAB provides following types of loops to handle looping requirements. Click the following links to check their detail −"
},
{
"code": null,
"e": 31098,
"s": 30967,
"text": "Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body."
},
{
"code": null,
"e": 31204,
"s": 31098,
"text": "Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable."
},
{
"code": null,
"e": 31259,
"s": 31204,
"text": "You can use one or more loops inside any another loop."
},
{
"code": null,
"e": 31426,
"s": 31259,
"text": "Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed."
},
{
"code": null,
"e": 31525,
"s": 31426,
"text": "MATLAB supports the following control statements. Click the following links to check their detail."
},
{
"code": null,
"e": 31628,
"s": 31525,
"text": "Terminates the loop statement and transfers execution to the statement immediately following the loop."
},
{
"code": null,
"e": 31737,
"s": 31628,
"text": "Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating."
},
{
"code": null,
"e": 31831,
"s": 31737,
"text": "A vector is a one-dimensional array of numbers. MATLAB allows creating two types of vectors −"
},
{
"code": null,
"e": 31843,
"s": 31831,
"text": "Row vectors"
},
{
"code": null,
"e": 31858,
"s": 31843,
"text": "Column vectors"
},
{
"code": null,
"e": 31981,
"s": 31858,
"text": "Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit the elements."
},
{
"code": null,
"e": 31999,
"s": 31981,
"text": "r = [7 8 9 10 11]"
},
{
"code": null,
"e": 32073,
"s": 31999,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 32105,
"s": 32073,
"text": "r =\n\n 7 8 9 10 11 \n"
},
{
"code": null,
"e": 32226,
"s": 32105,
"text": "Column vectors are created by enclosing the set of elements in square brackets, using semicolon to delimit the elements."
},
{
"code": null,
"e": 32251,
"s": 32226,
"text": "c = [7; 8; 9; 10; 11]"
},
{
"code": null,
"e": 32325,
"s": 32251,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 32404,
"s": 32325,
"text": "c =\n 7 \n 8 \n 9 \n 10 \n 11 \n \n"
},
{
"code": null,
"e": 32546,
"s": 32404,
"text": "You can reference one or more of the elements of a vector in several ways. The ith component of a vector v is referred as v(i). For example −"
},
{
"code": null,
"e": 32617,
"s": 32546,
"text": "v = [ 1; 2; 3; 4; 5; 6];\t% creating a column vector of 6 elements\nv(3)"
},
{
"code": null,
"e": 32691,
"s": 32617,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 32701,
"s": 32691,
"text": "ans = 3\n"
},
{
"code": null,
"e": 32802,
"s": 32701,
"text": "When you reference a vector with a colon, such as v(:), all the components of the vector are listed."
},
{
"code": null,
"e": 32873,
"s": 32802,
"text": "v = [ 1; 2; 3; 4; 5; 6];\t% creating a column vector of 6 elements\nv(:)"
},
{
"code": null,
"e": 32947,
"s": 32873,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 32996,
"s": 32947,
"text": "ans =\n 1\n 2\n 3\n 4\n 5\n 6\n"
},
{
"code": null,
"e": 33059,
"s": 32996,
"text": "MATLAB allows you to select a range of elements from a vector."
},
{
"code": null,
"e": 33217,
"s": 33059,
"text": "For example, let us create a row vector rv of 9 elements, then we will reference the elements 3 to 7 by writing rv(3:7) and create a new vector named sub_rv."
},
{
"code": null,
"e": 33260,
"s": 33217,
"text": "rv = [1 2 3 4 5 6 7 8 9];\nsub_rv = rv(3:7)"
},
{
"code": null,
"e": 33334,
"s": 33260,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 33366,
"s": 33334,
"text": "sub_rv =\n\n 3 4 5 6 7\n"
},
{
"code": null,
"e": 33432,
"s": 33366,
"text": "In this section, let us discuss the following vector operations −"
},
{
"code": null,
"e": 33468,
"s": 33432,
"text": "Addition and Subtraction of Vectors"
},
{
"code": null,
"e": 33504,
"s": 33468,
"text": "Addition and Subtraction of Vectors"
},
{
"code": null,
"e": 33537,
"s": 33504,
"text": "Scalar Multiplication of Vectors"
},
{
"code": null,
"e": 33570,
"s": 33537,
"text": "Scalar Multiplication of Vectors"
},
{
"code": null,
"e": 33592,
"s": 33570,
"text": "Transpose of a Vector"
},
{
"code": null,
"e": 33614,
"s": 33592,
"text": "Transpose of a Vector"
},
{
"code": null,
"e": 33632,
"s": 33614,
"text": "Appending Vectors"
},
{
"code": null,
"e": 33650,
"s": 33632,
"text": "Appending Vectors"
},
{
"code": null,
"e": 33672,
"s": 33650,
"text": "Magnitude of a Vector"
},
{
"code": null,
"e": 33694,
"s": 33672,
"text": "Magnitude of a Vector"
},
{
"code": null,
"e": 33713,
"s": 33694,
"text": "Vector Dot Product"
},
{
"code": null,
"e": 33732,
"s": 33713,
"text": "Vector Dot Product"
},
{
"code": null,
"e": 33771,
"s": 33732,
"text": "Vectors with Uniformly Spaced Elements"
},
{
"code": null,
"e": 33810,
"s": 33771,
"text": "Vectors with Uniformly Spaced Elements"
},
{
"code": null,
"e": 33858,
"s": 33810,
"text": "A matrix is a two-dimensional array of numbers."
},
{
"code": null,
"e": 34008,
"s": 33858,
"text": "In MATLAB, you create a matrix by entering elements in each row as comma or space delimited numbers and using semicolons to mark the end of each row."
},
{
"code": null,
"e": 34055,
"s": 34008,
"text": "For example, let us create a 4-by-5 matrix a −"
},
{
"code": null,
"e": 34105,
"s": 34055,
"text": "a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]"
},
{
"code": null,
"e": 34179,
"s": 34105,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 34312,
"s": 34179,
"text": "a =\n 1 2 3 4 5\n 2 3 4 5 6\n 3 4 5 6 7\n 4 5 6 7 8\n"
},
{
"code": null,
"e": 34394,
"s": 34312,
"text": "To reference an element in the mth row and nth column, of a matrix mx, we write −"
},
{
"code": null,
"e": 34405,
"s": 34394,
"text": "mx(m, n);\n"
},
{
"code": null,
"e": 34532,
"s": 34405,
"text": "For example, to refer to the element in the 2nd row and 5th column, of the matrix a, as created in the last section, we type −"
},
{
"code": null,
"e": 34590,
"s": 34532,
"text": "a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];\na(2,5)"
},
{
"code": null,
"e": 34664,
"s": 34590,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 34674,
"s": 34664,
"text": "ans = 6\n"
},
{
"code": null,
"e": 34738,
"s": 34674,
"text": "To reference all the elements in the mth column we type A(:,m)."
},
{
"code": null,
"e": 34822,
"s": 34738,
"text": "Let us create a column vector v, from the elements of the 4th row of the matrix a −"
},
{
"code": null,
"e": 34884,
"s": 34822,
"text": "a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];\nv = a(:,4)"
},
{
"code": null,
"e": 34958,
"s": 34884,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 34995,
"s": 34958,
"text": "v =\n 4\n 5\n 6\n 7\n"
},
{
"code": null,
"e": 35080,
"s": 34995,
"text": "You can also select the elements in the mth through nth columns, for this we write −"
},
{
"code": null,
"e": 35089,
"s": 35080,
"text": "a(:,m:n)"
},
{
"code": null,
"e": 35176,
"s": 35089,
"text": "Let us create a smaller matrix taking the elements from the second and third columns −"
},
{
"code": null,
"e": 35237,
"s": 35176,
"text": "a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];\na(:, 2:3)"
},
{
"code": null,
"e": 35311,
"s": 35237,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 35374,
"s": 35311,
"text": "ans =\n 2 3\n 3 4\n 4 5\n 5 6\n"
},
{
"code": null,
"e": 35450,
"s": 35374,
"text": "In the same way, you can create a sub-matrix taking a sub-part of a matrix."
},
{
"code": null,
"e": 35511,
"s": 35450,
"text": "a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];\na(:, 2:3)"
},
{
"code": null,
"e": 35585,
"s": 35511,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 35648,
"s": 35585,
"text": "ans =\n 2 3\n 3 4\n 4 5\n 5 6\n"
},
{
"code": null,
"e": 35724,
"s": 35648,
"text": "In the same way, you can create a sub-matrix taking a sub-part of a matrix."
},
{
"code": null,
"e": 35799,
"s": 35724,
"text": "For example, let us create a sub-matrix sa taking the inner subpart of a −"
},
{
"code": null,
"e": 35838,
"s": 35799,
"text": "3 4 5 \n4 5 6 \n"
},
{
"code": null,
"e": 35858,
"s": 35838,
"text": "To do this, write −"
},
{
"code": null,
"e": 35925,
"s": 35858,
"text": "a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];\nsa = a(2:3,2:4)"
},
{
"code": null,
"e": 35999,
"s": 35925,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 36045,
"s": 35999,
"text": "sa =\n 3 4 5\n 4 5 6\n"
},
{
"code": null,
"e": 36203,
"s": 36045,
"text": "You can delete an entire row or column of a matrix by assigning an empty set of square braces [] to that row or column. Basically, [] denotes an empty array."
},
{
"code": null,
"e": 36252,
"s": 36203,
"text": "For example, let us delete the fourth row of a −"
},
{
"code": null,
"e": 36319,
"s": 36252,
"text": "a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];\na( 4 , : ) = []"
},
{
"code": null,
"e": 36393,
"s": 36319,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 36494,
"s": 36393,
"text": "a =\n 1 2 3 4 5\n 2 3 4 5 6\n 3 4 5 6 7\n"
},
{
"code": null,
"e": 36538,
"s": 36494,
"text": "Next, let us delete the fifth column of a −"
},
{
"code": null,
"e": 36601,
"s": 36538,
"text": "a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];\na(: , 5)=[]"
},
{
"code": null,
"e": 36675,
"s": 36601,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 36784,
"s": 36675,
"text": "a =\n 1 2 3 4\n 2 3 4 5\n 3 4 5 6\n 4 5 6 7\n"
},
{
"code": null,
"e": 36926,
"s": 36784,
"text": "In this example, let us create a 3-by-3 matrix m, then we will copy the second and third rows of this matrix twice to create a 4-by-3 matrix."
},
{
"code": null,
"e": 36973,
"s": 36926,
"text": "Create a script file with the following code −"
},
{
"code": null,
"e": 37027,
"s": 36973,
"text": "a = [ 1 2 3 ; 4 5 6; 7 8 9];\nnew_mat = a([2,3,2,3],:)"
},
{
"code": null,
"e": 37085,
"s": 37027,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 37176,
"s": 37085,
"text": "new_mat =\n 4 5 6\n 7 8 9\n 4 5 6\n 7 8 9\n"
},
{
"code": null,
"e": 37266,
"s": 37176,
"text": "In this section, let us discuss the following basic and commonly used matrix operations −"
},
{
"code": null,
"e": 37303,
"s": 37266,
"text": "Addition and Subtraction of Matrices"
},
{
"code": null,
"e": 37340,
"s": 37303,
"text": "Addition and Subtraction of Matrices"
},
{
"code": null,
"e": 37361,
"s": 37340,
"text": "Division of Matrices"
},
{
"code": null,
"e": 37382,
"s": 37361,
"text": "Division of Matrices"
},
{
"code": null,
"e": 37412,
"s": 37382,
"text": "Scalar Operations of Matrices"
},
{
"code": null,
"e": 37442,
"s": 37412,
"text": "Scalar Operations of Matrices"
},
{
"code": null,
"e": 37464,
"s": 37442,
"text": "Transpose of a Matrix"
},
{
"code": null,
"e": 37486,
"s": 37464,
"text": "Transpose of a Matrix"
},
{
"code": null,
"e": 37510,
"s": 37486,
"text": "Concatenating Matrices "
},
{
"code": null,
"e": 37534,
"s": 37510,
"text": "Concatenating Matrices "
},
{
"code": null,
"e": 37556,
"s": 37534,
"text": "Matrix Multiplication"
},
{
"code": null,
"e": 37578,
"s": 37556,
"text": "Matrix Multiplication"
},
{
"code": null,
"e": 37602,
"s": 37578,
"text": "Determinant of a Matrix"
},
{
"code": null,
"e": 37626,
"s": 37602,
"text": "Determinant of a Matrix"
},
{
"code": null,
"e": 37646,
"s": 37626,
"text": "Inverse of a Matrix"
},
{
"code": null,
"e": 37666,
"s": 37646,
"text": "Inverse of a Matrix"
},
{
"code": null,
"e": 37814,
"s": 37666,
"text": "All variables of all data types in MATLAB are multidimensional arrays. A vector is a one-dimensional array and a matrix is a two-dimensional array."
},
{
"code": null,
"e": 37987,
"s": 37814,
"text": "We have already discussed vectors and matrices. In this chapter, we will discuss multidimensional arrays. However, before that, let us discuss some special types of arrays."
},
{
"code": null,
"e": 38178,
"s": 37987,
"text": "In this section, we will discuss some functions that create some special arrays. For all these functions, a single argument creates a square array, double arguments create rectangular array."
},
{
"code": null,
"e": 38231,
"s": 38178,
"text": "The zeros() function creates an array of all zeros −"
},
{
"code": null,
"e": 38245,
"s": 38231,
"text": "For example −"
},
{
"code": null,
"e": 38254,
"s": 38245,
"text": "zeros(5)"
},
{
"code": null,
"e": 38328,
"s": 38254,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 38495,
"s": 38328,
"text": "ans =\n 0 0 0 0 0\n 0 0 0 0 0\n 0 0 0 0 0\n 0 0 0 0 0\n 0 0 0 0 0\n"
},
{
"code": null,
"e": 38546,
"s": 38495,
"text": "The ones() function creates an array of all ones −"
},
{
"code": null,
"e": 38560,
"s": 38546,
"text": "For example −"
},
{
"code": null,
"e": 38570,
"s": 38560,
"text": "ones(4,3)"
},
{
"code": null,
"e": 38644,
"s": 38570,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 38731,
"s": 38644,
"text": "ans =\n 1 1 1\n 1 1 1\n 1 1 1\n 1 1 1\n"
},
{
"code": null,
"e": 38778,
"s": 38731,
"text": "The eye() function creates an identity matrix."
},
{
"code": null,
"e": 38792,
"s": 38778,
"text": "For example −"
},
{
"code": null,
"e": 38799,
"s": 38792,
"text": "eye(4)"
},
{
"code": null,
"e": 38873,
"s": 38799,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 38984,
"s": 38873,
"text": "ans =\n 1 0 0 0\n 0 1 0 0\n 0 0 1 0\n 0 0 0 1\n"
},
{
"code": null,
"e": 39072,
"s": 38984,
"text": "The rand() function creates an array of uniformly distributed random numbers on (0,1) −"
},
{
"code": null,
"e": 39086,
"s": 39072,
"text": "For example −"
},
{
"code": null,
"e": 39097,
"s": 39086,
"text": "rand(3, 5)"
},
{
"code": null,
"e": 39171,
"s": 39097,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 39328,
"s": 39171,
"text": "ans =\n 0.8147 0.9134 0.2785 0.9649 0.9572\n 0.9058 0.6324 0.5469 0.1576 0.4854\n 0.1270 0.0975 0.9575 0.9706 0.8003\n"
},
{
"code": null,
"e": 39448,
"s": 39328,
"text": "A magic square is a square that produces the same sum, when its elements are added row-wise, column-wise or diagonally."
},
{
"code": null,
"e": 39621,
"s": 39448,
"text": "The magic() function creates a magic square array. It takes a singular argument that gives the size of the square. The argument must be a scalar greater than or equal to 3."
},
{
"code": null,
"e": 39630,
"s": 39621,
"text": "magic(4)"
},
{
"code": null,
"e": 39704,
"s": 39630,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 39804,
"s": 39704,
"text": "ans =\n 16 2 3 13\n 5 11 10 8\n 9 7 6 12\n 4 14 15 1\n"
},
{
"code": null,
"e": 39980,
"s": 39804,
"text": "An array having more than two dimensions is called a multidimensional array in MATLAB. Multidimensional arrays in MATLAB are an extension of the normal two-dimensional matrix."
},
{
"code": null,
"e": 40083,
"s": 39980,
"text": "Generally to generate a multidimensional array, we first create a two-dimensional array and extend it."
},
{
"code": null,
"e": 40136,
"s": 40083,
"text": "For example, let's create a two-dimensional array a."
},
{
"code": null,
"e": 40162,
"s": 40136,
"text": "a = [7 9 5; 6 1 9; 4 3 2]"
},
{
"code": null,
"e": 40236,
"s": 40162,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 40292,
"s": 40236,
"text": "a =\n 7 9 5\n 6 1 9\n 4 3 2\n"
},
{
"code": null,
"e": 40389,
"s": 40292,
"text": "The array a is a 3-by-3 array; we can add a third dimension to a, by providing the values like −"
},
{
"code": null,
"e": 40424,
"s": 40389,
"text": "a(:, :, 2)= [ 1 2 3; 4 5 6; 7 8 9]"
},
{
"code": null,
"e": 40498,
"s": 40424,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 40611,
"s": 40498,
"text": "a =\n\nans(:,:,1) =\n\n 0 0 0\n 0 0 0\n 0 0 0\n\nans(:,:,2) =\n\n 1 2 3\n 4 5 6\n 7 8 9\n"
},
{
"code": null,
"e": 40705,
"s": 40611,
"text": "We can also create multidimensional arrays using the ones(), zeros() or the rand() functions."
},
{
"code": null,
"e": 40718,
"s": 40705,
"text": "For example,"
},
{
"code": null,
"e": 40734,
"s": 40718,
"text": "b = rand(4,3,2)"
},
{
"code": null,
"e": 40808,
"s": 40734,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 41072,
"s": 40808,
"text": "b(:,:,1) =\n 0.0344 0.7952 0.6463\n 0.4387 0.1869 0.7094\n 0.3816 0.4898 0.7547\n 0.7655 0.4456 0.2760\n\nb(:,:,2) =\n 0.6797 0.4984 0.2238\n 0.6551 0.9597 0.7513\n 0.1626 0.3404 0.2551\n 0.1190 0.5853 0.5060\n"
},
{
"code": null,
"e": 41204,
"s": 41072,
"text": "We can also use the cat() function to build multidimensional arrays. It concatenates a list of arrays along a specified dimension −"
},
{
"code": null,
"e": 41239,
"s": 41204,
"text": "Syntax for the cat() function is −"
},
{
"code": null,
"e": 41263,
"s": 41239,
"text": "B = cat(dim, A1, A2...)"
},
{
"code": null,
"e": 41270,
"s": 41263,
"text": "Where,"
},
{
"code": null,
"e": 41297,
"s": 41270,
"text": "B is the new array created"
},
{
"code": null,
"e": 41324,
"s": 41297,
"text": "B is the new array created"
},
{
"code": null,
"e": 41370,
"s": 41324,
"text": "A1, A2, ... are the arrays to be concatenated"
},
{
"code": null,
"e": 41416,
"s": 41370,
"text": "A1, A2, ... are the arrays to be concatenated"
},
{
"code": null,
"e": 41475,
"s": 41416,
"text": "dim is the dimension along which to concatenate the arrays"
},
{
"code": null,
"e": 41534,
"s": 41475,
"text": "dim is the dimension along which to concatenate the arrays"
},
{
"code": null,
"e": 41593,
"s": 41534,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 41688,
"s": 41593,
"text": "a = [9 8 7; 6 5 4; 3 2 1];\nb = [1 2 3; 4 5 6; 7 8 9];\nc = cat(3, a, b, [ 2 3 1; 4 7 8; 3 9 0])"
},
{
"code": null,
"e": 41725,
"s": 41688,
"text": "When you run the file, it displays −"
},
{
"code": null,
"e": 41939,
"s": 41725,
"text": "c(:,:,1) =\n 9 8 7\n 6 5 4\n 3 2 1\nc(:,:,2) =\n 1 2 3\n 4 5 6\n 7 8 9\nc(:,:,3) =\n 2 3 1\n 4 7 8\n 3 9 0\n"
},
{
"code": null,
"e": 42040,
"s": 41939,
"text": "MATLAB provides the following functions to sort, rotate, permute, reshape, or shift array contents. "
},
{
"code": null,
"e": 42113,
"s": 42040,
"text": "The following examples illustrate some of the functions mentioned above."
},
{
"code": null,
"e": 42156,
"s": 42113,
"text": "Length, Dimension and Number of elements −"
},
{
"code": null,
"e": 42215,
"s": 42156,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 42450,
"s": 42215,
"text": "x = [7.1, 3.4, 7.2, 28/4, 3.6, 17, 9.4, 8.9];\nlength(x) % length of x vector\ny = rand(3, 4, 5, 2);\nndims(y) % no of dimensions in array y\ns = ['Zara', 'Nuha', 'Shamim', 'Riz', 'Shadab'];\nnumel(s) % no of elements in s"
},
{
"code": null,
"e": 42508,
"s": 42450,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 42537,
"s": 42508,
"text": "ans = 8\nans = 4\nans = 23\n"
},
{
"code": null,
"e": 42579,
"s": 42537,
"text": "Circular Shifting of the Array Elements −"
},
{
"code": null,
"e": 42638,
"s": 42579,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 42924,
"s": 42638,
"text": "a = [1 2 3; 4 5 6; 7 8 9] % the original array a\nb = circshift(a,1) % circular shift first dimension values down by 1.\nc = circshift(a,[1 -1]) % circular shift first dimension values % down by 1 \n % and second dimension values to the left % by 1."
},
{
"code": null,
"e": 42982,
"s": 42924,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 43150,
"s": 42982,
"text": "a =\n 1 2 3\n 4 5 6\n 7 8 9\n\nb =\n 7 8 9\n 1 2 3\n 4 5 6\n\nc =\n 8 9 7\n 2 3 1\n 5 6 4\n"
},
{
"code": null,
"e": 43209,
"s": 43150,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 43465,
"s": 43209,
"text": "v = [ 23 45 12 9 5 0 19 17] % horizontal vector\nsort(v) % sorting v\nm = [2 6 4; 5 3 9; 2 0 1] % two dimensional array\nsort(m, 1) % sorting m along the row\nsort(m, 2) % sorting m along the column"
},
{
"code": null,
"e": 43523,
"s": 43465,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 43798,
"s": 43523,
"text": "v =\n 23 45 12 9 5 0 19 17\nans =\n 0 5 9 12 17 19 23 45\nm =\n 2 6 4\n 5 3 9\n 2 0 1\nans =\n 2 0 1\n 2 3 4\n 5 6 9\nans =\n 2 4 6\n 3 5 9\n 0 1 2\n"
},
{
"code": null,
"e": 43915,
"s": 43798,
"text": "Cell arrays are arrays of indexed cells where each cell can store an array of a different dimensions and data types."
},
{
"code": null,
"e": 44002,
"s": 43915,
"text": "The cell function is used for creating a cell array. Syntax for the cell function is −"
},
{
"code": null,
"e": 44054,
"s": 44002,
"text": "C = cell(dim)\nC = cell(dim1,...,dimN)\nD = cell(obj)"
},
{
"code": null,
"e": 44075,
"s": 44054,
"text": "C is the cell array;"
},
{
"code": null,
"e": 44096,
"s": 44075,
"text": "C is the cell array;"
},
{
"code": null,
"e": 44189,
"s": 44096,
"text": "dim is a scalar integer or vector of integers that specifies the dimensions of cell array C;"
},
{
"code": null,
"e": 44282,
"s": 44189,
"text": "dim is a scalar integer or vector of integers that specifies the dimensions of cell array C;"
},
{
"code": null,
"e": 44353,
"s": 44282,
"text": "dim1, ... , dimN are scalar integers that specify the dimensions of C;"
},
{
"code": null,
"e": 44424,
"s": 44353,
"text": "dim1, ... , dimN are scalar integers that specify the dimensions of C;"
},
{
"code": null,
"e": 44528,
"s": 44424,
"text": "obj is One of the following −\n\nJava array or object\n.NET array of type System.String or System.Object\n\n"
},
{
"code": null,
"e": 44558,
"s": 44528,
"text": "obj is One of the following −"
},
{
"code": null,
"e": 44579,
"s": 44558,
"text": "Java array or object"
},
{
"code": null,
"e": 44629,
"s": 44579,
"text": ".NET array of type System.String or System.Object"
},
{
"code": null,
"e": 44688,
"s": 44629,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 44763,
"s": 44688,
"text": "c = cell(2, 5);\nc = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5}"
},
{
"code": null,
"e": 44821,
"s": 44763,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 44984,
"s": 44821,
"text": "c = \n{\n [1,1] = Red\n [2,1] = 1\n [1,2] = Blue\n [2,2] = 2\n [1,3] = Green\n [2,3] = 3\n [1,4] = Yellow\n [2,4] = 4\n [1,5] = White\n [2,5] = 5\n}\n"
},
{
"code": null,
"e": 45046,
"s": 44984,
"text": "There are two ways to refer to the elements of a cell array −"
},
{
"code": null,
"e": 45115,
"s": 45046,
"text": "Enclosing the indices in first bracket (), to refer to sets of cells"
},
{
"code": null,
"e": 45196,
"s": 45115,
"text": "Enclosing the indices in braces {}, to refer to the data within individual cells"
},
{
"code": null,
"e": 45274,
"s": 45196,
"text": "When you enclose the indices in first bracket, it refers to the set of cells."
},
{
"code": null,
"e": 45339,
"s": 45274,
"text": "Cell array indices in smooth parentheses refer to sets of cells."
},
{
"code": null,
"e": 45353,
"s": 45339,
"text": "For example −"
},
{
"code": null,
"e": 45424,
"s": 45353,
"text": "c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5};\nc(1:2,1:2)"
},
{
"code": null,
"e": 45498,
"s": 45424,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 45569,
"s": 45498,
"text": "ans = \n{\n [1,1] = Red\n [2,1] = 1\n [1,2] = Blue\n [2,2] = 2\n}\n"
},
{
"code": null,
"e": 45642,
"s": 45569,
"text": "You can also access the contents of cells by indexing with curly braces."
},
{
"code": null,
"e": 45656,
"s": 45642,
"text": "For example −"
},
{
"code": null,
"e": 45726,
"s": 45656,
"text": "c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5};\nc{1, 2:4}"
},
{
"code": null,
"e": 45800,
"s": 45726,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 45837,
"s": 45800,
"text": "ans = Blue\nans = Green\nans = Yellow\n"
},
{
"code": null,
"e": 45972,
"s": 45837,
"text": "The colon(:) is one of the most useful operator in MATLAB. It is used to create vectors, subscript arrays, and specify for iterations."
},
{
"code": null,
"e": 46054,
"s": 45972,
"text": "If you want to create a row vector, containing integers from 1 to 10, you write −"
},
{
"code": null,
"e": 46059,
"s": 46054,
"text": "1:10"
},
{
"code": null,
"e": 46153,
"s": 46059,
"text": "MATLAB executes the statement and returns a row vector containing the integers from 1 to 10 −"
},
{
"code": null,
"e": 46367,
"s": 46153,
"text": "ans = \n \n 1 2 3 4 5 6 7 8 9 10 \n"
},
{
"code": null,
"e": 46439,
"s": 46367,
"text": "If you want to specify an increment value other than one, for example −"
},
{
"code": null,
"e": 46451,
"s": 46439,
"text": "100: -5: 50"
},
{
"code": null,
"e": 46516,
"s": 46451,
"text": "MATLAB executes the statement and returns the following result −"
},
{
"code": null,
"e": 46590,
"s": 46516,
"text": "ans =\n 100 95 90 85 80 75 70 65 60 55 50\n"
},
{
"code": null,
"e": 46620,
"s": 46590,
"text": "Let us take another example −"
},
{
"code": null,
"e": 46630,
"s": 46620,
"text": "0:pi/8:pi"
},
{
"code": null,
"e": 46695,
"s": 46630,
"text": "MATLAB executes the statement and returns the following result −"
},
{
"code": null,
"e": 46839,
"s": 46695,
"text": "ans =\n Columns 1 through 7\n 0 0.3927 0.7854 1.1781 1.5708 1.9635 2.3562\n Columns 8 through 9\n 2.7489 3.1416\n"
},
{
"code": null,
"e": 46947,
"s": 46839,
"text": "You can use the colon operator to create a vector of indices to select rows, columns or elements of arrays."
},
{
"code": null,
"e": 47029,
"s": 46947,
"text": "The following table describes its use for this purpose (let us have a matrix A) −"
},
{
"code": null,
"e": 47086,
"s": 47029,
"text": "Create a script file and type the following code in it −"
},
{
"code": null,
"e": 47260,
"s": 47086,
"text": "A = [1 2 3 4; 4 5 6 7; 7 8 9 10]\nA(:,2) % second column of A\nA(:,2:3) % second and third column of A\nA(2:3,2:3) % second and third rows and second and third columns"
},
{
"code": null,
"e": 47318,
"s": 47260,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 47516,
"s": 47318,
"text": "A =\n 1 2 3 4\n 4 5 6 7\n 7 8 9 10\n\nans =\n 2\n 5\n 8\n\nans =\n 2 3\n 5 6\n 8 9\n\nans =\n 5 6\n 8 9\n"
},
{
"code": null,
"e": 47753,
"s": 47516,
"text": "MATLAB supports various numeric classes that include signed and unsigned integers and single-precision and double-precision floating-point numbers. By default, MATLAB stores all numeric values as double-precision floating point numbers."
},
{
"code": null,
"e": 47852,
"s": 47753,
"text": "You can choose to store any number or array of numbers as integers or as single-precision numbers."
},
{
"code": null,
"e": 47930,
"s": 47852,
"text": "All numeric types support basic array operations and mathematical operations."
},
{
"code": null,
"e": 48013,
"s": 47930,
"text": "MATLAB provides the following functions to convert to various numeric data types −"
},
{
"code": null,
"e": 48064,
"s": 48013,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 48275,
"s": 48064,
"text": "x = single([5.32 3.47 6.28]) .* 7.5\nx = double([5.32 3.47 6.28]) .* 7.5\nx = int8([5.32 3.47 6.28]) .* 7.5\nx = int16([5.32 3.47 6.28]) .* 7.5\nx = int32([5.32 3.47 6.28]) .* 7.5\nx = int64([5.32 3.47 6.28]) .* 7.5"
},
{
"code": null,
"e": 48330,
"s": 48275,
"text": "When you run the file, it shows the following result −"
},
{
"code": null,
"e": 48478,
"s": 48330,
"text": "x =\n\n 39.900 26.025 47.100\n\nx =\n\n 39.900 26.025 47.100\n\nx =\n\n 38 23 45\n\nx =\n\n 38 23 45\n\nx =\n\n 38 23 45\n\nx =\n\n 38 23 45\n"
},
{
"code": null,
"e": 48579,
"s": 48478,
"text": "Let us extend the previous example a little more. Create a script file and type the following code −"
},
{
"code": null,
"e": 48665,
"s": 48579,
"text": "x = int32([5.32 3.47 6.28]) .* 7.5\nx = int64([5.32 3.47 6.28]) .* 7.5\nx = num2cell(x)"
},
{
"code": null,
"e": 48720,
"s": 48665,
"text": "When you run the file, it shows the following result −"
},
{
"code": null,
"e": 48812,
"s": 48720,
"text": "x =\n\n 38 23 45\n\nx =\n\n 38 23 45\n\nx = \n{\n [1,1] = 38\n [1,2] = 23\n [1,3] = 45\n}\n"
},
{
"code": null,
"e": 48945,
"s": 48812,
"text": "The functions intmax() and intmin() return the maximum and minimum values that can be represented with all types of integer numbers."
},
{
"code": null,
"e": 49144,
"s": 48945,
"text": "Both the functions take the integer data type as the argument, for example, intmax(int8) or intmin(int64) and return the maximum and minimum values that you can represent with the integer data type."
},
{
"code": null,
"e": 49295,
"s": 49144,
"text": "The following example illustrates how to obtain the smallest and largest values of integers. Create a script file and write the following code in it −"
},
{
"code": null,
"e": 50165,
"s": 49295,
"text": "% displaying the smallest and largest signed integer data\nstr = 'The range for int8 is:\\n\\t%d to %d ';\nsprintf(str, intmin('int8'), intmax('int8'))\nstr = 'The range for int16 is:\\n\\t%d to %d ';\nsprintf(str, intmin('int16'), intmax('int16'))\nstr = 'The range for int32 is:\\n\\t%d to %d ';\nsprintf(str, intmin('int32'), intmax('int32'))\nstr = 'The range for int64 is:\\n\\t%d to %d ';\nsprintf(str, intmin('int64'), intmax('int64'))\n \n% displaying the smallest and largest unsigned integer data\nstr = 'The range for uint8 is:\\n\\t%d to %d ';\nsprintf(str, intmin('uint8'), intmax('uint8'))\nstr = 'The range for uint16 is:\\n\\t%d to %d ';\nsprintf(str, intmin('uint16'), intmax('uint16'))\nstr = 'The range for uint32 is:\\n\\t%d to %d ';\nsprintf(str, intmin('uint32'), intmax('uint32'))\nstr = 'The range for uint64 is:\\n\\t%d to %d ';\nsprintf(str, intmin('uint64'), intmax('uint64'))"
},
{
"code": null,
"e": 50220,
"s": 50165,
"text": "When you run the file, it shows the following result −"
},
{
"code": null,
"e": 50594,
"s": 50220,
"text": "ans = The range for int8 is:\n\t-128 to 127 \nans = The range for int16 is:\n\t-32768 to 32767 \nans = The range for int32 is:\n\t-2147483648 to 2147483647 \nans = The range for int64 is:\n\t0 to 0 \nans = The range for uint8 is:\n\t0 to 255 \nans = The range for uint16 is:\n\t0 to 65535 \nans = The range for uint32 is:\n\t0 to -1 \nans = The range for uint64 is:\n\t0 to 18446744073709551616 \n"
},
{
"code": null,
"e": 50723,
"s": 50594,
"text": "The functions realmax() and realmin() return the maximum and minimum values that can be represented with floating point numbers."
},
{
"code": null,
"e": 51021,
"s": 50723,
"text": "Both the functions when called with the argument 'single', return the maximum and minimum values that you can represent with the single-precision data type and when called with the argument 'double', return the maximum and minimum values that you can represent with the double-precision data type."
},
{
"code": null,
"e": 51176,
"s": 51021,
"text": "The following example illustrates how to obtain the smallest and largest floating point numbers. Create a script file and write the following code in it −"
},
{
"code": null,
"e": 51661,
"s": 51176,
"text": "% displaying the smallest and largest single-precision \n% floating point number\nstr = 'The range for single is:\\n\\t%g to %g and\\n\\t %g to %g';\nsprintf(str, -realmax('single'), -realmin('single'), ...\n realmin('single'), realmax('single'))\n\n% displaying the smallest and largest double-precision \n% floating point number\nstr = 'The range for double is:\\n\\t%g to %g and\\n\\t %g to %g';\nsprintf(str, -realmax('double'), -realmin('double'), ...\n realmin('double'), realmax('double'))"
},
{
"code": null,
"e": 51719,
"s": 51661,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 52164,
"s": 51719,
"text": "ans = The range for single is: \n -3.40282e+38 to -1.17549e-38 and \n 1.17549e-38 to 3.40282e+38 \nans = The range for double is: \n -1.79769e+308 to -2.22507e-308 and \n 2.22507e-308 to 1.79769e+308\n"
},
{
"code": null,
"e": 52316,
"s": 52164,
"text": "Creating a character string is quite simple in MATLAB. In fact, we have used it many times. For example, you type the following in the command prompt −"
},
{
"code": null,
"e": 52346,
"s": 52316,
"text": "my_string = 'Tutorials Point'"
},
{
"code": null,
"e": 52420,
"s": 52346,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 52449,
"s": 52420,
"text": "my_string = Tutorials Point\n"
},
{
"code": null,
"e": 52605,
"s": 52449,
"text": "MATLAB considers all variables as arrays, and strings are considered as character arrays. Let us use the whos command to check the variable created above −"
},
{
"code": null,
"e": 52610,
"s": 52605,
"text": "whos"
},
{
"code": null,
"e": 52684,
"s": 52610,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 52786,
"s": 52684,
"text": "Name Size Bytes Class Attributes\nmy_string 1x16 32 char\n"
},
{
"code": null,
"e": 52994,
"s": 52786,
"text": "Interestingly, you can use numeric conversion functions like uint8 or uint16 to convert the characters in the string to their numeric codes. The char function converts the integer vector back to characters −"
},
{
"code": null,
"e": 53053,
"s": 52994,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 53274,
"s": 53053,
"text": "my_string = 'Tutorial''s Point';\nstr_ascii = uint8(my_string) % 8-bit ascii values\nstr_back_to_char= char(str_ascii) \nstr_16bit = uint16(my_string) % 16-bit ascii values\nstr_back_to_char = char(str_16bit) "
},
{
"code": null,
"e": 53332,
"s": 53274,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 53595,
"s": 53332,
"text": "str_ascii =\n\n 84 117 116 111 114 105 97 108 39 115 32 80 111 105 110 116\n\nstr_back_to_char = Tutorial's Point\nstr_16bit =\n\n 84 117 116 111 114 105 97 108 39 115 32 80 111 105 110 116\n\nstr_back_to_char = Tutorial's Point\n"
},
{
"code": null,
"e": 53834,
"s": 53595,
"text": "The strings we have discussed so far are one-dimensional character arrays; however, we need to store more than that. We need to store more dimensional textual data in our program. This is achieved by creating rectangular character arrays."
},
{
"code": null,
"e": 54002,
"s": 53834,
"text": "Simplest way of creating a rectangular character array is by concatenating two or more one-dimensional character arrays, either vertically or horizontally as required."
},
{
"code": null,
"e": 54071,
"s": 54002,
"text": "You can combine strings vertically in either of the following ways −"
},
{
"code": null,
"e": 54329,
"s": 54071,
"text": "Using the MATLAB concatenation operator [] and separating each row with a semicolon (;). Please note that in this method each row must contain the same number of characters. For strings with different lengths, you should pad with space characters as needed."
},
{
"code": null,
"e": 54587,
"s": 54329,
"text": "Using the MATLAB concatenation operator [] and separating each row with a semicolon (;). Please note that in this method each row must contain the same number of characters. For strings with different lengths, you should pad with space characters as needed."
},
{
"code": null,
"e": 54756,
"s": 54587,
"text": "Using the char function. If the strings are of different lengths, char pads the shorter strings with trailing blanks so that each row has the same number of characters."
},
{
"code": null,
"e": 54925,
"s": 54756,
"text": "Using the char function. If the strings are of different lengths, char pads the shorter strings with trailing blanks so that each row has the same number of characters."
},
{
"code": null,
"e": 54984,
"s": 54925,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 55268,
"s": 54984,
"text": "doc_profile = ['Zara Ali '; ...\n 'Sr. Surgeon '; ...\n 'R N Tagore Cardiology Research Center']\ndoc_profile = char('Zara Ali', 'Sr. Surgeon', ...\n 'RN Tagore Cardiology Research Center')"
},
{
"code": null,
"e": 55326,
"s": 55268,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 55580,
"s": 55326,
"text": "doc_profile =\nZara Ali \nSr. Surgeon \nR N Tagore Cardiology Research Center\ndoc_profile =\nZara Ali \nSr. Surgeon \nRN Tagore Cardiology Research Center\n"
},
{
"code": null,
"e": 55651,
"s": 55580,
"text": "You can combine strings horizontally in either of the following ways −"
},
{
"code": null,
"e": 55816,
"s": 55651,
"text": "Using the MATLAB concatenation operator, [] and separating the input strings with a comma or a space. This method preserves any trailing spaces in the input arrays."
},
{
"code": null,
"e": 55981,
"s": 55816,
"text": "Using the MATLAB concatenation operator, [] and separating the input strings with a comma or a space. This method preserves any trailing spaces in the input arrays."
},
{
"code": null,
"e": 56081,
"s": 55981,
"text": "Using the string concatenation function, strcat. This method removes trailing spaces in the inputs."
},
{
"code": null,
"e": 56181,
"s": 56081,
"text": "Using the string concatenation function, strcat. This method removes trailing spaces in the inputs."
},
{
"code": null,
"e": 56240,
"s": 56181,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 56495,
"s": 56240,
"text": "name = 'Zara Ali ';\nposition = 'Sr. Surgeon '; \nworksAt = 'R N Tagore Cardiology Research Center';\nprofile = [name ', ' position ', ' worksAt]\nprofile = strcat(name, ', ', position, ', ', worksAt)"
},
{
"code": null,
"e": 56553,
"s": 56495,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 56706,
"s": 56553,
"text": "profile = Zara Ali , Sr. Surgeon , R N Tagore Cardiology Research Center\nprofile = Zara Ali,Sr. Surgeon,R N Tagore Cardiology Research Center\n"
},
{
"code": null,
"e": 56942,
"s": 56706,
"text": "From our previous discussion, it is clear that combining strings with different lengths could be a pain as all strings in the array has to be of the same length. We have used blank spaces at the end of strings to equalize their length."
},
{
"code": null,
"e": 57048,
"s": 56942,
"text": "However, a more efficient way to combine the strings is to convert the resulting array into a cell array."
},
{
"code": null,
"e": 57198,
"s": 57048,
"text": "MATLAB cell array can hold different sizes and types of data in an array. Cell arrays provide a more flexible way to store strings of varying length."
},
{
"code": null,
"e": 57276,
"s": 57198,
"text": "The cellstr function converts a character array into a cell array of strings."
},
{
"code": null,
"e": 57335,
"s": 57276,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 57575,
"s": 57335,
"text": "name = 'Zara Ali ';\nposition = 'Sr. Surgeon '; \nworksAt = 'R N Tagore Cardiology Research Center';\nprofile = char(name, position, worksAt);\nprofile = cellstr(profile);\ndisp(profile)"
},
{
"code": null,
"e": 57633,
"s": 57575,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 57966,
"s": 57633,
"text": "{ \n [1,1] = Zara Ali \n [2,1] = Sr. Surgeon \n [3,1] = R N Tagore Cardiology Research Center \n} \n"
},
{
"code": null,
"e": 58074,
"s": 57966,
"text": "MATLAB provides numerous string functions creating, combining, parsing, comparing and manipulating strings."
},
{
"code": null,
"e": 58153,
"s": 58074,
"text": "Following table provides brief description of the string functions in MATLAB −"
},
{
"code": null,
"e": 58234,
"s": 58153,
"text": "The following examples illustrate some of the above-mentioned string functions −"
},
{
"code": null,
"e": 58293,
"s": 58234,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 58375,
"s": 58293,
"text": "A = pi*1000*ones(1,5);\nsprintf(' %f \\n %.2f \\n %+.2f \\n %12.2f \\n %012.2f \\n', A)"
},
{
"code": null,
"e": 58433,
"s": 58375,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 58511,
"s": 58433,
"text": "ans = 3141.592654 \n 3141.59 \n +3141.59 \n 3141.59 \n 000003141.59 \n"
},
{
"code": null,
"e": 58570,
"s": 58511,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 58760,
"s": 58570,
"text": "%cell array of strings\nstr_array = {'red','blue','green', 'yellow', 'orange'};\n\n% Join strings in cell array into single string\nstr1 = strjoin(str_array, \"-\")\nstr2 = strjoin(str_array, \",\")"
},
{
"code": null,
"e": 58818,
"s": 58760,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 58891,
"s": 58818,
"text": "str1 = red-blue-green-yellow-orange\nstr2 = red,blue,green,yellow,orange\n"
},
{
"code": null,
"e": 58950,
"s": 58891,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 59341,
"s": 58950,
"text": "students = {'Zara Ali', 'Neha Bhatnagar', ...\n 'Monica Malik', 'Madhu Gautam', ...\n 'Madhu Sharma', 'Bhawna Sharma',...\n 'Nuha Ali', 'Reva Dutta', ...\n 'Sunaina Ali', 'Sofia Kabir'};\n \n% The strrep function searches and replaces sub-string.\nnew_student = strrep(students(8), 'Reva', 'Poulomi')\n% Display first names\nfirst_names = strtok(students)"
},
{
"code": null,
"e": 59399,
"s": 59341,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 59634,
"s": 59399,
"text": "new_student = \n{\n [1,1] = Poulomi Dutta\n}\nfirst_names = \n{\n [1,1] = Zara\n [1,2] = Neha\n [1,3] = Monica\n [1,4] = Madhu\n [1,5] = Madhu\n [1,6] = Bhawna\n [1,7] = Nuha\n [1,8] = Reva\n [1,9] = Sunaina\n [1,10] = Sofia\n}\n"
},
{
"code": null,
"e": 59693,
"s": 59634,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 59866,
"s": 59693,
"text": "str1 = 'This is test'\nstr2 = 'This is text'\nif (strcmp(str1, str2))\n sprintf('%s and %s are equal', str1, str2)\nelse\n sprintf('%s and %s are not equal', str1, str2)\nend"
},
{
"code": null,
"e": 59924,
"s": 59866,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 60015,
"s": 59924,
"text": "str1 = This is test\nstr2 = This is text\nans = This is test and This is text are not equal\n"
},
{
"code": null,
"e": 60194,
"s": 60015,
"text": "A function is a group of statements that together perform a task. In MATLAB, functions are defined in separate files. The name of the file and of the function should be the same."
},
{
"code": null,
"e": 60399,
"s": 60194,
"text": "Functions operate on variables within their own workspace, which is also called the local workspace, separate from the workspace you access at the MATLAB command prompt which is called the base workspace."
},
{
"code": null,
"e": 60497,
"s": 60399,
"text": "Functions can accept more than one input arguments and may return more than one output arguments."
},
{
"code": null,
"e": 60533,
"s": 60497,
"text": "Syntax of a function statement is −"
},
{
"code": null,
"e": 60597,
"s": 60533,
"text": "function [out1,out2, ..., outN] = myfun(in1,in2,in3, ..., inN)\n"
},
{
"code": null,
"e": 60749,
"s": 60597,
"text": "The following function named mymax should be written in a file named mymax.m. It takes five numbers as argument and returns the maximum of the numbers."
},
{
"code": null,
"e": 60823,
"s": 60749,
"text": "Create a function file, named mymax.m and type the following code in it −"
},
{
"code": null,
"e": 61071,
"s": 60823,
"text": "function max = mymax(n1, n2, n3, n4, n5)\n\n%This function calculates the maximum of the\n% five numbers given as input\nmax = n1;\nif(n2 > max)\n max = n2;\nend\nif(n3 > max)\n max = n3;\nend\nif(n4 > max)\n max = n4;\nend\nif(n5 > max)\n max = n5;\nend"
},
{
"code": null,
"e": 61277,
"s": 61071,
"text": "The first line of a function starts with the keyword function. It gives the name of the function and order of arguments. In our example, the mymax function has five input arguments and one output argument."
},
{
"code": null,
"e": 61403,
"s": 61277,
"text": "The comment lines that come right after the function statement provide the help text. These lines are printed when you type −"
},
{
"code": null,
"e": 61415,
"s": 61403,
"text": "help mymax\n"
},
{
"code": null,
"e": 61489,
"s": 61415,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 61565,
"s": 61489,
"text": "This function calculates the maximum of the\n five numbers given as input\n"
},
{
"code": null,
"e": 61596,
"s": 61565,
"text": "You can call the function as −"
},
{
"code": null,
"e": 61623,
"s": 61596,
"text": "mymax(34, 78, 89, 23, 11)\n"
},
{
"code": null,
"e": 61697,
"s": 61623,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 61707,
"s": 61697,
"text": "ans = 89\n"
},
{
"code": null,
"e": 61924,
"s": 61707,
"text": "An anonymous function is like an inline function in traditional programming languages, defined within a single MATLAB statement. It consists of a single MATLAB expression and any number of input and output arguments."
},
{
"code": null,
"e": 62026,
"s": 61924,
"text": "You can define an anonymous function right at the MATLAB command line or within a function or script."
},
{
"code": null,
"e": 62109,
"s": 62026,
"text": "This way you can create simple functions without having to create a file for them."
},
{
"code": null,
"e": 62177,
"s": 62109,
"text": "The syntax for creating an anonymous function from an expression is"
},
{
"code": null,
"e": 62203,
"s": 62177,
"text": "f = @(arglist)expression\n"
},
{
"code": null,
"e": 62372,
"s": 62203,
"text": "In this example, we will write an anonymous function named power, which will take two numbers as input and return first number raised to the power of the second number."
},
{
"code": null,
"e": 62429,
"s": 62372,
"text": "Create a script file and type the following code in it −"
},
{
"code": null,
"e": 62550,
"s": 62429,
"text": "power = @(x, n) x.^n;\nresult1 = power(7, 3)\nresult2 = power(49, 0.5)\nresult3 = power(10, -10)\nresult4 = power (4.5, 1.5)"
},
{
"code": null,
"e": 62587,
"s": 62550,
"text": "When you run the file, it displays −"
},
{
"code": null,
"e": 62656,
"s": 62587,
"text": "result1 = 343\nresult2 = 7\nresult3 = 1.0000e-10\nresult4 = 9.5459\n"
},
{
"code": null,
"e": 62903,
"s": 62656,
"text": "Any function other than an anonymous function must be defined within a file. Each function file contains a required primary function that appears first and any number of optional sub-functions that comes after the primary function and used by it."
},
{
"code": null,
"e": 63129,
"s": 62903,
"text": "Primary functions can be called from outside of the file that defines them, either from command line or from other functions, but sub-functions cannot be called from command line or other functions, outside the function file."
},
{
"code": null,
"e": 63252,
"s": 63129,
"text": "Sub-functions are visible only to the primary function and other sub-functions within the function file that defines them."
},
{
"code": null,
"e": 63488,
"s": 63252,
"text": "Let us write a function named quadratic that would calculate the roots of a quadratic equation. The function would take three inputs, the quadratic co-efficient, the linear co-efficient and the constant term. It would return the roots."
},
{
"code": null,
"e": 63624,
"s": 63488,
"text": "The function file quadratic.m will contain the primary function quadratic and the sub-function disc, which calculates the discriminant."
},
{
"code": null,
"e": 63695,
"s": 63624,
"text": "Create a function file quadratic.m and type the following code in it −"
},
{
"code": null,
"e": 64117,
"s": 63695,
"text": "function [x1,x2] = quadratic(a,b,c)\n\n%this function returns the roots of \n% a quadratic equation.\n% It takes 3 input arguments\n% which are the co-efficients of x2, x and the \n%constant term\n% It returns the roots\nd = disc(a,b,c); \nx1 = (-b + d) / (2*a);\nx2 = (-b - d) / (2*a);\nend % end of quadratic\n\nfunction dis = disc(a,b,c) \n%function calculates the discriminant\ndis = sqrt(b^2 - 4*a*c);\nend % end of sub-function"
},
{
"code": null,
"e": 64174,
"s": 64117,
"text": "You can call the above function from command prompt as −"
},
{
"code": null,
"e": 64192,
"s": 64174,
"text": "quadratic(2,4,-4)"
},
{
"code": null,
"e": 64266,
"s": 64192,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 64280,
"s": 64266,
"text": "ans = 0.7321\n"
},
{
"code": null,
"e": 64456,
"s": 64280,
"text": "You can define functions within the body of another function. These are called nested functions. A nested function contains any or all of the components of any other function."
},
{
"code": null,
"e": 64584,
"s": 64456,
"text": "Nested functions are defined within the scope of another function and they share access to the containing function's workspace."
},
{
"code": null,
"e": 64633,
"s": 64584,
"text": "A nested function follows the following syntax −"
},
{
"code": null,
"e": 64711,
"s": 64633,
"text": "function x = A(p1, p2)\n...\nB(p2)\n function y = B(p3)\n ...\n end\n...\nend\n"
},
{
"code": null,
"e": 64837,
"s": 64711,
"text": "Let us rewrite the function quadratic, from previous example, however, this time the disc function will be a nested function."
},
{
"code": null,
"e": 64909,
"s": 64837,
"text": "Create a function file quadratic2.m and type the following code in it −"
},
{
"code": null,
"e": 65119,
"s": 64909,
"text": "function [x1,x2] = quadratic2(a,b,c)\nfunction disc % nested function\nd = sqrt(b^2 - 4*a*c);\nend % end of function disc\n\ndisc;\nx1 = (-b + d) / (2*a);\nx2 = (-b - d) / (2*a);\nend % end of function quadratic2"
},
{
"code": null,
"e": 65176,
"s": 65119,
"text": "You can call the above function from command prompt as −"
},
{
"code": null,
"e": 65195,
"s": 65176,
"text": "quadratic2(2,4,-4)"
},
{
"code": null,
"e": 65269,
"s": 65195,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 65285,
"s": 65269,
"text": "ans = 0.73205\n"
},
{
"code": null,
"e": 65494,
"s": 65285,
"text": "A private function is a primary function that is visible only to a limited group of other functions. If you do not want to expose the implementation of a function(s), you can create them as private functions."
},
{
"code": null,
"e": 65564,
"s": 65494,
"text": "Private functions reside in subfolders with the special name private."
},
{
"code": null,
"e": 65621,
"s": 65564,
"text": "They are visible only to functions in the parent folder."
},
{
"code": null,
"e": 65756,
"s": 65621,
"text": "Let us rewrite the quadratic function. This time, however, the disc function calculating the discriminant, will be a private function."
},
{
"code": null,
"e": 65860,
"s": 65756,
"text": "Create a subfolder named private in working directory. Store the following function file disc.m in it −"
},
{
"code": null,
"e": 65982,
"s": 65860,
"text": "function dis = disc(a,b,c) \n%function calculates the discriminant\ndis = sqrt(b^2 - 4*a*c);\nend % end of sub-function"
},
{
"code": null,
"e": 66075,
"s": 65982,
"text": "Create a function quadratic3.m in your working directory and type the following code in it −"
},
{
"code": null,
"e": 66382,
"s": 66075,
"text": "function [x1,x2] = quadratic3(a,b,c)\n\n%this function returns the roots of \n% a quadratic equation.\n% It takes 3 input arguments\n% which are the co-efficient of x2, x and the \n%constant term\n% It returns the roots\nd = disc(a,b,c); \n\nx1 = (-b + d) / (2*a);\nx2 = (-b - d) / (2*a);\nend % end of quadratic3"
},
{
"code": null,
"e": 66439,
"s": 66382,
"text": "You can call the above function from command prompt as −"
},
{
"code": null,
"e": 66458,
"s": 66439,
"text": "quadratic3(2,4,-4)"
},
{
"code": null,
"e": 66532,
"s": 66458,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 66548,
"s": 66532,
"text": "ans = 0.73205\n"
},
{
"code": null,
"e": 66681,
"s": 66548,
"text": "Global variables can be shared by more than one function. For this, you need to declare the variable as global in all the functions."
},
{
"code": null,
"e": 66789,
"s": 66681,
"text": "If you want to access that variable from the base workspace, then declare the variable at the command line."
},
{
"code": null,
"e": 66996,
"s": 66789,
"text": "The global declaration must occur before the variable is actually used in a function. It is a good practice to use capital letters for the names of global variables to distinguish them from other variables."
},
{
"code": null,
"e": 67078,
"s": 66996,
"text": "Let us create a function file named average.m and type the following code in it −"
},
{
"code": null,
"e": 67147,
"s": 67078,
"text": "function avg = average(nums)\nglobal TOTAL\navg = sum(nums)/TOTAL;\nend"
},
{
"code": null,
"e": 67204,
"s": 67147,
"text": "Create a script file and type the following code in it −"
},
{
"code": null,
"e": 67292,
"s": 67204,
"text": "global TOTAL;\nTOTAL = 10;\nn = [34, 45, 25, 45, 33, 19, 40, 34, 38, 42];\nav = average(n)"
},
{
"code": null,
"e": 67354,
"s": 67292,
"text": "When you run the file, it will display the following result −"
},
{
"code": null,
"e": 67368,
"s": 67354,
"text": "av = 35.500\n"
},
{
"code": null,
"e": 67549,
"s": 67368,
"text": "Importing data in MATLAB means loading data from an external file. The importdata function allows loading various data files of different formats. It has the following five forms −"
},
{
"code": null,
"e": 67574,
"s": 67549,
"text": "A = importdata(filename)"
},
{
"code": null,
"e": 67633,
"s": 67574,
"text": "Loads data into array A from the file denoted by filename."
},
{
"code": null,
"e": 67665,
"s": 67633,
"text": "A = importdata('-pastespecial')"
},
{
"code": null,
"e": 67727,
"s": 67665,
"text": "Loads data from the system clipboard rather than from a file."
},
{
"code": null,
"e": 67760,
"s": 67727,
"text": "A = importdata(___, delimiterIn)"
},
{
"code": null,
"e": 67934,
"s": 67760,
"text": "Interprets delimiterIn as the column separator in ASCII file, filename, or the clipboard data. You can use delimiterIn with any of the input arguments in the above syntaxes."
},
{
"code": null,
"e": 67982,
"s": 67934,
"text": "A = importdata(___, delimiterIn, headerlinesIn)"
},
{
"code": null,
"e": 68095,
"s": 67982,
"text": "Loads data from ASCII file, filename, or the clipboard, reading numeric data starting from line headerlinesIn+1."
},
{
"code": null,
"e": 68147,
"s": 68095,
"text": "[A, delimiterOut, headerlinesOut] = importdata(___)"
},
{
"code": null,
"e": 68347,
"s": 68147,
"text": "Returns the detected delimiter character for the input ASCII file in delimiterOut and the detected number of header lines in headerlinesOut, using any of the input arguments in the previous syntaxes."
},
{
"code": null,
"e": 68443,
"s": 68347,
"text": "Let us load and display an image file. Create a script file and type the following code in it −"
},
{
"code": null,
"e": 68503,
"s": 68443,
"text": "filename = 'smile.jpg';\nA = importdata(filename);\nimage(A);"
},
{
"code": null,
"e": 68611,
"s": 68503,
"text": "When you run the file, MATLAB displays the image file. However, you must store it in the current directory."
},
{
"code": null,
"e": 68777,
"s": 68611,
"text": "In this example, we import a text file and specify Delimiter and Column Header. Let us create a space-delimited ASCII file with column headers, named weeklydata.txt."
},
{
"code": null,
"e": 68824,
"s": 68777,
"text": "Our text file weeklydata.txt looks like this −"
},
{
"code": null,
"e": 69188,
"s": 68824,
"text": "SunDay MonDay TuesDay WednesDay ThursDay FriDay SaturDay\n95.01 76.21 61.54 40.57 55.79 70.28 81.53\n73.11 45.65 79.19 93.55 75.29 69.87 74.68\n60.68 41.85 92.18 91.69 81.32 90.38 74.51\n48.60 82.14 73.82 41.03 0.99 67.22 93.18\n89.13 44.47 57.63 89.36 13.89 19.88 46.60\n"
},
{
"code": null,
"e": 69245,
"s": 69188,
"text": "Create a script file and type the following code in it −"
},
{
"code": null,
"e": 69458,
"s": 69245,
"text": "filename = 'weeklydata.txt';\ndelimiterIn = ' ';\nheaderlinesIn = 1;\nA = importdata(filename,delimiterIn,headerlinesIn);\n\n% View data\nfor k = [1:7]\n disp(A.colheaders{1, k})\n disp(A.data(:, k))\n disp(' ')\nend"
},
{
"code": null,
"e": 69516,
"s": 69458,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 69968,
"s": 69516,
"text": "SunDay\n 95.0100\n 73.1100\n 60.6800\n 48.6000\n 89.1300\n \nMonDay\n 76.2100\n 45.6500\n 41.8500\n 82.1400\n 44.4700\n \nTuesDay\n 61.5400\n 79.1900\n 92.1800\n 73.8200\n 57.6300\n\nWednesDay\n 40.5700\n 93.5500\n 91.6900\n 41.0300\n 89.3600\n \nThursDay\n 55.7900\n 75.2900\n 81.3200\n 0.9900\n 13.8900\n \nFriDay\n 70.2800\n 69.8700\n 90.3800\n 67.2200\n 19.8800\n\nSaturDay\n 81.5300\n 74.6800\n 74.5100\n 93.1800\n 46.6000\n"
},
{
"code": null,
"e": 70020,
"s": 69968,
"text": "In this example, let us import data from clipboard."
},
{
"code": null,
"e": 70064,
"s": 70020,
"text": "Copy the following lines to the clipboard −"
},
{
"code": null,
"e": 70086,
"s": 70064,
"text": "Mathematics is simple"
},
{
"code": null,
"e": 70137,
"s": 70086,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 70170,
"s": 70137,
"text": "A = importdata('-pastespecial')\n"
},
{
"code": null,
"e": 70228,
"s": 70170,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 70261,
"s": 70228,
"text": "A = \n 'Mathematics is simple'\n"
},
{
"code": null,
"e": 70510,
"s": 70261,
"text": "The importdata function is a high-level function. The low-level file I/O functions in MATLAB allow the most control over reading or writing data to a file. However, these functions need more detailed information about your file to work efficiently."
},
{
"code": null,
"e": 70613,
"s": 70510,
"text": "MATLAB provides the following functions for read and write operations at the byte or character level −"
},
{
"code": null,
"e": 70695,
"s": 70613,
"text": "MATLAB provides the following functions for low-level import of text data files −"
},
{
"code": null,
"e": 70761,
"s": 70695,
"text": "The fscanf function reads formatted data in a text or ASCII file."
},
{
"code": null,
"e": 70827,
"s": 70761,
"text": "The fscanf function reads formatted data in a text or ASCII file."
},
{
"code": null,
"e": 70939,
"s": 70827,
"text": "The fgetl and fgets functions read one line of a file at a time, where a newline character separates each line."
},
{
"code": null,
"e": 71051,
"s": 70939,
"text": "The fgetl and fgets functions read one line of a file at a time, where a newline character separates each line."
},
{
"code": null,
"e": 71120,
"s": 71051,
"text": "The fread function reads a stream of data at the byte or bit level. "
},
{
"code": null,
"e": 71189,
"s": 71120,
"text": "The fread function reads a stream of data at the byte or bit level. "
},
{
"code": null,
"e": 71349,
"s": 71189,
"text": "We have a text data file 'myfile.txt' saved in our working directory. The file stores rainfall data for three months; June, July and August for the year 2012. "
},
{
"code": null,
"e": 71534,
"s": 71349,
"text": "The data in myfile.txt contains repeated sets of time, month and rainfall measurements at five places. The header data stores the number of months M; so we have M sets of measurements."
},
{
"code": null,
"e": 71561,
"s": 71534,
"text": "The file looks like this −"
},
{
"code": null,
"e": 72364,
"s": 71561,
"text": "Rainfall Data\nMonths: June, July, August\n \nM = 3\n12:00:00\nJune-2012\n17.21 28.52 39.78 16.55 23.67\n19.15 0.35 17.57 NaN 12.01\n17.92 28.49 17.40 17.06 11.09\n9.59 9.33 NaN 0.31 0.23 \n10.46 13.17 NaN 14.89 19.33\n20.97 19.50 17.65 14.45 14.00\n18.23 10.34 17.95 16.46 19.34\n09:10:02\nJuly-2012\n12.76 16.94 14.38 11.86 16.89\n20.46 23.17 NaN 24.89 19.33\n30.97 49.50 47.65 24.45 34.00\n18.23 30.34 27.95 16.46 19.34\n30.46 33.17 NaN 34.89 29.33\n30.97 49.50 47.65 24.45 34.00\n28.67 30.34 27.95 36.46 29.34\n15:03:40\nAugust-2012\n17.09 16.55 19.59 17.25 19.22\n17.54 11.45 13.48 22.55 24.01\nNaN 21.19 25.85 25.05 27.21\n26.79 24.98 12.23 16.99 18.67\n17.54 11.45 13.48 22.55 24.01\nNaN 21.19 25.85 25.05 27.21\n26.79 24.98 12.23 16.99 18.67\n"
},
{
"code": null,
"e": 72449,
"s": 72364,
"text": "We will import data from this file and display this data. Take the following steps −"
},
{
"code": null,
"e": 72513,
"s": 72449,
"text": "Open the file with fopen function and get the file identifier. "
},
{
"code": null,
"e": 72577,
"s": 72513,
"text": "Open the file with fopen function and get the file identifier. "
},
{
"code": null,
"e": 72716,
"s": 72577,
"text": "Describe the data in the file with format specifiers, such as '%s' for a string, '%d' for an integer, or '%f' for a floating-point number."
},
{
"code": null,
"e": 72855,
"s": 72716,
"text": "Describe the data in the file with format specifiers, such as '%s' for a string, '%d' for an integer, or '%f' for a floating-point number."
},
{
"code": null,
"e": 73135,
"s": 72855,
"text": "To skip literal characters in the file, include them in the format description. To skip a data field, use an asterisk ('*') in the specifier.\nFor example, to read the headers and return the single value for M, we write −\nM = fscanf(fid, '%*s %*s\\n%*s %*s %*s %*s\\nM=%d\\n\\n', 1);\n"
},
{
"code": null,
"e": 73277,
"s": 73135,
"text": "To skip literal characters in the file, include them in the format description. To skip a data field, use an asterisk ('*') in the specifier."
},
{
"code": null,
"e": 73356,
"s": 73277,
"text": "For example, to read the headers and return the single value for M, we write −"
},
{
"code": null,
"e": 73414,
"s": 73356,
"text": "M = fscanf(fid, '%*s %*s\\n%*s %*s %*s %*s\\nM=%d\\n\\n', 1);"
},
{
"code": null,
"e": 73665,
"s": 73414,
"text": "By default, fscanf reads data according to our format description until it does not find any match for the data, or it reaches the end of the file. Here we will use for loop for reading 3 sets of data and each time, it will read 7 rows and 5 columns."
},
{
"code": null,
"e": 73916,
"s": 73665,
"text": "By default, fscanf reads data according to our format description until it does not find any match for the data, or it reaches the end of the file. Here we will use for loop for reading 3 sets of data and each time, it will read 7 rows and 5 columns."
},
{
"code": null,
"e": 74074,
"s": 73916,
"text": "We will create a structure named mydata in the workspace to store data read from the file. This structure has three fields - time, month, and raindata array."
},
{
"code": null,
"e": 74232,
"s": 74074,
"text": "We will create a structure named mydata in the workspace to store data read from the file. This structure has three fields - time, month, and raindata array."
},
{
"code": null,
"e": 74289,
"s": 74232,
"text": "Create a script file and type the following code in it −"
},
{
"code": null,
"e": 74895,
"s": 74289,
"text": "filename = '/data/myfile.txt';\nrows = 7;\ncols = 5;\n \n% open the file\nfid = fopen(filename);\n \n% read the file headers, find M (number of months)\nM = fscanf(fid, '%*s %*s\\n%*s %*s %*s %*s\\nM=%d\\n\\n', 1);\n \n% read each set of measurements\nfor n = 1:M\n mydata(n).time = fscanf(fid, '%s', 1);\n mydata(n).month = fscanf(fid, '%s', 1);\n \n % fscanf fills the array in column order,\n % so transpose the results\n mydata(n).raindata = ...\n fscanf(fid, '%f', [rows, cols]);\nend\nfor n = 1:M\n disp(mydata(n).time), disp(mydata(n).month)\n disp(mydata(n).raindata)\nend\n \n% close the file\nfclose(fid);"
},
{
"code": null,
"e": 74953,
"s": 74895,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 76085,
"s": 74953,
"text": "12:00:00\nJune-2012\n 17.2100 17.5700 11.0900 13.1700 14.4500\n 28.5200 NaN 9.5900 NaN 14.0000\n 39.7800 12.0100 9.3300 14.8900 18.2300\n 16.5500 17.9200 NaN 19.3300 10.3400\n 23.6700 28.4900 0.3100 20.9700 17.9500\n 19.1500 17.4000 0.2300 19.5000 16.4600\n 0.3500 17.0600 10.4600 17.6500 19.3400\n\n09:10:02\nJuly-2012\n 12.7600 NaN 34.0000 33.1700 24.4500\n 16.9400 24.8900 18.2300 NaN 34.0000\n 14.3800 19.3300 30.3400 34.8900 28.6700\n 11.8600 30.9700 27.9500 29.3300 30.3400\n 16.8900 49.5000 16.4600 30.9700 27.9500\n 20.4600 47.6500 19.3400 49.5000 36.4600\n 23.1700 24.4500 30.4600 47.6500 29.3400\n\n15:03:40\nAugust-2012\n 17.0900 13.4800 27.2100 11.4500 25.0500\n 16.5500 22.5500 26.7900 13.4800 27.2100\n 19.5900 24.0100 24.9800 22.5500 26.7900\n 17.2500 NaN 12.2300 24.0100 24.9800\n 19.2200 21.1900 16.9900 NaN 12.2300\n 17.5400 25.8500 18.6700 21.1900 16.9900\n 11.4500 25.0500 17.5400 25.8500 18.6700\n"
},
{
"code": null,
"e": 76283,
"s": 76085,
"text": "Data export (or output) in MATLAB means to write into files. MATLAB allows you to use your data in another application that reads ASCII files. For this, MATLAB provides several data export options."
},
{
"code": null,
"e": 76328,
"s": 76283,
"text": "You can create the following type of files −"
},
{
"code": null,
"e": 76382,
"s": 76328,
"text": "Rectangular, delimited ASCII data file from an array."
},
{
"code": null,
"e": 76436,
"s": 76382,
"text": "Rectangular, delimited ASCII data file from an array."
},
{
"code": null,
"e": 76501,
"s": 76436,
"text": "Diary (or log) file of keystrokes and the resulting text output."
},
{
"code": null,
"e": 76566,
"s": 76501,
"text": "Diary (or log) file of keystrokes and the resulting text output."
},
{
"code": null,
"e": 76632,
"s": 76566,
"text": "Specialized ASCII file using low-level functions such as fprintf."
},
{
"code": null,
"e": 76698,
"s": 76632,
"text": "Specialized ASCII file using low-level functions such as fprintf."
},
{
"code": null,
"e": 76793,
"s": 76698,
"text": "MEX-file to access your C/C++ or Fortran routine that writes to a particular text file format."
},
{
"code": null,
"e": 76888,
"s": 76793,
"text": "MEX-file to access your C/C++ or Fortran routine that writes to a particular text file format."
},
{
"code": null,
"e": 76947,
"s": 76888,
"text": "Apart from this, you can also export data to spreadsheets."
},
{
"code": null,
"e": 77025,
"s": 76947,
"text": "There are two ways to export a numeric array as a delimited ASCII data file −"
},
{
"code": null,
"e": 77085,
"s": 77025,
"text": "Using the save function and specifying the -ascii qualifier"
},
{
"code": null,
"e": 77145,
"s": 77085,
"text": "Using the save function and specifying the -ascii qualifier"
},
{
"code": null,
"e": 77173,
"s": 77145,
"text": "Using the dlmwrite function"
},
{
"code": null,
"e": 77201,
"s": 77173,
"text": "Using the dlmwrite function"
},
{
"code": null,
"e": 77241,
"s": 77201,
"text": "Syntax for using the save function is −"
},
{
"code": null,
"e": 77276,
"s": 77241,
"text": "save my_data.out num_array -ascii\n"
},
{
"code": null,
"e": 77396,
"s": 77276,
"text": "where, my_data.out is the delimited ASCII data file created, num_array is a numeric array and −ascii is the specifier."
},
{
"code": null,
"e": 77440,
"s": 77396,
"text": "Syntax for using the dlmwrite function is −"
},
{
"code": null,
"e": 77488,
"s": 77440,
"text": "dlmwrite('my_data.out', num_array, 'dlm_char')\n"
},
{
"code": null,
"e": 77620,
"s": 77488,
"text": "where, my_data.out is the delimited ASCII data file created, num_array is a numeric array and dlm_char is the delimiter character."
},
{
"code": null,
"e": 77719,
"s": 77620,
"text": "The following example demonstrates the concept. Create a script file and type the following code −"
},
{
"code": null,
"e": 77888,
"s": 77719,
"text": "num_array = [ 1 2 3 4 ; 4 5 6 7; 7 8 9 0];\nsave array_data1.out num_array -ascii;\ntype array_data1.out\ndlmwrite('array_data2.out', num_array, ' ');\ntype array_data2.out"
},
{
"code": null,
"e": 77946,
"s": 77888,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 78167,
"s": 77946,
"text": " 1.0000000e+00 2.0000000e+00 3.0000000e+00 4.0000000e+00\n 4.0000000e+00 5.0000000e+00 6.0000000e+00 7.0000000e+00\n 7.0000000e+00 8.0000000e+00 9.0000000e+00 0.0000000e+00\n\n1 2 3 4\n4 5 6 7\n7 8 9 0\n"
},
{
"code": null,
"e": 78351,
"s": 78167,
"text": "Please note that the save -ascii command and the dlmwrite function does not work with cell arrays as input. To create a delimited ASCII file from the contents of a cell array, you can"
},
{
"code": null,
"e": 78422,
"s": 78351,
"text": "Either, convert the cell array to a matrix using the cell2mat function"
},
{
"code": null,
"e": 78493,
"s": 78422,
"text": "Either, convert the cell array to a matrix using the cell2mat function"
},
{
"code": null,
"e": 78554,
"s": 78493,
"text": "Or export the cell array using low-level file I/O functions."
},
{
"code": null,
"e": 78615,
"s": 78554,
"text": "Or export the cell array using low-level file I/O functions."
},
{
"code": null,
"e": 78751,
"s": 78615,
"text": "If you use the save function to write a character array to an ASCII file, it writes the ASCII equivalent of the characters to the file."
},
{
"code": null,
"e": 78806,
"s": 78751,
"text": "For example, let us write the word 'hello' to a file −"
},
{
"code": null,
"e": 78864,
"s": 78806,
"text": "h = 'hello';\nsave textdata.out h -ascii\ntype textdata.out"
},
{
"code": null,
"e": 79007,
"s": 78864,
"text": "MATLAB executes the above statements and displays the following result. which is the characters of the string 'hello' in 8-digit ASCII format."
},
{
"code": null,
"e": 79086,
"s": 79007,
"text": "1.0400000e+02 1.0100000e+02 1.0800000e+02 1.0800000e+02 1.1100000e+02\n"
},
{
"code": null,
"e": 79233,
"s": 79086,
"text": "Diary files are activity logs of your MATLAB session. The diary function creates an exact copy of your session in a disk file, excluding graphics."
},
{
"code": null,
"e": 79271,
"s": 79233,
"text": "To turn on the diary function, type −"
},
{
"code": null,
"e": 79277,
"s": 79271,
"text": "diary"
},
{
"code": null,
"e": 79335,
"s": 79277,
"text": " Optionally, you can give the name of the log file, say −"
},
{
"code": null,
"e": 79354,
"s": 79335,
"text": "diary logdata.out\n"
},
{
"code": null,
"e": 79387,
"s": 79354,
"text": "To turn off the diary function −"
},
{
"code": null,
"e": 79398,
"s": 79387,
"text": "diary off\n"
},
{
"code": null,
"e": 79444,
"s": 79398,
"text": "You can open the diary file in a text editor."
},
{
"code": null,
"e": 79728,
"s": 79444,
"text": "So far, we have exported numeric arrays. However, you may need to create other text files, including combinations of numeric and character data, nonrectangular output files, or files with non-ASCII encoding schemes. For these purposes, MATLAB provides the low-level fprintf function."
},
{
"code": null,
"e": 79997,
"s": 79728,
"text": "As in low-level I/O file activities, before exporting, you need to open or create a file with the fopen function and get the file identifier. By default, fopen opens a file for read-only access. You should specify the permission to write or append, such as 'w' or 'a'."
},
{
"code": null,
"e": 80072,
"s": 79997,
"text": "After processing the file, you need to close it with fclose(fid) function."
},
{
"code": null,
"e": 80121,
"s": 80072,
"text": "The following example demonstrates the concept −"
},
{
"code": null,
"e": 80178,
"s": 80121,
"text": "Create a script file and type the following code in it −"
},
{
"code": null,
"e": 80528,
"s": 80178,
"text": "% create a matrix y, with two rows\nx = 0:10:100;\ny = [x; log(x)];\n \n% open a file for writing\nfid = fopen('logtable.txt', 'w');\n \n% Table Header\nfprintf(fid, 'Log Function\\n\\n');\n \n% print values in column order\n% two values appear on each row of the file\nfprintf(fid, '%f %f\\n', y);\nfclose(fid);\n\n% display the file created\ntype logtable.txt"
},
{
"code": null,
"e": 80586,
"s": 80528,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 80847,
"s": 80586,
"text": "Log Function\n\n0.000000 -Inf\n10.000000 2.302585\n20.000000 2.995732\n30.000000 3.401197\n40.000000 3.688879\n50.000000 3.912023\n60.000000 4.094345\n70.000000 4.248495\n80.000000 4.382027\n90.000000 4.499810\n100.000000 4.605170\n"
},
{
"code": null,
"e": 80919,
"s": 80847,
"text": "To plot the graph of a function, you need to take the following steps −"
},
{
"code": null,
"e": 81023,
"s": 80919,
"text": "Define x, by specifying the range of values for the variable x, for which the function is to be plotted"
},
{
"code": null,
"e": 81127,
"s": 81023,
"text": "Define x, by specifying the range of values for the variable x, for which the function is to be plotted"
},
{
"code": null,
"e": 81157,
"s": 81127,
"text": "Define the function, y = f(x)"
},
{
"code": null,
"e": 81187,
"s": 81157,
"text": "Define the function, y = f(x)"
},
{
"code": null,
"e": 81224,
"s": 81187,
"text": "Call the plot command, as plot(x, y)"
},
{
"code": null,
"e": 81261,
"s": 81224,
"text": "Call the plot command, as plot(x, y)"
},
{
"code": null,
"e": 81417,
"s": 81261,
"text": "Following example would demonstrate the concept. Let us plot the simple function y = x for the range of values for x from 0 to 100, with an increment of 5."
},
{
"code": null,
"e": 81468,
"s": 81417,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 81501,
"s": 81468,
"text": "x = [0:5:100];\ny = x;\nplot(x, y)"
},
{
"code": null,
"e": 81561,
"s": 81501,
"text": "When you run the file, MATLAB displays the following plot −"
},
{
"code": null,
"e": 81818,
"s": 81561,
"text": "Let us take one more example to plot the function y = x2. In this example, we will draw two graphs with the same function, but in second time, we will reduce the value of increment. Please note that as we decrease the increment, the graph becomes smoother."
},
{
"code": null,
"e": 81869,
"s": 81818,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 81937,
"s": 81869,
"text": "x = [1 2 3 4 5 6 7 8 9 10];\nx = [-100:20:100];\ny = x.^2;\nplot(x, y)"
},
{
"code": null,
"e": 81997,
"s": 81937,
"text": "When you run the file, MATLAB displays the following plot −"
},
{
"code": null,
"e": 82056,
"s": 81997,
"text": "Change the code file a little, reduce the increment to 5 −"
},
{
"code": null,
"e": 82095,
"s": 82056,
"text": "x = [-100:5:100];\ny = x.^2;\nplot(x, y)"
},
{
"code": null,
"e": 82127,
"s": 82095,
"text": "MATLAB draws a smoother graph −"
},
{
"code": null,
"e": 82258,
"s": 82127,
"text": "MATLAB allows you to add title, labels along the x-axis and y-axis, grid lines and also to adjust the axes to spruce up the graph."
},
{
"code": null,
"e": 82330,
"s": 82258,
"text": "The xlabel and ylabel commands generate labels along x-axis and y-axis."
},
{
"code": null,
"e": 82402,
"s": 82330,
"text": "The xlabel and ylabel commands generate labels along x-axis and y-axis."
},
{
"code": null,
"e": 82460,
"s": 82402,
"text": "The title command allows you to put a title on the graph."
},
{
"code": null,
"e": 82518,
"s": 82460,
"text": "The title command allows you to put a title on the graph."
},
{
"code": null,
"e": 82585,
"s": 82518,
"text": "The grid on command allows you to put the grid lines on the graph."
},
{
"code": null,
"e": 82652,
"s": 82585,
"text": "The grid on command allows you to put the grid lines on the graph."
},
{
"code": null,
"e": 82759,
"s": 82652,
"text": "The axis equal command allows generating the plot with the same scale factors and the spaces on both axes."
},
{
"code": null,
"e": 82866,
"s": 82759,
"text": "The axis equal command allows generating the plot with the same scale factors and the spaces on both axes."
},
{
"code": null,
"e": 82915,
"s": 82866,
"text": "The axis square command generates a square plot."
},
{
"code": null,
"e": 82964,
"s": 82915,
"text": "The axis square command generates a square plot."
},
{
"code": null,
"e": 83015,
"s": 82964,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 83130,
"s": 83015,
"text": "x = [0:0.01:10];\ny = sin(x);\nplot(x, y), xlabel('x'), ylabel('Sin(x)'), title('Sin(x) Graph'),\ngrid on, axis equal"
},
{
"code": null,
"e": 83169,
"s": 83130,
"text": "MATLAB generates the following graph −"
},
{
"code": null,
"e": 83265,
"s": 83169,
"text": "You can draw multiple graphs on the same plot. The following example demonstrates the concept −"
},
{
"code": null,
"e": 83316,
"s": 83265,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 83411,
"s": 83316,
"text": "x = [0 : 0.01: 10];\ny = sin(x);\ng = cos(x);\nplot(x, y, x, g, '.-'), legend('Sin(x)', 'Cos(x)')"
},
{
"code": null,
"e": 83450,
"s": 83411,
"text": "MATLAB generates the following graph −"
},
{
"code": null,
"e": 83567,
"s": 83450,
"text": "MATLAB provides eight basic color options for drawing graphs. The following table shows the colors and their codes −"
},
{
"code": null,
"e": 83608,
"s": 83567,
"text": "Let us draw the graph of two polynomials"
},
{
"code": null,
"e": 83643,
"s": 83608,
"text": "f(x) = 3x4 + 2x3+ 7x2 + 2x + 9 and"
},
{
"code": null,
"e": 83678,
"s": 83643,
"text": "f(x) = 3x4 + 2x3+ 7x2 + 2x + 9 and"
},
{
"code": null,
"e": 83698,
"s": 83678,
"text": "g(x) = 5x3 + 9x + 2"
},
{
"code": null,
"e": 83718,
"s": 83698,
"text": "g(x) = 5x3 + 9x + 2"
},
{
"code": null,
"e": 83769,
"s": 83718,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 83890,
"s": 83769,
"text": "x = [-10 : 0.01: 10];\ny = 3*x.^4 + 2 * x.^3 + 7 * x.^2 + 2 * x + 9;\ng = 5 * x.^3 + 9 * x + 2;\nplot(x, y, 'r', x, g, 'g')"
},
{
"code": null,
"e": 83952,
"s": 83890,
"text": "When you run the file, MATLAB generates the following graph −"
},
{
"code": null,
"e": 84110,
"s": 83952,
"text": "The axis command allows you to set the axis scales. You can provide minimum and maximum values for x and y axes using the axis command in the following way −"
},
{
"code": null,
"e": 84142,
"s": 84110,
"text": "axis ( [xmin xmax ymin ymax] )\n"
},
{
"code": null,
"e": 84177,
"s": 84142,
"text": "The following example shows this −"
},
{
"code": null,
"e": 84228,
"s": 84177,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 84306,
"s": 84228,
"text": "x = [0 : 0.01: 10];\ny = exp(-x).* sin(2*x + 3);\nplot(x, y), axis([0 10 -1 1])"
},
{
"code": null,
"e": 84368,
"s": 84306,
"text": "When you run the file, MATLAB generates the following graph −"
},
{
"code": null,
"e": 84514,
"s": 84368,
"text": "When you create an array of plots in the same figure, each of these plots is called a subplot. The subplot command is used for creating subplots."
},
{
"code": null,
"e": 84542,
"s": 84514,
"text": "Syntax for the command is −"
},
{
"code": null,
"e": 84560,
"s": 84542,
"text": "subplot(m, n, p)\n"
},
{
"code": null,
"e": 84676,
"s": 84560,
"text": "where, m and n are the number of rows and columns of the plot array and p specifies where to put a particular plot."
},
{
"code": null,
"e": 84798,
"s": 84676,
"text": "Each plot created with the subplot command can have its own characteristics. Following example demonstrates the concept −"
},
{
"code": null,
"e": 84826,
"s": 84798,
"text": "Let us generate two plots −"
},
{
"code": null,
"e": 84845,
"s": 84826,
"text": "y = e−1.5xsin(10x)"
},
{
"code": null,
"e": 84862,
"s": 84845,
"text": "y = e−2xsin(10x)"
},
{
"code": null,
"e": 84913,
"s": 84862,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 85150,
"s": 84913,
"text": "x = [0:0.01:5];\ny = exp(-1.5*x).*sin(10*x);\nsubplot(1,2,1)\nplot(x,y), xlabel('x'),ylabel('exp(–1.5x)*sin(10x)'),axis([0 5 -1 1])\ny = exp(-2*x).*sin(10*x);\nsubplot(1,2,2)\nplot(x,y),xlabel('x'),ylabel('exp(–2x)*sin(10x)'),axis([0 5 -1 1])"
},
{
"code": null,
"e": 85212,
"s": 85150,
"text": "When you run the file, MATLAB generates the following graph −"
},
{
"code": null,
"e": 85317,
"s": 85212,
"text": "This chapter will continue exploring the plotting and graphics capabilities of MATLAB. We will discuss −"
},
{
"code": null,
"e": 85336,
"s": 85317,
"text": "Drawing bar charts"
},
{
"code": null,
"e": 85353,
"s": 85336,
"text": "Drawing contours"
},
{
"code": null,
"e": 85377,
"s": 85353,
"text": "Three dimensional plots"
},
{
"code": null,
"e": 85479,
"s": 85377,
"text": "The bar command draws a two dimensional bar chart. Let us take up an example to demonstrate the idea."
},
{
"code": null,
"e": 85677,
"s": 85479,
"text": "Let us have an imaginary classroom with 10 students. We know the percent of marks obtained by these students are 75, 58, 90, 87, 50, 85, 92, 75, 60 and 95. We will draw the bar chart for this data."
},
{
"code": null,
"e": 85728,
"s": 85677,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 85873,
"s": 85728,
"text": "x = [1:10];\ny = [75, 58, 90, 87, 50, 85, 92, 75, 60, 95];\nbar(x,y), xlabel('Student'),ylabel('Score'),\ntitle('First Sem:')\nprint -deps graph.eps"
},
{
"code": null,
"e": 85938,
"s": 85873,
"text": "When you run the file, MATLAB displays the following bar chart −"
},
{
"code": null,
"e": 86173,
"s": 85938,
"text": "A contour line of a function of two variables is a curve along which the function has a constant value. Contour lines are used for creating contour maps by joining points of equal elevation above a given level, such as mean sea level."
},
{
"code": null,
"e": 86234,
"s": 86173,
"text": "MATLAB provides a contour function for drawing contour maps."
},
{
"code": null,
"e": 86491,
"s": 86234,
"text": "Let us generate a contour map that shows the contour lines for a given function g = f(x, y). This function has two variables. So, we will have to generate two independent variables, i.e., two data sets x and y. This is done by calling the meshgrid command."
},
{
"code": null,
"e": 86645,
"s": 86491,
"text": "The meshgrid command is used for generating a matrix of elements that give the range over x and y along with the specification of increment in each case."
},
{
"code": null,
"e": 86793,
"s": 86645,
"text": "Let us plot our function g = f(x, y), where −5 ≤ x ≤ 5, −3 ≤ y ≤ 3. Let us take an increment of 0.1 for both the values. The variables are set as −"
},
{
"code": null,
"e": 86831,
"s": 86793,
"text": "[x,y] = meshgrid(–5:0.1:5, –3:0.1:3);"
},
{
"code": null,
"e": 86900,
"s": 86831,
"text": "Lastly, we need to assign the function. Let our function be: x2 + y2"
},
{
"code": null,
"e": 86951,
"s": 86900,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 87156,
"s": 86951,
"text": "[x,y] = meshgrid(-5:0.1:5,-3:0.1:3); %independent variables\ng = x.^2 + y.^2; % our function\ncontour(x,y,g) % call the contour function\nprint -deps graph.eps"
},
{
"code": null,
"e": 87223,
"s": 87156,
"text": "When you run the file, MATLAB displays the following contour map −"
},
{
"code": null,
"e": 87276,
"s": 87223,
"text": "Let us modify the code a little to spruce up the map"
},
{
"code": null,
"e": 87536,
"s": 87276,
"text": "[x,y] = meshgrid(-5:0.1:5,-3:0.1:3); %independent variables\ng = x.^2 + y.^2; % our function\n[C, h] = contour(x,y,g); % call the contour function\nset(h,'ShowText','on','TextStep',get(h,'LevelStep')*2)\nprint -deps graph.eps"
},
{
"code": null,
"e": 87603,
"s": 87536,
"text": "When you run the file, MATLAB displays the following contour map −"
},
{
"code": null,
"e": 87708,
"s": 87603,
"text": "Three-dimensional plots basically display a surface defined by a function in two variables, g = f (x,y)."
},
{
"code": null,
"e": 87926,
"s": 87708,
"text": "As before, to define g, we first create a set of (x,y) points over the domain of the function using the meshgrid command. Next, we assign the function itself. Finally, we use the surf command to create a surface plot."
},
{
"code": null,
"e": 87975,
"s": 87926,
"text": "The following example demonstrates the concept −"
},
{
"code": null,
"e": 88040,
"s": 87975,
"text": "Let us create a 3D surface map for the function g = xe-(x2 + y2)"
},
{
"code": null,
"e": 88091,
"s": 88040,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 88182,
"s": 88091,
"text": "[x,y] = meshgrid(-2:.2:2);\ng = x .* exp(-x.^2 - y.^2);\nsurf(x, y, g)\nprint -deps graph.eps"
},
{
"code": null,
"e": 88245,
"s": 88182,
"text": "When you run the file, MATLAB displays the following 3-D map −"
},
{
"code": null,
"e": 88525,
"s": 88245,
"text": "You can also use the mesh command to generate a three-dimensional surface. However, the surf command displays both the connecting lines and the faces of the surface in color, whereas, the mesh command creates a wireframe surface with colored lines connecting the defining points."
},
{
"code": null,
"e": 88786,
"s": 88525,
"text": "So far, we have seen that all the examples work in MATLAB as well as its GNU, alternatively called Octave. But for solving basic algebraic equations, both MATLAB and Octave are little different, so we will try to cover MATLAB and Octave in separate sections."
},
{
"code": null,
"e": 88864,
"s": 88786,
"text": "We will also discuss factorizing and simplification of algebraic expressions."
},
{
"code": null,
"e": 89019,
"s": 88864,
"text": "The solve function is used for solving algebraic equations. In its simplest form, the solve function takes the equation enclosed in quotes as an argument."
},
{
"code": null,
"e": 89075,
"s": 89019,
"text": "For example, let us solve for x in the equation x-5 = 0"
},
{
"code": null,
"e": 89091,
"s": 89075,
"text": "solve('x-5=0')\n"
},
{
"code": null,
"e": 89165,
"s": 89091,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 89177,
"s": 89165,
"text": "ans =\n 5\n"
},
{
"code": null,
"e": 89219,
"s": 89177,
"text": "You can also call the solve function as −"
},
{
"code": null,
"e": 89240,
"s": 89219,
"text": "y = solve('x-5 = 0')"
},
{
"code": null,
"e": 89314,
"s": 89240,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 89324,
"s": 89314,
"text": "y =\n 5\n"
},
{
"code": null,
"e": 89387,
"s": 89324,
"text": "You may even not include the right hand side of the equation −"
},
{
"code": null,
"e": 89400,
"s": 89387,
"text": "solve('x-5')"
},
{
"code": null,
"e": 89474,
"s": 89400,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 89486,
"s": 89474,
"text": "ans =\n 5\n"
},
{
"code": null,
"e": 89635,
"s": 89486,
"text": "If the equation involves multiple symbols, then MATLAB by default assumes that you are solving for x, however, the solve function has another form −"
},
{
"code": null,
"e": 89661,
"s": 89635,
"text": "solve(equation, variable)"
},
{
"code": null,
"e": 89703,
"s": 89661,
"text": "where, you can also mention the variable."
},
{
"code": null,
"e": 89798,
"s": 89703,
"text": "For example, let us solve the equation v – u – 3t2 = 0, for v. In this case, we should write −"
},
{
"code": null,
"e": 89824,
"s": 89798,
"text": "solve('v-u-3*t^2=0', 'v')"
},
{
"code": null,
"e": 89898,
"s": 89824,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 89918,
"s": 89898,
"text": "ans =\n 3*t^2 + u\n"
},
{
"code": null,
"e": 90033,
"s": 89918,
"text": "The roots function is used for solving algebraic equations in Octave and you can write above examples as follows −"
},
{
"code": null,
"e": 90089,
"s": 90033,
"text": "For example, let us solve for x in the equation x-5 = 0"
},
{
"code": null,
"e": 90104,
"s": 90089,
"text": "roots([1, -5])"
},
{
"code": null,
"e": 90178,
"s": 90104,
"text": "Octave will execute the above statement and return the following result −"
},
{
"code": null,
"e": 90187,
"s": 90178,
"text": "ans = 5\n"
},
{
"code": null,
"e": 90229,
"s": 90187,
"text": "You can also call the solve function as −"
},
{
"code": null,
"e": 90248,
"s": 90229,
"text": "y = roots([1, -5])"
},
{
"code": null,
"e": 90322,
"s": 90248,
"text": "Octave will execute the above statement and return the following result −"
},
{
"code": null,
"e": 90329,
"s": 90322,
"text": "y = 5\n"
},
{
"code": null,
"e": 90494,
"s": 90329,
"text": "The solve function can also solve higher order equations. It is often used to solve quadratic equations. The function returns the roots of the equation in an array."
},
{
"code": null,
"e": 90613,
"s": 90494,
"text": "The following example solves the quadratic equation x2 -7x +12 = 0. Create a script file and type the following code −"
},
{
"code": null,
"e": 90737,
"s": 90613,
"text": "eq = 'x^2 -7*x + 12 = 0';\ns = solve(eq);\ndisp('The first root is: '), disp(s(1));\ndisp('The second root is: '), disp(s(2));"
},
{
"code": null,
"e": 90795,
"s": 90737,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 90847,
"s": 90795,
"text": "The first root is: \n 3\nThe second root is: \n 4\n"
},
{
"code": null,
"e": 90976,
"s": 90847,
"text": "The following example solves the quadratic equation x2 -7x +12 = 0 in Octave. Create a script file and type the following code −"
},
{
"code": null,
"e": 91084,
"s": 90976,
"text": "s = roots([1, -7, 12]);\n\ndisp('The first root is: '), disp(s(1));\ndisp('The second root is: '), disp(s(2));"
},
{
"code": null,
"e": 91142,
"s": 91084,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 91194,
"s": 91142,
"text": "The first root is: \n 4\nThe second root is: \n 3\n"
},
{
"code": null,
"e": 91314,
"s": 91194,
"text": "The solve function can also solve higher order equations. For example, let us solve a cubic equation as (x-3)2(x-7) = 0"
},
{
"code": null,
"e": 91339,
"s": 91314,
"text": "solve('(x-3)^2*(x-7)=0')"
},
{
"code": null,
"e": 91413,
"s": 91339,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 91435,
"s": 91413,
"text": "ans =\n 3\n 3\n 7\n"
},
{
"code": null,
"e": 91668,
"s": 91435,
"text": "In case of higher order equations, roots are long containing many terms. You can get the numerical value of such roots by converting them to double. The following example solves the fourth order equation x4 − 7x3 + 3x2 − 5x + 9 = 0."
},
{
"code": null,
"e": 91719,
"s": 91668,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 92211,
"s": 91719,
"text": "eq = 'x^4 - 7*x^3 + 3*x^2 - 5*x + 9 = 0';\ns = solve(eq);\ndisp('The first root is: '), disp(s(1));\ndisp('The second root is: '), disp(s(2));\ndisp('The third root is: '), disp(s(3));\ndisp('The fourth root is: '), disp(s(4));\n\n% converting the roots to double type\ndisp('Numeric value of first root'), disp(double(s(1)));\ndisp('Numeric value of second root'), disp(double(s(2)));\ndisp('Numeric value of third root'), disp(double(s(3)));\ndisp('Numeric value of fourth root'), disp(double(s(4)));"
},
{
"code": null,
"e": 92268,
"s": 92211,
"text": "When you run the file, it returns the following result −"
},
{
"code": null,
"e": 92747,
"s": 92268,
"text": "The first root is: \n6.630396332390718431485053218985\n The second root is: \n1.0597804633025896291682772499885\n The third root is: \n- 0.34508839784665403032666523448675 - 1.0778362954630176596831109269793*i\n The fourth root is: \n- 0.34508839784665403032666523448675 + 1.0778362954630176596831109269793*i\nNumeric value of first root\n 6.6304\nNumeric value of second root\n 1.0598\nNumeric value of third root\n -0.3451 - 1.0778i\nNumeric value of fourth root\n -0.3451 + 1.0778i\n"
},
{
"code": null,
"e": 92804,
"s": 92747,
"text": "Please note that the last two roots are complex numbers."
},
{
"code": null,
"e": 92888,
"s": 92804,
"text": "The following example solves the fourth order equation x4 − 7x3 + 3x2 − 5x + 9 = 0."
},
{
"code": null,
"e": 92939,
"s": 92888,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 93246,
"s": 92939,
"text": "v = [1, -7, 3, -5, 9];\ns = roots(v);\n\n% converting the roots to double type\ndisp('Numeric value of first root'), disp(double(s(1)));\ndisp('Numeric value of second root'), disp(double(s(2)));\ndisp('Numeric value of third root'), disp(double(s(3)));\ndisp('Numeric value of fourth root'), disp(double(s(4)));"
},
{
"code": null,
"e": 93303,
"s": 93246,
"text": "When you run the file, it returns the following result −"
},
{
"code": null,
"e": 93474,
"s": 93303,
"text": "Numeric value of first root\n 6.6304\nNumeric value of second root\n-0.34509 + 1.07784i\nNumeric value of third root\n-0.34509 - 1.07784i\nNumeric value of fourth root\n 1.0598\n"
},
{
"code": null,
"e": 93648,
"s": 93474,
"text": "The solve function can also be used to generate solutions of systems of equations involving more than one variables. Let us take up a simple example to demonstrate this use."
},
{
"code": null,
"e": 93677,
"s": 93648,
"text": "Let us solve the equations −"
},
{
"code": null,
"e": 93689,
"s": 93677,
"text": "5x + 9y = 5"
},
{
"code": null,
"e": 93701,
"s": 93689,
"text": "3x – 6y = 4"
},
{
"code": null,
"e": 93752,
"s": 93701,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 93804,
"s": 93752,
"text": "s = solve('5*x + 9*y = 5','3*x - 6*y = 4');\ns.x\ns.y"
},
{
"code": null,
"e": 93862,
"s": 93804,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 93893,
"s": 93862,
"text": "ans =\n 22/19\nans =\n -5/57\n"
},
{
"code": null,
"e": 93985,
"s": 93893,
"text": "In same way, you can solve larger linear systems. Consider the following set of equations −"
},
{
"code": null,
"e": 94000,
"s": 93985,
"text": "x + 3y -2z = 5"
},
{
"code": null,
"e": 94017,
"s": 94000,
"text": "3x + 5y + 6z = 7"
},
{
"code": null,
"e": 94034,
"s": 94017,
"text": "2x + 4y + 3z = 8"
},
{
"code": null,
"e": 94186,
"s": 94034,
"text": "We have a little different approach to solve a system of 'n' linear equations in 'n' unknowns. Let us take up a simple example to demonstrate this use."
},
{
"code": null,
"e": 94215,
"s": 94186,
"text": "Let us solve the equations −"
},
{
"code": null,
"e": 94227,
"s": 94215,
"text": "5x + 9y = 5"
},
{
"code": null,
"e": 94239,
"s": 94227,
"text": "3x – 6y = 4"
},
{
"code": null,
"e": 94524,
"s": 94239,
"text": "Such a system of linear equations can be written as the single matrix equation Ax = b, where A is the coefficient matrix, b is the column vector containing the right-hand side of the linear equations and x is the column vector representing the solution as shown in the below program −"
},
{
"code": null,
"e": 94575,
"s": 94524,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 94611,
"s": 94575,
"text": "A = [5, 9; 3, -6];\nb = [5;4];\nA \\ b"
},
{
"code": null,
"e": 94669,
"s": 94611,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 94701,
"s": 94669,
"text": "ans =\n\n 1.157895\n -0.087719\n"
},
{
"code": null,
"e": 94767,
"s": 94701,
"text": "In same way, you can solve larger linear systems as given below −"
},
{
"code": null,
"e": 94782,
"s": 94767,
"text": "x + 3y -2z = 5"
},
{
"code": null,
"e": 94799,
"s": 94782,
"text": "3x + 5y + 6z = 7"
},
{
"code": null,
"e": 94816,
"s": 94799,
"text": "2x + 4y + 3z = 8"
},
{
"code": null,
"e": 94949,
"s": 94816,
"text": "The expand and the collect function expands and collects an equation respectively. The following example demonstrates the concepts −"
},
{
"code": null,
"e": 95046,
"s": 94949,
"text": "When you work with many symbolic functions, you should declare that your variables are symbolic."
},
{
"code": null,
"e": 95097,
"s": 95046,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 95335,
"s": 95097,
"text": "syms x %symbolic variable x\nsyms y %symbolic variable x\n% expanding equations\nexpand((x-5)*(x+9))\nexpand((x+2)*(x-3)*(x-5)*(x+7))\nexpand(sin(2*x))\nexpand(cos(x+y))\n \n% collecting equations\ncollect(x^3 *(x-7))\ncollect(x^4*(x-3)*(x-5))"
},
{
"code": null,
"e": 95393,
"s": 95335,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 95574,
"s": 95393,
"text": "ans =\n x^2 + 4*x - 45\nans =\n x^4 + x^3 - 43*x^2 + 23*x + 210\nans =\n 2*cos(x)*sin(x)\nans =\n cos(x)*cos(y) - sin(x)*sin(y)\nans =\n x^4 - 7*x^3\nans =\n x^6 - 8*x^5 + 15*x^4\n"
},
{
"code": null,
"e": 95756,
"s": 95574,
"text": "You need to have symbolic package, which provides expand and the collect function to expand and collect an equation, respectively. The following example demonstrates the concepts −"
},
{
"code": null,
"e": 95991,
"s": 95756,
"text": "When you work with many symbolic functions, you should declare that your variables are symbolic but Octave has different approach to define symbolic variables. Notice the use of Sin and Cos, which are also defined in symbolic package."
},
{
"code": null,
"e": 96042,
"s": 95991,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 96418,
"s": 96042,
"text": "% first of all load the package, make sure its installed.\npkg load symbolic\n\n% make symbols module available\nsymbols\n\n% define symbolic variables\nx = sym ('x');\ny = sym ('y');\nz = sym ('z');\n\n% expanding equations\nexpand((x-5)*(x+9))\nexpand((x+2)*(x-3)*(x-5)*(x+7))\nexpand(Sin(2*x))\nexpand(Cos(x+y))\n \n% collecting equations\ncollect(x^3 *(x-7), z)\ncollect(x^4*(x-3)*(x-5), z)"
},
{
"code": null,
"e": 96476,
"s": 96418,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 96636,
"s": 96476,
"text": "ans =\n\n-45.0+x^2+(4.0)*x\nans =\n\n210.0+x^4-(43.0)*x^2+x^3+(23.0)*x\nans =\n\nsin((2.0)*x)\nans =\n\ncos(y+x)\nans =\n\nx^(3.0)*(-7.0+x)\nans =\n\n(-3.0+x)*x^(4.0)*(-5.0+x)\n"
},
{
"code": null,
"e": 96782,
"s": 96636,
"text": "The factor function factorizes an expression and the simplify function simplifies an expression. The following example demonstrates the concept −"
},
{
"code": null,
"e": 96833,
"s": 96782,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 96918,
"s": 96833,
"text": "syms x\nsyms y\nfactor(x^3 - y^3)\nfactor([x^2-y^2,x^3+y^3])\nsimplify((x^4-16)/(x^2-4))"
},
{
"code": null,
"e": 96976,
"s": 96918,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 97084,
"s": 96976,
"text": "ans =\n (x - y)*(x^2 + x*y + y^2)\nans =\n [ (x - y)*(x + y), (x + y)*(x^2 - x*y + y^2)]\nans =\n x^2 + 4\n"
},
{
"code": null,
"e": 97435,
"s": 97084,
"text": "MATLAB provides various ways for solving problems of differential and integral calculus, solving differential equations of any degree and calculation of limits. Best of all, you can easily plot the graphs of complex functions and check maxima, minima and other stationery points on a graph by solving the original function, as well as its derivative."
},
{
"code": null,
"e": 97618,
"s": 97435,
"text": "This chapter will deal with problems of calculus. In this chapter, we will discuss pre-calculus concepts i.e., calculating limits of functions and verifying the properties of limits."
},
{
"code": null,
"e": 97798,
"s": 97618,
"text": "In the next chapter Differential, we will compute derivative of an expression and find the local maxima and minima on a graph. We will also discuss solving differential equations."
},
{
"code": null,
"e": 97870,
"s": 97798,
"text": "Finally, in the Integration chapter, we will discuss integral calculus."
},
{
"code": null,
"e": 98084,
"s": 97870,
"text": "MATLAB provides the limit function for calculating limits. In its most basic form, the limit function takes expression as an argument and finds the limit of the expression as the independent variable goes to zero."
},
{
"code": null,
"e": 98184,
"s": 98084,
"text": "For example, let us calculate the limit of a function f(x) = (x3 + 5)/(x4 + 7), as x tends to zero."
},
{
"code": null,
"e": 98218,
"s": 98184,
"text": "syms x\nlimit((x^3 + 5)/(x^4 + 7))"
},
{
"code": null,
"e": 98292,
"s": 98218,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 98306,
"s": 98292,
"text": "ans =\n 5/7\n"
},
{
"code": null,
"e": 98717,
"s": 98306,
"text": "The limit function falls in the realm of symbolic computing; you need to use the syms function to tell MATLAB which symbolic variables you are using. You can also compute limit of a function, as the variable tends to some number other than zero. To calculate lim x->a(f(x)), we use the limit command with arguments. The first being the expression and the second is the number, that x approaches, here it is a."
},
{
"code": null,
"e": 98804,
"s": 98717,
"text": "For example, let us calculate limit of a function f(x) = (x-3)/(x-1), as x tends to 1."
},
{
"code": null,
"e": 98827,
"s": 98804,
"text": "limit((x - 3)/(x-1),1)"
},
{
"code": null,
"e": 98901,
"s": 98827,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 98915,
"s": 98901,
"text": "ans =\n NaN\n"
},
{
"code": null,
"e": 98943,
"s": 98915,
"text": "Let's take another example,"
},
{
"code": null,
"e": 98961,
"s": 98943,
"text": "limit(x^2 + 5, 3)"
},
{
"code": null,
"e": 99035,
"s": 98961,
"text": "MATLAB will execute the above statement and return the following result −"
},
{
"code": null,
"e": 99048,
"s": 99035,
"text": "ans =\n 14\n"
},
{
"code": null,
"e": 99161,
"s": 99048,
"text": "Following is Octave version of the above example using symbolic package, try to execute and compare the result −"
},
{
"code": null,
"e": 99228,
"s": 99161,
"text": "pkg load symbolic\nsymbols\n\nx = sym(\"x\");\nsubs((x^3+5)/(x^4+7),x,0)"
},
{
"code": null,
"e": 99302,
"s": 99228,
"text": "Octave will execute the above statement and return the following result −"
},
{
"code": null,
"e": 99334,
"s": 99302,
"text": "ans =\n 0.7142857142857142857\n"
},
{
"code": null,
"e": 99423,
"s": 99334,
"text": "Algebraic Limit Theorem provides some basic properties of limits. These are as follows −"
},
{
"code": null,
"e": 99455,
"s": 99423,
"text": "Let us consider two functions −"
},
{
"code": null,
"e": 99479,
"s": 99455,
"text": "f(x) = (3x + 5)/(x - 3)"
},
{
"code": null,
"e": 99494,
"s": 99479,
"text": "g(x) = x2 + 1."
},
{
"code": null,
"e": 99654,
"s": 99494,
"text": "Let us calculate the limits of the functions as x tends to 5, of both functions and verify the basic properties of limits using these two functions and MATLAB."
},
{
"code": null,
"e": 99713,
"s": 99654,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 99879,
"s": 99713,
"text": "syms x\nf = (3*x + 5)/(x-3);\ng = x^2 + 1;\nl1 = limit(f, 4)\nl2 = limit (g, 4)\nlAdd = limit(f + g, 4)\nlSub = limit(f - g, 4)\nlMult = limit(f*g, 4)\nlDiv = limit (f/g, 4)"
},
{
"code": null,
"e": 99916,
"s": 99879,
"text": "When you run the file, it displays −"
},
{
"code": null,
"e": 100005,
"s": 99916,
"text": "l1 =\n 17\n \nl2 =\n 17\n \nlAdd =\n 34\n \nlSub =\n 0\n \nlMult =\n 289\n \nlDiv =\n 1\n"
},
{
"code": null,
"e": 100118,
"s": 100005,
"text": "Following is Octave version of the above example using symbolic package, try to execute and compare the result −"
},
{
"code": null,
"e": 100330,
"s": 100118,
"text": "pkg load symbolic\nsymbols\n\nx = sym(\"x\");\nf = (3*x + 5)/(x-3);\ng = x^2 + 1;\n\nl1 = subs(f, x, 4)\nl2 = subs (g, x, 4)\nlAdd = subs (f+g, x, 4)\nlSub = subs (f-g, x, 4)\nlMult = subs (f*g, x, 4)\nlDiv = subs (f/g, x, 4)"
},
{
"code": null,
"e": 100404,
"s": 100330,
"text": "Octave will execute the above statement and return the following result −"
},
{
"code": null,
"e": 100491,
"s": 100404,
"text": "l1 =\n 17.0\nl2 =\n 17.0\nlAdd =\n 34.0\nlSub =\n 0.0\nlMult =\n 289.0\nlDiv =\n 1.0\n"
},
{
"code": null,
"e": 100810,
"s": 100491,
"text": "When a function has a discontinuity for some particular value of the variable, the limit does not exist at that point. In other words, limits of a function f(x) has discontinuity at x = a, when the value of limit, as x approaches x from left side, does not equal the value of the limit as x approaches from right side."
},
{
"code": null,
"e": 101195,
"s": 100810,
"text": "This leads to the concept of left-handed and right-handed limits. A left-handed limit is defined as the limit as x -> a, from the left, i.e., x approaches a, for values of x < a. A right-handed limit is defined as the limit as x -> a, from the right, i.e., x approaches a, for values of x > a. When the left-handed limit and right-handed limit are not equal, the limit does not exist."
},
{
"code": null,
"e": 101224,
"s": 101195,
"text": "Let us consider a function −"
},
{
"code": null,
"e": 101247,
"s": 101224,
"text": "f(x) = (x - 3)/|x - 3|"
},
{
"code": null,
"e": 101347,
"s": 101247,
"text": "We will show that limx->3 f(x) does not exist. MATLAB helps us to establish this fact in two ways −"
},
{
"code": null,
"e": 101416,
"s": 101347,
"text": "By plotting the graph of the function and showing the discontinuity."
},
{
"code": null,
"e": 101477,
"s": 101416,
"text": "By computing the limits and showing that both are different."
},
{
"code": null,
"e": 101625,
"s": 101477,
"text": "The left-handed and right-handed limits are computed by passing the character strings 'left' and 'right' to the limit command as the last argument."
},
{
"code": null,
"e": 101684,
"s": 101625,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 101772,
"s": 101684,
"text": "f = (x - 3)/abs(x-3);\nezplot(f,[-1,5])\nl = limit(f,x,3,'left')\nr = limit(f,x,3,'right')"
},
{
"code": null,
"e": 101827,
"s": 101772,
"text": "When you run the file, MATLAB draws the following plot"
},
{
"code": null,
"e": 101870,
"s": 101827,
"text": "After this following output is displayed −"
},
{
"code": null,
"e": 101893,
"s": 101870,
"text": "l =\n -1\n \nr =\n 1\n"
},
{
"code": null,
"e": 102064,
"s": 101893,
"text": "MATLAB provides the diff command for computing symbolic derivatives. In its simplest form, you pass the function you want to differentiate to diff command as an argument."
},
{
"code": null,
"e": 102141,
"s": 102064,
"text": "For example, let us compute the derivative of the function f(t) = 3t2 + 2t-2"
},
{
"code": null,
"e": 102200,
"s": 102141,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 102237,
"s": 102200,
"text": "syms t\nf = 3*t^2 + 2*t^(-2);\ndiff(f)"
},
{
"code": null,
"e": 102318,
"s": 102237,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 102337,
"s": 102318,
"text": "ans =\n6*t - 4/t^3\n"
},
{
"code": null,
"e": 102395,
"s": 102337,
"text": "Following is Octave equivalent of the above calculation −"
},
{
"code": null,
"e": 102477,
"s": 102395,
"text": "pkg load symbolic\nsymbols\n\nt = sym(\"t\");\nf = 3*t^2 + 2*t^(-2);\ndifferentiate(f,t)"
},
{
"code": null,
"e": 102537,
"s": 102477,
"text": "Octave executes the code and returns the following result −"
},
{
"code": null,
"e": 102571,
"s": 102537,
"text": "ans =\n -(4.0)*t^(-3.0)+(6.0)*t\n"
},
{
"code": null,
"e": 102784,
"s": 102571,
"text": "Let us briefly state various equations or rules for differentiation of functions and verify these rules. For this purpose, we will write f'(x) for a first order derivative and f\"(x) for a second order derivative."
},
{
"code": null,
"e": 102830,
"s": 102784,
"text": "Following are the rules for differentiation −"
},
{
"code": null,
"e": 102922,
"s": 102830,
"text": "For any functions f and g and any real numbers a and b are the derivative of the function −"
},
{
"code": null,
"e": 102975,
"s": 102922,
"text": "h(x) = af(x) + bg(x) with respect to x is given by −"
},
{
"code": null,
"e": 102999,
"s": 102975,
"text": "h'(x) = af'(x) + bg'(x)"
},
{
"code": null,
"e": 103122,
"s": 102999,
"text": "The sum and subtraction rules state that if f and g are two functions, f' and g' are their derivatives respectively, then,"
},
{
"code": null,
"e": 103141,
"s": 103122,
"text": "(f + g)' = f' + g'"
},
{
"code": null,
"e": 103160,
"s": 103141,
"text": "(f - g)' = f' - g'"
},
{
"code": null,
"e": 103271,
"s": 103160,
"text": "The product rule states that if f and g are two functions, f' and g' are their derivatives respectively, then,"
},
{
"code": null,
"e": 103292,
"s": 103271,
"text": "(f.g)' = f'.g + g'.f"
},
{
"code": null,
"e": 103404,
"s": 103292,
"text": "The quotient rule states that if f and g are two functions, f' and g' are their derivatives respectively, then,"
},
{
"code": null,
"e": 103430,
"s": 103404,
"text": "(f/g)' = (f'.g - g'.f)/g2"
},
{
"code": null,
"e": 103521,
"s": 103430,
"text": "The polynomial or elementary power rule states that, if y = f(x) = xn, then f' = n. x(n-1)"
},
{
"code": null,
"e": 103634,
"s": 103521,
"text": "A direct outcome of this rule is that the derivative of any constant is zero, i.e., if y = k, any constant, then"
},
{
"code": null,
"e": 103641,
"s": 103634,
"text": "f' = 0"
},
{
"code": null,
"e": 103747,
"s": 103641,
"text": "The chain rule states that, derivative of the function of a function h(x) = f(g(x)) with respect to x is,"
},
{
"code": null,
"e": 103769,
"s": 103747,
"text": "h'(x)= f'(g(x)).g'(x)"
},
{
"code": null,
"e": 103828,
"s": 103769,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 104103,
"s": 103828,
"text": "syms x\nsyms t\n\nf = (x + 2)*(x^2 + 3)\nder1 = diff(f)\nf = (t^2 + 3)*(sqrt(t) + t^3)\nder2 = diff(f)\nf = (x^2 - 2*x + 1)*(3*x^3 - 5*x^2 + 2)\nder3 = diff(f)\nf = (2*x^2 + 3*x)/(x^3 + 1)\nder4 = diff(f)\nf = (x^2 + 1)^17\nder5 = diff(f)\nf = (t^3 + 3* t^2 + 5*t -9)^(-6)\nder6 = diff(f)"
},
{
"code": null,
"e": 104165,
"s": 104103,
"text": "When you run the file, MATLAB displays the following result −"
},
{
"code": null,
"e": 104715,
"s": 104165,
"text": "f =\n (x^2 + 3)*(x + 2)\n \n der1 =\n 2*x*(x + 2) + x^2 + 3\n \nf =\n (t^(1/2) + t^3)*(t^2 + 3)\n \n der2 =\n (t^2 + 3)*(3*t^2 + 1/(2*t^(1/2))) + 2*t*(t^(1/2) + t^3)\n \nf =\n (x^2 - 2*x + 1)*(3*x^3 - 5*x^2 + 2)\n \nder3 =\n (2*x - 2)*(3*x^3 - 5*x^2 + 2) - (- 9*x^2 + 10*x)*(x^2 - 2*x + 1)\n \nf =\n (2*x^2 + 3*x)/(x^3 + 1)\n \nder4 =\n (4*x + 3)/(x^3 + 1) - (3*x^2*(2*x^2 + 3*x))/(x^3 + 1)^2\n \nf =\n (x^2 + 1)^17\n \nder5 =\n 34*x*(x^2 + 1)^16\n \nf =\n 1/(t^3 + 3*t^2 + 5*t - 9)^6\n \nder6 =\n -(6*(3*t^2 + 6*t + 5))/(t^3 + 3*t^2 + 5*t - 9)^7\n"
},
{
"code": null,
"e": 104773,
"s": 104715,
"text": "Following is Octave equivalent of the above calculation −"
},
{
"code": null,
"e": 105165,
"s": 104773,
"text": "pkg load symbolic\nsymbols\n\nx = sym(\"x\");\nt = sym(\"t\");\nf = (x + 2)*(x^2 + 3) \nder1 = differentiate(f,x) \nf = (t^2 + 3)*(t^(1/2) + t^3) \nder2 = differentiate(f,t) \nf = (x^2 - 2*x + 1)*(3*x^3 - 5*x^2 + 2) \nder3 = differentiate(f,x) \nf = (2*x^2 + 3*x)/(x^3 + 1) \nder4 = differentiate(f,x) \nf = (x^2 + 1)^17 \nder5 = differentiate(f,x) \nf = (t^3 + 3* t^2 + 5*t -9)^(-6) \nder6 = differentiate(f,t)"
},
{
"code": null,
"e": 105225,
"s": 105165,
"text": "Octave executes the code and returns the following result −"
},
{
"code": null,
"e": 105916,
"s": 105225,
"text": "f =\n\n(2.0+x)*(3.0+x^(2.0))\nder1 =\n\n3.0+x^(2.0)+(2.0)*(2.0+x)*x\nf =\n\n(t^(3.0)+sqrt(t))*(3.0+t^(2.0))\nder2 =\n\n(2.0)*(t^(3.0)+sqrt(t))*t+((3.0)*t^(2.0)+(0.5)*t^(-0.5))*(3.0+t^(2.0))\nf =\n\n(1.0+x^(2.0)-(2.0)*x)*(2.0-(5.0)*x^(2.0)+(3.0)*x^(3.0))\nder3 =\n\n(-2.0+(2.0)*x)*(2.0-(5.0)*x^(2.0)+(3.0)*x^(3.0))+((9.0)*x^(2.0)-(10.0)*x)*(1.0+x^(2.0)-(2.0)*x)\nf =\n\n(1.0+x^(3.0))^(-1)*((2.0)*x^(2.0)+(3.0)*x)\nder4 =\n\n(1.0+x^(3.0))^(-1)*(3.0+(4.0)*x)-(3.0)*(1.0+x^(3.0))^(-2)*x^(2.0)*((2.0)*x^(2.0)+(3.0)*x)\nf =\n\n(1.0+x^(2.0))^(17.0)\nder5 =\n\n(34.0)*(1.0+x^(2.0))^(16.0)*x\nf =\n\n(-9.0+(3.0)*t^(2.0)+t^(3.0)+(5.0)*t)^(-6.0)\nder6 =\n\n-(6.0)*(-9.0+(3.0)*t^(2.0)+t^(3.0)+(5.0)*t)^(-7.0)*(5.0+(3.0)*t^(2.0)+(6.0)*t)\n"
},
{
"code": null,
"e": 106033,
"s": 105916,
"text": "The following table provides the derivatives of commonly used exponential, logarithmic and trigonometric functions −"
},
{
"code": null,
"e": 106092,
"s": 106033,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 106311,
"s": 106092,
"text": "syms x\ny = exp(x)\ndiff(y)\ny = x^9\ndiff(y)\ny = sin(x)\ndiff(y)\ny = tan(x)\ndiff(y)\ny = cos(x)\ndiff(y)\ny = log(x)\ndiff(y)\ny = log10(x)\ndiff(y)\ny = sin(x)^2\ndiff(y)\ny = cos(3*x^2 + 2*x + 1)\ndiff(y)\ny = exp(x)/sin(x)\ndiff(y)"
},
{
"code": null,
"e": 106373,
"s": 106311,
"text": "When you run the file, MATLAB displays the following result −"
},
{
"code": null,
"e": 106832,
"s": 106373,
"text": "y =\n exp(x)\n ans =\n exp(x)\n\ny =\n x^9\n ans =\n 9*x^8\n \ny =\n sin(x)\n ans =\n cos(x)\n \ny =\n tan(x)\n ans =\n tan(x)^2 + 1\n \ny =\n cos(x)\n ans =\n -sin(x)\n \ny =\n log(x)\n ans =\n 1/x\n \ny =\n log(x)/log(10)\n ans =\n 1/(x*log(10))\n \ny =\n sin(x)^2\n ans =\n 2*cos(x)*sin(x)\n \ny =\n cos(3*x^2 + 2*x + 1)\n ans =\n -sin(3*x^2 + 2*x + 1)*(6*x + 2)\n \ny =\n exp(x)/sin(x)\n ans =\n exp(x)/sin(x) - (exp(x)*cos(x))/sin(x)^2\n"
},
{
"code": null,
"e": 106890,
"s": 106832,
"text": "Following is Octave equivalent of the above calculation −"
},
{
"code": null,
"e": 107311,
"s": 106890,
"text": "pkg load symbolic\nsymbols\n\nx = sym(\"x\");\ny = Exp(x)\ndifferentiate(y,x)\n\ny = x^9\ndifferentiate(y,x)\n\ny = Sin(x)\ndifferentiate(y,x)\n\ny = Tan(x)\ndifferentiate(y,x)\n\ny = Cos(x)\ndifferentiate(y,x)\n\ny = Log(x)\ndifferentiate(y,x)\n\n% symbolic packages does not have this support\n%y = Log10(x)\n%differentiate(y,x)\n\ny = Sin(x)^2\ndifferentiate(y,x)\n\ny = Cos(3*x^2 + 2*x + 1)\ndifferentiate(y,x)\n\ny = Exp(x)/Sin(x)\ndifferentiate(y,x)"
},
{
"code": null,
"e": 107371,
"s": 107311,
"text": "Octave executes the code and returns the following result −"
},
{
"code": null,
"e": 107751,
"s": 107371,
"text": "y =\n\nexp(x)\nans =\n\nexp(x)\ny =\n\nx^(9.0)\nans =\n\n(9.0)*x^(8.0)\ny =\n\nsin(x)\nans =\n\ncos(x)\ny =\n\ntan(x)\nans =\n\n1+tan(x)^2\ny =\n\ncos(x)\nans =\n\n-sin(x)\ny =\n\nlog(x)\nans =\n\nx^(-1)\ny =\n\nsin(x)^(2.0)\nans =\n\n(2.0)*sin(x)*cos(x)\ny =\n\ncos(1.0+(2.0)*x+(3.0)*x^(2.0))\nans =\n\n-(2.0+(6.0)*x)*sin(1.0+(2.0)*x+(3.0)*x^(2.0))\ny =\n\nsin(x)^(-1)*exp(x)\nans =\n\nsin(x)^(-1)*exp(x)-sin(x)^(-2)*cos(x)*exp(x)\n"
},
{
"code": null,
"e": 107827,
"s": 107751,
"text": "To compute higher derivatives of a function f, we use the syntax diff(f,n)."
},
{
"code": null,
"e": 107899,
"s": 107827,
"text": "Let us compute the second derivative of the function y = f(x) = x .e-3x"
},
{
"code": null,
"e": 107927,
"s": 107899,
"text": "f = x*exp(-3*x);\ndiff(f, 2)"
},
{
"code": null,
"e": 107987,
"s": 107927,
"text": "MATLAB executes the code and returns the following result −"
},
{
"code": null,
"e": 108022,
"s": 107987,
"text": "ans =\n9*x*exp(-3*x) - 6*exp(-3*x)\n"
},
{
"code": null,
"e": 108080,
"s": 108022,
"text": "Following is Octave equivalent of the above calculation −"
},
{
"code": null,
"e": 108161,
"s": 108080,
"text": "pkg load symbolic\nsymbols\n\nx = sym(\"x\");\nf = x*Exp(-3*x);\ndifferentiate(f, x, 2)"
},
{
"code": null,
"e": 108221,
"s": 108161,
"text": "Octave executes the code and returns the following result −"
},
{
"code": null,
"e": 108271,
"s": 108221,
"text": "ans =\n\n(9.0)*exp(-(3.0)*x)*x-(6.0)*exp(-(3.0)*x)\n"
},
{
"code": null,
"e": 108444,
"s": 108271,
"text": "In this example, let us solve a problem. Given that a function y = f(x) = 3 sin(x) + 7 cos(5x). We will have to find out whether the equation f\" + f = -5cos(2x) holds true."
},
{
"code": null,
"e": 108503,
"s": 108444,
"text": "Create a script file and type the following code into it −"
},
{
"code": null,
"e": 108825,
"s": 108503,
"text": "syms x\ny = 3*sin(x)+7*cos(5*x); % defining the function\nlhs = diff(y,2)+y; %evaluting the lhs of the equation\nrhs = -5*cos(2*x); %rhs of the equation\nif(isequal(lhs,rhs))\n disp('Yes, the equation holds true');\nelse\n disp('No, the equation does not hold true');\nend\ndisp('Value of LHS is: '), disp(lhs);"
},
{
"code": null,
"e": 108883,
"s": 108825,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 108952,
"s": 108883,
"text": "No, the equation does not hold true\nValue of LHS is: \n-168*cos(5*x)\n"
},
{
"code": null,
"e": 109010,
"s": 108952,
"text": "Following is Octave equivalent of the above calculation −"
},
{
"code": null,
"e": 109388,
"s": 109010,
"text": "pkg load symbolic\nsymbols\n\nx = sym(\"x\");\ny = 3*Sin(x)+7*Cos(5*x); % defining the function\nlhs = differentiate(y, x, 2) + y; %evaluting the lhs of the equation\nrhs = -5*Cos(2*x); %rhs of the equation\n\nif(lhs == rhs)\n disp('Yes, the equation holds true');\nelse\n disp('No, the equation does not hold true');\nend\ndisp('Value of LHS is: '), disp(lhs);"
},
{
"code": null,
"e": 109448,
"s": 109388,
"text": "Octave executes the code and returns the following result −"
},
{
"code": null,
"e": 109525,
"s": 109448,
"text": "No, the equation does not hold true\nValue of LHS is: \n-(168.0)*cos((5.0)*x)\n"
},
{
"code": null,
"e": 109765,
"s": 109525,
"text": "If we are searching for the local maxima and minima for a graph, we are basically looking for the highest or lowest points on the graph of the function at a particular locality, or for a particular range of values of the symbolic variable."
},
{
"code": null,
"e": 109928,
"s": 109765,
"text": "For a function y = f(x) the points on the graph where the graph has zero slope are called stationary points. In other words stationary points are where f'(x) = 0."
},
{
"code": null,
"e": 110058,
"s": 109928,
"text": "To find the stationary points of a function we differentiate, we need to set the derivative equal to zero and solve the equation."
},
{
"code": null,
"e": 110136,
"s": 110058,
"text": "Let us find the stationary points of the function f(x) = 2x3 + 3x2 − 12x + 17"
},
{
"code": null,
"e": 110163,
"s": 110136,
"text": "Take the following steps −"
},
{
"code": null,
"e": 110215,
"s": 110163,
"text": "First let us enter the function and plot its graph."
},
{
"code": null,
"e": 110289,
"s": 110215,
"text": "syms x\ny = 2*x^3 + 3*x^2 - 12*x + 17; % defining the function\nezplot(y)"
},
{
"code": null,
"e": 110347,
"s": 110289,
"text": "MATLAB executes the code and returns the following plot −"
},
{
"code": null,
"e": 110402,
"s": 110347,
"text": "Here is Octave equivalent code for the above example −"
},
{
"code": null,
"e": 110517,
"s": 110402,
"text": "pkg load symbolic\nsymbols\n\nx = sym('x');\ny = inline(\"2*x^3 + 3*x^2 - 12*x + 17\");\n\nezplot(y)\nprint -deps graph.eps"
},
{
"code": null,
"e": 110661,
"s": 110517,
"text": "Our aim is to find some local maxima and minima on the graph, so let us find the local maxima and minima for the interval [-2, 2] on the graph."
},
{
"code": null,
"e": 110744,
"s": 110661,
"text": "syms x\ny = 2*x^3 + 3*x^2 - 12*x + 17; % defining the function\nezplot(y, [-2, 2])"
},
{
"code": null,
"e": 110802,
"s": 110744,
"text": "MATLAB executes the code and returns the following plot −"
},
{
"code": null,
"e": 110857,
"s": 110802,
"text": "Here is Octave equivalent code for the above example −"
},
{
"code": null,
"e": 110981,
"s": 110857,
"text": "pkg load symbolic\nsymbols\n\nx = sym('x');\ny = inline(\"2*x^3 + 3*x^2 - 12*x + 17\");\n\nezplot(y, [-2, 2])\nprint -deps graph.eps"
},
{
"code": null,
"e": 111018,
"s": 110981,
"text": "Next, let us compute the derivative."
},
{
"code": null,
"e": 111030,
"s": 111018,
"text": "g = diff(y)"
},
{
"code": null,
"e": 111090,
"s": 111030,
"text": "MATLAB executes the code and returns the following result −"
},
{
"code": null,
"e": 111115,
"s": 111090,
"text": "g =\n 6*x^2 + 6*x - 12\n"
},
{
"code": null,
"e": 111168,
"s": 111115,
"text": "Here is Octave equivalent of the above calculation −"
},
{
"code": null,
"e": 111263,
"s": 111168,
"text": "pkg load symbolic\nsymbols\n\nx = sym(\"x\");\ny = 2*x^3 + 3*x^2 - 12*x + 17;\ng = differentiate(y,x)"
},
{
"code": null,
"e": 111323,
"s": 111263,
"text": "Octave executes the code and returns the following result −"
},
{
"code": null,
"e": 111359,
"s": 111323,
"text": "g =\n -12.0+(6.0)*x+(6.0)*x^(2.0)\n"
},
{
"code": null,
"e": 111441,
"s": 111359,
"text": "Let us solve the derivative function, g, to get the values where it becomes zero."
},
{
"code": null,
"e": 111454,
"s": 111441,
"text": "s = solve(g)"
},
{
"code": null,
"e": 111514,
"s": 111454,
"text": "MATLAB executes the code and returns the following result −"
},
{
"code": null,
"e": 111530,
"s": 111514,
"text": "s =\n 1\n -2\n"
},
{
"code": null,
"e": 111588,
"s": 111530,
"text": "Following is Octave equivalent of the above calculation −"
},
{
"code": null,
"e": 111702,
"s": 111588,
"text": "pkg load symbolic\nsymbols\n\nx = sym(\"x\");\ny = 2*x^3 + 3*x^2 - 12*x + 17;\ng = differentiate(y,x)\nroots([6, 6, -12])"
},
{
"code": null,
"e": 111762,
"s": 111702,
"text": "Octave executes the code and returns the following result −"
},
{
"code": null,
"e": 111813,
"s": 111762,
"text": "g =\n\n-12.0+(6.0)*x^(2.0)+(6.0)*x\nans =\n\n -2\n 1\n"
},
{
"code": null,
"e": 111984,
"s": 111813,
"text": "This agrees with our plot. So let us evaluate the function f at the critical points x = 1, -2. We can substitute a value in a symbolic function by using the subs command."
},
{
"code": null,
"e": 112008,
"s": 111984,
"text": "subs(y, 1), subs(y, -2)"
},
{
"code": null,
"e": 112068,
"s": 112008,
"text": "MATLAB executes the code and returns the following result −"
},
{
"code": null,
"e": 112093,
"s": 112068,
"text": "ans =\n 10\nans =\n 37\n"
},
{
"code": null,
"e": 112151,
"s": 112093,
"text": "Following is Octave equivalent of the above calculation −"
},
{
"code": null,
"e": 112296,
"s": 112151,
"text": "pkg load symbolic\nsymbols\n\nx = sym(\"x\");\ny = 2*x^3 + 3*x^2 - 12*x + 17;\ng = differentiate(y,x)\n\nroots([6, 6, -12])\nsubs(y, x, 1), subs(y, x, -2)"
},
{
"code": null,
"e": 112353,
"s": 112296,
"text": "ans =\n 10.0\nans =\n 37.0-4.6734207789940138748E-18*I\n"
},
{
"code": null,
"e": 112478,
"s": 112353,
"text": "Therefore, The minimum and maximum values on the function f(x) = 2x3 + 3x2 − 12x + 17, in the interval [-2,2] are 10 and 37."
},
{
"code": null,
"e": 112562,
"s": 112478,
"text": "MATLAB provides the dsolve command for solving differential equations symbolically."
},
{
"code": null,
"e": 112653,
"s": 112562,
"text": "The most basic form of the dsolve command for finding the solution to a single equation is"
},
{
"code": null,
"e": 112669,
"s": 112653,
"text": "dsolve('eqn') \n"
},
{
"code": null,
"e": 112724,
"s": 112669,
"text": "where eqn is a text string used to enter the equation."
},
{
"code": null,
"e": 112828,
"s": 112724,
"text": "It returns a symbolic solution with a set of arbitrary constants that MATLAB labels C1, C2, and so on. "
},
{
"code": null,
"e": 112950,
"s": 112828,
"text": "You can also specify initial and boundary conditions for the problem, as comma-delimited list following the equation as −"
},
{
"code": null,
"e": 112988,
"s": 112950,
"text": "dsolve('eqn','cond1', 'cond2',...) \n"
},
{
"code": null,
"e": 113134,
"s": 112988,
"text": "For the purpose of using dsolve command, derivatives are indicated with a D. For example, an equation like f'(t) = -2*f + cost(t) is entered as −"
},
{
"code": null,
"e": 113155,
"s": 113134,
"text": "'Df = -2*f + cos(t)'"
},
{
"code": null,
"e": 113235,
"s": 113155,
"text": "Higher derivatives are indicated by following D by the order of the derivative."
},
{
"code": null,
"e": 113307,
"s": 113235,
"text": "For example the equation f\"(x) + 2f'(x) = 5sin3x should be entered as −"
},
{
"code": null,
"e": 113332,
"s": 113307,
"text": "'D2y + 2Dy = 5*sin(3*x)'"
},
{
"code": null,
"e": 113413,
"s": 113332,
"text": "Let us take up a simple example of a first order differential equation: y' = 5y."
},
{
"code": null,
"e": 113437,
"s": 113413,
"text": "s = dsolve('Dy = 5*y')\n"
},
{
"code": null,
"e": 113497,
"s": 113437,
"text": "MATLAB executes the code and returns the following result −"
},
{
"code": null,
"e": 113517,
"s": 113497,
"text": "s =\n C2*exp(5*t)\n"
},
{
"code": null,
"e": 113626,
"s": 113517,
"text": "Let us take up another example of a second order differential equation as: y\" - y = 0, y(0) = -1, y'(0) = 2."
},
{
"code": null,
"e": 113672,
"s": 113626,
"text": "dsolve('D2y - y = 0','y(0) = -1','Dy(0) = 2')"
},
{
"code": null,
"e": 113732,
"s": 113672,
"text": "MATLAB executes the code and returns the following result −"
},
{
"code": null,
"e": 113767,
"s": 113732,
"text": "ans =\n exp(t)/2 - (3*exp(-t))/2\n"
},
{
"code": null,
"e": 113835,
"s": 113767,
"text": "Integration deals with two essentially different types of problems."
},
{
"code": null,
"e": 114111,
"s": 113835,
"text": "In the first type, derivative of a function is given and we want to find the function. Therefore, we basically reverse the process of differentiation. This reverse process is known as anti-differentiation, or finding the primitive function, or finding an indefinite integral."
},
{
"code": null,
"e": 114387,
"s": 114111,
"text": "In the first type, derivative of a function is given and we want to find the function. Therefore, we basically reverse the process of differentiation. This reverse process is known as anti-differentiation, or finding the primitive function, or finding an indefinite integral."
},
{
"code": null,
"e": 114656,
"s": 114387,
"text": "The second type of problems involve adding up a very large number of very small quantities and then taking a limit as the size of the quantities approaches zero, while the number of terms tend to infinity. This process leads to the definition of the definite integral."
},
{
"code": null,
"e": 114925,
"s": 114656,
"text": "The second type of problems involve adding up a very large number of very small quantities and then taking a limit as the size of the quantities approaches zero, while the number of terms tend to infinity. This process leads to the definition of the definite integral."
},
{
"code": null,
"e": 115075,
"s": 114925,
"text": "Definite integrals are used for finding area, volume, center of gravity, moment of inertia, work done by a force, and in numerous other applications."
},
{
"code": null,
"e": 115333,
"s": 115075,
"text": "By definition, if the derivative of a function f(x) is f'(x), then we say that an indefinite integral of f'(x) with respect to x is f(x). For example, since the derivative (with respect to x) of x2 is 2x, we can say that an indefinite integral of 2x is x2."
},
{
"code": null,
"e": 115346,
"s": 115333,
"text": "In symbols −"
},
{
"code": null,
"e": 115370,
"s": 115346,
"text": "f'(x2) = 2x, therefore,"
},
{
"code": null,
"e": 115383,
"s": 115370,
"text": "∫ 2xdx = x2."
},
{
"code": null,
"e": 115496,
"s": 115383,
"text": "Indefinite integral is not unique, because derivative of x2 + c, for any value of a constant c, will also be 2x."
},
{
"code": null,
"e": 115530,
"s": 115496,
"text": "This is expressed in symbols as −"
},
{
"code": null,
"e": 115547,
"s": 115530,
"text": "∫ 2xdx = x2 + c."
},
{
"code": null,
"e": 115591,
"s": 115547,
"text": "Where, c is called an 'arbitrary constant'."
},
{
"code": null,
"e": 115743,
"s": 115591,
"text": "MATLAB provides an int command for calculating integral of an expression. To derive an expression for the indefinite integral of a function, we write −"
},
{
"code": null,
"e": 115752,
"s": 115743,
"text": "int(f);\n"
},
{
"code": null,
"e": 115793,
"s": 115752,
"text": "For example, from our previous example −"
},
{
"code": null,
"e": 115810,
"s": 115793,
"text": "syms x \nint(2*x)"
},
{
"code": null,
"e": 115881,
"s": 115810,
"text": "MATLAB executes the above statement and returns the following result −"
},
{
"code": null,
"e": 115895,
"s": 115881,
"text": "ans =\n x^2\n"
},
{
"code": null,
"e": 116029,
"s": 115895,
"text": "In this example, let us find the integral of some commonly used expressions. Create a script file and type the following code in it −"
},
{
"code": null,
"e": 116115,
"s": 116029,
"text": "syms x n\n\nint(sym(x^n))\nf = 'sin(n*t)'\nint(sym(f))\nsyms a t\nint(a*cos(pi*t))\nint(a^x)"
},
{
"code": null,
"e": 116173,
"s": 116115,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 116328,
"s": 116173,
"text": "ans =\n piecewise([n == -1, log(x)], [n ~= -1, x^(n + 1)/(n + 1)])\nf =\nsin(n*t)\nans =\n -cos(n*t)/n\n ans =\n (a*sin(pi*t))/pi\n ans =\n a^x/log(a)\n"
},
{
"code": null,
"e": 116385,
"s": 116328,
"text": "Create a script file and type the following code in it −"
},
{
"code": null,
"e": 116620,
"s": 116385,
"text": "syms x n\nint(cos(x))\nint(exp(x))\nint(log(x))\nint(x^-1)\nint(x^5*cos(5*x))\npretty(int(x^5*cos(5*x)))\nint(x^-5)\nint(sec(x)^2)\npretty(int(1 - 10*x + 9 * x^2))\nint((3 + 5*x -6*x^2 - 7*x^3)/2*x^2)\npretty(int((3 + 5*x -6*x^2 - 7*x^3)/2*x^2))"
},
{
"code": null,
"e": 116699,
"s": 116620,
"text": "Note that the pretty function returns an expression in a more readable format."
},
{
"code": null,
"e": 116757,
"s": 116699,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 117564,
"s": 116757,
"text": "ans =\n sin(x)\n \nans =\n exp(x)\n \nans =\n x*(log(x) - 1)\n \nans =\n log(x)\n \nans =\n(24*cos(5*x))/3125 + (24*x*sin(5*x))/625 - (12*x^2*cos(5*x))/125 + (x^4*cos(5*x))/5 - (4*x^3*sin(5*x))/25 + (x^5*sin(5*x))/5\n 2 4 \n 24 cos(5 x) 24 x sin(5 x) 12 x cos(5 x) x cos(5 x) \n ----------- + ------------- - -------------- + ------------ \n 3125 625 125 5 \n \n 3 5 \n \n 4 x sin(5 x) x sin(5 x) \n ------------- + ----------- \n 25 5\n \nans =\n-1/(4*x^4)\n \nans =\ntan(x)\n 2 \n x (3 x - 5 x + 1)\n \nans = \n- (7*x^6)/12 - (3*x^5)/5 + (5*x^4)/8 + x^3/2\n \n 6 5 4 3 \n 7 x 3 x 5 x x \n - ---- - ---- + ---- + -- \n 12 5 8 2\n\n"
},
{
"code": null,
"e": 117876,
"s": 117564,
"text": "By definition, definite integral is basically the limit of a sum. We use definite integrals to find areas such as the area between a curve and the x-axis and the area between two curves. Definite integrals can also be used in other situations, where the quantity required can be expressed as the limit of a sum."
},
{
"code": null,
"e": 117999,
"s": 117876,
"text": "The int function can be used for definite integration by passing the limits over which you want to calculate the integral."
},
{
"code": null,
"e": 118012,
"s": 117999,
"text": "To calculate"
},
{
"code": null,
"e": 118022,
"s": 118012,
"text": "we write,"
},
{
"code": null,
"e": 118036,
"s": 118022,
"text": "int(x, a, b)\n"
},
{
"code": null,
"e": 118087,
"s": 118036,
"text": "For example, to calculate the value of we write −"
},
{
"code": null,
"e": 118100,
"s": 118087,
"text": "int(x, 4, 9)"
},
{
"code": null,
"e": 118171,
"s": 118100,
"text": "MATLAB executes the above statement and returns the following result −"
},
{
"code": null,
"e": 118186,
"s": 118171,
"text": "ans =\n 65/2\n"
},
{
"code": null,
"e": 118244,
"s": 118186,
"text": "Following is Octave equivalent of the above calculation −"
},
{
"code": null,
"e": 118413,
"s": 118244,
"text": "pkg load symbolic\nsymbols\n\nx = sym(\"x\");\nf = x;\nc = [1, 0];\nintegral = polyint(c);\n\na = polyval(integral, 9) - polyval(integral, 4);\ndisplay('Area: '), disp(double(a));"
},
{
"code": null,
"e": 118473,
"s": 118413,
"text": "Octave executes the code and returns the following result −"
},
{
"code": null,
"e": 118492,
"s": 118473,
"text": "Area: \n\n 32.500\n"
},
{
"code": null,
"e": 118583,
"s": 118492,
"text": "An alternative solution can be given using quad() function provided by Octave as follows −"
},
{
"code": null,
"e": 118702,
"s": 118583,
"text": "pkg load symbolic\nsymbols\n\nf = inline(\"x\");\n[a, ierror, nfneval] = quad(f, 4, 9);\n\ndisplay('Area: '), disp(double(a));"
},
{
"code": null,
"e": 118762,
"s": 118702,
"text": "Octave executes the code and returns the following result −"
},
{
"code": null,
"e": 118780,
"s": 118762,
"text": "Area: \n 32.500\n"
},
{
"code": null,
"e": 118896,
"s": 118780,
"text": "Let us calculate the area enclosed between the x-axis, and the curve y = x3−2x+5 and the ordinates x = 1 and x = 2."
},
{
"code": null,
"e": 118928,
"s": 118896,
"text": "The required area is given by −"
},
{
"code": null,
"e": 118979,
"s": 118928,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 119050,
"s": 118979,
"text": "f = x^3 - 2*x +5;\na = int(f, 1, 2)\ndisplay('Area: '), disp(double(a));"
},
{
"code": null,
"e": 119108,
"s": 119050,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 119135,
"s": 119108,
"text": "a =\n23/4\nArea: \n 5.7500\n"
},
{
"code": null,
"e": 119193,
"s": 119135,
"text": "Following is Octave equivalent of the above calculation −"
},
{
"code": null,
"e": 119380,
"s": 119193,
"text": "pkg load symbolic\nsymbols\n\nx = sym(\"x\");\nf = x^3 - 2*x +5;\nc = [1, 0, -2, 5];\nintegral = polyint(c);\n\na = polyval(integral, 2) - polyval(integral, 1);\ndisplay('Area: '), disp(double(a));"
},
{
"code": null,
"e": 119440,
"s": 119380,
"text": "Octave executes the code and returns the following result −"
},
{
"code": null,
"e": 119459,
"s": 119440,
"text": "Area: \n\n 5.7500\n"
},
{
"code": null,
"e": 119550,
"s": 119459,
"text": "An alternative solution can be given using quad() function provided by Octave as follows −"
},
{
"code": null,
"e": 119694,
"s": 119550,
"text": "pkg load symbolic\nsymbols\n\nx = sym(\"x\");\nf = inline(\"x^3 - 2*x +5\");\n\n[a, ierror, nfneval] = quad(f, 1, 2);\ndisplay('Area: '), disp(double(a));"
},
{
"code": null,
"e": 119754,
"s": 119694,
"text": "Octave executes the code and returns the following result −"
},
{
"code": null,
"e": 119772,
"s": 119754,
"text": "Area: \n 5.7500\n"
},
{
"code": null,
"e": 119837,
"s": 119772,
"text": "Find the area under the curve: f(x) = x2 cos(x) for −4 ≤ x ≤ 9."
},
{
"code": null,
"e": 119889,
"s": 119837,
"text": "Create a script file and write the following code −"
},
{
"code": null,
"e": 119974,
"s": 119889,
"text": "f = x^2*cos(x);\nezplot(f, [-4,9])\na = int(f, -4, 9)\ndisp('Area: '), disp(double(a));"
},
{
"code": null,
"e": 120022,
"s": 119974,
"text": "When you run the file, MATLAB plots the graph −"
},
{
"code": null,
"e": 120050,
"s": 120022,
"text": "The output is given below −"
},
{
"code": null,
"e": 120120,
"s": 120050,
"text": "a = \n8*cos(4) + 18*cos(9) + 14*sin(4) + 79*sin(9)\n \nArea: \n 0.3326\n"
},
{
"code": null,
"e": 120178,
"s": 120120,
"text": "Following is Octave equivalent of the above calculation −"
},
{
"code": null,
"e": 120362,
"s": 120178,
"text": "pkg load symbolic\nsymbols\n\nx = sym(\"x\");\nf = inline(\"x^2*cos(x)\");\n\nezplot(f, [-4,9])\nprint -deps graph.eps\n\n[a, ierror, nfneval] = quad(f, -4, 9);\ndisplay('Area: '), disp(double(a));"
},
{
"code": null,
"e": 120538,
"s": 120362,
"text": "MATLAB represents polynomials as row vectors containing coefficients ordered by descending powers. For example, the equation P(x) = x4 + 7x3 - 5x + 9 could be represented as −"
},
{
"code": null,
"e": 120557,
"s": 120538,
"text": "p = [1 7 0 -5 9];"
},
{
"code": null,
"e": 120705,
"s": 120557,
"text": "The polyval function is used for evaluating a polynomial at a specified value. For example, to evaluate our previous polynomial p, at x = 4, type −"
},
{
"code": null,
"e": 120737,
"s": 120705,
"text": "p = [1 7 0 -5 9];\npolyval(p,4)"
},
{
"code": null,
"e": 120809,
"s": 120737,
"text": "MATLAB executes the above statements and returns the following result −"
},
{
"code": null,
"e": 120820,
"s": 120809,
"text": "ans = 693\n"
},
{
"code": null,
"e": 120963,
"s": 120820,
"text": "MATLAB also provides the polyvalm function for evaluating a matrix polynomial. A matrix polynomial is a polynomial with matrices as variables."
},
{
"code": null,
"e": 121046,
"s": 120963,
"text": "For example, let us create a square matrix X and evaluate the polynomial p, at X −"
},
{
"code": null,
"e": 121125,
"s": 121046,
"text": "p = [1 7 0 -5 9];\nX = [1 2 -3 4; 2 -5 6 3; 3 1 0 2; 5 -7 3 8];\npolyvalm(p, X)"
},
{
"code": null,
"e": 121197,
"s": 121125,
"text": "MATLAB executes the above statements and returns the following result −"
},
{
"code": null,
"e": 121392,
"s": 121197,
"text": "ans =\n 2307 -1769 -939 4499\n 2314 -2376 -249 4695\n 2256 -1892 -549 4310\n 4570 -4532 -1062 9269\n"
},
{
"code": null,
"e": 121513,
"s": 121392,
"text": "The roots function calculates the roots of a polynomial. For example, to calculate the roots of our polynomial p, type −"
},
{
"code": null,
"e": 121545,
"s": 121513,
"text": "p = [1 7 0 -5 9];\nr = roots(p)"
},
{
"code": null,
"e": 121617,
"s": 121545,
"text": "MATLAB executes the above statements and returns the following result −"
},
{
"code": null,
"e": 121704,
"s": 121617,
"text": "r =\n -6.8661 + 0.0000i\n -1.4247 + 0.0000i\n 0.6454 + 0.7095i\n 0.6454 - 0.7095i\n"
},
{
"code": null,
"e": 121816,
"s": 121704,
"text": "The function poly is an inverse of the roots function and returns to the polynomial coefficients. For example −"
},
{
"code": null,
"e": 121829,
"s": 121816,
"text": "p2 = poly(r)"
},
{
"code": null,
"e": 121901,
"s": 121829,
"text": "MATLAB executes the above statements and returns the following result −"
},
{
"code": null,
"e": 122069,
"s": 121901,
"text": "p2 =\n\n Columns 1 through 3:\n\n 1.00000 + 0.00000i 7.00000 + 0.00000i 0.00000 + 0.00000i\n\n Columns 4 and 5:\n\n -5.00000 - 0.00000i 9.00000 + 0.00000i\n"
},
{
"code": null,
"e": 122330,
"s": 122069,
"text": "The polyfit function finds the coefficients of a polynomial that fits a set of data in a least-squares sense. If x and y are two vectors containing the x and y data to be fitted to a n-degree polynomial, then we get the polynomial fitting the data by writing −"
},
{
"code": null,
"e": 122349,
"s": 122330,
"text": "p = polyfit(x,y,n)"
},
{
"code": null,
"e": 122400,
"s": 122349,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 122711,
"s": 122400,
"text": "x = [1 2 3 4 5 6]; y = [5.5 43.1 128 290.7 498.4 978.67]; %data\np = polyfit(x,y,4) %get the polynomial\n\n% Compute the values of the polyfit estimate over a finer range, \n% and plot the estimate over the real data values for comparison:\nx2 = 1:.1:6; \ny2 = polyval(p,x2);\nplot(x,y,'o',x2,y2)\ngrid on"
},
{
"code": null,
"e": 122773,
"s": 122711,
"text": "When you run the file, MATLAB displays the following result −"
},
{
"code": null,
"e": 122828,
"s": 122773,
"text": "p =\n 4.1056 -47.9607 222.2598 -362.7453 191.1250\n"
},
{
"code": null,
"e": 122860,
"s": 122828,
"text": "And plots the following graph −"
},
{
"code": null,
"e": 123076,
"s": 122860,
"text": "MATLAB provides command for working with transforms, such as the Laplace and Fourier transforms. Transforms are used in science and engineering as a tool for simplifying analysis and look at data from another angle."
},
{
"code": null,
"e": 123292,
"s": 123076,
"text": "For example, the Fourier transform allows us to convert a signal represented as a function of time to a function of frequency. Laplace transform allows us to convert a differential equation to an algebraic equation."
},
{
"code": null,
"e": 123405,
"s": 123292,
"text": "MATLAB provides the laplace, fourier and fft commands to work with Laplace, Fourier and Fast Fourier transforms."
},
{
"code": null,
"e": 123491,
"s": 123405,
"text": "The Laplace transform of a function of time f(t) is given by the following integral −"
},
{
"code": null,
"e": 123712,
"s": 123491,
"text": "Laplace transform is also denoted as transform of f(t) to F(s). You can see this transform or integration process converts f(t), a function of the symbolic variable t, into another function F(s), with another variable s."
},
{
"code": null,
"e": 123839,
"s": 123712,
"text": "Laplace transform turns differential equations into algebraic ones. To compute a Laplace transform of a function f(t), write −"
},
{
"code": null,
"e": 123853,
"s": 123839,
"text": "laplace(f(t))"
},
{
"code": null,
"e": 123941,
"s": 123853,
"text": "In this example, we will compute the Laplace transform of some commonly used functions."
},
{
"code": null,
"e": 123992,
"s": 123941,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 124100,
"s": 123992,
"text": "syms s t a b w\n\nlaplace(a)\nlaplace(t^2)\nlaplace(t^9)\nlaplace(exp(-b*t))\nlaplace(sin(w*t))\nlaplace(cos(w*t))"
},
{
"code": null,
"e": 124158,
"s": 124100,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 124284,
"s": 124158,
"text": "ans =\n 1/s^2\n\nans =\n 2/s^3\n\nans =\n 362880/s^10\n\nans =\n 1/(b + s)\n \nans =\n w/(s^2 + w^2)\n \nans =\n s/(s^2 + w^2)\n"
},
{
"code": null,
"e": 124370,
"s": 124284,
"text": "MATLAB allows us to compute the inverse Laplace transform using the command ilaplace."
},
{
"code": null,
"e": 124383,
"s": 124370,
"text": "For example,"
},
{
"code": null,
"e": 124399,
"s": 124383,
"text": "ilaplace(1/s^3)"
},
{
"code": null,
"e": 124464,
"s": 124399,
"text": "MATLAB will execute the above statement and display the result −"
},
{
"code": null,
"e": 124480,
"s": 124464,
"text": "ans =\n t^2/2\n"
},
{
"code": null,
"e": 124531,
"s": 124480,
"text": "Create a script file and type the following code −"
},
{
"code": null,
"e": 124669,
"s": 124531,
"text": "syms s t a b w\n\nilaplace(1/s^7)\nilaplace(2/(w+s))\nilaplace(s/(s^2+4))\nilaplace(exp(-b*t))\nilaplace(w/(s^2 + w^2))\nilaplace(s/(s^2 + w^2))"
},
{
"code": null,
"e": 124727,
"s": 124669,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 124860,
"s": 124727,
"text": "ans =\n t^6/720\n\nans =\n 2*exp(-t*w)\n\nans =\n cos(2*t)\n\nans =\n ilaplace(exp(-b*t), t, x)\n\nans =\n sin(t*w)\n\nans =\n cos(t*w)\n"
},
{
"code": null,
"e": 125174,
"s": 124860,
"text": "Fourier transforms commonly transforms a mathematical function of time, f(t), into a new function, sometimes denoted by or F, whose argument is frequency with units of cycles/s (hertz) or radians per second. The new function is then known as the Fourier transform and/or the frequency spectrum of the function f."
},
{
"code": null,
"e": 125231,
"s": 125174,
"text": "Create a script file and type the following code in it −"
},
{
"code": null,
"e": 125359,
"s": 125231,
"text": "syms x \nf = exp(-2*x^2); %our function\nezplot(f,[-2,2]) % plot of our function\nFT = fourier(f) % Fourier transform"
},
{
"code": null,
"e": 125417,
"s": 125359,
"text": "When you run the file, MATLAB plots the following graph −"
},
{
"code": null,
"e": 125453,
"s": 125417,
"text": "The following result is displayed −"
},
{
"code": null,
"e": 125495,
"s": 125453,
"text": "FT =\n (2^(1/2)*pi^(1/2)*exp(-w^2/8))/2\n"
},
{
"code": null,
"e": 125531,
"s": 125495,
"text": "Plotting the Fourier transform as −"
},
{
"code": null,
"e": 125542,
"s": 125531,
"text": "ezplot(FT)"
},
{
"code": null,
"e": 125570,
"s": 125542,
"text": "Gives the following graph −"
},
{
"code": null,
"e": 125679,
"s": 125570,
"text": "MATLAB provides the ifourier command for computing the inverse Fourier transform of a function. For example,"
},
{
"code": null,
"e": 125709,
"s": 125679,
"text": "f = ifourier(-2*exp(-abs(w)))"
},
{
"code": null,
"e": 125774,
"s": 125709,
"text": "MATLAB will execute the above statement and display the result −"
},
{
"code": null,
"e": 125800,
"s": 125774,
"text": "f =\n -2/(pi*(x^2 + 1))\n"
},
{
"code": null,
"e": 125945,
"s": 125800,
"text": "GNU Octave is a high-level programming language like MATLAB and it is mostly compatible with MATLAB. It is also used for numerical computations."
},
{
"code": null,
"e": 126000,
"s": 125945,
"text": "Octave has the following common features with MATLAB −"
},
{
"code": null,
"e": 126035,
"s": 126000,
"text": "matrices are fundamental data type"
},
{
"code": null,
"e": 126079,
"s": 126035,
"text": "it has built-in support for complex numbers"
},
{
"code": null,
"e": 126124,
"s": 126079,
"text": "it has built-in math functions and libraries"
},
{
"code": null,
"e": 126159,
"s": 126124,
"text": "it supports user-defined functions"
},
{
"code": null,
"e": 126354,
"s": 126159,
"text": "GNU Octave is also freely redistributable software. You may redistribute it and/or modify it under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation."
},
{
"code": null,
"e": 126501,
"s": 126354,
"text": "Most MATLAB programs run in Octave, but some of the Octave programs may not run in MATLAB because, Octave allows some syntax that MATLAB does not."
},
{
"code": null,
"e": 126764,
"s": 126501,
"text": "For example, MATLAB supports single quotes only, but Octave supports both single and double quotes for defining strings. If you are looking for a tutorial on Octave, then kindly go through this tutorial from beginning which covers both MATLAB as well as Octave."
},
{
"code": null,
"e": 126964,
"s": 126764,
"text": "Almost all the examples covered in this tutorial are compatible with MATLAB as well as Octave. Let's try following example in MATLAB and Octave which produces same result without any syntax changes −"
},
{
"code": null,
"e": 127088,
"s": 126964,
"text": "This example creates a 3D surface map for the function g = xe-(x2 + y2). Create a script file and type the following code −"
},
{
"code": null,
"e": 127179,
"s": 127088,
"text": "[x,y] = meshgrid(-2:.2:2);\ng = x .* exp(-x.^2 - y.^2);\nsurf(x, y, g)\nprint -deps graph.eps"
},
{
"code": null,
"e": 127242,
"s": 127179,
"text": "When you run the file, MATLAB displays the following 3-D map −"
},
{
"code": null,
"e": 127532,
"s": 127242,
"text": "Though all the core functionality of MATLAB is available in Octave, there are some functionality for example, Differential & Integration Calculus, which does not match exactly in both the languages. This tutorial has tried to give both type of examples where they differed in their syntax."
},
{
"code": null,
"e": 127718,
"s": 127532,
"text": "Consider following example where MATLAB and Octave make use of different functions to get the area of a curve: f(x) = x2 cos(x) for −4 ≤ x ≤ 9. Following is MATLAB version of the code −"
},
{
"code": null,
"e": 127803,
"s": 127718,
"text": "f = x^2*cos(x);\nezplot(f, [-4,9])\na = int(f, -4, 9)\ndisp('Area: '), disp(double(a));"
},
{
"code": null,
"e": 127851,
"s": 127803,
"text": "When you run the file, MATLAB plots the graph −"
},
{
"code": null,
"e": 127885,
"s": 127851,
"text": "The following result is displayed"
},
{
"code": null,
"e": 127954,
"s": 127885,
"text": "a =\n8*cos(4) + 18*cos(9) + 14*sin(4) + 79*sin(9)\n \nArea: \n 0.3326\n"
},
{
"code": null,
"e": 128059,
"s": 127954,
"text": "But to give area of the same curve in Octave, you will have to make use of symbolic package as follows −"
},
{
"code": null,
"e": 128243,
"s": 128059,
"text": "pkg load symbolic\nsymbols\n\nx = sym(\"x\");\nf = inline(\"x^2*cos(x)\");\n\nezplot(f, [-4,9])\nprint -deps graph.eps\n\n[a, ierror, nfneval] = quad(f, -4, 9);\ndisplay('Area: '), disp(double(a));"
},
{
"code": null,
"e": 128614,
"s": 128243,
"text": "Simulink is a simulation and model-based design environment for dynamic and embedded systems, integrated with MATLAB. Simulink, also developed by MathWorks, is a data flow graphical programming language tool for modelling, simulating and analyzing multi-domain dynamic systems. It is basically a graphical block diagramming tool with customizable set of block libraries."
},
{
"code": null,
"e": 128748,
"s": 128614,
"text": "It allows you to incorporate MATLAB algorithms into models as well as export the simulation results into MATLAB for further analysis."
},
{
"code": null,
"e": 128768,
"s": 128748,
"text": "Simulink supports −"
},
{
"code": null,
"e": 128788,
"s": 128768,
"text": "system-level design"
},
{
"code": null,
"e": 128799,
"s": 128788,
"text": "simulation"
},
{
"code": null,
"e": 128825,
"s": 128799,
"text": "automatic code generation"
},
{
"code": null,
"e": 128870,
"s": 128825,
"text": "testing and verification of embedded systems"
},
{
"code": null,
"e": 129021,
"s": 128870,
"text": "There are several other add-on products provided by MathWorks and third-party hardware and software products that are available for use with Simulink."
},
{
"code": null,
"e": 129082,
"s": 129021,
"text": "The following list gives brief description of some of them −"
},
{
"code": null,
"e": 129142,
"s": 129082,
"text": "Stateflow allows developing state machines and flow charts."
},
{
"code": null,
"e": 129202,
"s": 129142,
"text": "Stateflow allows developing state machines and flow charts."
},
{
"code": null,
"e": 129311,
"s": 129202,
"text": "Simulink Coder allows the generation of C source code for real-time implementation of systems automatically."
},
{
"code": null,
"e": 129420,
"s": 129311,
"text": "Simulink Coder allows the generation of C source code for real-time implementation of systems automatically."
},
{
"code": null,
"e": 129584,
"s": 129420,
"text": "xPC Target together with x86-based real-time systems provide an environment to simulate and test Simulink and Stateflow models in real-time on the physical system."
},
{
"code": null,
"e": 129748,
"s": 129584,
"text": "xPC Target together with x86-based real-time systems provide an environment to simulate and test Simulink and Stateflow models in real-time on the physical system."
},
{
"code": null,
"e": 129799,
"s": 129748,
"text": "Embedded Coder supports specific embedded targets."
},
{
"code": null,
"e": 129850,
"s": 129799,
"text": "Embedded Coder supports specific embedded targets."
},
{
"code": null,
"e": 129925,
"s": 129850,
"text": "HDL Coder allows to automatically generate synthesizable VHDL and Verilog."
},
{
"code": null,
"e": 130000,
"s": 129925,
"text": "HDL Coder allows to automatically generate synthesizable VHDL and Verilog."
},
{
"code": null,
"e": 130089,
"s": 130000,
"text": "SimEvents provides a library of graphical building blocks for modelling queuing systems."
},
{
"code": null,
"e": 130178,
"s": 130089,
"text": "SimEvents provides a library of graphical building blocks for modelling queuing systems."
},
{
"code": null,
"e": 130339,
"s": 130178,
"text": "Simulink is capable of systematic verification and validation of models through modelling style checking, requirements traceability and model coverage analysis."
},
{
"code": null,
"e": 130457,
"s": 130339,
"text": "Simulink Design Verifier allows you to identify design errors and to generate test case scenarios for model checking."
},
{
"code": null,
"e": 130507,
"s": 130457,
"text": "To open Simulink, type in the MATLAB work space −"
},
{
"code": null,
"e": 130517,
"s": 130507,
"text": "simulink\n"
},
{
"code": null,
"e": 130618,
"s": 130517,
"text": "Simulink opens with the Library Browser. The Library Browser is used for building simulation models."
},
{
"code": null,
"e": 130803,
"s": 130618,
"text": "On the left side window pane, you will find several libraries categorized on the basis of various systems, clicking on each one will display the design blocks on the right window pane."
},
{
"code": null,
"e": 130921,
"s": 130803,
"text": "To create a new model, click the New button on the Library Browser's toolbar. This opens a new untitled model window."
},
{
"code": null,
"e": 130958,
"s": 130921,
"text": "A Simulink model is a block diagram."
},
{
"code": null,
"e": 131087,
"s": 130958,
"text": "Model elements are added by selecting the appropriate elements from the Library Browser and dragging them into the Model window."
},
{
"code": null,
"e": 131170,
"s": 131087,
"text": "Alternately, you can copy the model elements and paste them into the model window."
},
{
"code": null,
"e": 131238,
"s": 131170,
"text": "Drag and drop items from the Simulink library to make your project."
},
{
"code": null,
"e": 131484,
"s": 131238,
"text": "For the purpose of this example, two blocks will be used for the simulation - A Source (a signal) and a Sink (a scope). A signal generator (the source) generates an analog signal, which will then be graphically visualized by the scope(the sink)."
},
{
"code": null,
"e": 131694,
"s": 131484,
"text": "Begin by dragging the required blocks from the library to the project window. Then, connect the blocks together which can be done by dragging connectors from connection points on one block to those of another."
},
{
"code": null,
"e": 131742,
"s": 131694,
"text": "Let us drag a 'Sine Wave' block into the model."
},
{
"code": null,
"e": 131815,
"s": 131742,
"text": "Select 'Sinks' from the library and drag a 'Scope' block into the model."
},
{
"code": null,
"e": 131906,
"s": 131815,
"text": "Drag a signal line from the output of the Sine Wave block to the input of the Scope block."
},
{
"code": null,
"e": 132033,
"s": 131906,
"text": "Run the simulation by pressing the 'Run' button, keeping all parameters default (you can change them from the Simulation menu)"
},
{
"code": null,
"e": 132080,
"s": 132033,
"text": "You should get the below graph from the scope."
},
{
"code": null,
"e": 132113,
"s": 132080,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 132126,
"s": 132113,
"text": " Nouman Azam"
},
{
"code": null,
"e": 132161,
"s": 132126,
"text": "\n 127 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 132174,
"s": 132161,
"text": " Nouman Azam"
},
{
"code": null,
"e": 132207,
"s": 132174,
"text": "\n 17 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 132216,
"s": 132207,
"text": " Sanjeev"
},
{
"code": null,
"e": 132249,
"s": 132216,
"text": "\n 37 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 132265,
"s": 132249,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 132298,
"s": 132265,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 132314,
"s": 132298,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 132347,
"s": 132314,
"text": "\n 18 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 132364,
"s": 132347,
"text": " Phinite Academy"
},
{
"code": null,
"e": 132371,
"s": 132364,
"text": " Print"
},
{
"code": null,
"e": 132382,
"s": 132371,
"text": " Add Notes"
}
] |
ReactJS ReactStrap Tooltip Component - GeeksforGeeks
|
28 Jul, 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 Tooltip component helps in displaying informative text when users hover over, focus on, or tap an element. We can use the following approach in ReactJS to use the ReactJS Reactstrap Tooltip Component.
Tooltip Props:
children: It is used to pass the children element to this component.
trigger: It is used to denote a space-separated list of triggers.
boundariesElement: It is used to denote the boundaries for a popper.
isOpen: It is used to indicate whether to open tooltip or not.
hideArrow: It is used to indicate whether to hide an arrow or not.
toggle: It is a callback function for toggling isOpen in the controlling component.
target: It is used to denote the target element or element ID.
container: It is used to indicate where to inject the popper DOM node.
delay: It is used to denote the delay value.
className: It is used to denote the class name for styling.
popperClassName: It is used to apply a class to the popper component.
innerClassName: It is used to apply a class to the inner-tooltip.
arrowClassName: It is used to apply a class to the arrow-tooltip.
autohide: It is used to indicate whether to hide tooltip when hovering over tooltip content or not.
placement: It is used for the placement of the tooltip.
modifiers: It is used to denote a custom modifier that are passed to Popper.js
positionFixed: It is used to indicate whether the tooltip pointing element has position: fixed styling or not.
offset: It is used to denote offset element.
innerRef: It is used to denote the inner reference element.
fade: It is used to indicate whether to show/hide the tooltip with a fade effect.
flip: It is used to indicate whether to flip the direction of the tooltip if too close to the container edge.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd 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
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 a tooltip at the right position without delay props.
App.js
import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Tooltip, Button } from "reactstrap" function App() { // Tooltip Open state const [tooltipOpen, setTooltipOpen] = React.useState(false); return ( <div style={{ display: 'block', width: 900, padding: 30 }}> <h4>ReactJS Reactstrap Tooltip Component</h4> <Button id="TooltipExample">Hover me to see Tooltip</Button> <Tooltip isOpen={tooltipOpen} placement="right" target="TooltipExample" toggle={() => { setTooltipOpen(!tooltipOpen) }}> Sample Tooltip Text... </Tooltip> </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 a tooltip at the bottom position without delay props set to show tooltip after 1 second and hide it after 2 seconds.
App.js
import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Tooltip } from "reactstrap" function App() { // Tooltip Open state const [tooltipOpen, setTooltipOpen] = React.useState(false); return ( <div style={{ display: 'block', width: 900, padding: 30 }}> <h4>ReactJS Reactstrap Tooltip Component</h4> <span id="testID">Hover Me to see Tooltip!!</span> <Tooltip isOpen={tooltipOpen} delay={{ show:1000, hide: 2000 }} target="testID" placement="bottom" toggle={() => setTooltipOpen(!tooltipOpen)}> Sample ToolTip Information... </Tooltip> </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/tooltips/
Reactstrap
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to filter object array based on attributes?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
|
[
{
"code": null,
"e": 25312,
"s": 25284,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 25679,
"s": 25312,
"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 Tooltip component helps in displaying informative text when users hover over, focus on, or tap an element. We can use the following approach in ReactJS to use the ReactJS Reactstrap Tooltip Component."
},
{
"code": null,
"e": 25694,
"s": 25679,
"text": "Tooltip Props:"
},
{
"code": null,
"e": 25763,
"s": 25694,
"text": "children: It is used to pass the children element to this component."
},
{
"code": null,
"e": 25829,
"s": 25763,
"text": "trigger: It is used to denote a space-separated list of triggers."
},
{
"code": null,
"e": 25898,
"s": 25829,
"text": "boundariesElement: It is used to denote the boundaries for a popper."
},
{
"code": null,
"e": 25961,
"s": 25898,
"text": "isOpen: It is used to indicate whether to open tooltip or not."
},
{
"code": null,
"e": 26028,
"s": 25961,
"text": "hideArrow: It is used to indicate whether to hide an arrow or not."
},
{
"code": null,
"e": 26112,
"s": 26028,
"text": "toggle: It is a callback function for toggling isOpen in the controlling component."
},
{
"code": null,
"e": 26175,
"s": 26112,
"text": "target: It is used to denote the target element or element ID."
},
{
"code": null,
"e": 26246,
"s": 26175,
"text": "container: It is used to indicate where to inject the popper DOM node."
},
{
"code": null,
"e": 26291,
"s": 26246,
"text": "delay: It is used to denote the delay value."
},
{
"code": null,
"e": 26351,
"s": 26291,
"text": "className: It is used to denote the class name for styling."
},
{
"code": null,
"e": 26421,
"s": 26351,
"text": "popperClassName: It is used to apply a class to the popper component."
},
{
"code": null,
"e": 26487,
"s": 26421,
"text": "innerClassName: It is used to apply a class to the inner-tooltip."
},
{
"code": null,
"e": 26553,
"s": 26487,
"text": "arrowClassName: It is used to apply a class to the arrow-tooltip."
},
{
"code": null,
"e": 26653,
"s": 26553,
"text": "autohide: It is used to indicate whether to hide tooltip when hovering over tooltip content or not."
},
{
"code": null,
"e": 26709,
"s": 26653,
"text": "placement: It is used for the placement of the tooltip."
},
{
"code": null,
"e": 26788,
"s": 26709,
"text": "modifiers: It is used to denote a custom modifier that are passed to Popper.js"
},
{
"code": null,
"e": 26899,
"s": 26788,
"text": "positionFixed: It is used to indicate whether the tooltip pointing element has position: fixed styling or not."
},
{
"code": null,
"e": 26944,
"s": 26899,
"text": "offset: It is used to denote offset element."
},
{
"code": null,
"e": 27004,
"s": 26944,
"text": "innerRef: It is used to denote the inner reference element."
},
{
"code": null,
"e": 27086,
"s": 27004,
"text": "fade: It is used to indicate whether to show/hide the tooltip with a fade effect."
},
{
"code": null,
"e": 27196,
"s": 27086,
"text": "flip: It is used to indicate whether to flip the direction of the tooltip if too close to the container edge."
},
{
"code": null,
"e": 27246,
"s": 27196,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 27342,
"s": 27246,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername "
},
{
"code": null,
"e": 27406,
"s": 27342,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 27438,
"s": 27406,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 27553,
"s": 27440,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 27653,
"s": 27553,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 27667,
"s": 27653,
"text": "cd foldername"
},
{
"code": null,
"e": 27804,
"s": 27667,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install reactstrap bootstrap"
},
{
"code": null,
"e": 27909,
"s": 27804,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 27942,
"s": 27909,
"text": "npm install reactstrap bootstrap"
},
{
"code": null,
"e": 27994,
"s": 27942,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 28012,
"s": 27994,
"text": "Project Structure"
},
{
"code": null,
"e": 28150,
"s": 28012,
"text": "Example 1: Now write down the following code in the App.js file. Here, we have shown a tooltip at the right position without delay props."
},
{
"code": null,
"e": 28157,
"s": 28150,
"text": "App.js"
},
{
"code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Tooltip, Button } from \"reactstrap\" function App() { // Tooltip Open state const [tooltipOpen, setTooltipOpen] = React.useState(false); return ( <div style={{ display: 'block', width: 900, padding: 30 }}> <h4>ReactJS Reactstrap Tooltip Component</h4> <Button id=\"TooltipExample\">Hover me to see Tooltip</Button> <Tooltip isOpen={tooltipOpen} placement=\"right\" target=\"TooltipExample\" toggle={() => { setTooltipOpen(!tooltipOpen) }}> Sample Tooltip Text... </Tooltip> </div > );} export default App;",
"e": 28905,
"s": 28157,
"text": null
},
{
"code": null,
"e": 29018,
"s": 28905,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 29028,
"s": 29018,
"text": "npm start"
},
{
"code": null,
"e": 29127,
"s": 29028,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 29329,
"s": 29127,
"text": "Example 2: Now write down the following code in the App.js file. Here, we have shown a tooltip at the bottom position without delay props set to show tooltip after 1 second and hide it after 2 seconds."
},
{
"code": null,
"e": 29336,
"s": 29329,
"text": "App.js"
},
{
"code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Tooltip } from \"reactstrap\" function App() { // Tooltip Open state const [tooltipOpen, setTooltipOpen] = React.useState(false); return ( <div style={{ display: 'block', width: 900, padding: 30 }}> <h4>ReactJS Reactstrap Tooltip Component</h4> <span id=\"testID\">Hover Me to see Tooltip!!</span> <Tooltip isOpen={tooltipOpen} delay={{ show:1000, hide: 2000 }} target=\"testID\" placement=\"bottom\" toggle={() => setTooltipOpen(!tooltipOpen)}> Sample ToolTip Information... </Tooltip> </div > );} export default App;",
"e": 30096,
"s": 29336,
"text": null
},
{
"code": null,
"e": 30209,
"s": 30096,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 30219,
"s": 30209,
"text": "npm start"
},
{
"code": null,
"e": 30318,
"s": 30219,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 30379,
"s": 30318,
"text": "Reference: https://reactstrap.github.io/components/tooltips/"
},
{
"code": null,
"e": 30390,
"s": 30379,
"text": "Reactstrap"
},
{
"code": null,
"e": 30401,
"s": 30390,
"text": "JavaScript"
},
{
"code": null,
"e": 30409,
"s": 30401,
"text": "ReactJS"
},
{
"code": null,
"e": 30426,
"s": 30409,
"text": "Web Technologies"
},
{
"code": null,
"e": 30524,
"s": 30426,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30533,
"s": 30524,
"text": "Comments"
},
{
"code": null,
"e": 30546,
"s": 30533,
"text": "Old Comments"
},
{
"code": null,
"e": 30607,
"s": 30546,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30648,
"s": 30607,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30702,
"s": 30648,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 30742,
"s": 30702,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30790,
"s": 30742,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 30833,
"s": 30790,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30878,
"s": 30833,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 30943,
"s": 30878,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 31011,
"s": 30943,
"text": "How to pass data from one component to other component in ReactJS ?"
}
] |
Difference between align-content and align-items - GeeksforGeeks
|
14 Aug, 2020
Both align-content and align-items function on the cross-axis.Cross-axis in flexbox is dependent on the flex-direction and runs perpendicular to the main-axis, if flex-direction is either row or row-reverse then the cross-axis is vertical, if flex-direction is either column or column-reverse then the cross-axis is horizontal.
flex-start:lines packed to the start of the container
flex-end:lines packed to the end of the container
center:lines packed to the center of the container
space-between:lines evenly distributed; the first line is at the start of the container while the last one is at the end
space-around:lines evenly distributed with equal space between
stretch(Default):lines stretch to take up the remaining space
flex-start:cross-start margin edge of the items is placed on the cross-start line
flex-end:cross-end margin edge of the items is placed on the cross-end line
center:items are centered in the cross-axis
baseline:items are aligned such as their baselines align
stretch(Default):stretch to fill the container
Syntax:
align-content:element{align-content:stretch | center | flex-start | flex-end | space-between | space-around | initial | inherit;// CSS Property}
element{align-content:stretch | center | flex-start | flex-end | space-between | space-around | initial | inherit;// CSS Property}
align-items:element{align-items:stretch | center | flex-start | flex-end | baseline | initial | inherit;// CSS Property}
element{align-items:stretch | center | flex-start | flex-end | baseline | initial | inherit;// CSS Property}
Example for align-content
<!DOCTYPE html><html lang="en"> <head> <title>Align-content</title> <style> /* flex-container(flex-box) */ .flex { background-color: greenyellow; margin: 2% 2%; padding: 0% 3%; float: left; height: 500px; width: 50px; border: 1px solid black; display: flex; flex-wrap: wrap; flex-direction: row; } /* flex-start */ .flexStart { align-content: flex-start; } /* flex-end */ .flexEnd { align-content: flex-end; } /* center */ .center { align-content: center; } /* space-between */ .spaceBetween { align-content: space-between; } /* space-around */ .spaceAround { align-content: space-around; } /* stretch */ .stretch { align-content: stretch; } ul { list-style: none; } .flex-item { background: green; padding: 5px; width: 50px; margin: 5px; line-height: 10px; color: white; font-weight: bold; } </style></head> <body> <ul class="flex flexStart"> <li class="flex-item"> <p>F</p> </li> <li class="flex-item"> <p>LE</p> </li> <li class="flex-item"> <p>X</p> </li> <li class="flex-item"> <p>ST</p> </li> <li class="flex-item"> <p>A</p> </li> <li class="flex-item"> <p>RT</p> </li> </ul> <ul class="flex flexEnd"> <li class="flex-item"> <p>F</p> </li> <li class="flex-item"> <p>LE</p> </li> <li class="flex-item"> <p>X</p> </li> <li class="flex-item"> <p>E</p> </li> <li class="flex-item"> <p>N</p> </li> <li class="flex-item"> <p>D</p> </li> </ul> <ul class="flex center"> <li class="flex-item"> <p>C</p> </li> <li class="flex-item"> <p>E</p> </li> <li class="flex-item"> <p>N</p> </li> <li class="flex-item"> <p>T</p> </li> <li class="flex-item"> <p>E</p> </li> <li class="flex-item"> <p>R</p> </li> </ul> <ul class="flex spaceBetween"> <li class="flex-item"> <p>SP</p> </li> <li class="flex-item"> <p>AC</p> </li> <li class="flex-item"> <p>EB</p> </li> <li class="flex-item"> <p>ET</p> </li> <li class="flex-item"> <p>WE</p> </li> <li class="flex-item"> <p>EN</p> </li> </ul> <ul class="flex spaceAround"> <li class="flex-item"> <p>SP</p> </li> <li class="flex-item"> <p>AC</p> </li> <li class="flex-item"> <p>E</p> </li> <li class="flex-item"> <p>AR</p> </li> <li class="flex-item"> <p>OU</p> </li> <li class="flex-item"> <p>ND</p> </li> </ul> <ul class="flex stretch"> <li class="flex-item"> <p>S</p> </li> <li class="flex-item"> <p>T</p> </li> <li class="flex-item"> <p>R</p> </li> <li class="flex-item"> <p>E</p> </li> <li class="flex-item"> <p>T</p> </li> <li class="flex-item"> <p>CH</p> </li> </ul></body> </html>
Output
Example for align-items
<!DOCTYPE html><html lang="en"> <head> <title>Align-items</title> <style> /* flex-container(flex-box) */ .flex { background-color: greenyellow; margin:0; padding:0% 2%; float: left; height: 200px; width: 160px; border: 1px solid black; display: flex; flex-direction: row; } /* flex-start */ .flexStart { align-items: flex-start; } /* flex-end */ .flexEnd { align-items: flex-end; } /* center */ .center { align-items: center; } /* baseline */ .baseLine { align-items: baseline; } /* stretch */ .stretch { align-items: stretch; } ul { list-style: none; } .flex-item { background: green; padding: 0px; width: 40px; margin: 0px; line-height: 10px; color: white; font-weight: bold; text-align:center; } </style></head> <body> <ul class="flex flexStart"> <li class="flex-item"> <p>F</p><br> <p>LE</p> </li> <li class="flex-item"> <p>X</p> </li> <li class="flex-item"> <p>ST</p><br> <p>A</p> </li> <li class="flex-item"> <p>RT</p> </li> </ul> <ul class="flex flexEnd"> <li class="flex-item"> <p>F</p><br> <p>LE</p> </li> <li class="flex-item"> <p>X</p> </li> <li class="flex-item"> <p>E</p><br> <p>N</p> </li> <li class="flex-item"> <p>D</p> </li> </ul> <ul class="flex center"> <li class="flex-item"> <p>C</p><br> <p>E</p> </li> <li class="flex-item"> <p>N</p> </li> <li class="flex-item"> <p>T</p><br> <p>E</p> </li> <li class="flex-item"> <p>R</p> </li> </ul> <ul class="flex baseLine"> <li class="flex-item"> <p>BA</p><br> <p>S</p> </li> <li class="flex-item"> <p>E</p> </li> <li class="flex-item"> <p>LI</p><br> <p>N</p> </li> <li class="flex-item"> <p>E</p> </li> </ul> <ul class="flex stretch"> <li class="flex-item"> <p>S</p><br> <p>T</p> </li> <li class="flex-item"> <p>R</p> </li> <li class="flex-item"> <p>E</p><br> <p>T</p> </li> <li class="flex-item"> <p>CH</p> </li> </ul></body> </html>
Output
CSS-Misc
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 25400,
"s": 25372,
"text": "\n14 Aug, 2020"
},
{
"code": null,
"e": 25728,
"s": 25400,
"text": "Both align-content and align-items function on the cross-axis.Cross-axis in flexbox is dependent on the flex-direction and runs perpendicular to the main-axis, if flex-direction is either row or row-reverse then the cross-axis is vertical, if flex-direction is either column or column-reverse then the cross-axis is horizontal."
},
{
"code": null,
"e": 25782,
"s": 25728,
"text": "flex-start:lines packed to the start of the container"
},
{
"code": null,
"e": 25832,
"s": 25782,
"text": "flex-end:lines packed to the end of the container"
},
{
"code": null,
"e": 25883,
"s": 25832,
"text": "center:lines packed to the center of the container"
},
{
"code": null,
"e": 26004,
"s": 25883,
"text": "space-between:lines evenly distributed; the first line is at the start of the container while the last one is at the end"
},
{
"code": null,
"e": 26067,
"s": 26004,
"text": "space-around:lines evenly distributed with equal space between"
},
{
"code": null,
"e": 26129,
"s": 26067,
"text": "stretch(Default):lines stretch to take up the remaining space"
},
{
"code": null,
"e": 26211,
"s": 26129,
"text": "flex-start:cross-start margin edge of the items is placed on the cross-start line"
},
{
"code": null,
"e": 26287,
"s": 26211,
"text": "flex-end:cross-end margin edge of the items is placed on the cross-end line"
},
{
"code": null,
"e": 26331,
"s": 26287,
"text": "center:items are centered in the cross-axis"
},
{
"code": null,
"e": 26388,
"s": 26331,
"text": "baseline:items are aligned such as their baselines align"
},
{
"code": null,
"e": 26435,
"s": 26388,
"text": "stretch(Default):stretch to fill the container"
},
{
"code": null,
"e": 26443,
"s": 26435,
"text": "Syntax:"
},
{
"code": null,
"e": 26588,
"s": 26443,
"text": "align-content:element{align-content:stretch | center | flex-start | flex-end | space-between | space-around | initial | inherit;// CSS Property}"
},
{
"code": null,
"e": 26719,
"s": 26588,
"text": "element{align-content:stretch | center | flex-start | flex-end | space-between | space-around | initial | inherit;// CSS Property}"
},
{
"code": null,
"e": 26840,
"s": 26719,
"text": "align-items:element{align-items:stretch | center | flex-start | flex-end | baseline | initial | inherit;// CSS Property}"
},
{
"code": null,
"e": 26949,
"s": 26840,
"text": "element{align-items:stretch | center | flex-start | flex-end | baseline | initial | inherit;// CSS Property}"
},
{
"code": null,
"e": 26975,
"s": 26949,
"text": "Example for align-content"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Align-content</title> <style> /* flex-container(flex-box) */ .flex { background-color: greenyellow; margin: 2% 2%; padding: 0% 3%; float: left; height: 500px; width: 50px; border: 1px solid black; display: flex; flex-wrap: wrap; flex-direction: row; } /* flex-start */ .flexStart { align-content: flex-start; } /* flex-end */ .flexEnd { align-content: flex-end; } /* center */ .center { align-content: center; } /* space-between */ .spaceBetween { align-content: space-between; } /* space-around */ .spaceAround { align-content: space-around; } /* stretch */ .stretch { align-content: stretch; } ul { list-style: none; } .flex-item { background: green; padding: 5px; width: 50px; margin: 5px; line-height: 10px; color: white; font-weight: bold; } </style></head> <body> <ul class=\"flex flexStart\"> <li class=\"flex-item\"> <p>F</p> </li> <li class=\"flex-item\"> <p>LE</p> </li> <li class=\"flex-item\"> <p>X</p> </li> <li class=\"flex-item\"> <p>ST</p> </li> <li class=\"flex-item\"> <p>A</p> </li> <li class=\"flex-item\"> <p>RT</p> </li> </ul> <ul class=\"flex flexEnd\"> <li class=\"flex-item\"> <p>F</p> </li> <li class=\"flex-item\"> <p>LE</p> </li> <li class=\"flex-item\"> <p>X</p> </li> <li class=\"flex-item\"> <p>E</p> </li> <li class=\"flex-item\"> <p>N</p> </li> <li class=\"flex-item\"> <p>D</p> </li> </ul> <ul class=\"flex center\"> <li class=\"flex-item\"> <p>C</p> </li> <li class=\"flex-item\"> <p>E</p> </li> <li class=\"flex-item\"> <p>N</p> </li> <li class=\"flex-item\"> <p>T</p> </li> <li class=\"flex-item\"> <p>E</p> </li> <li class=\"flex-item\"> <p>R</p> </li> </ul> <ul class=\"flex spaceBetween\"> <li class=\"flex-item\"> <p>SP</p> </li> <li class=\"flex-item\"> <p>AC</p> </li> <li class=\"flex-item\"> <p>EB</p> </li> <li class=\"flex-item\"> <p>ET</p> </li> <li class=\"flex-item\"> <p>WE</p> </li> <li class=\"flex-item\"> <p>EN</p> </li> </ul> <ul class=\"flex spaceAround\"> <li class=\"flex-item\"> <p>SP</p> </li> <li class=\"flex-item\"> <p>AC</p> </li> <li class=\"flex-item\"> <p>E</p> </li> <li class=\"flex-item\"> <p>AR</p> </li> <li class=\"flex-item\"> <p>OU</p> </li> <li class=\"flex-item\"> <p>ND</p> </li> </ul> <ul class=\"flex stretch\"> <li class=\"flex-item\"> <p>S</p> </li> <li class=\"flex-item\"> <p>T</p> </li> <li class=\"flex-item\"> <p>R</p> </li> <li class=\"flex-item\"> <p>E</p> </li> <li class=\"flex-item\"> <p>T</p> </li> <li class=\"flex-item\"> <p>CH</p> </li> </ul></body> </html>",
"e": 30009,
"s": 26975,
"text": null
},
{
"code": null,
"e": 30016,
"s": 30009,
"text": "Output"
},
{
"code": null,
"e": 30040,
"s": 30016,
"text": "Example for align-items"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Align-items</title> <style> /* flex-container(flex-box) */ .flex { background-color: greenyellow; margin:0; padding:0% 2%; float: left; height: 200px; width: 160px; border: 1px solid black; display: flex; flex-direction: row; } /* flex-start */ .flexStart { align-items: flex-start; } /* flex-end */ .flexEnd { align-items: flex-end; } /* center */ .center { align-items: center; } /* baseline */ .baseLine { align-items: baseline; } /* stretch */ .stretch { align-items: stretch; } ul { list-style: none; } .flex-item { background: green; padding: 0px; width: 40px; margin: 0px; line-height: 10px; color: white; font-weight: bold; text-align:center; } </style></head> <body> <ul class=\"flex flexStart\"> <li class=\"flex-item\"> <p>F</p><br> <p>LE</p> </li> <li class=\"flex-item\"> <p>X</p> </li> <li class=\"flex-item\"> <p>ST</p><br> <p>A</p> </li> <li class=\"flex-item\"> <p>RT</p> </li> </ul> <ul class=\"flex flexEnd\"> <li class=\"flex-item\"> <p>F</p><br> <p>LE</p> </li> <li class=\"flex-item\"> <p>X</p> </li> <li class=\"flex-item\"> <p>E</p><br> <p>N</p> </li> <li class=\"flex-item\"> <p>D</p> </li> </ul> <ul class=\"flex center\"> <li class=\"flex-item\"> <p>C</p><br> <p>E</p> </li> <li class=\"flex-item\"> <p>N</p> </li> <li class=\"flex-item\"> <p>T</p><br> <p>E</p> </li> <li class=\"flex-item\"> <p>R</p> </li> </ul> <ul class=\"flex baseLine\"> <li class=\"flex-item\"> <p>BA</p><br> <p>S</p> </li> <li class=\"flex-item\"> <p>E</p> </li> <li class=\"flex-item\"> <p>LI</p><br> <p>N</p> </li> <li class=\"flex-item\"> <p>E</p> </li> </ul> <ul class=\"flex stretch\"> <li class=\"flex-item\"> <p>S</p><br> <p>T</p> </li> <li class=\"flex-item\"> <p>R</p> </li> <li class=\"flex-item\"> <p>E</p><br> <p>T</p> </li> <li class=\"flex-item\"> <p>CH</p> </li> </ul></body> </html>",
"e": 32307,
"s": 30040,
"text": null
},
{
"code": null,
"e": 32314,
"s": 32307,
"text": "Output"
},
{
"code": null,
"e": 32323,
"s": 32314,
"text": "CSS-Misc"
},
{
"code": null,
"e": 32330,
"s": 32323,
"text": "Picked"
},
{
"code": null,
"e": 32334,
"s": 32330,
"text": "CSS"
},
{
"code": null,
"e": 32351,
"s": 32334,
"text": "Web Technologies"
},
{
"code": null,
"e": 32449,
"s": 32351,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32486,
"s": 32449,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 32515,
"s": 32486,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 32554,
"s": 32515,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 32596,
"s": 32554,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 32643,
"s": 32596,
"text": "How to Create Time-Table schedule using HTML ?"
},
{
"code": null,
"e": 32685,
"s": 32643,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 32728,
"s": 32685,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 32761,
"s": 32728,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32806,
"s": 32761,
"text": "Convert a string to an integer in JavaScript"
}
] |
Single and Multi-Step Temperature Time Series Forecasting for Vilnius Using LSTM Deep Learning Model | by Eligijus Bujokas | Towards Data Science
|
The aim of this article is to provide code examples and explain the intuition behind modeling time series data using python and TensorFlow.
All the code and data is public and can be seen in the following repository:
github.com
This article is a generalization of one of my previous articles:
towardsdatascience.com
The article above explains how to forecast time-series data for a single step forward. This article shows how to do multi-step forecasting and use more than 1 feature in the model.
The very brief version of this article is that using the past 48 hours of data and forecasting 1 hour into the future (single step) I have achieved a mean absolute error of 0.48 (0.34 median) degrees of Celcius error.
Using the past 168 hours of data and forecasting 24 hours ahead, the mean absolute error was 1.69 (1.27 median) degrees of Celcius.
The features used were the hourly past data of temperature, the daily and yearly cyclical signals, pressure, and wind speed.
The data is obtained using an API from https://openweathermap.org/. The data was gathered every hour from 1990.01.01 to 2020.11.30 near the TV tower of Vilnius. Vilnius is not a large metropolis and the TV tower is in the city itself so the temperature that is near the tower should be very similar to what is the temperature in all parts of the city.
Here and throughout the article the main data object is called d. It is created by reading the raw data:
d = pd.read_csv(‘data/weather.csv’)# Converting the dt column to datetime object d[‘dt’] = [datetime.datetime.utcfromtimestamp(x) for x in d[‘dt’]]# Sorting by the date d.sort_values(‘dt’, inplace=True)
There are 271008 total data points in the dataset.
The data seems to be stationary with a clear cyclical pattern.
The graph above shows that there is a clear day cycle of temperatures — the median temperature is the highest around noon and the lowest around midnight.
The cyclical pattern is even more evident in the temperatures grouped by month — the hottest months are June up to August and the coldest ones are December to February.
The problem with the data as it is now, we only have the date column. If would convert it to numeric (let us say, extract the timestamp in seconds) and add it as a feature in modeling the cyclical nature would be lost. Thus, the first thing we need to do is to engineer some features that catch the cyclical trend.
We want the machine to know that hours 23 and 0 are closer to each other than hours 0 and 4. We know that the period of the cycle is 24 hours. We can use the cos(x) and sin(x) functions. The x in the functions is the hour of the day.
# Extracting the hour of dayd["hour"] = [x.hour for x in d["dt"]]# Creating the cyclical daily feature d["day_cos"] = [np.cos(x * (2 * np.pi / 24)) for x in d["hour"]]d["day_sin"] = [np.sin(x * (2 * np.pi / 24)) for x in d["hour"]]
The head of the resulting data frame:
The newly created features catch the cyclical pattern. The question may arise, why do we use both sin and cos functions?
Drawing a horizontal line in the above graph and analyzing just one of the curves we would get that, for example, cos(7.5h) = cos(17.5h) and so on. This may lead to some errors when learning and predicting so in order to make every point unique, we add another cyclical function. Using the two features together, all times can be distinguished from each other.
To create the same cyclical logic for the time of the year, we will use the timestamp functionality. Timestamp in python is a value that calculates how many seconds have passed since 1970.01.01 0H:0m:0s. Every date object in python has the function timestamp().
# Extracting the timestamp from the datetime object d["timestamp"] = [x.timestamp() for x in d["dt"]]# Seconds in day s = 24 * 60 * 60# Seconds in year year = (365.25) * sd["month_cos"] = [np.cos((x) * (2 * np.pi / year)) for x in d["timestamp"]]d["month_sin"] = [np.sin((x) * (2 * np.pi / year)) for x in d["timestamp"]]
In this section, we have created 4 additional features from the datetime column: day_sin, day_cos, month_sin and month_cos.
In the weather dataset, there are two additional columns: wind_speed and pressure. Wind speed is measured in meters per second (m/s) and the pressure is measured in hectopascals (hPa).
To see any relationship between the temperature and the two features we can plot the 2d histograms:
The more intense the color the bigger the relationship in certain bin values of the two distributions. For example, the temperatures tend to be higher when the pressure is around 1010 and 1020 hPa.
We will use these two features in modeling as well.
The data that we have with all the feature engineering is this:
The function f that we want to approximate is:
The goal is to use past values to predict the future. The data is a time series or a sequence. For sequence modeling, we will choose tensorflow implementation of recurrent neural network with an LSTM layer.
The input to an LSTM network is a 3D array:
(samples, timesteps, features)
samples — total number of sequences constructed for training.
timesteps — the length of the samples.
features — number of features used.
The first thing before modeling is from the data that is in a 2D format convert into a 3D array. The following function does that:
For example, if we assume that the whole data is the first 10 rows of the data, we use 3 past hours as features and we want to forecast 1 step ahead:
ts = d[‘temp’, ‘day_cos’, ‘day_sin’, ‘month_sin’, ‘month_cos’, ‘pressure’, ‘wind_speed’].head(10).valuesX, Y = create_X_Y(ts, lag=3, n_ahead=1)
As we can see, the shape of the X matrix is 6 samples, 3 timesteps and 7 features. In other words, we have 6 observations each with 3 rows of data and 7 columns. There are 6 observations because the first 3 lags are dropped and used only as X data and we are forecasting 1 step ahead thus the last observation is lost as well.
The first value pairs of X and Y are presented in the above picture.
The hyperparameter list for the final model:
# Number of lags (hours back) to use for modelslag = 48# Steps ahead to forecast n_ahead = 1# Share of obs in testing test_share = 0.1# Epochs for trainingepochs = 20# Batch size batch_size = 512# Learning ratelr = 0.001# Number of neurons in LSTM layern_layer = 10# The features used in the modeling features_final = [‘temp’, ‘day_cos’, ‘day_sin’, ‘month_sin’, ‘month_cos’, ‘pressure’, ‘wind_speed’]
The model class:
The last step before creating all the matrices for the modeling is to scale the data.
# Subseting only the needed columns ts = d[features_final]nrows = ts.shape[0]# Spliting into train and test setstrain = ts[0:int(nrows * (1 — test_share))]test = ts[int(nrows * (1 — test_share)):]# Scaling the data train_mean = train.mean()train_std = train.std()train = (train — train_mean) / train_stdtest = (test — train_mean) / train_std# Creating the final scaled frame ts_s = pd.concat([train, test])# Creating the X and Y for trainingX, Y = create_X_Y(ts_s.values, lag=lag, n_ahead=n_ahead)n_ft = X.shape[2]
Now we split the matrices into training and validation matrices
# Spliting into train and test sets Xtrain, Ytrain = X[0:int(X.shape[0] * (1 — test_share))], Y[0:int(X.shape[0] * (1 — test_share))]Xval, Yval = X[int(X.shape[0] * (1 — test_share)):], Y[int(X.shape[0] * (1 — test_share)):]
The final shapes of the matrices:
Shape of training data: (243863, 48, 7)Shape of the target data: (243863, 1)Shape of validation data: (27096, 48, 7)Shape of the validation target data: (27096, 1)
All that is left is to create the object using the model class, train the model, and inspect the results on the validation set.
# Initiating the model objectmodel = NNMultistepModel( X=Xtrain, Y=Ytrain, n_outputs=n_ahead, n_lag=lag, n_ft=n_ft, n_layer=n_layer, batch=batch_size, epochs=epochs, lr=lr, Xval=Xval, Yval=Yval,)# Training of the model history = model.train()
With the trained model we can forecast and compare the values with the original ones.
# Comparing the forecasts with the actual valuesyhat = [x[0] for x in model.predict(Xval)]y = [y[0] for y in Yval]# Creating the frame to store both predictionsdays = d[‘dt’].values[-len(y):]frame = pd.concat([ pd.DataFrame({‘day’: days, ‘temp’: y, ‘type’: ‘original’}), pd.DataFrame({‘day’: days, ‘temp’: yhat, ‘type’: ‘forecast’})])# Creating the unscaled values columnframe[‘temp_absolute’] = [(x * train_std[‘temp’]) + train_mean[‘temp’] for x in frame[‘temp’]]# Pivotingpivoted = frame.pivot_table(index=’day’, columns=’type’)pivoted.columns = [‘_’.join(x).strip() for x in pivoted.columns.values]pivoted[‘res’] = pivoted[‘temp_absolute_original’] — pivoted[‘temp_absolute_forecast’]pivoted[‘res_abs’] = [abs(x) for x in pivoted[‘res’]]
Plotting the results:
plt.figure(figsize=(12, 12))plt.plot(pivoted.index, pivoted.temp_absolute_original, color=’blue’, label=’original’)plt.plot(pivoted.index, pivoted.temp_absolute_forecast, color=’red’, label=’forecast’, alpha=0.6)plt.title(‘Temperature forecasts — absolute data’)plt.legend()plt.show()
The two lines are very close to each other, they basically overlap. The distribution of absolute errors:
The median absolute error is 0.34 degrees Celcius and the average is 0.48 degrees Celcius.
To predict 24 hours ahead the only thing needed is to change the hyperparameters. Specifically, the n_ahead variable. The model will try to predict the next 24 hour values using 168 hours from before (one week).
# Number of lags (hours back) to use for modelslag = 168# Steps ahead to forecast n_ahead = 24# Share of obs in testing test_share = 0.1# Epochs for trainingepochs = 20# Batch size batch_size = 512# Learning ratelr = 0.001# Number of neurons in LSTM layern_layer = 10# Creating the X and Y for trainingX, Y = create_X_Y(ts_s.values, lag=lag, n_ahead=n_ahead)n_ft = X.shape[2]Xtrain, Ytrain = X[0:int(X.shape[0] * (1 - test_share))], Y[0:int(X.shape[0] * (1 - test_share))]Xval, Yval = X[int(X.shape[0] * (1 - test_share)):], Y[int(X.shape[0] * (1 - test_share)):]# Creating the model object model = NNMultistepModel( X=Xtrain, Y=Ytrain, n_outputs=n_ahead, n_lag=lag, n_ft=n_ft, n_layer=n_layer, batch=batch_size, epochs=epochs, lr=lr, Xval=Xval, Yval=Yval,)# Training the model history = model.train()
Inspecting some random chunks of 24 hours chunks:
Some 24 hours sequences seem to be close to one another while others are not.
The mean absolute error is 1.69 C and the median is 1.27 C.
In conclusion, this article presented a simple pipeline example when working with modeling and forecasting of the time series data:
Reading, cleaning, and augmenting the input data
Selecting the hyperparameters for the lag and n steps ahead
Selecting the hyperparameters for the deep learning model
Initiating the NNMultistepModel() class
Fitting the model
Forecasting n_steps ahead
I hope that the reader can use the code showcased in this article in his/her professional and academic work.
|
[
{
"code": null,
"e": 311,
"s": 171,
"text": "The aim of this article is to provide code examples and explain the intuition behind modeling time series data using python and TensorFlow."
},
{
"code": null,
"e": 388,
"s": 311,
"text": "All the code and data is public and can be seen in the following repository:"
},
{
"code": null,
"e": 399,
"s": 388,
"text": "github.com"
},
{
"code": null,
"e": 464,
"s": 399,
"text": "This article is a generalization of one of my previous articles:"
},
{
"code": null,
"e": 487,
"s": 464,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 668,
"s": 487,
"text": "The article above explains how to forecast time-series data for a single step forward. This article shows how to do multi-step forecasting and use more than 1 feature in the model."
},
{
"code": null,
"e": 886,
"s": 668,
"text": "The very brief version of this article is that using the past 48 hours of data and forecasting 1 hour into the future (single step) I have achieved a mean absolute error of 0.48 (0.34 median) degrees of Celcius error."
},
{
"code": null,
"e": 1018,
"s": 886,
"text": "Using the past 168 hours of data and forecasting 24 hours ahead, the mean absolute error was 1.69 (1.27 median) degrees of Celcius."
},
{
"code": null,
"e": 1143,
"s": 1018,
"text": "The features used were the hourly past data of temperature, the daily and yearly cyclical signals, pressure, and wind speed."
},
{
"code": null,
"e": 1495,
"s": 1143,
"text": "The data is obtained using an API from https://openweathermap.org/. The data was gathered every hour from 1990.01.01 to 2020.11.30 near the TV tower of Vilnius. Vilnius is not a large metropolis and the TV tower is in the city itself so the temperature that is near the tower should be very similar to what is the temperature in all parts of the city."
},
{
"code": null,
"e": 1600,
"s": 1495,
"text": "Here and throughout the article the main data object is called d. It is created by reading the raw data:"
},
{
"code": null,
"e": 1803,
"s": 1600,
"text": "d = pd.read_csv(‘data/weather.csv’)# Converting the dt column to datetime object d[‘dt’] = [datetime.datetime.utcfromtimestamp(x) for x in d[‘dt’]]# Sorting by the date d.sort_values(‘dt’, inplace=True)"
},
{
"code": null,
"e": 1854,
"s": 1803,
"text": "There are 271008 total data points in the dataset."
},
{
"code": null,
"e": 1917,
"s": 1854,
"text": "The data seems to be stationary with a clear cyclical pattern."
},
{
"code": null,
"e": 2071,
"s": 1917,
"text": "The graph above shows that there is a clear day cycle of temperatures — the median temperature is the highest around noon and the lowest around midnight."
},
{
"code": null,
"e": 2240,
"s": 2071,
"text": "The cyclical pattern is even more evident in the temperatures grouped by month — the hottest months are June up to August and the coldest ones are December to February."
},
{
"code": null,
"e": 2555,
"s": 2240,
"text": "The problem with the data as it is now, we only have the date column. If would convert it to numeric (let us say, extract the timestamp in seconds) and add it as a feature in modeling the cyclical nature would be lost. Thus, the first thing we need to do is to engineer some features that catch the cyclical trend."
},
{
"code": null,
"e": 2789,
"s": 2555,
"text": "We want the machine to know that hours 23 and 0 are closer to each other than hours 0 and 4. We know that the period of the cycle is 24 hours. We can use the cos(x) and sin(x) functions. The x in the functions is the hour of the day."
},
{
"code": null,
"e": 3021,
"s": 2789,
"text": "# Extracting the hour of dayd[\"hour\"] = [x.hour for x in d[\"dt\"]]# Creating the cyclical daily feature d[\"day_cos\"] = [np.cos(x * (2 * np.pi / 24)) for x in d[\"hour\"]]d[\"day_sin\"] = [np.sin(x * (2 * np.pi / 24)) for x in d[\"hour\"]]"
},
{
"code": null,
"e": 3059,
"s": 3021,
"text": "The head of the resulting data frame:"
},
{
"code": null,
"e": 3180,
"s": 3059,
"text": "The newly created features catch the cyclical pattern. The question may arise, why do we use both sin and cos functions?"
},
{
"code": null,
"e": 3541,
"s": 3180,
"text": "Drawing a horizontal line in the above graph and analyzing just one of the curves we would get that, for example, cos(7.5h) = cos(17.5h) and so on. This may lead to some errors when learning and predicting so in order to make every point unique, we add another cyclical function. Using the two features together, all times can be distinguished from each other."
},
{
"code": null,
"e": 3803,
"s": 3541,
"text": "To create the same cyclical logic for the time of the year, we will use the timestamp functionality. Timestamp in python is a value that calculates how many seconds have passed since 1970.01.01 0H:0m:0s. Every date object in python has the function timestamp()."
},
{
"code": null,
"e": 4125,
"s": 3803,
"text": "# Extracting the timestamp from the datetime object d[\"timestamp\"] = [x.timestamp() for x in d[\"dt\"]]# Seconds in day s = 24 * 60 * 60# Seconds in year year = (365.25) * sd[\"month_cos\"] = [np.cos((x) * (2 * np.pi / year)) for x in d[\"timestamp\"]]d[\"month_sin\"] = [np.sin((x) * (2 * np.pi / year)) for x in d[\"timestamp\"]]"
},
{
"code": null,
"e": 4249,
"s": 4125,
"text": "In this section, we have created 4 additional features from the datetime column: day_sin, day_cos, month_sin and month_cos."
},
{
"code": null,
"e": 4434,
"s": 4249,
"text": "In the weather dataset, there are two additional columns: wind_speed and pressure. Wind speed is measured in meters per second (m/s) and the pressure is measured in hectopascals (hPa)."
},
{
"code": null,
"e": 4534,
"s": 4434,
"text": "To see any relationship between the temperature and the two features we can plot the 2d histograms:"
},
{
"code": null,
"e": 4732,
"s": 4534,
"text": "The more intense the color the bigger the relationship in certain bin values of the two distributions. For example, the temperatures tend to be higher when the pressure is around 1010 and 1020 hPa."
},
{
"code": null,
"e": 4784,
"s": 4732,
"text": "We will use these two features in modeling as well."
},
{
"code": null,
"e": 4848,
"s": 4784,
"text": "The data that we have with all the feature engineering is this:"
},
{
"code": null,
"e": 4895,
"s": 4848,
"text": "The function f that we want to approximate is:"
},
{
"code": null,
"e": 5102,
"s": 4895,
"text": "The goal is to use past values to predict the future. The data is a time series or a sequence. For sequence modeling, we will choose tensorflow implementation of recurrent neural network with an LSTM layer."
},
{
"code": null,
"e": 5146,
"s": 5102,
"text": "The input to an LSTM network is a 3D array:"
},
{
"code": null,
"e": 5177,
"s": 5146,
"text": "(samples, timesteps, features)"
},
{
"code": null,
"e": 5239,
"s": 5177,
"text": "samples — total number of sequences constructed for training."
},
{
"code": null,
"e": 5278,
"s": 5239,
"text": "timesteps — the length of the samples."
},
{
"code": null,
"e": 5314,
"s": 5278,
"text": "features — number of features used."
},
{
"code": null,
"e": 5445,
"s": 5314,
"text": "The first thing before modeling is from the data that is in a 2D format convert into a 3D array. The following function does that:"
},
{
"code": null,
"e": 5595,
"s": 5445,
"text": "For example, if we assume that the whole data is the first 10 rows of the data, we use 3 past hours as features and we want to forecast 1 step ahead:"
},
{
"code": null,
"e": 5739,
"s": 5595,
"text": "ts = d[‘temp’, ‘day_cos’, ‘day_sin’, ‘month_sin’, ‘month_cos’, ‘pressure’, ‘wind_speed’].head(10).valuesX, Y = create_X_Y(ts, lag=3, n_ahead=1)"
},
{
"code": null,
"e": 6066,
"s": 5739,
"text": "As we can see, the shape of the X matrix is 6 samples, 3 timesteps and 7 features. In other words, we have 6 observations each with 3 rows of data and 7 columns. There are 6 observations because the first 3 lags are dropped and used only as X data and we are forecasting 1 step ahead thus the last observation is lost as well."
},
{
"code": null,
"e": 6135,
"s": 6066,
"text": "The first value pairs of X and Y are presented in the above picture."
},
{
"code": null,
"e": 6180,
"s": 6135,
"text": "The hyperparameter list for the final model:"
},
{
"code": null,
"e": 6581,
"s": 6180,
"text": "# Number of lags (hours back) to use for modelslag = 48# Steps ahead to forecast n_ahead = 1# Share of obs in testing test_share = 0.1# Epochs for trainingepochs = 20# Batch size batch_size = 512# Learning ratelr = 0.001# Number of neurons in LSTM layern_layer = 10# The features used in the modeling features_final = [‘temp’, ‘day_cos’, ‘day_sin’, ‘month_sin’, ‘month_cos’, ‘pressure’, ‘wind_speed’]"
},
{
"code": null,
"e": 6598,
"s": 6581,
"text": "The model class:"
},
{
"code": null,
"e": 6684,
"s": 6598,
"text": "The last step before creating all the matrices for the modeling is to scale the data."
},
{
"code": null,
"e": 7199,
"s": 6684,
"text": "# Subseting only the needed columns ts = d[features_final]nrows = ts.shape[0]# Spliting into train and test setstrain = ts[0:int(nrows * (1 — test_share))]test = ts[int(nrows * (1 — test_share)):]# Scaling the data train_mean = train.mean()train_std = train.std()train = (train — train_mean) / train_stdtest = (test — train_mean) / train_std# Creating the final scaled frame ts_s = pd.concat([train, test])# Creating the X and Y for trainingX, Y = create_X_Y(ts_s.values, lag=lag, n_ahead=n_ahead)n_ft = X.shape[2]"
},
{
"code": null,
"e": 7263,
"s": 7199,
"text": "Now we split the matrices into training and validation matrices"
},
{
"code": null,
"e": 7488,
"s": 7263,
"text": "# Spliting into train and test sets Xtrain, Ytrain = X[0:int(X.shape[0] * (1 — test_share))], Y[0:int(X.shape[0] * (1 — test_share))]Xval, Yval = X[int(X.shape[0] * (1 — test_share)):], Y[int(X.shape[0] * (1 — test_share)):]"
},
{
"code": null,
"e": 7522,
"s": 7488,
"text": "The final shapes of the matrices:"
},
{
"code": null,
"e": 7686,
"s": 7522,
"text": "Shape of training data: (243863, 48, 7)Shape of the target data: (243863, 1)Shape of validation data: (27096, 48, 7)Shape of the validation target data: (27096, 1)"
},
{
"code": null,
"e": 7814,
"s": 7686,
"text": "All that is left is to create the object using the model class, train the model, and inspect the results on the validation set."
},
{
"code": null,
"e": 8058,
"s": 7814,
"text": "# Initiating the model objectmodel = NNMultistepModel( X=Xtrain, Y=Ytrain, n_outputs=n_ahead, n_lag=lag, n_ft=n_ft, n_layer=n_layer, batch=batch_size, epochs=epochs, lr=lr, Xval=Xval, Yval=Yval,)# Training of the model history = model.train()"
},
{
"code": null,
"e": 8144,
"s": 8058,
"text": "With the trained model we can forecast and compare the values with the original ones."
},
{
"code": null,
"e": 8886,
"s": 8144,
"text": "# Comparing the forecasts with the actual valuesyhat = [x[0] for x in model.predict(Xval)]y = [y[0] for y in Yval]# Creating the frame to store both predictionsdays = d[‘dt’].values[-len(y):]frame = pd.concat([ pd.DataFrame({‘day’: days, ‘temp’: y, ‘type’: ‘original’}), pd.DataFrame({‘day’: days, ‘temp’: yhat, ‘type’: ‘forecast’})])# Creating the unscaled values columnframe[‘temp_absolute’] = [(x * train_std[‘temp’]) + train_mean[‘temp’] for x in frame[‘temp’]]# Pivotingpivoted = frame.pivot_table(index=’day’, columns=’type’)pivoted.columns = [‘_’.join(x).strip() for x in pivoted.columns.values]pivoted[‘res’] = pivoted[‘temp_absolute_original’] — pivoted[‘temp_absolute_forecast’]pivoted[‘res_abs’] = [abs(x) for x in pivoted[‘res’]]"
},
{
"code": null,
"e": 8908,
"s": 8886,
"text": "Plotting the results:"
},
{
"code": null,
"e": 9193,
"s": 8908,
"text": "plt.figure(figsize=(12, 12))plt.plot(pivoted.index, pivoted.temp_absolute_original, color=’blue’, label=’original’)plt.plot(pivoted.index, pivoted.temp_absolute_forecast, color=’red’, label=’forecast’, alpha=0.6)plt.title(‘Temperature forecasts — absolute data’)plt.legend()plt.show()"
},
{
"code": null,
"e": 9298,
"s": 9193,
"text": "The two lines are very close to each other, they basically overlap. The distribution of absolute errors:"
},
{
"code": null,
"e": 9389,
"s": 9298,
"text": "The median absolute error is 0.34 degrees Celcius and the average is 0.48 degrees Celcius."
},
{
"code": null,
"e": 9601,
"s": 9389,
"text": "To predict 24 hours ahead the only thing needed is to change the hyperparameters. Specifically, the n_ahead variable. The model will try to predict the next 24 hour values using 168 hours from before (one week)."
},
{
"code": null,
"e": 10437,
"s": 9601,
"text": "# Number of lags (hours back) to use for modelslag = 168# Steps ahead to forecast n_ahead = 24# Share of obs in testing test_share = 0.1# Epochs for trainingepochs = 20# Batch size batch_size = 512# Learning ratelr = 0.001# Number of neurons in LSTM layern_layer = 10# Creating the X and Y for trainingX, Y = create_X_Y(ts_s.values, lag=lag, n_ahead=n_ahead)n_ft = X.shape[2]Xtrain, Ytrain = X[0:int(X.shape[0] * (1 - test_share))], Y[0:int(X.shape[0] * (1 - test_share))]Xval, Yval = X[int(X.shape[0] * (1 - test_share)):], Y[int(X.shape[0] * (1 - test_share)):]# Creating the model object model = NNMultistepModel( X=Xtrain, Y=Ytrain, n_outputs=n_ahead, n_lag=lag, n_ft=n_ft, n_layer=n_layer, batch=batch_size, epochs=epochs, lr=lr, Xval=Xval, Yval=Yval,)# Training the model history = model.train()"
},
{
"code": null,
"e": 10487,
"s": 10437,
"text": "Inspecting some random chunks of 24 hours chunks:"
},
{
"code": null,
"e": 10565,
"s": 10487,
"text": "Some 24 hours sequences seem to be close to one another while others are not."
},
{
"code": null,
"e": 10625,
"s": 10565,
"text": "The mean absolute error is 1.69 C and the median is 1.27 C."
},
{
"code": null,
"e": 10757,
"s": 10625,
"text": "In conclusion, this article presented a simple pipeline example when working with modeling and forecasting of the time series data:"
},
{
"code": null,
"e": 10806,
"s": 10757,
"text": "Reading, cleaning, and augmenting the input data"
},
{
"code": null,
"e": 10866,
"s": 10806,
"text": "Selecting the hyperparameters for the lag and n steps ahead"
},
{
"code": null,
"e": 10924,
"s": 10866,
"text": "Selecting the hyperparameters for the deep learning model"
},
{
"code": null,
"e": 10964,
"s": 10924,
"text": "Initiating the NNMultistepModel() class"
},
{
"code": null,
"e": 10982,
"s": 10964,
"text": "Fitting the model"
},
{
"code": null,
"e": 11008,
"s": 10982,
"text": "Forecasting n_steps ahead"
}
] |
Pair in C++ Standard Template Library (STL)
|
In this tutorial, we will be discussing a program to understand pair in C++ Standard Template Library.
Pair is a container defined in the utility header that contains two values. It is used to combine two values and associate them even if they are of different types.
Live Demo
#include <iostream>
#include <utility>
using namespace std;
int main(){
//initializing a pair
pair <int, char> PAIR1 ;
PAIR1.first = 100;
PAIR1.second = 'G' ;
cout << PAIR1.first << " " ;
cout << PAIR1.second << endl ;
return 0;
}
100 G
|
[
{
"code": null,
"e": 1165,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to understand pair in C++ Standard Template Library."
},
{
"code": null,
"e": 1330,
"s": 1165,
"text": "Pair is a container defined in the utility header that contains two values. It is used to combine two values and associate them even if they are of different types."
},
{
"code": null,
"e": 1341,
"s": 1330,
"text": " Live Demo"
},
{
"code": null,
"e": 1593,
"s": 1341,
"text": "#include <iostream>\n#include <utility>\nusing namespace std;\nint main(){\n //initializing a pair\n pair <int, char> PAIR1 ;\n PAIR1.first = 100;\n PAIR1.second = 'G' ;\n cout << PAIR1.first << \" \" ;\n cout << PAIR1.second << endl ;\n return 0;\n}"
},
{
"code": null,
"e": 1599,
"s": 1593,
"text": "100 G"
}
] |
How to Easily Perform Pandas Operations on S3 With AWS Data Wrangler | by Ahmed Besbes | Towards Data Science
|
I’ve always found it a bit complex and non-intuitive to programmatically interact with S3 to perform simple tasks such as file readings or writings, bulk downloads or uploads or even massive file deletions (with wildcards and stuff).
My typical use-cases deal with Pandas dataframes I download from (or save to) S3 in any of these three formats: CSV, JSON and Parquet for analysis and processing.
While searching for an alternative to boto3 (which is, don’t get me wrong, a great package to interface with AWS programmatically) I came across AWS Data Wrangler, a python library that extends the power of Pandas to AWS by connecting dataframes to AWS data related services such as Athena, Glue, Redshift, DynamoDB, EMR ... and most importantly (for me, at least) S3.
In this post, I’ll be reviewing AWS Data Wrangler’s functionalities to easily interface Pandas with S3.
If you’re not an AWS user, S3 stands for Amazon Simple Storage Service. It’s a suite of web services that you can use to store any amount of data, at any time, from anywhere on the web.
It provides any developer access to highly scalable, reliable, fast and inexpensive data storage.
→For a complete overview of S3, have a look at the official documentation.
→To be able to use S3 and reproduce the following code snippets you need to set up an AWS account.
Before using AWS Data Wrangler, you’ll have to create an IAM user.
IAM stands for Identity and Access Management: it’s a service that enables you to manage access to AWS services and resources securely. IAM allows you to create users and groups and use permissions to allow or deny access to AWS resources.
Once you create an IAM user, AWS will provide you with two credentials: Access key IDand Secret access key. You'll have to use them to configure an AWS profile on your machine.
AWS Data Wrangler will then use this profile to programmatically access AWS services on your behalf.
To create an IAM user, go to the AWS console and search for IAM. On the top-left sidebar, click on Users .
This will list the users you’ve already created. To add a new one, click on Add users.
Enter a name for this user and assign it Programmatic access.
Then, add it to a group to define its set of permissions. For simplicity, give it Administrator Access, but you may want to limit this to a restricted set of permissions in general.
Skip the tag steps and validate the user creation.
Once the user is created, credentials will appear on the screen: Access key ID and Secret access key. We'll use them to configure an AWS profile.
To configure an AWS profile, you’ll have to first install the AWS CLI by following this guide and then enter the following command
aws configure --profile ahmed
A prompt will ask you to enter the previous credentials. Just do it and leave the region name and output format to their default values.
Now, the AWS profile is properly configured.
To make AWS Data Wrangler use it, we’ll have to set up a default session with boto3 at the start of our experiments: just leave these lines at the beginning of your script or notebook.
The subsequent commands will use the permission given to this profile.
First things first, let’s install AWS Data Wrangler.
pip install awswrangler
Before running any command to interact with S3, let’s look at the current structure of my buckets.
Nothing really fancy, just a bunch of buckets I use for personal projects.
AWS Data Wrangler can perform basic operations on these buckets:
checks if an object exists:
>>> wr.s3.does_object_exist("s3://ahmedbesbes.com/plot.html")True
recursively lists objects inside a bucket:
>>> wr.s3.list_objects("s3://ahmedbesbes.com")['s3://ahmedbesbes.com/app.mp4', 's3://ahmedbesbes.com/plot.html', 's3://ahmedbesbes.com/pyldavis.html']
lists directories inside a bucket
>>> wr.s3.list_directories("s3://sozy")['s3://sozy/assets/', 's3://sozy/images/', 's3://sozy/saved_images/']
shows the region name of each bucket
>>> wr.s3.get_bucket_region("ahmedbesbes.com")'eu-west-3'
get information about each object
>>> wr.s3.describe_objects("s3://ahmedbesbes.com/plot.html")
This will output a JSON object describing the file. It includes attributes such as the content type, size as well as permission metadata.
The describe_objectsmethod can also take a folder as input. In that case, it will return a list of JSON objects, each one describing each file in the folder.
Now comes the fun part where we make Pandas perform operations on S3.
Read files
Let’s start by saving a dummy dataframe as a CSV file inside a bucket.
This is as simple as interacting with the local file system. One cool thing here: if the /csv/sub-folder/ didn't already exist, AWS Data Wrangler will create it automatically.
Read multiple CSV files at once:
This is actually quite simple. All you have to do is to pass a list of remote paths. Behind the scenes, AWS Data Wrangler will concatenate the four dataframes along the row axis (axis=0).
Use prefixes
Assume that you have 1000 CSV files inside a folder and you want to read them all at once in a single dataframe. To do this, you can pass the path to the folder to the read_csv method. AWS Data Wrangler will look for all CSV files in it.
wr.s3.read_csv(f"s3://{bucket}/csv/")
Delete objects
You can delete objects by using the delete_objects methods
This method accepts Unix shell-style wildcards in the path argument.
Assume, for example, that you want to delete all the 1000 CSV files that are in a specific folder.
Here’s how you’d do it:
wr.s3.delete_objects(f"s3://{bucket}/folder/*.csv")
You can perform these same operations on JSON and Parquet files as well
Just replace with:
wr.s3.read_csv with wr.s3.read_json or wr.s3.read_parquet
wr.s3.to_csv with wr.s3.to_json or wr.s3.to_parquet
Download objects
AWS Data Wrangler makes it very easy to download objects from S3. This is the main reason why I’ve started using it.
To download a remote object, just use the download method. This method accepts as the first argument the remote path to the object and as the second argument the local path where the object will be saved.
Alternatively, you can download an object in binary mode.
upload objects
Uploading objects follows the same logic.
This post is a collection of notes I took while using AWS Data Wrangler to per. I hope you found them useful.
In later posts, I’ll be reviewing other AWS services such as DynamoDB and EMR and how to interact with them using AWS Data Wrangler.
For the time being, here are some resources worth the read if you want to dig deeper.
AWS S3: https://aws.amazon.com/s3/?nc1=h_ls
AWS IAM: https://aws.amazon.com/iam/?nc2=type_a
AWS Data Wrangler documentation: https://aws-data-wrangler.readthedocs.io/
Github: https://github.com/awslabs/aws-data-wrangler
See you next time!
|
[
{
"code": null,
"e": 405,
"s": 171,
"text": "I’ve always found it a bit complex and non-intuitive to programmatically interact with S3 to perform simple tasks such as file readings or writings, bulk downloads or uploads or even massive file deletions (with wildcards and stuff)."
},
{
"code": null,
"e": 568,
"s": 405,
"text": "My typical use-cases deal with Pandas dataframes I download from (or save to) S3 in any of these three formats: CSV, JSON and Parquet for analysis and processing."
},
{
"code": null,
"e": 937,
"s": 568,
"text": "While searching for an alternative to boto3 (which is, don’t get me wrong, a great package to interface with AWS programmatically) I came across AWS Data Wrangler, a python library that extends the power of Pandas to AWS by connecting dataframes to AWS data related services such as Athena, Glue, Redshift, DynamoDB, EMR ... and most importantly (for me, at least) S3."
},
{
"code": null,
"e": 1041,
"s": 937,
"text": "In this post, I’ll be reviewing AWS Data Wrangler’s functionalities to easily interface Pandas with S3."
},
{
"code": null,
"e": 1227,
"s": 1041,
"text": "If you’re not an AWS user, S3 stands for Amazon Simple Storage Service. It’s a suite of web services that you can use to store any amount of data, at any time, from anywhere on the web."
},
{
"code": null,
"e": 1325,
"s": 1227,
"text": "It provides any developer access to highly scalable, reliable, fast and inexpensive data storage."
},
{
"code": null,
"e": 1400,
"s": 1325,
"text": "→For a complete overview of S3, have a look at the official documentation."
},
{
"code": null,
"e": 1499,
"s": 1400,
"text": "→To be able to use S3 and reproduce the following code snippets you need to set up an AWS account."
},
{
"code": null,
"e": 1566,
"s": 1499,
"text": "Before using AWS Data Wrangler, you’ll have to create an IAM user."
},
{
"code": null,
"e": 1806,
"s": 1566,
"text": "IAM stands for Identity and Access Management: it’s a service that enables you to manage access to AWS services and resources securely. IAM allows you to create users and groups and use permissions to allow or deny access to AWS resources."
},
{
"code": null,
"e": 1983,
"s": 1806,
"text": "Once you create an IAM user, AWS will provide you with two credentials: Access key IDand Secret access key. You'll have to use them to configure an AWS profile on your machine."
},
{
"code": null,
"e": 2084,
"s": 1983,
"text": "AWS Data Wrangler will then use this profile to programmatically access AWS services on your behalf."
},
{
"code": null,
"e": 2191,
"s": 2084,
"text": "To create an IAM user, go to the AWS console and search for IAM. On the top-left sidebar, click on Users ."
},
{
"code": null,
"e": 2278,
"s": 2191,
"text": "This will list the users you’ve already created. To add a new one, click on Add users."
},
{
"code": null,
"e": 2340,
"s": 2278,
"text": "Enter a name for this user and assign it Programmatic access."
},
{
"code": null,
"e": 2522,
"s": 2340,
"text": "Then, add it to a group to define its set of permissions. For simplicity, give it Administrator Access, but you may want to limit this to a restricted set of permissions in general."
},
{
"code": null,
"e": 2573,
"s": 2522,
"text": "Skip the tag steps and validate the user creation."
},
{
"code": null,
"e": 2719,
"s": 2573,
"text": "Once the user is created, credentials will appear on the screen: Access key ID and Secret access key. We'll use them to configure an AWS profile."
},
{
"code": null,
"e": 2850,
"s": 2719,
"text": "To configure an AWS profile, you’ll have to first install the AWS CLI by following this guide and then enter the following command"
},
{
"code": null,
"e": 2880,
"s": 2850,
"text": "aws configure --profile ahmed"
},
{
"code": null,
"e": 3017,
"s": 2880,
"text": "A prompt will ask you to enter the previous credentials. Just do it and leave the region name and output format to their default values."
},
{
"code": null,
"e": 3062,
"s": 3017,
"text": "Now, the AWS profile is properly configured."
},
{
"code": null,
"e": 3247,
"s": 3062,
"text": "To make AWS Data Wrangler use it, we’ll have to set up a default session with boto3 at the start of our experiments: just leave these lines at the beginning of your script or notebook."
},
{
"code": null,
"e": 3318,
"s": 3247,
"text": "The subsequent commands will use the permission given to this profile."
},
{
"code": null,
"e": 3371,
"s": 3318,
"text": "First things first, let’s install AWS Data Wrangler."
},
{
"code": null,
"e": 3395,
"s": 3371,
"text": "pip install awswrangler"
},
{
"code": null,
"e": 3494,
"s": 3395,
"text": "Before running any command to interact with S3, let’s look at the current structure of my buckets."
},
{
"code": null,
"e": 3569,
"s": 3494,
"text": "Nothing really fancy, just a bunch of buckets I use for personal projects."
},
{
"code": null,
"e": 3634,
"s": 3569,
"text": "AWS Data Wrangler can perform basic operations on these buckets:"
},
{
"code": null,
"e": 3662,
"s": 3634,
"text": "checks if an object exists:"
},
{
"code": null,
"e": 3728,
"s": 3662,
"text": ">>> wr.s3.does_object_exist(\"s3://ahmedbesbes.com/plot.html\")True"
},
{
"code": null,
"e": 3771,
"s": 3728,
"text": "recursively lists objects inside a bucket:"
},
{
"code": null,
"e": 3922,
"s": 3771,
"text": ">>> wr.s3.list_objects(\"s3://ahmedbesbes.com\")['s3://ahmedbesbes.com/app.mp4', 's3://ahmedbesbes.com/plot.html', 's3://ahmedbesbes.com/pyldavis.html']"
},
{
"code": null,
"e": 3956,
"s": 3922,
"text": "lists directories inside a bucket"
},
{
"code": null,
"e": 4065,
"s": 3956,
"text": ">>> wr.s3.list_directories(\"s3://sozy\")['s3://sozy/assets/', 's3://sozy/images/', 's3://sozy/saved_images/']"
},
{
"code": null,
"e": 4102,
"s": 4065,
"text": "shows the region name of each bucket"
},
{
"code": null,
"e": 4160,
"s": 4102,
"text": ">>> wr.s3.get_bucket_region(\"ahmedbesbes.com\")'eu-west-3'"
},
{
"code": null,
"e": 4194,
"s": 4160,
"text": "get information about each object"
},
{
"code": null,
"e": 4255,
"s": 4194,
"text": ">>> wr.s3.describe_objects(\"s3://ahmedbesbes.com/plot.html\")"
},
{
"code": null,
"e": 4393,
"s": 4255,
"text": "This will output a JSON object describing the file. It includes attributes such as the content type, size as well as permission metadata."
},
{
"code": null,
"e": 4551,
"s": 4393,
"text": "The describe_objectsmethod can also take a folder as input. In that case, it will return a list of JSON objects, each one describing each file in the folder."
},
{
"code": null,
"e": 4621,
"s": 4551,
"text": "Now comes the fun part where we make Pandas perform operations on S3."
},
{
"code": null,
"e": 4632,
"s": 4621,
"text": "Read files"
},
{
"code": null,
"e": 4703,
"s": 4632,
"text": "Let’s start by saving a dummy dataframe as a CSV file inside a bucket."
},
{
"code": null,
"e": 4879,
"s": 4703,
"text": "This is as simple as interacting with the local file system. One cool thing here: if the /csv/sub-folder/ didn't already exist, AWS Data Wrangler will create it automatically."
},
{
"code": null,
"e": 4912,
"s": 4879,
"text": "Read multiple CSV files at once:"
},
{
"code": null,
"e": 5100,
"s": 4912,
"text": "This is actually quite simple. All you have to do is to pass a list of remote paths. Behind the scenes, AWS Data Wrangler will concatenate the four dataframes along the row axis (axis=0)."
},
{
"code": null,
"e": 5113,
"s": 5100,
"text": "Use prefixes"
},
{
"code": null,
"e": 5351,
"s": 5113,
"text": "Assume that you have 1000 CSV files inside a folder and you want to read them all at once in a single dataframe. To do this, you can pass the path to the folder to the read_csv method. AWS Data Wrangler will look for all CSV files in it."
},
{
"code": null,
"e": 5389,
"s": 5351,
"text": "wr.s3.read_csv(f\"s3://{bucket}/csv/\")"
},
{
"code": null,
"e": 5404,
"s": 5389,
"text": "Delete objects"
},
{
"code": null,
"e": 5463,
"s": 5404,
"text": "You can delete objects by using the delete_objects methods"
},
{
"code": null,
"e": 5532,
"s": 5463,
"text": "This method accepts Unix shell-style wildcards in the path argument."
},
{
"code": null,
"e": 5631,
"s": 5532,
"text": "Assume, for example, that you want to delete all the 1000 CSV files that are in a specific folder."
},
{
"code": null,
"e": 5655,
"s": 5631,
"text": "Here’s how you’d do it:"
},
{
"code": null,
"e": 5707,
"s": 5655,
"text": "wr.s3.delete_objects(f\"s3://{bucket}/folder/*.csv\")"
},
{
"code": null,
"e": 5779,
"s": 5707,
"text": "You can perform these same operations on JSON and Parquet files as well"
},
{
"code": null,
"e": 5798,
"s": 5779,
"text": "Just replace with:"
},
{
"code": null,
"e": 5856,
"s": 5798,
"text": "wr.s3.read_csv with wr.s3.read_json or wr.s3.read_parquet"
},
{
"code": null,
"e": 5908,
"s": 5856,
"text": "wr.s3.to_csv with wr.s3.to_json or wr.s3.to_parquet"
},
{
"code": null,
"e": 5925,
"s": 5908,
"text": "Download objects"
},
{
"code": null,
"e": 6042,
"s": 5925,
"text": "AWS Data Wrangler makes it very easy to download objects from S3. This is the main reason why I’ve started using it."
},
{
"code": null,
"e": 6247,
"s": 6042,
"text": "To download a remote object, just use the download method. This method accepts as the first argument the remote path to the object and as the second argument the local path where the object will be saved."
},
{
"code": null,
"e": 6305,
"s": 6247,
"text": "Alternatively, you can download an object in binary mode."
},
{
"code": null,
"e": 6320,
"s": 6305,
"text": "upload objects"
},
{
"code": null,
"e": 6362,
"s": 6320,
"text": "Uploading objects follows the same logic."
},
{
"code": null,
"e": 6472,
"s": 6362,
"text": "This post is a collection of notes I took while using AWS Data Wrangler to per. I hope you found them useful."
},
{
"code": null,
"e": 6605,
"s": 6472,
"text": "In later posts, I’ll be reviewing other AWS services such as DynamoDB and EMR and how to interact with them using AWS Data Wrangler."
},
{
"code": null,
"e": 6691,
"s": 6605,
"text": "For the time being, here are some resources worth the read if you want to dig deeper."
},
{
"code": null,
"e": 6735,
"s": 6691,
"text": "AWS S3: https://aws.amazon.com/s3/?nc1=h_ls"
},
{
"code": null,
"e": 6783,
"s": 6735,
"text": "AWS IAM: https://aws.amazon.com/iam/?nc2=type_a"
},
{
"code": null,
"e": 6858,
"s": 6783,
"text": "AWS Data Wrangler documentation: https://aws-data-wrangler.readthedocs.io/"
},
{
"code": null,
"e": 6911,
"s": 6858,
"text": "Github: https://github.com/awslabs/aws-data-wrangler"
}
] |
Private VLAN - GeeksforGeeks
|
02 Nov, 2021
Prerequisite – Virtual LAN (VLAN)Virtual LAN (VLAN) is used to break a broadcast domain into smaller domain at layer 2. Only (all) hosts belonging to same VLAN are able to communicate with each other while communicating with other VLAN hosts, Inter Vlan routing is done. But in same VLAN, if we want some hosts should not be able to communicate with other hosts (in the same VLAN) at layer 2 level then VLAN access-list or concept of private VLAN is used.
Private VLAN –Private VLAN are used to break the layer 2 broadcast domain into small subdomains. A subdomain consists of one primary VLAN and one or more secondary VLAN.
Types of VLANs –
There are two types of VLANs in Private VLANs:
Primary VLAN –All the ports in the private VLAN belong to a primary VLAN. A private VLAN can have only one primary VLAN. All the VLANs in a private VLAN domain share the same primary VLAN.Secondary VLAN –A private VLAN can have one or more secondary VLANs. It provides isolation between the ports belonging to same private VLAN domain.These are of two types:Isolated VLANs –Hosts belonging to Isolated VLAN can only communicate with its associated promiscuous port and cannot communicate directly with other hosts (belonging to other isolated or community VLAN) directly at layer 2. Usually, a single port is assigned to Isolated VLANs but you can have more than one port associated to it.Community VLANs –A private VLAN can have one or more than one community VLANs. Hosts belonging to the same community VLANs can communicate with each other and its associated promiscuous port but hosts belonging to different community VLANs cannot communicate with each other at layer 2.
Primary VLAN –All the ports in the private VLAN belong to a primary VLAN. A private VLAN can have only one primary VLAN. All the VLANs in a private VLAN domain share the same primary VLAN.
Secondary VLAN –A private VLAN can have one or more secondary VLANs. It provides isolation between the ports belonging to same private VLAN domain.These are of two types:Isolated VLANs –Hosts belonging to Isolated VLAN can only communicate with its associated promiscuous port and cannot communicate directly with other hosts (belonging to other isolated or community VLAN) directly at layer 2. Usually, a single port is assigned to Isolated VLANs but you can have more than one port associated to it.Community VLANs –A private VLAN can have one or more than one community VLANs. Hosts belonging to the same community VLANs can communicate with each other and its associated promiscuous port but hosts belonging to different community VLANs cannot communicate with each other at layer 2.
Isolated VLANs –Hosts belonging to Isolated VLAN can only communicate with its associated promiscuous port and cannot communicate directly with other hosts (belonging to other isolated or community VLAN) directly at layer 2. Usually, a single port is assigned to Isolated VLANs but you can have more than one port associated to it.Community VLANs –A private VLAN can have one or more than one community VLANs. Hosts belonging to the same community VLANs can communicate with each other and its associated promiscuous port but hosts belonging to different community VLANs cannot communicate with each other at layer 2.
Isolated VLANs –Hosts belonging to Isolated VLAN can only communicate with its associated promiscuous port and cannot communicate directly with other hosts (belonging to other isolated or community VLAN) directly at layer 2. Usually, a single port is assigned to Isolated VLANs but you can have more than one port associated to it.
Community VLANs –A private VLAN can have one or more than one community VLANs. Hosts belonging to the same community VLANs can communicate with each other and its associated promiscuous port but hosts belonging to different community VLANs cannot communicate with each other at layer 2.
Types of ports in A Private VLAN are:
Promiscuous port –It belongs to the primary VLAN. These ports can communicate with all interfaces, that are a part of secondary VLANs associated with that promiscuous port and that primary VLAN. Generally, it is used for connecting switches with routers, Firewalls etc.Isolated port –An isolated port belongs to a secondary isolated VLAN. These are the host ports whose traffic is forwarded to the promiscuous port. A private VLAN allows only that traffic to the isolated port which is coming from its associated promiscuous port.Community port –This port belongs to a secondary community VLAN. These host ports can communicate with other ports in the same community VLAN and also with its associated promiscuous port. These ports are completely isolated from other community VLAN ports and isolated ports.
Promiscuous port –It belongs to the primary VLAN. These ports can communicate with all interfaces, that are a part of secondary VLANs associated with that promiscuous port and that primary VLAN. Generally, it is used for connecting switches with routers, Firewalls etc.
Isolated port –An isolated port belongs to a secondary isolated VLAN. These are the host ports whose traffic is forwarded to the promiscuous port. A private VLAN allows only that traffic to the isolated port which is coming from its associated promiscuous port.
Community port –This port belongs to a secondary community VLAN. These host ports can communicate with other ports in the same community VLAN and also with its associated promiscuous port. These ports are completely isolated from other community VLAN ports and isolated ports.
Note –VTP (VLAN Trunking Protocol) should be operating in mode transparent or off in order to configure private VLANs.
Configuration –
Here is a topology in which Router1 (IP address- 192.168.1.1/24), PC1(IP address- 192.168.1.10/24 ), PC2(IP address- 192.168.1.20/24 ), PC3 (IP address- 192.168.1.30/24) and switch are connected to each other as shown in the figure.In this task, we will assign VLAN 10 to fa0/1, fa0/2, and VLAN 20 to fa0/3 and fa0/0 as VLAN 100. Then, we will make VLAN 10 as community VLAN, VLAN 20 as isolated VLAN and VLAN 100 as primary VLAN.
Configuring Private VLAN on switch:
switch(config)#vlan 10
switch(config-vlan)#private-vlan community
switch(config-vlan)#exit
Here, we have created VLAN 10 and configured it as community VLAN. Now, configuring isolated VLAN.
switch(config)#vlan 20
switch(config-vlan)#private-vlan isolated
switch(config-vlan)#exit
Now, creating vlan 100 and configuring it as primary VLAN and associating secondary vlan 10, 20 to it.
switch(config)#vlan 100
switch(config-vlan)#private-vlan primary
switch(config-vlan)#private-vlan association 10, 20
switch(config-vlan)#exit
Now, configuring ports as private-vlan host port and associating them with primary and secondary VLAN. First configuring fa0/1 and fa0/2 and associating vlan 10 (secondary VLAN) with its primary VLAN (vlan 100).
switch(config)#int range fa0/1-2
switch(config-vlan)#switchport mode private-vlan host
switch(config-vlan)#switchport Private-vlan host-association 100 10
Now, configuring fa0/3 and associating vlan 20 (secondary VLAN) with its primary VLAN (vlan 100).
switch(config)#int fa0/3
switch(config-vlan)#switchport mode private-vlan host
switch(config-vlan)#switchport Private-vlan host-association 100 20
Now, at last we will configure interface fa0/0 as promiscuous port and associate the port with primary vlan (vlan 100) and secondary VLAN (vlan 10, 20).
switch(config)#int fa0/0
switch(config-vlan)#switchport mode private-vlan promiscuous
switch(config-vlan)#switchport Private-vlan mapping 100 10, 20
We can verify the ports associated with secondary VLANs by command.
switch#show vlan private-vlan
If you want to verify the primary VLAN and secondary VLAN (Isolated or Community) then use the command.
switch# show vlan private-vlan type
kmbh
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Differences between IPv4 and IPv6
Socket Programming in Java
Hamming Code in Computer Network
Types of area networks - LAN, MAN and WAN
Error Detection in Computer Networks
Advanced Encryption Standard (AES)
Implementation of Diffie-Hellman Algorithm
Distance Vector Routing (DVR) Protocol
Introduction of Classful IP Addressing
Simple Chat Room using Python
|
[
{
"code": null,
"e": 23825,
"s": 23797,
"text": "\n02 Nov, 2021"
},
{
"code": null,
"e": 24281,
"s": 23825,
"text": "Prerequisite – Virtual LAN (VLAN)Virtual LAN (VLAN) is used to break a broadcast domain into smaller domain at layer 2. Only (all) hosts belonging to same VLAN are able to communicate with each other while communicating with other VLAN hosts, Inter Vlan routing is done. But in same VLAN, if we want some hosts should not be able to communicate with other hosts (in the same VLAN) at layer 2 level then VLAN access-list or concept of private VLAN is used."
},
{
"code": null,
"e": 24451,
"s": 24281,
"text": "Private VLAN –Private VLAN are used to break the layer 2 broadcast domain into small subdomains. A subdomain consists of one primary VLAN and one or more secondary VLAN."
},
{
"code": null,
"e": 24468,
"s": 24451,
"text": "Types of VLANs –"
},
{
"code": null,
"e": 24515,
"s": 24468,
"text": "There are two types of VLANs in Private VLANs:"
},
{
"code": null,
"e": 25491,
"s": 24515,
"text": "Primary VLAN –All the ports in the private VLAN belong to a primary VLAN. A private VLAN can have only one primary VLAN. All the VLANs in a private VLAN domain share the same primary VLAN.Secondary VLAN –A private VLAN can have one or more secondary VLANs. It provides isolation between the ports belonging to same private VLAN domain.These are of two types:Isolated VLANs –Hosts belonging to Isolated VLAN can only communicate with its associated promiscuous port and cannot communicate directly with other hosts (belonging to other isolated or community VLAN) directly at layer 2. Usually, a single port is assigned to Isolated VLANs but you can have more than one port associated to it.Community VLANs –A private VLAN can have one or more than one community VLANs. Hosts belonging to the same community VLANs can communicate with each other and its associated promiscuous port but hosts belonging to different community VLANs cannot communicate with each other at layer 2."
},
{
"code": null,
"e": 25680,
"s": 25491,
"text": "Primary VLAN –All the ports in the private VLAN belong to a primary VLAN. A private VLAN can have only one primary VLAN. All the VLANs in a private VLAN domain share the same primary VLAN."
},
{
"code": null,
"e": 26468,
"s": 25680,
"text": "Secondary VLAN –A private VLAN can have one or more secondary VLANs. It provides isolation between the ports belonging to same private VLAN domain.These are of two types:Isolated VLANs –Hosts belonging to Isolated VLAN can only communicate with its associated promiscuous port and cannot communicate directly with other hosts (belonging to other isolated or community VLAN) directly at layer 2. Usually, a single port is assigned to Isolated VLANs but you can have more than one port associated to it.Community VLANs –A private VLAN can have one or more than one community VLANs. Hosts belonging to the same community VLANs can communicate with each other and its associated promiscuous port but hosts belonging to different community VLANs cannot communicate with each other at layer 2."
},
{
"code": null,
"e": 27086,
"s": 26468,
"text": "Isolated VLANs –Hosts belonging to Isolated VLAN can only communicate with its associated promiscuous port and cannot communicate directly with other hosts (belonging to other isolated or community VLAN) directly at layer 2. Usually, a single port is assigned to Isolated VLANs but you can have more than one port associated to it.Community VLANs –A private VLAN can have one or more than one community VLANs. Hosts belonging to the same community VLANs can communicate with each other and its associated promiscuous port but hosts belonging to different community VLANs cannot communicate with each other at layer 2."
},
{
"code": null,
"e": 27418,
"s": 27086,
"text": "Isolated VLANs –Hosts belonging to Isolated VLAN can only communicate with its associated promiscuous port and cannot communicate directly with other hosts (belonging to other isolated or community VLAN) directly at layer 2. Usually, a single port is assigned to Isolated VLANs but you can have more than one port associated to it."
},
{
"code": null,
"e": 27705,
"s": 27418,
"text": "Community VLANs –A private VLAN can have one or more than one community VLANs. Hosts belonging to the same community VLANs can communicate with each other and its associated promiscuous port but hosts belonging to different community VLANs cannot communicate with each other at layer 2."
},
{
"code": null,
"e": 27743,
"s": 27705,
"text": "Types of ports in A Private VLAN are:"
},
{
"code": null,
"e": 28550,
"s": 27743,
"text": "Promiscuous port –It belongs to the primary VLAN. These ports can communicate with all interfaces, that are a part of secondary VLANs associated with that promiscuous port and that primary VLAN. Generally, it is used for connecting switches with routers, Firewalls etc.Isolated port –An isolated port belongs to a secondary isolated VLAN. These are the host ports whose traffic is forwarded to the promiscuous port. A private VLAN allows only that traffic to the isolated port which is coming from its associated promiscuous port.Community port –This port belongs to a secondary community VLAN. These host ports can communicate with other ports in the same community VLAN and also with its associated promiscuous port. These ports are completely isolated from other community VLAN ports and isolated ports."
},
{
"code": null,
"e": 28820,
"s": 28550,
"text": "Promiscuous port –It belongs to the primary VLAN. These ports can communicate with all interfaces, that are a part of secondary VLANs associated with that promiscuous port and that primary VLAN. Generally, it is used for connecting switches with routers, Firewalls etc."
},
{
"code": null,
"e": 29082,
"s": 28820,
"text": "Isolated port –An isolated port belongs to a secondary isolated VLAN. These are the host ports whose traffic is forwarded to the promiscuous port. A private VLAN allows only that traffic to the isolated port which is coming from its associated promiscuous port."
},
{
"code": null,
"e": 29359,
"s": 29082,
"text": "Community port –This port belongs to a secondary community VLAN. These host ports can communicate with other ports in the same community VLAN and also with its associated promiscuous port. These ports are completely isolated from other community VLAN ports and isolated ports."
},
{
"code": null,
"e": 29478,
"s": 29359,
"text": "Note –VTP (VLAN Trunking Protocol) should be operating in mode transparent or off in order to configure private VLANs."
},
{
"code": null,
"e": 29494,
"s": 29478,
"text": "Configuration –"
},
{
"code": null,
"e": 29925,
"s": 29494,
"text": "Here is a topology in which Router1 (IP address- 192.168.1.1/24), PC1(IP address- 192.168.1.10/24 ), PC2(IP address- 192.168.1.20/24 ), PC3 (IP address- 192.168.1.30/24) and switch are connected to each other as shown in the figure.In this task, we will assign VLAN 10 to fa0/1, fa0/2, and VLAN 20 to fa0/3 and fa0/0 as VLAN 100. Then, we will make VLAN 10 as community VLAN, VLAN 20 as isolated VLAN and VLAN 100 as primary VLAN."
},
{
"code": null,
"e": 29961,
"s": 29925,
"text": "Configuring Private VLAN on switch:"
},
{
"code": null,
"e": 30053,
"s": 29961,
"text": "switch(config)#vlan 10\nswitch(config-vlan)#private-vlan community\nswitch(config-vlan)#exit\n"
},
{
"code": null,
"e": 30152,
"s": 30053,
"text": "Here, we have created VLAN 10 and configured it as community VLAN. Now, configuring isolated VLAN."
},
{
"code": null,
"e": 30242,
"s": 30152,
"text": "switch(config)#vlan 20\nswitch(config-vlan)#private-vlan isolated\nswitch(config-vlan)#exit"
},
{
"code": null,
"e": 30345,
"s": 30242,
"text": "Now, creating vlan 100 and configuring it as primary VLAN and associating secondary vlan 10, 20 to it."
},
{
"code": null,
"e": 30488,
"s": 30345,
"text": "switch(config)#vlan 100\nswitch(config-vlan)#private-vlan primary\nswitch(config-vlan)#private-vlan association 10, 20\nswitch(config-vlan)#exit "
},
{
"code": null,
"e": 30700,
"s": 30488,
"text": "Now, configuring ports as private-vlan host port and associating them with primary and secondary VLAN. First configuring fa0/1 and fa0/2 and associating vlan 10 (secondary VLAN) with its primary VLAN (vlan 100)."
},
{
"code": null,
"e": 30855,
"s": 30700,
"text": "switch(config)#int range fa0/1-2\nswitch(config-vlan)#switchport mode private-vlan host\nswitch(config-vlan)#switchport Private-vlan host-association 100 10"
},
{
"code": null,
"e": 30953,
"s": 30855,
"text": "Now, configuring fa0/3 and associating vlan 20 (secondary VLAN) with its primary VLAN (vlan 100)."
},
{
"code": null,
"e": 31100,
"s": 30953,
"text": "switch(config)#int fa0/3\nswitch(config-vlan)#switchport mode private-vlan host\nswitch(config-vlan)#switchport Private-vlan host-association 100 20"
},
{
"code": null,
"e": 31253,
"s": 31100,
"text": "Now, at last we will configure interface fa0/0 as promiscuous port and associate the port with primary vlan (vlan 100) and secondary VLAN (vlan 10, 20)."
},
{
"code": null,
"e": 31403,
"s": 31253,
"text": "switch(config)#int fa0/0\nswitch(config-vlan)#switchport mode private-vlan promiscuous \nswitch(config-vlan)#switchport Private-vlan mapping 100 10, 20"
},
{
"code": null,
"e": 31471,
"s": 31403,
"text": "We can verify the ports associated with secondary VLANs by command."
},
{
"code": null,
"e": 31501,
"s": 31471,
"text": "switch#show vlan private-vlan"
},
{
"code": null,
"e": 31605,
"s": 31501,
"text": "If you want to verify the primary VLAN and secondary VLAN (Isolated or Community) then use the command."
},
{
"code": null,
"e": 31642,
"s": 31605,
"text": "switch# show vlan private-vlan type "
},
{
"code": null,
"e": 31647,
"s": 31642,
"text": "kmbh"
},
{
"code": null,
"e": 31665,
"s": 31647,
"text": "Computer Networks"
},
{
"code": null,
"e": 31683,
"s": 31665,
"text": "Computer Networks"
},
{
"code": null,
"e": 31781,
"s": 31683,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31790,
"s": 31781,
"text": "Comments"
},
{
"code": null,
"e": 31803,
"s": 31790,
"text": "Old Comments"
},
{
"code": null,
"e": 31837,
"s": 31803,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 31864,
"s": 31837,
"text": "Socket Programming in Java"
},
{
"code": null,
"e": 31897,
"s": 31864,
"text": "Hamming Code in Computer Network"
},
{
"code": null,
"e": 31939,
"s": 31897,
"text": "Types of area networks - LAN, MAN and WAN"
},
{
"code": null,
"e": 31976,
"s": 31939,
"text": "Error Detection in Computer Networks"
},
{
"code": null,
"e": 32011,
"s": 31976,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 32054,
"s": 32011,
"text": "Implementation of Diffie-Hellman Algorithm"
},
{
"code": null,
"e": 32093,
"s": 32054,
"text": "Distance Vector Routing (DVR) Protocol"
},
{
"code": null,
"e": 32132,
"s": 32093,
"text": "Introduction of Classful IP Addressing"
}
] |
Check if concatenation of two strings is balanced or not - GeeksforGeeks
|
24 Sep, 2021
Given two bracket sequences S1 and S2 consisting of ‘(‘ and ‘)’. The task is to check if the string obtained by concatenating both the sequences is balanced or not. Concatenation can be done by s1+s2 or s2+s1.
Examples:
Input: s1 = “)()(())))”, s2 = “(()(()(” Output: Balanced s2 + s1 = “(()(()()()(())))”, which is a balanced parenthesis sequence.
Input: s1 = “(()))(“, s2 = “())())” Output: Not balanced s1 + s2 = “(()))(())())” –> Not balanced s2 + s1 = “())())(()))(” –> Not balanced
A naive solution is to first concatenate both sequences and then check if the resultant sequence is balanced or not using a stack. First, check if s1 + s2 is balanced or not. If not, then check if s2 + s1 is balanced or not. To check if a given sequence of brackets is balanced or not using a stack, the following algorithm can be used.
Declare a character stack S.Now traverse the expression string exp. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from the stack and if the popped character is the matching starting bracket then fine else parenthesis are not balanced.After complete traversal, if there is some starting bracket left in the stack then “not balanced”.
Declare a character stack S.
Now traverse the expression string exp. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from the stack and if the popped character is the matching starting bracket then fine else parenthesis are not balanced.
If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from the stack and if the popped character is the matching starting bracket then fine else parenthesis are not balanced.
After complete traversal, if there is some starting bracket left in the stack then “not balanced”.
Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// CPP program to check if sequence obtained// by concatenating two bracket sequences// is balanced or not.#include <bits/stdc++.h>using namespace std; // Check if given string is balanced bracket// sequence or not.bool isBalanced(string s){ stack<char> st; int n = s.length(); for (int i = 0; i < n; i++) { // If current bracket is an opening // bracket push it to stack. if (s[i] == '(') st.push(s[i]); // If current bracket is a closing // bracket then pop from stack if // it is not empty. If stack is empty // then sequence is not balanced. else { if (st.empty()) { return false; } else st.pop(); } } // If stack is not empty, then sequence // is not balanced. if (!st.empty()) return false; return true;} // Function to check if string obtained by// concatenating two bracket sequences is// balanced or not.bool isBalancedSeq(string s1, string s2){ // Check if s1 + s2 is balanced or not. if (isBalanced(s1 + s2)) return true; // Check if s2 + s1 is balanced or not. return isBalanced(s2 + s1);} // Driver code.int main(){ string s1 = ")()(())))"; string s2 = "(()(()("; if (isBalancedSeq(s1, s2)) cout << "Balanced"; else cout << "Not Balanced"; return 0;}
// Java program to check if sequence obtained// by concatenating two bracket sequences// is balanced or not.import java.util.Stack; class GFG{ // Check if given string is balanced bracket // sequence or not. static boolean isBalanced(String s) { Stack<Character> st = new Stack<Character>(); int n = s.length(); for (int i = 0; i < n; i++) { // If current bracket is an opening // bracket push it to stack. if (s.charAt(i) == '(') { st.push(s.charAt(i)); } // If current bracket is a closing // bracket then pop from stack if // it is not empty. If stack is empty // then sequence is not balanced. else if (st.empty()) { return false; } else { st.pop(); } } // If stack is not empty, then sequence // is not balanced. if (!st.empty()) { return false; } return true; } // Function to check if string obtained by // concatenating two bracket sequences is // balanced or not. static boolean isBalancedSeq(String s1, String s2) { // Check if s1 + s2 is balanced or not. if (isBalanced(s1 + s2)) { return true; } // Check if s2 + s1 is balanced or not. return isBalanced(s2 + s1); } // Driver code. public static void main(String[] args) { String s1 = ")()(())))"; String s2 = "(()(()("; if (isBalancedSeq(s1, s2)) { System.out.println("Balanced"); } else { System.out.println("Not Balanced"); } }} // This code is contributed by Rajput-Ji
# Python3 program to check if sequence obtained# by concatenating two bracket sequences# is balanced or not. # Check if given string is balanced bracket# sequence or not.def isBalanced(s): st = list() n = len(s) for i in range(n): # If current bracket is an opening # bracket push it to stack. if s[i] == '(': st.append(s[i]) # If current bracket is a closing # bracket then pop from stack if # it is not empty. If stack is empty # then sequence is not balanced. else: if len(st) == 0: return False else: st.pop() # If stack is not empty, then sequence # is not balanced. if len(st) > 0: return False return True # Function to check if string obtained by# concatenating two bracket sequences is# balanced or not.def isBalancedSeq(s1, s2): # Check if s1 + s2 is balanced or not. if (isBalanced(s1 + s2)): return True # Check if s2 + s1 is balanced or not. return isBalanced(s2 + s1) # Driver Codeif __name__ == "__main__": s1 = ")()(())))" s2 = "(()(()(" if isBalancedSeq(s1, s2): print("Balanced") else: print("Not Balanced") # This code is contributed by# sanjeev2552
// C# program to check if sequence obtained// by concatenating two bracket sequences// is balanced or not.using System;using System.Collections.Generic; class GFG{ // Check if given string is balanced bracket // sequence or not. static bool isBalanced(String s) { Stack<char> st = new Stack<char>(); int n = s.Length; for (int i = 0; i < n; i++) { // If current bracket is an opening // bracket push it to stack. if (s[i] == '(') { st.Push(s[i]); } // If current bracket is a closing // bracket then pop from stack if // it is not empty. If stack is empty // then sequence is not balanced. else if (st.Count==0) { return false; } else { st.Pop(); } } // If stack is not empty, then sequence // is not balanced. if (st.Count!=0) { return false; } return true; } // Function to check if string obtained by // concatenating two bracket sequences is // balanced or not. static bool isBalancedSeq(String s1, String s2) { // Check if s1 + s2 is balanced or not. if (isBalanced(s1 + s2)) { return true; } // Check if s2 + s1 is balanced or not. return isBalanced(s2 + s1); } // Driver code. public static void Main(String[] args) { String s1 = ")()(())))"; String s2 = "(()(()("; if (isBalancedSeq(s1, s2)) { Console.WriteLine("Balanced"); } else { Console.WriteLine("Not Balanced"); } }} // This code has been contributed by 29AjayKumar
<script> // Javascript program to check if sequence// obtained by concatenating two bracket// sequences is balanced or not. // Check if given string is balanced// bracket sequence or not.function isBalanced(s){ let st = []; let n = s.length; for(let i = 0; i < n; i++) { // If current bracket is an opening // bracket push it to stack. if (s[i] == '(') { st.push(s[i]); } // If current bracket is a closing // bracket then pop from stack if // it is not empty. If stack is empty // then sequence is not balanced. else if (st.length == 0) { return false; } else { st.pop(); } } // If stack is not empty, then sequence // is not balanced. if (st.length != 0) { return false; } return true;} // Function to check if string obtained by// concatenating two bracket sequences is// balanced or not.function isBalancedSeq(s1, s2){ // Check if s1 + s2 is balanced or not. if (isBalanced(s1 + s2)) { return true; } // Check if s2 + s1 is balanced or not. return isBalanced(s2 + s1);} // Driver codelet s1 = ")()(())))";let s2 = "(()(()("; if (isBalancedSeq(s1, s2)){ document.write("Balanced");}else{ document.write("Not Balanced");} // This code is contributed by mukesh07 </script>
Balanced
Time complexity: O(n) Auxiliary Space: O(n)
An efficient solution is to check if given sequences can result in a balanced parenthesis sequence without using a stack, i.e., in constant extra space. Let the concatenated sequence is s. There are two possibilities: either s = s1 + s2 is balanced or s = s2 + s1 is balanced. Check for both possibilities whether s is balanced or not.
If s is balanced, then the number of opening brackets in s should always be greater than or equal to the number of closing brackets in S at any instant of traversing it. This is because if at any instant number of closing brackets in s is greater than the number of opening brackets, then the last closing bracket will not have a matching opening bracket (that is why the count is more) in s.
If the sequence is balanced then at the end of traversal, the number of opening brackets in s is equal to the number of closing brackets in s.
Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check if sequence obtained// by concatenating two bracket sequences// is balanced or not.#include <bits/stdc++.h>using namespace std; // Check if given string is balanced bracket// sequence or not.bool isBalanced(string s){ // To store result of comparison of // count of opening brackets and // closing brackets. int cnt = 0; int n = s.length(); for (int i = 0; i < n; i++) { // If current bracket is an // opening bracket, then // increment count. if (s[i] == '(') cnt++; // If current bracket is a // closing bracket, then // decrement count and check // if count is negative. else { cnt--; if (cnt < 0) return false; } } // If count is positive then // some opening brackets are // not balanced. if (cnt > 0) return false; return true;} // Function to check if string obtained by// concatenating two bracket sequences is// balanced or not.bool isBalancedSeq(string s1, string s2){ // Check if s1 + s2 is balanced or not. if (isBalanced(s1 + s2)) return true; // Check if s2 + s1 is balanced or not. return isBalanced(s2 + s1);} // Driver code.int main(){ string s1 = ")()(())))"; string s2 = "(()(()("; if (isBalancedSeq(s1, s2)) cout << "Balanced"; else cout << "Not Balanced"; return 0;}
// Java program to check if// sequence obtained by// concatenating two bracket// sequences is balanced or not.import java.io.*; class GFG{ // Check if given string// is balanced bracket// sequence or not.static boolean isBalanced(String s){ // To store result of comparison// of count of opening brackets// and closing brackets.int cnt = 0;int n = s.length();for (int i = 0; i < n; i++){ // If current bracket is // an opening bracket, // then increment count. if (s.charAt(i) =='(') { cnt = cnt + 1; } // If current bracket is a // closing bracket, then // decrement count and check // if count is negative. else { cnt = cnt - 1; if (cnt < 0) return false; }} // If count is positive then// some opening brackets are// not balanced.if (cnt > 0) return false; return true;} // Function to check if string// obtained by concatenating// two bracket sequences is// balanced or not.static boolean isBalancedSeq(String s1, String s2){ // Check if s1 + s2 is// balanced or not.if (isBalanced(s1 + s2)) return true; // Check if s2 + s1 is// balanced or not.return isBalanced(s2 + s1);} // Driver codepublic static void main(String [] args){ String s1 = ")()(())))"; String s2 = "(()(()("; if (isBalancedSeq(s1, s2)) { System.out.println("Balanced"); } else { System.out.println("Not Balanced"); }}} // This code is contributed// by Shivi_Aggarwal
# Python3 program to check# if sequence obtained by# concatenating two bracket# sequences is balanced or not. # Check if given string# is balanced bracket# sequence or not.def isBalanced(s): # To store result of # comparison of count # of opening brackets # and closing brackets. cnt = 0 n = len(s) for i in range(0, n): if (s[i] == '('): cnt = cnt + 1 else : cnt = cnt - 1 if (cnt < 0): return False if (cnt > 0): return False return True def isBalancedSeq(s1, s2): if (isBalanced(s1 + s2)): return True return isBalanced(s2 + s1) # Driver codea = ")()(())))";b = "(()(()("; if (isBalancedSeq(a, b)): print("Balanced")else: print("Not Balanced") # This code is contributed# by Shivi_Aggarwal
// C# program to check if// sequence obtained by// concatenating two bracket// sequences is balanced or not.using System;class GFG{ // Check if given string // is balanced bracket // sequence or not. static bool isBalanced(String s) { // To store result of comparison // of count of opening brackets // and closing brackets. int cnt = 0; int n = s.Length; for (int i = 0; i < n; i++) { // If current bracket is // an opening bracket, // then increment count. if (s[i] =='(') { cnt = cnt + 1; } // If current bracket is a // closing bracket, then // decrement count and check // if count is negative. else { cnt = cnt - 1; if (cnt < 0) return false; } } // If count is positive then // some opening brackets are // not balanced. if (cnt > 0) return false; return true; } // Function to check if string // obtained by concatenating // two bracket sequences is // balanced or not. static bool isBalancedSeq(String s1, String s2) { // Check if s1 + s2 is // balanced or not. if (isBalanced(s1 + s2)) return true; // Check if s2 + s1 is // balanced or not. return isBalanced(s2 + s1); } // Driver code public static void Main() { String s1 = ")()(())))"; String s2 = "(()(()("; if (isBalancedSeq(s1, s2)) { Console.WriteLine("Balanced"); } else { Console.WriteLine("Not Balanced"); } }} // This code is contributed by// PrinciRaj1992
<?php // PHP program to check if sequence obtained// by concatenating two bracket sequences// is balanced or not.// Check if given string is balanced bracket// sequence or not. function isBalanced($s){ // To store result of comparison of // count of opening brackets and // closing brackets. $cnt = 0; $n = strlen($s); for ($i = 0; $i < $n; $i++) { // If current bracket is an // opening bracket, then // increment count. if ($s[$i] == '(') $cnt++; // If current bracket is a // closing bracket, then // decrement count and check // if count is negative. else { $cnt--; if ($cnt < 0) return false; } } // If count is positive then // some opening brackets are // not balanced. if ($cnt > 0) return false; return true;} // Function to check if string obtained by// concatenating two bracket sequences is// balanced or not.function isBalancedSeq($s1, $s2){ // Check if s1 + s2 is balanced or not. if (isBalanced($s1 + $s2)) return true; // Check if s2 + s1 is balanced or not. return isBalanced($s2 + $s1);} // Driver code. $s1 = ")()(())))"; $s2 = "(()(()("; if (!isBalancedSeq($s1, $s2)) echo "Balanced"; else echo "Not Balanced"; // This code is contributed by ajit.?>
<script> // Javascript program to check if sequence obtained// by concatenating two bracket sequences// is balanced or not. // Check if given string is balanced bracket// sequence or not.function isBalanced(s){ // To store result of comparison of // count of opening brackets and // closing brackets. var cnt = 0; var n = s.length; for (var i = 0; i < n; i++) { // If current bracket is an // opening bracket, then // increment count. if (s[i] == '(') cnt++; // If current bracket is a // closing bracket, then // decrement count and check // if count is negative. else { cnt--; if (cnt < 0) return false; } } // If count is positive then // some opening brackets are // not balanced. if (cnt > 0) return false; return true;} // Function to check if string obtained by// concatenating two bracket sequences is// balanced or not.function isBalancedSeq(s1, s2){ // Check if s1 + s2 is balanced or not. if (isBalanced(s1 + s2)) return true; // Check if s2 + s1 is balanced or not. return isBalanced(s2 + s1);} // Driver code.var s1 = ")()(())))";var s2 = "(()(()(";if (isBalancedSeq(s1, s2)) document.write( "Balanced");else document.write( "Not Balanced"); </script>
Balanced
Time complexity: O(n) Auxiliary Space: O(1)
Shivi_Aggarwal
princiraj1992
Rajput-Ji
jit_t
29AjayKumar
sanjeev2552
noob2000
mukesh07
surinderdawra388
C-String-Question
Constructive Algorithms
Bit Magic
Competitive Programming
Data Structures
Stack
Data Structures
Stack
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Set, Clear and Toggle a given bit of a number in C
Program to find parity
Check whether K-th bit is set or not
Hamming code Implementation in C/C++
Write an Efficient Method to Check if a Number is Multiple of 3
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Competitive Programming - A Complete Guide
Modulo 10^9+7 (1000000007)
Top 10 Algorithms and Data Structures for Competitive Programming
|
[
{
"code": null,
"e": 25012,
"s": 24984,
"text": "\n24 Sep, 2021"
},
{
"code": null,
"e": 25222,
"s": 25012,
"text": "Given two bracket sequences S1 and S2 consisting of ‘(‘ and ‘)’. The task is to check if the string obtained by concatenating both the sequences is balanced or not. Concatenation can be done by s1+s2 or s2+s1."
},
{
"code": null,
"e": 25233,
"s": 25222,
"text": "Examples: "
},
{
"code": null,
"e": 25362,
"s": 25233,
"text": "Input: s1 = “)()(())))”, s2 = “(()(()(” Output: Balanced s2 + s1 = “(()(()()()(())))”, which is a balanced parenthesis sequence."
},
{
"code": null,
"e": 25501,
"s": 25362,
"text": "Input: s1 = “(()))(“, s2 = “())())” Output: Not balanced s1 + s2 = “(()))(())())” –> Not balanced s2 + s1 = “())())(()))(” –> Not balanced"
},
{
"code": null,
"e": 25839,
"s": 25501,
"text": "A naive solution is to first concatenate both sequences and then check if the resultant sequence is balanced or not using a stack. First, check if s1 + s2 is balanced or not. If not, then check if s2 + s1 is balanced or not. To check if a given sequence of brackets is balanced or not using a stack, the following algorithm can be used. "
},
{
"code": null,
"e": 26290,
"s": 25839,
"text": "Declare a character stack S.Now traverse the expression string exp. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from the stack and if the popped character is the matching starting bracket then fine else parenthesis are not balanced.After complete traversal, if there is some starting bracket left in the stack then “not balanced”."
},
{
"code": null,
"e": 26319,
"s": 26290,
"text": "Declare a character stack S."
},
{
"code": null,
"e": 26644,
"s": 26319,
"text": "Now traverse the expression string exp. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from the stack and if the popped character is the matching starting bracket then fine else parenthesis are not balanced."
},
{
"code": null,
"e": 26734,
"s": 26644,
"text": "If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack."
},
{
"code": null,
"e": 26930,
"s": 26734,
"text": "If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from the stack and if the popped character is the matching starting bracket then fine else parenthesis are not balanced."
},
{
"code": null,
"e": 27029,
"s": 26930,
"text": "After complete traversal, if there is some starting bracket left in the stack then “not balanced”."
},
{
"code": null,
"e": 27077,
"s": 27029,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 27081,
"s": 27077,
"text": "C++"
},
{
"code": null,
"e": 27086,
"s": 27081,
"text": "Java"
},
{
"code": null,
"e": 27094,
"s": 27086,
"text": "Python3"
},
{
"code": null,
"e": 27097,
"s": 27094,
"text": "C#"
},
{
"code": null,
"e": 27108,
"s": 27097,
"text": "Javascript"
},
{
"code": "// CPP program to check if sequence obtained// by concatenating two bracket sequences// is balanced or not.#include <bits/stdc++.h>using namespace std; // Check if given string is balanced bracket// sequence or not.bool isBalanced(string s){ stack<char> st; int n = s.length(); for (int i = 0; i < n; i++) { // If current bracket is an opening // bracket push it to stack. if (s[i] == '(') st.push(s[i]); // If current bracket is a closing // bracket then pop from stack if // it is not empty. If stack is empty // then sequence is not balanced. else { if (st.empty()) { return false; } else st.pop(); } } // If stack is not empty, then sequence // is not balanced. if (!st.empty()) return false; return true;} // Function to check if string obtained by// concatenating two bracket sequences is// balanced or not.bool isBalancedSeq(string s1, string s2){ // Check if s1 + s2 is balanced or not. if (isBalanced(s1 + s2)) return true; // Check if s2 + s1 is balanced or not. return isBalanced(s2 + s1);} // Driver code.int main(){ string s1 = \")()(())))\"; string s2 = \"(()(()(\"; if (isBalancedSeq(s1, s2)) cout << \"Balanced\"; else cout << \"Not Balanced\"; return 0;}",
"e": 28500,
"s": 27108,
"text": null
},
{
"code": "// Java program to check if sequence obtained// by concatenating two bracket sequences// is balanced or not.import java.util.Stack; class GFG{ // Check if given string is balanced bracket // sequence or not. static boolean isBalanced(String s) { Stack<Character> st = new Stack<Character>(); int n = s.length(); for (int i = 0; i < n; i++) { // If current bracket is an opening // bracket push it to stack. if (s.charAt(i) == '(') { st.push(s.charAt(i)); } // If current bracket is a closing // bracket then pop from stack if // it is not empty. If stack is empty // then sequence is not balanced. else if (st.empty()) { return false; } else { st.pop(); } } // If stack is not empty, then sequence // is not balanced. if (!st.empty()) { return false; } return true; } // Function to check if string obtained by // concatenating two bracket sequences is // balanced or not. static boolean isBalancedSeq(String s1, String s2) { // Check if s1 + s2 is balanced or not. if (isBalanced(s1 + s2)) { return true; } // Check if s2 + s1 is balanced or not. return isBalanced(s2 + s1); } // Driver code. public static void main(String[] args) { String s1 = \")()(())))\"; String s2 = \"(()(()(\"; if (isBalancedSeq(s1, s2)) { System.out.println(\"Balanced\"); } else { System.out.println(\"Not Balanced\"); } }} // This code is contributed by Rajput-Ji",
"e": 30333,
"s": 28500,
"text": null
},
{
"code": "# Python3 program to check if sequence obtained# by concatenating two bracket sequences# is balanced or not. # Check if given string is balanced bracket# sequence or not.def isBalanced(s): st = list() n = len(s) for i in range(n): # If current bracket is an opening # bracket push it to stack. if s[i] == '(': st.append(s[i]) # If current bracket is a closing # bracket then pop from stack if # it is not empty. If stack is empty # then sequence is not balanced. else: if len(st) == 0: return False else: st.pop() # If stack is not empty, then sequence # is not balanced. if len(st) > 0: return False return True # Function to check if string obtained by# concatenating two bracket sequences is# balanced or not.def isBalancedSeq(s1, s2): # Check if s1 + s2 is balanced or not. if (isBalanced(s1 + s2)): return True # Check if s2 + s1 is balanced or not. return isBalanced(s2 + s1) # Driver Codeif __name__ == \"__main__\": s1 = \")()(())))\" s2 = \"(()(()(\" if isBalancedSeq(s1, s2): print(\"Balanced\") else: print(\"Not Balanced\") # This code is contributed by# sanjeev2552",
"e": 31603,
"s": 30333,
"text": null
},
{
"code": "// C# program to check if sequence obtained// by concatenating two bracket sequences// is balanced or not.using System;using System.Collections.Generic; class GFG{ // Check if given string is balanced bracket // sequence or not. static bool isBalanced(String s) { Stack<char> st = new Stack<char>(); int n = s.Length; for (int i = 0; i < n; i++) { // If current bracket is an opening // bracket push it to stack. if (s[i] == '(') { st.Push(s[i]); } // If current bracket is a closing // bracket then pop from stack if // it is not empty. If stack is empty // then sequence is not balanced. else if (st.Count==0) { return false; } else { st.Pop(); } } // If stack is not empty, then sequence // is not balanced. if (st.Count!=0) { return false; } return true; } // Function to check if string obtained by // concatenating two bracket sequences is // balanced or not. static bool isBalancedSeq(String s1, String s2) { // Check if s1 + s2 is balanced or not. if (isBalanced(s1 + s2)) { return true; } // Check if s2 + s1 is balanced or not. return isBalanced(s2 + s1); } // Driver code. public static void Main(String[] args) { String s1 = \")()(())))\"; String s2 = \"(()(()(\"; if (isBalancedSeq(s1, s2)) { Console.WriteLine(\"Balanced\"); } else { Console.WriteLine(\"Not Balanced\"); } }} // This code has been contributed by 29AjayKumar",
"e": 33432,
"s": 31603,
"text": null
},
{
"code": "<script> // Javascript program to check if sequence// obtained by concatenating two bracket// sequences is balanced or not. // Check if given string is balanced// bracket sequence or not.function isBalanced(s){ let st = []; let n = s.length; for(let i = 0; i < n; i++) { // If current bracket is an opening // bracket push it to stack. if (s[i] == '(') { st.push(s[i]); } // If current bracket is a closing // bracket then pop from stack if // it is not empty. If stack is empty // then sequence is not balanced. else if (st.length == 0) { return false; } else { st.pop(); } } // If stack is not empty, then sequence // is not balanced. if (st.length != 0) { return false; } return true;} // Function to check if string obtained by// concatenating two bracket sequences is// balanced or not.function isBalancedSeq(s1, s2){ // Check if s1 + s2 is balanced or not. if (isBalanced(s1 + s2)) { return true; } // Check if s2 + s1 is balanced or not. return isBalanced(s2 + s1);} // Driver codelet s1 = \")()(())))\";let s2 = \"(()(()(\"; if (isBalancedSeq(s1, s2)){ document.write(\"Balanced\");}else{ document.write(\"Not Balanced\");} // This code is contributed by mukesh07 </script>",
"e": 34839,
"s": 33432,
"text": null
},
{
"code": null,
"e": 34848,
"s": 34839,
"text": "Balanced"
},
{
"code": null,
"e": 34894,
"s": 34850,
"text": "Time complexity: O(n) Auxiliary Space: O(n)"
},
{
"code": null,
"e": 35231,
"s": 34894,
"text": "An efficient solution is to check if given sequences can result in a balanced parenthesis sequence without using a stack, i.e., in constant extra space. Let the concatenated sequence is s. There are two possibilities: either s = s1 + s2 is balanced or s = s2 + s1 is balanced. Check for both possibilities whether s is balanced or not. "
},
{
"code": null,
"e": 35624,
"s": 35231,
"text": "If s is balanced, then the number of opening brackets in s should always be greater than or equal to the number of closing brackets in S at any instant of traversing it. This is because if at any instant number of closing brackets in s is greater than the number of opening brackets, then the last closing bracket will not have a matching opening bracket (that is why the count is more) in s."
},
{
"code": null,
"e": 35767,
"s": 35624,
"text": "If the sequence is balanced then at the end of traversal, the number of opening brackets in s is equal to the number of closing brackets in s."
},
{
"code": null,
"e": 35816,
"s": 35767,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 35820,
"s": 35816,
"text": "C++"
},
{
"code": null,
"e": 35825,
"s": 35820,
"text": "Java"
},
{
"code": null,
"e": 35833,
"s": 35825,
"text": "Python3"
},
{
"code": null,
"e": 35836,
"s": 35833,
"text": "C#"
},
{
"code": null,
"e": 35840,
"s": 35836,
"text": "PHP"
},
{
"code": null,
"e": 35851,
"s": 35840,
"text": "Javascript"
},
{
"code": "// C++ program to check if sequence obtained// by concatenating two bracket sequences// is balanced or not.#include <bits/stdc++.h>using namespace std; // Check if given string is balanced bracket// sequence or not.bool isBalanced(string s){ // To store result of comparison of // count of opening brackets and // closing brackets. int cnt = 0; int n = s.length(); for (int i = 0; i < n; i++) { // If current bracket is an // opening bracket, then // increment count. if (s[i] == '(') cnt++; // If current bracket is a // closing bracket, then // decrement count and check // if count is negative. else { cnt--; if (cnt < 0) return false; } } // If count is positive then // some opening brackets are // not balanced. if (cnt > 0) return false; return true;} // Function to check if string obtained by// concatenating two bracket sequences is// balanced or not.bool isBalancedSeq(string s1, string s2){ // Check if s1 + s2 is balanced or not. if (isBalanced(s1 + s2)) return true; // Check if s2 + s1 is balanced or not. return isBalanced(s2 + s1);} // Driver code.int main(){ string s1 = \")()(())))\"; string s2 = \"(()(()(\"; if (isBalancedSeq(s1, s2)) cout << \"Balanced\"; else cout << \"Not Balanced\"; return 0;}",
"e": 37283,
"s": 35851,
"text": null
},
{
"code": "// Java program to check if// sequence obtained by// concatenating two bracket// sequences is balanced or not.import java.io.*; class GFG{ // Check if given string// is balanced bracket// sequence or not.static boolean isBalanced(String s){ // To store result of comparison// of count of opening brackets// and closing brackets.int cnt = 0;int n = s.length();for (int i = 0; i < n; i++){ // If current bracket is // an opening bracket, // then increment count. if (s.charAt(i) =='(') { cnt = cnt + 1; } // If current bracket is a // closing bracket, then // decrement count and check // if count is negative. else { cnt = cnt - 1; if (cnt < 0) return false; }} // If count is positive then// some opening brackets are// not balanced.if (cnt > 0) return false; return true;} // Function to check if string// obtained by concatenating// two bracket sequences is// balanced or not.static boolean isBalancedSeq(String s1, String s2){ // Check if s1 + s2 is// balanced or not.if (isBalanced(s1 + s2)) return true; // Check if s2 + s1 is// balanced or not.return isBalanced(s2 + s1);} // Driver codepublic static void main(String [] args){ String s1 = \")()(())))\"; String s2 = \"(()(()(\"; if (isBalancedSeq(s1, s2)) { System.out.println(\"Balanced\"); } else { System.out.println(\"Not Balanced\"); }}} // This code is contributed// by Shivi_Aggarwal",
"e": 38785,
"s": 37283,
"text": null
},
{
"code": "# Python3 program to check# if sequence obtained by# concatenating two bracket# sequences is balanced or not. # Check if given string# is balanced bracket# sequence or not.def isBalanced(s): # To store result of # comparison of count # of opening brackets # and closing brackets. cnt = 0 n = len(s) for i in range(0, n): if (s[i] == '('): cnt = cnt + 1 else : cnt = cnt - 1 if (cnt < 0): return False if (cnt > 0): return False return True def isBalancedSeq(s1, s2): if (isBalanced(s1 + s2)): return True return isBalanced(s2 + s1) # Driver codea = \")()(())))\";b = \"(()(()(\"; if (isBalancedSeq(a, b)): print(\"Balanced\")else: print(\"Not Balanced\") # This code is contributed# by Shivi_Aggarwal",
"e": 39606,
"s": 38785,
"text": null
},
{
"code": "// C# program to check if// sequence obtained by// concatenating two bracket// sequences is balanced or not.using System;class GFG{ // Check if given string // is balanced bracket // sequence or not. static bool isBalanced(String s) { // To store result of comparison // of count of opening brackets // and closing brackets. int cnt = 0; int n = s.Length; for (int i = 0; i < n; i++) { // If current bracket is // an opening bracket, // then increment count. if (s[i] =='(') { cnt = cnt + 1; } // If current bracket is a // closing bracket, then // decrement count and check // if count is negative. else { cnt = cnt - 1; if (cnt < 0) return false; } } // If count is positive then // some opening brackets are // not balanced. if (cnt > 0) return false; return true; } // Function to check if string // obtained by concatenating // two bracket sequences is // balanced or not. static bool isBalancedSeq(String s1, String s2) { // Check if s1 + s2 is // balanced or not. if (isBalanced(s1 + s2)) return true; // Check if s2 + s1 is // balanced or not. return isBalanced(s2 + s1); } // Driver code public static void Main() { String s1 = \")()(())))\"; String s2 = \"(()(()(\"; if (isBalancedSeq(s1, s2)) { Console.WriteLine(\"Balanced\"); } else { Console.WriteLine(\"Not Balanced\"); } }} // This code is contributed by// PrinciRaj1992",
"e": 41471,
"s": 39606,
"text": null
},
{
"code": "<?php // PHP program to check if sequence obtained// by concatenating two bracket sequences// is balanced or not.// Check if given string is balanced bracket// sequence or not. function isBalanced($s){ // To store result of comparison of // count of opening brackets and // closing brackets. $cnt = 0; $n = strlen($s); for ($i = 0; $i < $n; $i++) { // If current bracket is an // opening bracket, then // increment count. if ($s[$i] == '(') $cnt++; // If current bracket is a // closing bracket, then // decrement count and check // if count is negative. else { $cnt--; if ($cnt < 0) return false; } } // If count is positive then // some opening brackets are // not balanced. if ($cnt > 0) return false; return true;} // Function to check if string obtained by// concatenating two bracket sequences is// balanced or not.function isBalancedSeq($s1, $s2){ // Check if s1 + s2 is balanced or not. if (isBalanced($s1 + $s2)) return true; // Check if s2 + s1 is balanced or not. return isBalanced($s2 + $s1);} // Driver code. $s1 = \")()(())))\"; $s2 = \"(()(()(\"; if (!isBalancedSeq($s1, $s2)) echo \"Balanced\"; else echo \"Not Balanced\"; // This code is contributed by ajit.?>",
"e": 42868,
"s": 41471,
"text": null
},
{
"code": "<script> // Javascript program to check if sequence obtained// by concatenating two bracket sequences// is balanced or not. // Check if given string is balanced bracket// sequence or not.function isBalanced(s){ // To store result of comparison of // count of opening brackets and // closing brackets. var cnt = 0; var n = s.length; for (var i = 0; i < n; i++) { // If current bracket is an // opening bracket, then // increment count. if (s[i] == '(') cnt++; // If current bracket is a // closing bracket, then // decrement count and check // if count is negative. else { cnt--; if (cnt < 0) return false; } } // If count is positive then // some opening brackets are // not balanced. if (cnt > 0) return false; return true;} // Function to check if string obtained by// concatenating two bracket sequences is// balanced or not.function isBalancedSeq(s1, s2){ // Check if s1 + s2 is balanced or not. if (isBalanced(s1 + s2)) return true; // Check if s2 + s1 is balanced or not. return isBalanced(s2 + s1);} // Driver code.var s1 = \")()(())))\";var s2 = \"(()(()(\";if (isBalancedSeq(s1, s2)) document.write( \"Balanced\");else document.write( \"Not Balanced\"); </script>",
"e": 44229,
"s": 42868,
"text": null
},
{
"code": null,
"e": 44238,
"s": 44229,
"text": "Balanced"
},
{
"code": null,
"e": 44285,
"s": 44240,
"text": "Time complexity: O(n) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 44300,
"s": 44285,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 44314,
"s": 44300,
"text": "princiraj1992"
},
{
"code": null,
"e": 44324,
"s": 44314,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 44330,
"s": 44324,
"text": "jit_t"
},
{
"code": null,
"e": 44342,
"s": 44330,
"text": "29AjayKumar"
},
{
"code": null,
"e": 44354,
"s": 44342,
"text": "sanjeev2552"
},
{
"code": null,
"e": 44363,
"s": 44354,
"text": "noob2000"
},
{
"code": null,
"e": 44372,
"s": 44363,
"text": "mukesh07"
},
{
"code": null,
"e": 44389,
"s": 44372,
"text": "surinderdawra388"
},
{
"code": null,
"e": 44407,
"s": 44389,
"text": "C-String-Question"
},
{
"code": null,
"e": 44431,
"s": 44407,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 44441,
"s": 44431,
"text": "Bit Magic"
},
{
"code": null,
"e": 44465,
"s": 44441,
"text": "Competitive Programming"
},
{
"code": null,
"e": 44481,
"s": 44465,
"text": "Data Structures"
},
{
"code": null,
"e": 44487,
"s": 44481,
"text": "Stack"
},
{
"code": null,
"e": 44503,
"s": 44487,
"text": "Data Structures"
},
{
"code": null,
"e": 44509,
"s": 44503,
"text": "Stack"
},
{
"code": null,
"e": 44519,
"s": 44509,
"text": "Bit Magic"
},
{
"code": null,
"e": 44617,
"s": 44519,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44626,
"s": 44617,
"text": "Comments"
},
{
"code": null,
"e": 44639,
"s": 44626,
"text": "Old Comments"
},
{
"code": null,
"e": 44690,
"s": 44639,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 44713,
"s": 44690,
"text": "Program to find parity"
},
{
"code": null,
"e": 44750,
"s": 44713,
"text": "Check whether K-th bit is set or not"
},
{
"code": null,
"e": 44787,
"s": 44750,
"text": "Hamming code Implementation in C/C++"
},
{
"code": null,
"e": 44851,
"s": 44787,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 44894,
"s": 44851,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 44935,
"s": 44894,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 44978,
"s": 44935,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 45005,
"s": 44978,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
Using Jupyter Notebook in Virtual Environment
|
14 Sep, 2021
In this article, we are going to see how to set Virtual Environment in Jupyter. Sometimes we want to use the Jupyter notebook in a virtual environment so that only selected packages are available in the scope of the notebook. To do this we have to add a new kernel for the virtual environment in the list of kernels available for the Jupyter notebook. Let’s see how to do that:
Step 1: Create a virtual environment
Open the directory where you want to create your project. open cmd/powershell and navigate to the same directory and run the following commands to create a virtual environment.
python -m venv venv
Step 2: Activate the virtual environment
Now as we have our virtual environment let’s activate it.
venv\Scripts\activate
Step 3: Install jupyter kernel for the virtual environment using the following command:
Running the following command will create a kernel that can be used to run jupyter notebook commands inside the virtual environment.
ipython kernel install --user --name=venv
Step 4: Select the installed kernel when you want to use jupyter notebook in this virtual environment
Let’s now check if our kernel is created. Just run “jupyter notebook” command in the command prompt or Powershell and the jupyter environment will open up. Click on the kernel and click change kernel you will be able to see the kernel you just created.
You can see now you have the kernel in the list of kernels and now you can have separate dependencies for the jupyter notebook and be more organized. After you are done with the project and no longer need the kernel you can uninstall it by running the following code:
jupyter-kernelspec uninstall venv
Jupyter-notebook
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 Sep, 2021"
},
{
"code": null,
"e": 406,
"s": 28,
"text": "In this article, we are going to see how to set Virtual Environment in Jupyter. Sometimes we want to use the Jupyter notebook in a virtual environment so that only selected packages are available in the scope of the notebook. To do this we have to add a new kernel for the virtual environment in the list of kernels available for the Jupyter notebook. Let’s see how to do that:"
},
{
"code": null,
"e": 443,
"s": 406,
"text": "Step 1: Create a virtual environment"
},
{
"code": null,
"e": 620,
"s": 443,
"text": "Open the directory where you want to create your project. open cmd/powershell and navigate to the same directory and run the following commands to create a virtual environment."
},
{
"code": null,
"e": 640,
"s": 620,
"text": "python -m venv venv"
},
{
"code": null,
"e": 681,
"s": 640,
"text": "Step 2: Activate the virtual environment"
},
{
"code": null,
"e": 739,
"s": 681,
"text": "Now as we have our virtual environment let’s activate it."
},
{
"code": null,
"e": 761,
"s": 739,
"text": "venv\\Scripts\\activate"
},
{
"code": null,
"e": 849,
"s": 761,
"text": "Step 3: Install jupyter kernel for the virtual environment using the following command:"
},
{
"code": null,
"e": 982,
"s": 849,
"text": "Running the following command will create a kernel that can be used to run jupyter notebook commands inside the virtual environment."
},
{
"code": null,
"e": 1024,
"s": 982,
"text": "ipython kernel install --user --name=venv"
},
{
"code": null,
"e": 1126,
"s": 1024,
"text": "Step 4: Select the installed kernel when you want to use jupyter notebook in this virtual environment"
},
{
"code": null,
"e": 1379,
"s": 1126,
"text": "Let’s now check if our kernel is created. Just run “jupyter notebook” command in the command prompt or Powershell and the jupyter environment will open up. Click on the kernel and click change kernel you will be able to see the kernel you just created."
},
{
"code": null,
"e": 1647,
"s": 1379,
"text": "You can see now you have the kernel in the list of kernels and now you can have separate dependencies for the jupyter notebook and be more organized. After you are done with the project and no longer need the kernel you can uninstall it by running the following code:"
},
{
"code": null,
"e": 1681,
"s": 1647,
"text": "jupyter-kernelspec uninstall venv"
},
{
"code": null,
"e": 1698,
"s": 1681,
"text": "Jupyter-notebook"
},
{
"code": null,
"e": 1705,
"s": 1698,
"text": "Python"
}
] |
GUI Automation using Python
|
15 Jul, 2021
In this article, we will explore how we can do GUI automation using Python. There are many modules that can do these things, but in this article, we will use a module named PyAutoGUI to perform GUI and desktop automation using python.
We would explore two sections –
How to automatically use the mouse pointer to perform certain tasks like moving the cursor, clicking on a certain point on the screen, etc
Also, we would explore how we can automate the keyboard keystrokes.
This module does not come preloaded with Python. To install it type the below command in the terminal.
pip install pyautogui # for windows
or
pip3 install pyautogui #for linux and Macos
We should know the screen size of my device before doing any automation. Luckily PyautoGUI helps us to easily get it using the .size() function. It returns a size object with two values that represent the width and height of the screen respectively. Implementation is as follows.
Syntax: pyautogui.size()
Parameters: This function does not take any extra parameters
Return Type: It returns us the size of the present screen in pixels in a Size object
Below is the implementation:
Python3
# importing modulesimport pyautogui # returns a size object with# width and height of the screenprint(pyautogui.size())
Output:
Size(width=1920, height=1080)
Firstly, we would where currently my mouse cursor is at, for that we can use the .position() function. The function again returns a point object with x and y values that gets the current position of the mouse.
Syntax: pyautogui.position()
Parameters: This function does not take any extra parameters
Return Type: It returns us the position of the mouse cursor in a Point object
Below is the implementation:
Python3
import pyautogui # returns a point object with# x and y valuesprint(pyautogui.position())
Output:
Point(x=1710, y=81)
Now we would try to move the mouse cursor and click at specific spots and perform opening an application and closing it. For moving the mouse pointer we can use .moveto() and specify x,y values along with a duration in which it will perform the operation, and we would use the .click() function to click on the spot where our mouse pointer is located right now. The code basically moves the mouse cursor to (519,1060) (x,y) values and then simulate a click using the .click() where the cursor is situated right now, then we again move to the position (1717,352) using the moveTo() and simulate a click again.
Syntax: pyautogui.moveTo() and pyautogui.click()
Parameters: This moveTo function has two required and one optional parameter, the first two values of x and y are required values while the duration is an extra parameter that kind of animates the movement of the mouse over the no of seconds assigned to the duration parameter. The click method in the example doesn’t take any parameter but an optional pair of parameters can be used to click a particular position on the keyboard.
Return Type: The functions don’t return anything but performs the jobs of the cursor to a specific point and then clicking there programmatically.
Below is the implementation:
Python3
import pyautogui # moves to (519,1060) in 1 secpyautogui.moveTo(519, 1060, duration = 1) # simulates a click at the present# mouse positionpyautogui.click() # moves to (1717,352) in 1 secpyautogui.moveTo(1717, 352, duration = 1) # simulates a click at the present# mouse positionpyautogui.click()
Output:
Now we would explore two more methods namely .moveRel() which helps us to move relative to the position we are at right now and finally we would see how we can simulate a right-click using pyAutoGUI. We start with importing the package and stimulate the cursor to move 498 px & down 998px from its current position. Then we use the click() method to simulate a left-click. Then we move to a specific location using the .moveTo() method. Now we again click on the present position of the cursor but this time we instruct to simulate a right-click instead of left by passing the button=” right” parameter (default is button =” left”). Then we gain to move to a specified location and left click there.
Syntax: pyautogui.moveRel()
Parameters: This moveRel function has also two required and one optional parameter, the first two values of x and y are required values while the duration is an extra parameter that kind of animates the movement of the mouse over the no of seconds assigned to the duration parameter. Also, we used an extra parameter for the pyautogui.click() function, we used button=”right” which simulates a right-click instead of the default left-click.
Return Type: The functions don’t return anything but perform the jobs of moving the cursor left 498 px & down 998px from it’s current position and then simulate a right-click programmatically.
Below is the implementation:
Python3
import pyautogui # moving the cursor left 498 px & down# 998px from it's current positionpyautogui.moveRel(-498,996, duration = 1) # clicks at the present locationpyautogui.click() # moves to the specified locationpyautogui.moveTo(1165,637, duration = 1) # right clicks at the present cursor# locationpyautogui.click(button="right") # moves to the specified locationpyautogui.moveTo(1207,621, duration = 1) # clicks at the present locationpyautogui.click()
Output:
Now we would see how can we drag windows using pyAutoGUI. We can use the .dragto() and .dragrel() which are exactly the way the .moveto() and .movrel() works except that in this case, they hold the left click while moving the cursor. In this program we simply, import the modules, then we move to a specified using the .moveTo() function. Then we left-click at the current position of the cursor. Now we again move the cursor to a specified location. Then we use the .dragTo() function to drag (left-click and hold) the to a specific location. Finally, we use the dragRel() function that drags the cursor relative to its current position to 50px right and 50 px down.
Syntax: pyautogui.dragTo() and pyautogui.dragRel()
Parameters: Both the functions has two required and one optional parameter, the first two values of x and y are required values while the duration is an extra parameter that kind of animates the movement of the mouse over the no of seconds assigned to the duration parameter.
Return Type: The functions don’t return anything but perform the jobs of left-click and holding and moves the cursor to (500,500) position and drags the cursor relative to it’s position to 5opx right and 50 px down programmatically.
Below is the implementation:
Python3
import pyautogui # cursor moves to a specific positionpyautogui.moveTo(519,1060, duration = 1) # left clicks at the current positionpyautogui.click() # cursor moves to a specific positionpyautogui.moveTo(1550,352, duration = 1) # left clicks and holds and moves the# curson to (500,500) positionpyautogui.dragTo(500,500, duration = 1) # drags the cursor relative to it's# position to 5opx right and 50 px downpyautogui.dragRel(50,50, duration=1)
Output:
Note: Duration parameter in .moveTo(), .moveRel(), .dragTo() and .dragRel() functions are optional, but it is provided to get a animation effect, without the property functions will execute instantly, and it would be tough to understand. Also we optionally pass x and y values in .click() function which can be used to click at a different location that the location the cursor is currently at.
First, we would learn how to simulate typing something using pyAutoGUI. Here in this example, we would type something in a notepad file using the .typewrite() function. In this code, we first import the time and pyAutoGUI module and then use time.sleep() function to pause the execution of the program for some specified seconds. Then we use the pyautogui.typewrite() function to simulate typing of alphanumeric keys. The phrase inside the quotes would be typed. Implementation is as follows:
Syntax: pyautogui.typewrite()
Parameters: The function has only one parameter which is the string that needs to be typed.
Return Type: The functions don’t return anything but perform the jobs of simulating the typing of a string that is passed inside it.
Below is the implementation:
Python3
# used to access time related functionsimport timeimport pyautogui # pauses the execution of the program# for 5 sectime.sleep(5) # types the string passed inside the# functionpyautogui.typewrite("Geeks For Geeks!")
Output:
Next, we would explore two functions, the first one is .press() and the second one is .hotkey(), first one helps you to press a key generally used to press non-alphanumeric keys and the .hotkeys() functions helps us to press hotkeys like ctrl+shift+esc, etc. Here also we start the code by importing two modules, time and pyAutoGUI. Then we pause the execution of the program for 5 seconds using the sleep function. we type the string using the typewrite function. Then we use the .press() function to simulate a keypress and finally the .hotkey() function to simulate the pressing of hotkeys. In our example, we used hotkey ctrl+a that selects all the text. The implementation is as follows:
Syntax: pyautogui.press() and pyautogui.hotkey()
Parameters: The .press() function has only one parameter which is the key that needs to be pressed and the .hotkey() function has a number of parameters depending upon the number of keys to simulate the hotkey action.
Return Type: The functions don’t return anything but perform the job of simulating of pressing the enter key and simulates pressing the hotkey ctrl+a.
Below is the implementation:
Python3
# used to access time related functionsimport timeimport pyautogui # pauses the execution of the program# for 5 sectime.sleep(5) # types the string passed inside the# functionpyautogui.typewrite("Geeks For Geeks!") # simulates pressing the enter keypyautogui.press("enter") # simulates pressing the hotkey ctrl+apyautogui.hotkey("ctrl","a")
Output:
Now we would try to explore some cross-platform JavaScript style message boxes provided to us by pyAutoGUI. It uses Tkinter and PyMsgBox module to display these boxes. The code starts with importing modules, then we use different message boxes to display different messages. The .alert() function displays an alert in which we set the title and text to be blank with an “OK” button. Then the .confirm() function displays a confirm dialog box in which we again set the title and text to be blank and keep two buttons “OK” & “CANCEL” button. Then the .prompt() function displays a confirmation prompt box in which we again set the title, text, and default (what would be written by default in the prompt box before the user starts typing) to be blank. Finally, the .password() function displays a password dialog box in which we again set the title and text to be blank and set the mask (The character that gets replaced instead of the original letters in the password) to be “*”. The implementation is as follows:
Syntax: pyautogui.alert(), pyautogui.confirm(), pyautogui.prompt() and pyautogui.password()
Parameters: The .alert() function has three parameters defining the title, text and buttons to be placed. The .confirm() function also has three parameters for text, title and buttons. The .prompt() function has three parameters for text, title and default value. The .password() has four parameters for text, title, default value and mask (The character that gets replaced instead of the original letters in the password).
Return Type: The functions don’t return anything but show up an alert in which we set the title and text to be blank with an “OK” button. Then it displays a confirm dialogue box in which we again set the title and text to be blank and keep two buttons “OK” & “CANCEL” button. Then the .prompt() function displays a confirmation prompt box in which we again set the title, text and default (what would be written by default in the prompt box before the user starts typing) to be blank. Finally, the .password() function displays a password dialogue box in which we again set the title and text to be blank and set the mask to be “*”.
Below is the implementation:
Python3
import pyautogui # a alert displays with a ok button# on itpyautogui.alert(text='', title='', button='OK') # a confirm dialog box appears with ok# and cancel buttons on itpyautogui.confirm(text='', title='', buttons=['OK', 'Cancel']) # a prompt displays that lets you to# write somethingpyautogui.prompt(text='', title='' , default='') # a password field appears with entry box# to fill a passwordpyautogui.password(text='', title='', default='', mask='*')
Output:
Finally, we would see how to take a screenshot using pyAutoGUI using the .screenshot() function. We would start by importing the pyAutoGUI module. Then we use the .screenshot() function that takes a screenshot of the present window and stores it as “123.png” in the same directory, for storing in another directory, we need to provide its relative or absolute path. The implementation would be as follows:
Syntax: pyautogui.screenshot()
Parameters: The function has one optional parameter which is the path of the file along with the filename in which the screenshot needs to be stored.
Return Type: The function doesn’t return anything but takes a screenshot and stores it in the path passed inside it as a parameter.
Below is the implementation:
Python3
import pyautogui # takes a screenshot of the present# window and stores it as "123.png"pyautogui.screenshot("123.png")
Output:
arorakashish0911
Picked
python-modules
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Jul, 2021"
},
{
"code": null,
"e": 264,
"s": 28,
"text": "In this article, we will explore how we can do GUI automation using Python. There are many modules that can do these things, but in this article, we will use a module named PyAutoGUI to perform GUI and desktop automation using python. "
},
{
"code": null,
"e": 296,
"s": 264,
"text": "We would explore two sections –"
},
{
"code": null,
"e": 435,
"s": 296,
"text": "How to automatically use the mouse pointer to perform certain tasks like moving the cursor, clicking on a certain point on the screen, etc"
},
{
"code": null,
"e": 503,
"s": 435,
"text": "Also, we would explore how we can automate the keyboard keystrokes."
},
{
"code": null,
"e": 606,
"s": 503,
"text": "This module does not come preloaded with Python. To install it type the below command in the terminal."
},
{
"code": null,
"e": 690,
"s": 606,
"text": "pip install pyautogui # for windows\nor \npip3 install pyautogui #for linux and Macos"
},
{
"code": null,
"e": 970,
"s": 690,
"text": "We should know the screen size of my device before doing any automation. Luckily PyautoGUI helps us to easily get it using the .size() function. It returns a size object with two values that represent the width and height of the screen respectively. Implementation is as follows."
},
{
"code": null,
"e": 995,
"s": 970,
"text": "Syntax: pyautogui.size()"
},
{
"code": null,
"e": 1056,
"s": 995,
"text": "Parameters: This function does not take any extra parameters"
},
{
"code": null,
"e": 1142,
"s": 1056,
"text": "Return Type: It returns us the size of the present screen in pixels in a Size object "
},
{
"code": null,
"e": 1171,
"s": 1142,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 1179,
"s": 1171,
"text": "Python3"
},
{
"code": "# importing modulesimport pyautogui # returns a size object with# width and height of the screenprint(pyautogui.size())",
"e": 1299,
"s": 1179,
"text": null
},
{
"code": null,
"e": 1307,
"s": 1299,
"text": "Output:"
},
{
"code": null,
"e": 1337,
"s": 1307,
"text": "Size(width=1920, height=1080)"
},
{
"code": null,
"e": 1547,
"s": 1337,
"text": "Firstly, we would where currently my mouse cursor is at, for that we can use the .position() function. The function again returns a point object with x and y values that gets the current position of the mouse."
},
{
"code": null,
"e": 1576,
"s": 1547,
"text": "Syntax: pyautogui.position()"
},
{
"code": null,
"e": 1637,
"s": 1576,
"text": "Parameters: This function does not take any extra parameters"
},
{
"code": null,
"e": 1715,
"s": 1637,
"text": "Return Type: It returns us the position of the mouse cursor in a Point object"
},
{
"code": null,
"e": 1744,
"s": 1715,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 1752,
"s": 1744,
"text": "Python3"
},
{
"code": "import pyautogui # returns a point object with# x and y valuesprint(pyautogui.position())",
"e": 1843,
"s": 1752,
"text": null
},
{
"code": null,
"e": 1851,
"s": 1843,
"text": "Output:"
},
{
"code": null,
"e": 1871,
"s": 1851,
"text": "Point(x=1710, y=81)"
},
{
"code": null,
"e": 2483,
"s": 1871,
"text": "Now we would try to move the mouse cursor and click at specific spots and perform opening an application and closing it. For moving the mouse pointer we can use .moveto() and specify x,y values along with a duration in which it will perform the operation, and we would use the .click() function to click on the spot where our mouse pointer is located right now. The code basically moves the mouse cursor to (519,1060) (x,y) values and then simulate a click using the .click() where the cursor is situated right now, then we again move to the position (1717,352) using the moveTo() and simulate a click again. "
},
{
"code": null,
"e": 2532,
"s": 2483,
"text": "Syntax: pyautogui.moveTo() and pyautogui.click()"
},
{
"code": null,
"e": 2964,
"s": 2532,
"text": "Parameters: This moveTo function has two required and one optional parameter, the first two values of x and y are required values while the duration is an extra parameter that kind of animates the movement of the mouse over the no of seconds assigned to the duration parameter. The click method in the example doesn’t take any parameter but an optional pair of parameters can be used to click a particular position on the keyboard."
},
{
"code": null,
"e": 3113,
"s": 2964,
"text": "Return Type: The functions don’t return anything but performs the jobs of the cursor to a specific point and then clicking there programmatically. "
},
{
"code": null,
"e": 3142,
"s": 3113,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 3150,
"s": 3142,
"text": "Python3"
},
{
"code": "import pyautogui # moves to (519,1060) in 1 secpyautogui.moveTo(519, 1060, duration = 1) # simulates a click at the present# mouse positionpyautogui.click() # moves to (1717,352) in 1 secpyautogui.moveTo(1717, 352, duration = 1) # simulates a click at the present# mouse positionpyautogui.click()",
"e": 3448,
"s": 3150,
"text": null
},
{
"code": null,
"e": 3456,
"s": 3448,
"text": "Output:"
},
{
"code": null,
"e": 4157,
"s": 3456,
"text": "Now we would explore two more methods namely .moveRel() which helps us to move relative to the position we are at right now and finally we would see how we can simulate a right-click using pyAutoGUI. We start with importing the package and stimulate the cursor to move 498 px & down 998px from its current position. Then we use the click() method to simulate a left-click. Then we move to a specific location using the .moveTo() method. Now we again click on the present position of the cursor but this time we instruct to simulate a right-click instead of left by passing the button=” right” parameter (default is button =” left”). Then we gain to move to a specified location and left click there."
},
{
"code": null,
"e": 4185,
"s": 4157,
"text": "Syntax: pyautogui.moveRel()"
},
{
"code": null,
"e": 4626,
"s": 4185,
"text": "Parameters: This moveRel function has also two required and one optional parameter, the first two values of x and y are required values while the duration is an extra parameter that kind of animates the movement of the mouse over the no of seconds assigned to the duration parameter. Also, we used an extra parameter for the pyautogui.click() function, we used button=”right” which simulates a right-click instead of the default left-click."
},
{
"code": null,
"e": 4821,
"s": 4626,
"text": " Return Type: The functions don’t return anything but perform the jobs of moving the cursor left 498 px & down 998px from it’s current position and then simulate a right-click programmatically. "
},
{
"code": null,
"e": 4850,
"s": 4821,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 4858,
"s": 4850,
"text": "Python3"
},
{
"code": "import pyautogui # moving the cursor left 498 px & down# 998px from it's current positionpyautogui.moveRel(-498,996, duration = 1) # clicks at the present locationpyautogui.click() # moves to the specified locationpyautogui.moveTo(1165,637, duration = 1) # right clicks at the present cursor# locationpyautogui.click(button=\"right\") # moves to the specified locationpyautogui.moveTo(1207,621, duration = 1) # clicks at the present locationpyautogui.click()",
"e": 5315,
"s": 4858,
"text": null
},
{
"code": null,
"e": 5323,
"s": 5315,
"text": "Output:"
},
{
"code": null,
"e": 5991,
"s": 5323,
"text": "Now we would see how can we drag windows using pyAutoGUI. We can use the .dragto() and .dragrel() which are exactly the way the .moveto() and .movrel() works except that in this case, they hold the left click while moving the cursor. In this program we simply, import the modules, then we move to a specified using the .moveTo() function. Then we left-click at the current position of the cursor. Now we again move the cursor to a specified location. Then we use the .dragTo() function to drag (left-click and hold) the to a specific location. Finally, we use the dragRel() function that drags the cursor relative to its current position to 50px right and 50 px down."
},
{
"code": null,
"e": 6042,
"s": 5991,
"text": "Syntax: pyautogui.dragTo() and pyautogui.dragRel()"
},
{
"code": null,
"e": 6318,
"s": 6042,
"text": "Parameters: Both the functions has two required and one optional parameter, the first two values of x and y are required values while the duration is an extra parameter that kind of animates the movement of the mouse over the no of seconds assigned to the duration parameter."
},
{
"code": null,
"e": 6552,
"s": 6318,
"text": "Return Type: The functions don’t return anything but perform the jobs of left-click and holding and moves the cursor to (500,500) position and drags the cursor relative to it’s position to 5opx right and 50 px down programmatically. "
},
{
"code": null,
"e": 6581,
"s": 6552,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 6589,
"s": 6581,
"text": "Python3"
},
{
"code": "import pyautogui # cursor moves to a specific positionpyautogui.moveTo(519,1060, duration = 1) # left clicks at the current positionpyautogui.click() # cursor moves to a specific positionpyautogui.moveTo(1550,352, duration = 1) # left clicks and holds and moves the# curson to (500,500) positionpyautogui.dragTo(500,500, duration = 1) # drags the cursor relative to it's# position to 5opx right and 50 px downpyautogui.dragRel(50,50, duration=1)",
"e": 7035,
"s": 6589,
"text": null
},
{
"code": null,
"e": 7043,
"s": 7035,
"text": "Output:"
},
{
"code": null,
"e": 7438,
"s": 7043,
"text": "Note: Duration parameter in .moveTo(), .moveRel(), .dragTo() and .dragRel() functions are optional, but it is provided to get a animation effect, without the property functions will execute instantly, and it would be tough to understand. Also we optionally pass x and y values in .click() function which can be used to click at a different location that the location the cursor is currently at."
},
{
"code": null,
"e": 7931,
"s": 7438,
"text": "First, we would learn how to simulate typing something using pyAutoGUI. Here in this example, we would type something in a notepad file using the .typewrite() function. In this code, we first import the time and pyAutoGUI module and then use time.sleep() function to pause the execution of the program for some specified seconds. Then we use the pyautogui.typewrite() function to simulate typing of alphanumeric keys. The phrase inside the quotes would be typed. Implementation is as follows:"
},
{
"code": null,
"e": 7961,
"s": 7931,
"text": "Syntax: pyautogui.typewrite()"
},
{
"code": null,
"e": 8053,
"s": 7961,
"text": "Parameters: The function has only one parameter which is the string that needs to be typed."
},
{
"code": null,
"e": 8187,
"s": 8053,
"text": "Return Type: The functions don’t return anything but perform the jobs of simulating the typing of a string that is passed inside it. "
},
{
"code": null,
"e": 8216,
"s": 8187,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 8224,
"s": 8216,
"text": "Python3"
},
{
"code": "# used to access time related functionsimport timeimport pyautogui # pauses the execution of the program# for 5 sectime.sleep(5) # types the string passed inside the# functionpyautogui.typewrite(\"Geeks For Geeks!\")",
"e": 8439,
"s": 8224,
"text": null
},
{
"code": null,
"e": 8447,
"s": 8439,
"text": "Output:"
},
{
"code": null,
"e": 9141,
"s": 8447,
"text": "Next, we would explore two functions, the first one is .press() and the second one is .hotkey(), first one helps you to press a key generally used to press non-alphanumeric keys and the .hotkeys() functions helps us to press hotkeys like ctrl+shift+esc, etc. Here also we start the code by importing two modules, time and pyAutoGUI. Then we pause the execution of the program for 5 seconds using the sleep function. we type the string using the typewrite function. Then we use the .press() function to simulate a keypress and finally the .hotkey() function to simulate the pressing of hotkeys. In our example, we used hotkey ctrl+a that selects all the text. The implementation is as follows:"
},
{
"code": null,
"e": 9190,
"s": 9141,
"text": "Syntax: pyautogui.press() and pyautogui.hotkey()"
},
{
"code": null,
"e": 9408,
"s": 9190,
"text": "Parameters: The .press() function has only one parameter which is the key that needs to be pressed and the .hotkey() function has a number of parameters depending upon the number of keys to simulate the hotkey action."
},
{
"code": null,
"e": 9560,
"s": 9408,
"text": "Return Type: The functions don’t return anything but perform the job of simulating of pressing the enter key and simulates pressing the hotkey ctrl+a. "
},
{
"code": null,
"e": 9589,
"s": 9560,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 9597,
"s": 9589,
"text": "Python3"
},
{
"code": "# used to access time related functionsimport timeimport pyautogui # pauses the execution of the program# for 5 sectime.sleep(5) # types the string passed inside the# functionpyautogui.typewrite(\"Geeks For Geeks!\") # simulates pressing the enter keypyautogui.press(\"enter\") # simulates pressing the hotkey ctrl+apyautogui.hotkey(\"ctrl\",\"a\")",
"e": 9938,
"s": 9597,
"text": null
},
{
"code": null,
"e": 9946,
"s": 9938,
"text": "Output:"
},
{
"code": null,
"e": 10959,
"s": 9946,
"text": "Now we would try to explore some cross-platform JavaScript style message boxes provided to us by pyAutoGUI. It uses Tkinter and PyMsgBox module to display these boxes. The code starts with importing modules, then we use different message boxes to display different messages. The .alert() function displays an alert in which we set the title and text to be blank with an “OK” button. Then the .confirm() function displays a confirm dialog box in which we again set the title and text to be blank and keep two buttons “OK” & “CANCEL” button. Then the .prompt() function displays a confirmation prompt box in which we again set the title, text, and default (what would be written by default in the prompt box before the user starts typing) to be blank. Finally, the .password() function displays a password dialog box in which we again set the title and text to be blank and set the mask (The character that gets replaced instead of the original letters in the password) to be “*”. The implementation is as follows:"
},
{
"code": null,
"e": 11051,
"s": 10959,
"text": "Syntax: pyautogui.alert(), pyautogui.confirm(), pyautogui.prompt() and pyautogui.password()"
},
{
"code": null,
"e": 11477,
"s": 11051,
"text": "Parameters: The .alert() function has three parameters defining the title, text and buttons to be placed. The .confirm() function also has three parameters for text, title and buttons. The .prompt() function has three parameters for text, title and default value. The .password() has four parameters for text, title, default value and mask (The character that gets replaced instead of the original letters in the password). "
},
{
"code": null,
"e": 12111,
"s": 11477,
"text": "Return Type: The functions don’t return anything but show up an alert in which we set the title and text to be blank with an “OK” button. Then it displays a confirm dialogue box in which we again set the title and text to be blank and keep two buttons “OK” & “CANCEL” button. Then the .prompt() function displays a confirmation prompt box in which we again set the title, text and default (what would be written by default in the prompt box before the user starts typing) to be blank. Finally, the .password() function displays a password dialogue box in which we again set the title and text to be blank and set the mask to be “*”. "
},
{
"code": null,
"e": 12140,
"s": 12111,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 12148,
"s": 12140,
"text": "Python3"
},
{
"code": "import pyautogui # a alert displays with a ok button# on itpyautogui.alert(text='', title='', button='OK') # a confirm dialog box appears with ok# and cancel buttons on itpyautogui.confirm(text='', title='', buttons=['OK', 'Cancel']) # a prompt displays that lets you to# write somethingpyautogui.prompt(text='', title='' , default='') # a password field appears with entry box# to fill a passwordpyautogui.password(text='', title='', default='', mask='*')",
"e": 12607,
"s": 12148,
"text": null
},
{
"code": null,
"e": 12615,
"s": 12607,
"text": "Output:"
},
{
"code": null,
"e": 13021,
"s": 12615,
"text": "Finally, we would see how to take a screenshot using pyAutoGUI using the .screenshot() function. We would start by importing the pyAutoGUI module. Then we use the .screenshot() function that takes a screenshot of the present window and stores it as “123.png” in the same directory, for storing in another directory, we need to provide its relative or absolute path. The implementation would be as follows:"
},
{
"code": null,
"e": 13052,
"s": 13021,
"text": "Syntax: pyautogui.screenshot()"
},
{
"code": null,
"e": 13202,
"s": 13052,
"text": "Parameters: The function has one optional parameter which is the path of the file along with the filename in which the screenshot needs to be stored."
},
{
"code": null,
"e": 13334,
"s": 13202,
"text": "Return Type: The function doesn’t return anything but takes a screenshot and stores it in the path passed inside it as a parameter."
},
{
"code": null,
"e": 13363,
"s": 13334,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 13371,
"s": 13363,
"text": "Python3"
},
{
"code": "import pyautogui # takes a screenshot of the present# window and stores it as \"123.png\"pyautogui.screenshot(\"123.png\")",
"e": 13490,
"s": 13371,
"text": null
},
{
"code": null,
"e": 13498,
"s": 13490,
"text": "Output:"
},
{
"code": null,
"e": 13515,
"s": 13498,
"text": "arorakashish0911"
},
{
"code": null,
"e": 13522,
"s": 13515,
"text": "Picked"
},
{
"code": null,
"e": 13537,
"s": 13522,
"text": "python-modules"
},
{
"code": null,
"e": 13552,
"s": 13537,
"text": "python-utility"
},
{
"code": null,
"e": 13559,
"s": 13552,
"text": "Python"
}
] |
Python program to find birthdate on the same day you were born
|
11 Dec, 2019
Write a program to find birthdates till a given year on the same day you were born. Let the input be of the format: YYYY-MM-DD
Examples:
Input: 1996-11-12Output: [‘1996-11-12’, ‘2002-11-12’, ‘2013-11-12’, ‘2019-11-12’, ‘2024-11-12’, ‘2030-11-12’, ‘2041-11-12’, ‘2047-11-12’]
Input: 1992-11-2Output: [‘1992-11-2’, ‘1998-11-2’, ‘2009-11-2’, ‘2015-11-2’, ‘2020-11-2’, ‘2026-11-2’, ‘2037-11-2’, ‘2043-11-2’, ‘2048-11-2’]
Functions created:
split_date(birthdate): This function splits the date given by user into year, month and day.
get_birthday(birthdate): This function is used to return the day of the week the user was born.
true_birthdays(birthdate): This function is used to return a list of dates having the same week day the user was born.
To find the birthdates having the same day the user was born above three methods will help us. Firstly, The user will enter the date and split_date() function will split the date into year, month and day. Then the function get_birthday() will be used to find weekday for that particular date. Finally, the true_birthdays() function will be used to find the list of all the dates having the same weekday. Inside this function, a for loop will be iterating from birth year to a specific year and will check if the birthdate in any particular year having the same weekday or not. If the weekday is same then that date will be added to the list of dates.
Below is the implementation.
import datetimeimport calendar weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] # get_birth daydef split_date(birthday): # Split it to year, month and day year, month, day = birthday.split('-') return year, month, day def get_birthday(birthday): year, month, day = split_date(birthday) # Get a date object for the day of birth bdate = datetime.datetime(int(year), int(month), int(day)) # Get the integer weekday for the day of birth weekday = bdate.weekday() # Tell the user day = weekdays[weekday] return day def listToString(x): # initialize an empty string String = " " # return string return (String.join(x)) def true_birthdays(birthdate): year, month, day = split_date(birthdate) # get the year from birthday year = birthdate[:4].split('-') # convert list to string year = listToString(year) # get the weekday you are born d_day = get_birthday(birthdate) # list of true birthdate[birthday that have same # weekday as the day you were born] true_BD = [] j = 0 for i in range(int(year), 2050): # add + j to birth year new_year = int(year)+j # construct new birthday new_birthday = str(str(new_year)+"-"+month+"-"+day) # get weekday of the new birthday new_d_day = get_birthday(new_birthday) # if birthday that have same weekday # as the day you were born if d_day == new_d_day: # add to the list of true birthdate true_BD.append(new_birthday) else: pass j += 1 return true_BD def main(): # Get the birth date birthdate = "1996-11-12" # year_limit = input("search limit from your birthday- ") dates = true_birthdays(birthdate) print(dates) # Driver's codemain()
Output:
[‘1996-11-12’, ‘2002-11-12’, ‘2013-11-12’, ‘2019-11-12’, ‘2024-11-12’, ‘2030-11-12’, ‘2041-11-12’, ‘2047-11-12’]
Python-Miscellaneous
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
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": "\n11 Dec, 2019"
},
{
"code": null,
"e": 155,
"s": 28,
"text": "Write a program to find birthdates till a given year on the same day you were born. Let the input be of the format: YYYY-MM-DD"
},
{
"code": null,
"e": 165,
"s": 155,
"text": "Examples:"
},
{
"code": null,
"e": 303,
"s": 165,
"text": "Input: 1996-11-12Output: [‘1996-11-12’, ‘2002-11-12’, ‘2013-11-12’, ‘2019-11-12’, ‘2024-11-12’, ‘2030-11-12’, ‘2041-11-12’, ‘2047-11-12’]"
},
{
"code": null,
"e": 445,
"s": 303,
"text": "Input: 1992-11-2Output: [‘1992-11-2’, ‘1998-11-2’, ‘2009-11-2’, ‘2015-11-2’, ‘2020-11-2’, ‘2026-11-2’, ‘2037-11-2’, ‘2043-11-2’, ‘2048-11-2’]"
},
{
"code": null,
"e": 464,
"s": 445,
"text": "Functions created:"
},
{
"code": null,
"e": 557,
"s": 464,
"text": "split_date(birthdate): This function splits the date given by user into year, month and day."
},
{
"code": null,
"e": 653,
"s": 557,
"text": "get_birthday(birthdate): This function is used to return the day of the week the user was born."
},
{
"code": null,
"e": 772,
"s": 653,
"text": "true_birthdays(birthdate): This function is used to return a list of dates having the same week day the user was born."
},
{
"code": null,
"e": 1423,
"s": 772,
"text": "To find the birthdates having the same day the user was born above three methods will help us. Firstly, The user will enter the date and split_date() function will split the date into year, month and day. Then the function get_birthday() will be used to find weekday for that particular date. Finally, the true_birthdays() function will be used to find the list of all the dates having the same weekday. Inside this function, a for loop will be iterating from birth year to a specific year and will check if the birthdate in any particular year having the same weekday or not. If the weekday is same then that date will be added to the list of dates."
},
{
"code": null,
"e": 1452,
"s": 1423,
"text": "Below is the implementation."
},
{
"code": "import datetimeimport calendar weekdays = [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"] # get_birth daydef split_date(birthday): # Split it to year, month and day year, month, day = birthday.split('-') return year, month, day def get_birthday(birthday): year, month, day = split_date(birthday) # Get a date object for the day of birth bdate = datetime.datetime(int(year), int(month), int(day)) # Get the integer weekday for the day of birth weekday = bdate.weekday() # Tell the user day = weekdays[weekday] return day def listToString(x): # initialize an empty string String = \" \" # return string return (String.join(x)) def true_birthdays(birthdate): year, month, day = split_date(birthdate) # get the year from birthday year = birthdate[:4].split('-') # convert list to string year = listToString(year) # get the weekday you are born d_day = get_birthday(birthdate) # list of true birthdate[birthday that have same # weekday as the day you were born] true_BD = [] j = 0 for i in range(int(year), 2050): # add + j to birth year new_year = int(year)+j # construct new birthday new_birthday = str(str(new_year)+\"-\"+month+\"-\"+day) # get weekday of the new birthday new_d_day = get_birthday(new_birthday) # if birthday that have same weekday # as the day you were born if d_day == new_d_day: # add to the list of true birthdate true_BD.append(new_birthday) else: pass j += 1 return true_BD def main(): # Get the birth date birthdate = \"1996-11-12\" # year_limit = input(\"search limit from your birthday- \") dates = true_birthdays(birthdate) print(dates) # Driver's codemain()",
"e": 3386,
"s": 1452,
"text": null
},
{
"code": null,
"e": 3394,
"s": 3386,
"text": "Output:"
},
{
"code": null,
"e": 3507,
"s": 3394,
"text": "[‘1996-11-12’, ‘2002-11-12’, ‘2013-11-12’, ‘2019-11-12’, ‘2024-11-12’, ‘2030-11-12’, ‘2041-11-12’, ‘2047-11-12’]"
},
{
"code": null,
"e": 3528,
"s": 3507,
"text": "Python-Miscellaneous"
},
{
"code": null,
"e": 3535,
"s": 3528,
"text": "Python"
},
{
"code": null,
"e": 3551,
"s": 3535,
"text": "Python Programs"
},
{
"code": null,
"e": 3649,
"s": 3551,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3667,
"s": 3649,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3709,
"s": 3667,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3731,
"s": 3709,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3757,
"s": 3731,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3789,
"s": 3757,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3832,
"s": 3789,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 3854,
"s": 3832,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3893,
"s": 3854,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3931,
"s": 3893,
"text": "Python | Convert a list to dictionary"
}
] |
Java Program For Decimal to Hexadecimal Conversion
|
25 Apr, 2022
Given a decimal number N, convert N into an equivalent hexadecimal number i.e convert the number with base value 10 to base value 16. The decimal number system uses 10 digits 0-9 and the Hexadecimal number system uses 0-9, A-F to represent any numeric value.
Examples:
Input : 10Output: A
Input : 2545Output: 9F1
Approach:
Store the remainder when the number is divided by 16 in an array.Divide the number by 16 nowRepeat the above two steps until the number is not equal to 0.Print the array in reverse order now.
Store the remainder when the number is divided by 16 in an array.
Divide the number by 16 now
Repeat the above two steps until the number is not equal to 0.
Print the array in reverse order now.
Below is the implementation of the above approach:
Java
// Java program to convert Decimal Number// to Hexadecimal Number // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Method 1 // To convert decimal to hexadecimal static void decTohex(int n) { // Creating an array to store octal number int[] hexNum = new int[100]; // counter for hexadecimal number array int i = 0; while (n != 0) { // Storing remainder in hexadecimal array hexNum[i] = n % 16; n = n / 16; i++; } // Printing hexadecimal number array // in the reverse order for (int j = i - 1; j >= 0; j--) { if (hexNum[j] > 9) System.out.print((char)(55 + hexNum[j])); else System.out.print(hexNum[j]); } } // Method 2 // Main driver method public static void main(String[] args) { // Custom input decimal number // to be converted into hexadecimal number int n = 2545; // Calling the above Method1 over number 'n' // to convert this decimal into hexadecimal number decTohex(n); }}
9F1
Time Complexity: O(log N)Auxiliary Space: O(1)
Another method (using a built-in function): The java.lang.Integer.toString(int a, int base) is an inbuilt method in Java that is used to return a string representation of the argument in the base, specified by the second argument base. If the radix/base is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX, then the base 10 is used. The ASCII characters are used as digits: 0 to 9 and a to z.Syntax:
public static String toString(int a, int base)
Parameter: The method accepts two parameters:
a: This is of integer type and refers to the integer value that is to be converted.
base: This is also of integer type and refers to the base that is to be used while representing the strings.
Return Value: The method returns a string representation of the specified argument in the specified base.
Examples:
Input: a = 71, base = 2Output: 1000111
Input: a = 314, base = 16Output: 13a
The below programs illustrate the Java.lang.Integer.toString(int a, int base) Method:
Java
// To convert Decimal to Hexadecimal Number//import java.util.*; // Main driver methodpublic class Main { public static void main(String[] args) { // Number in decimal int number = 2545; // output System.out.println(Integer.toString(number, 16)); }} // This code is written by ZEESHAN AHMAD//
9f1
Time complexity: O(N)Auxiliary Space: O(1)
zeeshan118668
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Apr, 2022"
},
{
"code": null,
"e": 287,
"s": 28,
"text": "Given a decimal number N, convert N into an equivalent hexadecimal number i.e convert the number with base value 10 to base value 16. The decimal number system uses 10 digits 0-9 and the Hexadecimal number system uses 0-9, A-F to represent any numeric value."
},
{
"code": null,
"e": 298,
"s": 287,
"text": "Examples: "
},
{
"code": null,
"e": 318,
"s": 298,
"text": "Input : 10Output: A"
},
{
"code": null,
"e": 342,
"s": 318,
"text": "Input : 2545Output: 9F1"
},
{
"code": null,
"e": 352,
"s": 342,
"text": "Approach:"
},
{
"code": null,
"e": 544,
"s": 352,
"text": "Store the remainder when the number is divided by 16 in an array.Divide the number by 16 nowRepeat the above two steps until the number is not equal to 0.Print the array in reverse order now."
},
{
"code": null,
"e": 610,
"s": 544,
"text": "Store the remainder when the number is divided by 16 in an array."
},
{
"code": null,
"e": 638,
"s": 610,
"text": "Divide the number by 16 now"
},
{
"code": null,
"e": 701,
"s": 638,
"text": "Repeat the above two steps until the number is not equal to 0."
},
{
"code": null,
"e": 739,
"s": 701,
"text": "Print the array in reverse order now."
},
{
"code": null,
"e": 790,
"s": 739,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 795,
"s": 790,
"text": "Java"
},
{
"code": "// Java program to convert Decimal Number// to Hexadecimal Number // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Method 1 // To convert decimal to hexadecimal static void decTohex(int n) { // Creating an array to store octal number int[] hexNum = new int[100]; // counter for hexadecimal number array int i = 0; while (n != 0) { // Storing remainder in hexadecimal array hexNum[i] = n % 16; n = n / 16; i++; } // Printing hexadecimal number array // in the reverse order for (int j = i - 1; j >= 0; j--) { if (hexNum[j] > 9) System.out.print((char)(55 + hexNum[j])); else System.out.print(hexNum[j]); } } // Method 2 // Main driver method public static void main(String[] args) { // Custom input decimal number // to be converted into hexadecimal number int n = 2545; // Calling the above Method1 over number 'n' // to convert this decimal into hexadecimal number decTohex(n); }}",
"e": 1958,
"s": 795,
"text": null
},
{
"code": null,
"e": 1962,
"s": 1958,
"text": "9F1"
},
{
"code": null,
"e": 2009,
"s": 1962,
"text": "Time Complexity: O(log N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2428,
"s": 2009,
"text": "Another method (using a built-in function): The java.lang.Integer.toString(int a, int base) is an inbuilt method in Java that is used to return a string representation of the argument in the base, specified by the second argument base. If the radix/base is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX, then the base 10 is used. The ASCII characters are used as digits: 0 to 9 and a to z.Syntax:"
},
{
"code": null,
"e": 2475,
"s": 2428,
"text": "public static String toString(int a, int base)"
},
{
"code": null,
"e": 2521,
"s": 2475,
"text": "Parameter: The method accepts two parameters:"
},
{
"code": null,
"e": 2605,
"s": 2521,
"text": "a: This is of integer type and refers to the integer value that is to be converted."
},
{
"code": null,
"e": 2714,
"s": 2605,
"text": "base: This is also of integer type and refers to the base that is to be used while representing the strings."
},
{
"code": null,
"e": 2820,
"s": 2714,
"text": "Return Value: The method returns a string representation of the specified argument in the specified base."
},
{
"code": null,
"e": 2830,
"s": 2820,
"text": "Examples:"
},
{
"code": null,
"e": 2869,
"s": 2830,
"text": "Input: a = 71, base = 2Output: 1000111"
},
{
"code": null,
"e": 2906,
"s": 2869,
"text": "Input: a = 314, base = 16Output: 13a"
},
{
"code": null,
"e": 2992,
"s": 2906,
"text": "The below programs illustrate the Java.lang.Integer.toString(int a, int base) Method:"
},
{
"code": null,
"e": 2997,
"s": 2992,
"text": "Java"
},
{
"code": "// To convert Decimal to Hexadecimal Number//import java.util.*; // Main driver methodpublic class Main { public static void main(String[] args) { // Number in decimal int number = 2545; // output System.out.println(Integer.toString(number, 16)); }} // This code is written by ZEESHAN AHMAD//",
"e": 3328,
"s": 2997,
"text": null
},
{
"code": null,
"e": 3333,
"s": 3328,
"text": "9f1\n"
},
{
"code": null,
"e": 3376,
"s": 3333,
"text": "Time complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3390,
"s": 3376,
"text": "zeeshan118668"
},
{
"code": null,
"e": 3395,
"s": 3390,
"text": "Java"
},
{
"code": null,
"e": 3409,
"s": 3395,
"text": "Java Programs"
},
{
"code": null,
"e": 3414,
"s": 3409,
"text": "Java"
}
] |
Minimum number of replacements to make the binary string alternating | Set 2
|
22 Apr, 2022
Given a binary string str, the task is to find the minimum number of characters in the string that have to be replaced in order to make the string alternating (i.e. of the form 01010101... or 10101010...).Examples:
Input: str = “1100” Output: 2 Replace 2nd character with ‘0’ and 3rd character with ‘1’Input: str = “1010” Output: 0 The string is already alternating.
We have discussed one approach in Number of flips to make binary string alternate. In this post a better approach is discussed.Approach: For the string str, there can be two possible solutions. Either the resultant string can be
010101... or101010...
010101... or
101010...
In order to find the minimum replacements, count the number of replacements to convert the string in type 1 and store it in count then minimum replacement will be min(count, len – count) where len is the length of the string. len – count is the number of replacements to convert the string in type 2.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum number of// characters of the given binary string// to be replaced to make the string alternatingint minReplacement(string s, int len){ int ans = 0; for (int i = 0; i < len; i++) { // If there is 1 at even index positions if (i % 2 == 0 && s[i] == '1') ans++; // If there is 0 at odd index positions if (i % 2 == 1 && s[i] == '0') ans++; } return min(ans, len - ans);} // Driver codeint main(){ string s = "1100"; int len = s.size(); cout << minReplacement(s, len); return 0;}
// Java implementation of the approachclass GFG { // Function to return the minimum number of // characters of the given binary string // to be replaced to make the string alternating static int minReplacement(String s, int len) { int ans = 0; for (int i = 0; i < len; i++) { // If there is 1 at even index positions if (i % 2 == 0 && s.charAt(i) == '1') ans++; // If there is 0 at odd index positions if (i % 2 == 1 && s.charAt(i) == '0') ans++; } return Math.min(ans, len - ans); } // Driver code public static void main(String args[]) { String s = "1100"; int len = s.length(); System.out.print(minReplacement(s, len)); }}
# Python3 implementation of the approach. # Function to return the minimum number of# characters of the given binary string# to be replaced to make the string alternatingdef minReplacement(s, length): ans = 0 for i in range(0, length): # If there is 1 at even index positions if i % 2 == 0 and s[i] == '1': ans += 1 # If there is 0 at odd index positions if i % 2 == 1 and s[i] == '0': ans += 1 return min(ans, length - ans) # Driver codeif __name__ == "__main__": s = "1100" length = len(s) print(minReplacement(s, length)) # This code is contributed by Rituraj Jain
// C# implementation of the approachusing System; class GFG{ // Function to return the minimum number of // characters of the given binary string // to be replaced to make the string alternating static int minReplacement(String s, int len) { int ans = 0; for (int i = 0; i < len; i++) { // If there is 1 at even index positions if (i % 2 == 0 && s[i] == '1') ans++; // If there is 0 at odd index positions if (i % 2 == 1 && s[i] == '0') ans++; } return Math.Min(ans, len - ans); } // Driver code public static void Main(String []args) { String s = "1100"; int len = s.Length; Console.Write(minReplacement(s, len)); }} // This code contributed by Rajput-Ji
<?php// PHP implementation of the approach // Function to return the minimum number of// characters of the given binary string// to be replaced to make the string alternatingfunction minReplacement($s, $len){ $ans = 0; for ($i = 0; $i < $len; $i++) { // If there is 1 at even index positions if ($i % 2 == 0 && $s[$i] == '1') $ans++; // If there is 0 at odd index positions if ($i % 2 == 1 && $s[$i] == '0') $ans++; } return min($ans, $len - $ans);} // Driver code$s = "1100";$len = strlen($s);echo minReplacement($s, $len); // This code is contributed by chandan_jnu?>
<script> // Javascript implementation of the approach // Function to return the minimum number of// characters of the given binary string// to be replaced to make the string alternatingfunction minReplacement(s, len){ var ans = 0; for (var i = 0; i < len; i++) { // If there is 1 at even index positions if (i % 2 == 0 && s[i] == '1') ans++; // If there is 0 at odd index positions if (i % 2 == 1 && s[i] == '0') ans++; } return Math.min(ans, len - ans);} // Driver codevar s = "1100";var len = s.length;document.write(minReplacement(s, len)); </script>
2
Time Complexity: O(len), where len is the length of the given string. We are traversing till len.
Auxiliary Space: O(1), as we are not using any extra space.
Rajput-Ji
Chandan_Kumar
rituraj_jain
rutvik_56
rohitsingh07052
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Find minimum number of coins that make a given value
Sieve of Eratosthenes
Program to find GCD or HCF of two numbers
Write a program to reverse an array or string
Reverse a string in Java
Different Methods to Reverse a String in C++
Python program to check if a string is palindrome or not
Longest Common Subsequence | DP-4
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 269,
"s": 52,
"text": "Given a binary string str, the task is to find the minimum number of characters in the string that have to be replaced in order to make the string alternating (i.e. of the form 01010101... or 10101010...).Examples: "
},
{
"code": null,
"e": 423,
"s": 269,
"text": "Input: str = “1100” Output: 2 Replace 2nd character with ‘0’ and 3rd character with ‘1’Input: str = “1010” Output: 0 The string is already alternating. "
},
{
"code": null,
"e": 656,
"s": 425,
"text": "We have discussed one approach in Number of flips to make binary string alternate. In this post a better approach is discussed.Approach: For the string str, there can be two possible solutions. Either the resultant string can be "
},
{
"code": null,
"e": 678,
"s": 656,
"text": "010101... or101010..."
},
{
"code": null,
"e": 691,
"s": 678,
"text": "010101... or"
},
{
"code": null,
"e": 701,
"s": 691,
"text": "101010..."
},
{
"code": null,
"e": 1053,
"s": 701,
"text": "In order to find the minimum replacements, count the number of replacements to convert the string in type 1 and store it in count then minimum replacement will be min(count, len – count) where len is the length of the string. len – count is the number of replacements to convert the string in type 2.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1057,
"s": 1053,
"text": "C++"
},
{
"code": null,
"e": 1062,
"s": 1057,
"text": "Java"
},
{
"code": null,
"e": 1070,
"s": 1062,
"text": "Python3"
},
{
"code": null,
"e": 1073,
"s": 1070,
"text": "C#"
},
{
"code": null,
"e": 1077,
"s": 1073,
"text": "PHP"
},
{
"code": null,
"e": 1088,
"s": 1077,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum number of// characters of the given binary string// to be replaced to make the string alternatingint minReplacement(string s, int len){ int ans = 0; for (int i = 0; i < len; i++) { // If there is 1 at even index positions if (i % 2 == 0 && s[i] == '1') ans++; // If there is 0 at odd index positions if (i % 2 == 1 && s[i] == '0') ans++; } return min(ans, len - ans);} // Driver codeint main(){ string s = \"1100\"; int len = s.size(); cout << minReplacement(s, len); return 0;}",
"e": 1758,
"s": 1088,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Function to return the minimum number of // characters of the given binary string // to be replaced to make the string alternating static int minReplacement(String s, int len) { int ans = 0; for (int i = 0; i < len; i++) { // If there is 1 at even index positions if (i % 2 == 0 && s.charAt(i) == '1') ans++; // If there is 0 at odd index positions if (i % 2 == 1 && s.charAt(i) == '0') ans++; } return Math.min(ans, len - ans); } // Driver code public static void main(String args[]) { String s = \"1100\"; int len = s.length(); System.out.print(minReplacement(s, len)); }}",
"e": 2541,
"s": 1758,
"text": null
},
{
"code": "# Python3 implementation of the approach. # Function to return the minimum number of# characters of the given binary string# to be replaced to make the string alternatingdef minReplacement(s, length): ans = 0 for i in range(0, length): # If there is 1 at even index positions if i % 2 == 0 and s[i] == '1': ans += 1 # If there is 0 at odd index positions if i % 2 == 1 and s[i] == '0': ans += 1 return min(ans, length - ans) # Driver codeif __name__ == \"__main__\": s = \"1100\" length = len(s) print(minReplacement(s, length)) # This code is contributed by Rituraj Jain",
"e": 3194,
"s": 2541,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the minimum number of // characters of the given binary string // to be replaced to make the string alternating static int minReplacement(String s, int len) { int ans = 0; for (int i = 0; i < len; i++) { // If there is 1 at even index positions if (i % 2 == 0 && s[i] == '1') ans++; // If there is 0 at odd index positions if (i % 2 == 1 && s[i] == '0') ans++; } return Math.Min(ans, len - ans); } // Driver code public static void Main(String []args) { String s = \"1100\"; int len = s.Length; Console.Write(minReplacement(s, len)); }} // This code contributed by Rajput-Ji",
"e": 4014,
"s": 3194,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the minimum number of// characters of the given binary string// to be replaced to make the string alternatingfunction minReplacement($s, $len){ $ans = 0; for ($i = 0; $i < $len; $i++) { // If there is 1 at even index positions if ($i % 2 == 0 && $s[$i] == '1') $ans++; // If there is 0 at odd index positions if ($i % 2 == 1 && $s[$i] == '0') $ans++; } return min($ans, $len - $ans);} // Driver code$s = \"1100\";$len = strlen($s);echo minReplacement($s, $len); // This code is contributed by chandan_jnu?>",
"e": 4651,
"s": 4014,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the minimum number of// characters of the given binary string// to be replaced to make the string alternatingfunction minReplacement(s, len){ var ans = 0; for (var i = 0; i < len; i++) { // If there is 1 at even index positions if (i % 2 == 0 && s[i] == '1') ans++; // If there is 0 at odd index positions if (i % 2 == 1 && s[i] == '0') ans++; } return Math.min(ans, len - ans);} // Driver codevar s = \"1100\";var len = s.length;document.write(minReplacement(s, len)); </script>",
"e": 5271,
"s": 4651,
"text": null
},
{
"code": null,
"e": 5273,
"s": 5271,
"text": "2"
},
{
"code": null,
"e": 5373,
"s": 5275,
"text": "Time Complexity: O(len), where len is the length of the given string. We are traversing till len."
},
{
"code": null,
"e": 5433,
"s": 5373,
"text": "Auxiliary Space: O(1), as we are not using any extra space."
},
{
"code": null,
"e": 5443,
"s": 5433,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 5457,
"s": 5443,
"text": "Chandan_Kumar"
},
{
"code": null,
"e": 5470,
"s": 5457,
"text": "rituraj_jain"
},
{
"code": null,
"e": 5480,
"s": 5470,
"text": "rutvik_56"
},
{
"code": null,
"e": 5496,
"s": 5480,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 5509,
"s": 5496,
"text": "Mathematical"
},
{
"code": null,
"e": 5517,
"s": 5509,
"text": "Strings"
},
{
"code": null,
"e": 5525,
"s": 5517,
"text": "Strings"
},
{
"code": null,
"e": 5538,
"s": 5525,
"text": "Mathematical"
},
{
"code": null,
"e": 5636,
"s": 5538,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5660,
"s": 5636,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 5681,
"s": 5660,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 5734,
"s": 5681,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 5756,
"s": 5734,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 5798,
"s": 5756,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 5844,
"s": 5798,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 5869,
"s": 5844,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5914,
"s": 5869,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 5971,
"s": 5914,
"text": "Python program to check if a string is palindrome or not"
}
] |
Modular exponentiation (Recursive)
|
31 May, 2022
Given three numbers a, b and c, we need to find (ab) % cNow why do “% c” after exponentiation, because ab will be really large even for relatively small values of a, b and that is a problem because the data type of the language that we try to code the problem, will most probably not let us store such a large number.Examples:
Input : a = 2312 b = 3434 c = 6789
Output : 6343
Input : a = -3 b = 5 c = 89
Output : 24
Auxiliary Space: O(1)
The idea is based on below properties.Property 1: (m * n) % p has a very interesting property: (m * n) % p =((m % p) * (n % p)) % pProperty 2: if b is even: (a ^ b) % c = ((a ^ b/2) * (a ^ b/2))%c ? this suggests divide and conquer if b is odd: (a ^ b) % c = (a * (a ^( b-1))%cProperty 3: If we have to return the mod of a negative number x whose absolute value is less than y: then (x + y) % y will do the trickNote: Also as the product of (a ^ b/2) * (a ^ b/2) and a * (a ^( b-1) may cause overflow, hence we must be careful about those scenarios
C++
C
Java
Python3
C#
PHP
Javascript
// Recursive C++ program to compute modular power#include <bits/stdc++.h>using namespace std; int exponentMod(int A, int B, int C){ // Base cases if (A == 0) return 0; if (B == 0) return 1; // If B is even long y; if (B % 2 == 0) { y = exponentMod(A, B / 2, C); y = (y * y) % C; } // If B is odd else { y = A % C; y = (y * exponentMod(A, B - 1, C) % C) % C; } return (int)((y + C) % C);} // Driver codeint main(){ int A = 2, B = 5, C = 13; cout << "Power is " << exponentMod(A, B, C); return 0;} // This code is contributed by SHUBHAMSINGH10
// Recursive C program to compute modular power#include <stdio.h> int exponentMod(int A, int B, int C){ // Base cases if (A == 0) return 0; if (B == 0) return 1; // If B is even long y; if (B % 2 == 0) { y = exponentMod(A, B / 2, C); y = (y * y) % C; } // If B is odd else { y = A % C; y = (y * exponentMod(A, B - 1, C) % C) % C; } return (int)((y + C) % C);} // Driver program to test above functionsint main(){ int A = 2, B = 5, C = 13; printf("Power is %d", exponentMod(A, B, C)); return 0;}
// Recursive Java program// to compute modular powerimport java.io.*; class GFG{static int exponentMod(int A, int B, int C){ // Base cases if (A == 0) return 0; if (B == 0) return 1; // If B is even long y; if (B % 2 == 0) { y = exponentMod(A, B / 2, C); y = (y * y) % C; } // If B is odd else { y = A % C; y = (y * exponentMod(A, B - 1, C) % C) % C; } return (int)((y + C) % C);} // Driver Codepublic static void main(String args[]){ int A = 2, B = 5, C = 13; System.out.println("Power is " + exponentMod(A, B, C));}} // This code is contributed// by Swetank Modi.
# Recursive Python program# to compute modular powerdef exponentMod(A, B, C): # Base Cases if (A == 0): return 0 if (B == 0): return 1 # If B is Even y = 0 if (B % 2 == 0): y = exponentMod(A, B / 2, C) y = (y * y) % C # If B is Odd else: y = A % C y = (y * exponentMod(A, B - 1, C) % C) % C return ((y + C) % C) # Driver CodeA = 2B = 5C = 13print("Power is", exponentMod(A, B, C)) # This code is contributed# by Swetank Modi.
// Recursive C# program// to compute modular powerclass GFG{static int exponentMod(int A, int B, int C){ // Base cases if (A == 0) return 0; if (B == 0) return 1; // If B is even long y; if (B % 2 == 0) { y = exponentMod(A, B / 2, C); y = (y * y) % C; } // If B is odd else { y = A % C; y = (y * exponentMod(A, B - 1, C) % C) % C; } return (int)((y + C) % C);} // Driver Codepublic static void Main(){ int A = 2, B = 5, C = 13; System.Console.WriteLine("Power is " + exponentMod(A, B, C));}} // This code is contributed// by mits
<?php// Recursive PHP program to// compute modular powerfunction exponentMod($A, $B, $C){ // Base cases if ($A == 0) return 0; if ($B == 0) return 1; // If B is even if ($B % 2 == 0) { $y = exponentMod($A, $B / 2, $C); $y = ($y * $y) % $C; } // If B is odd else { $y = $A % $C; $y = ($y * exponentMod($A, $B - 1, $C) % $C) % $C; } return (($y + $C) % $C);} // Driver Code$A = 2;$B = 5;$C = 13;echo "Power is " . exponentMod($A, $B, $C); // This code is contributed// by Swetank Modi.?>
<script> // Recursive Javascript program// to compute modular power // Function to check if a given// quadilateral is valid or notfunction exponentMod(A, B, C){ // Base cases if (A == 0) return 0; if (B == 0) return 1; // If B is even var y; if (B % 2 == 0) { y = exponentMod(A, B / 2, C); y = (y * y) % C; } // If B is odd else { y = A % C; y = (y * exponentMod(A, B - 1, C) % C) % C; } return parseInt(((y + C) % C));} // Driver codevar A = 2, B = 5, C = 13;document.write("Power is " + exponentMod(A, B, C)); // This code is contributed by Khushboogoyal499 </script>
Power is 6
Time Complexity : O(logn)
Auxiliary Space: O(logn)
Iterative modular exponentiation.
swetankmodi
Mithun Kumar
SHUBHAMSINGH10
khushboogoyal499
rishavnitro
Modular Arithmetic
Divide and Conquer
Mathematical
Recursion
Mathematical
Recursion
Divide and Conquer
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 May, 2022"
},
{
"code": null,
"e": 383,
"s": 54,
"text": "Given three numbers a, b and c, we need to find (ab) % cNow why do “% c” after exponentiation, because ab will be really large even for relatively small values of a, b and that is a problem because the data type of the language that we try to code the problem, will most probably not let us store such a large number.Examples: "
},
{
"code": null,
"e": 474,
"s": 383,
"text": "Input : a = 2312 b = 3434 c = 6789\nOutput : 6343\n\nInput : a = -3 b = 5 c = 89 \nOutput : 24"
},
{
"code": null,
"e": 497,
"s": 474,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 1048,
"s": 497,
"text": "The idea is based on below properties.Property 1: (m * n) % p has a very interesting property: (m * n) % p =((m % p) * (n % p)) % pProperty 2: if b is even: (a ^ b) % c = ((a ^ b/2) * (a ^ b/2))%c ? this suggests divide and conquer if b is odd: (a ^ b) % c = (a * (a ^( b-1))%cProperty 3: If we have to return the mod of a negative number x whose absolute value is less than y: then (x + y) % y will do the trickNote: Also as the product of (a ^ b/2) * (a ^ b/2) and a * (a ^( b-1) may cause overflow, hence we must be careful about those scenarios "
},
{
"code": null,
"e": 1052,
"s": 1048,
"text": "C++"
},
{
"code": null,
"e": 1054,
"s": 1052,
"text": "C"
},
{
"code": null,
"e": 1059,
"s": 1054,
"text": "Java"
},
{
"code": null,
"e": 1067,
"s": 1059,
"text": "Python3"
},
{
"code": null,
"e": 1070,
"s": 1067,
"text": "C#"
},
{
"code": null,
"e": 1074,
"s": 1070,
"text": "PHP"
},
{
"code": null,
"e": 1085,
"s": 1074,
"text": "Javascript"
},
{
"code": "// Recursive C++ program to compute modular power#include <bits/stdc++.h>using namespace std; int exponentMod(int A, int B, int C){ // Base cases if (A == 0) return 0; if (B == 0) return 1; // If B is even long y; if (B % 2 == 0) { y = exponentMod(A, B / 2, C); y = (y * y) % C; } // If B is odd else { y = A % C; y = (y * exponentMod(A, B - 1, C) % C) % C; } return (int)((y + C) % C);} // Driver codeint main(){ int A = 2, B = 5, C = 13; cout << \"Power is \" << exponentMod(A, B, C); return 0;} // This code is contributed by SHUBHAMSINGH10",
"e": 1714,
"s": 1085,
"text": null
},
{
"code": "// Recursive C program to compute modular power#include <stdio.h> int exponentMod(int A, int B, int C){ // Base cases if (A == 0) return 0; if (B == 0) return 1; // If B is even long y; if (B % 2 == 0) { y = exponentMod(A, B / 2, C); y = (y * y) % C; } // If B is odd else { y = A % C; y = (y * exponentMod(A, B - 1, C) % C) % C; } return (int)((y + C) % C);} // Driver program to test above functionsint main(){ int A = 2, B = 5, C = 13; printf(\"Power is %d\", exponentMod(A, B, C)); return 0;}",
"e": 2293,
"s": 1714,
"text": null
},
{
"code": "// Recursive Java program// to compute modular powerimport java.io.*; class GFG{static int exponentMod(int A, int B, int C){ // Base cases if (A == 0) return 0; if (B == 0) return 1; // If B is even long y; if (B % 2 == 0) { y = exponentMod(A, B / 2, C); y = (y * y) % C; } // If B is odd else { y = A % C; y = (y * exponentMod(A, B - 1, C) % C) % C; } return (int)((y + C) % C);} // Driver Codepublic static void main(String args[]){ int A = 2, B = 5, C = 13; System.out.println(\"Power is \" + exponentMod(A, B, C));}} // This code is contributed// by Swetank Modi.",
"e": 3043,
"s": 2293,
"text": null
},
{
"code": "# Recursive Python program# to compute modular powerdef exponentMod(A, B, C): # Base Cases if (A == 0): return 0 if (B == 0): return 1 # If B is Even y = 0 if (B % 2 == 0): y = exponentMod(A, B / 2, C) y = (y * y) % C # If B is Odd else: y = A % C y = (y * exponentMod(A, B - 1, C) % C) % C return ((y + C) % C) # Driver CodeA = 2B = 5C = 13print(\"Power is\", exponentMod(A, B, C)) # This code is contributed# by Swetank Modi.",
"e": 3585,
"s": 3043,
"text": null
},
{
"code": "// Recursive C# program// to compute modular powerclass GFG{static int exponentMod(int A, int B, int C){ // Base cases if (A == 0) return 0; if (B == 0) return 1; // If B is even long y; if (B % 2 == 0) { y = exponentMod(A, B / 2, C); y = (y * y) % C; } // If B is odd else { y = A % C; y = (y * exponentMod(A, B - 1, C) % C) % C; } return (int)((y + C) % C);} // Driver Codepublic static void Main(){ int A = 2, B = 5, C = 13; System.Console.WriteLine(\"Power is \" + exponentMod(A, B, C));}} // This code is contributed// by mits",
"e": 4273,
"s": 3585,
"text": null
},
{
"code": "<?php// Recursive PHP program to// compute modular powerfunction exponentMod($A, $B, $C){ // Base cases if ($A == 0) return 0; if ($B == 0) return 1; // If B is even if ($B % 2 == 0) { $y = exponentMod($A, $B / 2, $C); $y = ($y * $y) % $C; } // If B is odd else { $y = $A % $C; $y = ($y * exponentMod($A, $B - 1, $C) % $C) % $C; } return (($y + $C) % $C);} // Driver Code$A = 2;$B = 5;$C = 13;echo \"Power is \" . exponentMod($A, $B, $C); // This code is contributed// by Swetank Modi.?>",
"e": 4883,
"s": 4273,
"text": null
},
{
"code": "<script> // Recursive Javascript program// to compute modular power // Function to check if a given// quadilateral is valid or notfunction exponentMod(A, B, C){ // Base cases if (A == 0) return 0; if (B == 0) return 1; // If B is even var y; if (B % 2 == 0) { y = exponentMod(A, B / 2, C); y = (y * y) % C; } // If B is odd else { y = A % C; y = (y * exponentMod(A, B - 1, C) % C) % C; } return parseInt(((y + C) % C));} // Driver codevar A = 2, B = 5, C = 13;document.write(\"Power is \" + exponentMod(A, B, C)); // This code is contributed by Khushboogoyal499 </script>",
"e": 5600,
"s": 4883,
"text": null
},
{
"code": null,
"e": 5611,
"s": 5600,
"text": "Power is 6"
},
{
"code": null,
"e": 5639,
"s": 5613,
"text": "Time Complexity : O(logn)"
},
{
"code": null,
"e": 5664,
"s": 5639,
"text": "Auxiliary Space: O(logn)"
},
{
"code": null,
"e": 5699,
"s": 5664,
"text": "Iterative modular exponentiation. "
},
{
"code": null,
"e": 5711,
"s": 5699,
"text": "swetankmodi"
},
{
"code": null,
"e": 5724,
"s": 5711,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 5739,
"s": 5724,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 5756,
"s": 5739,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 5768,
"s": 5756,
"text": "rishavnitro"
},
{
"code": null,
"e": 5787,
"s": 5768,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 5806,
"s": 5787,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 5819,
"s": 5806,
"text": "Mathematical"
},
{
"code": null,
"e": 5829,
"s": 5819,
"text": "Recursion"
},
{
"code": null,
"e": 5842,
"s": 5829,
"text": "Mathematical"
},
{
"code": null,
"e": 5852,
"s": 5842,
"text": "Recursion"
},
{
"code": null,
"e": 5871,
"s": 5852,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 5890,
"s": 5871,
"text": "Modular Arithmetic"
}
] |
Find an array element such that all elements are divisible by it
|
14 Jun, 2022
Given an array of numbers, find the number among them such that all numbers are divisible by it. If not possible print -1.Examples:
Input : arr = {25, 20, 5, 10, 100}
Output : 5
Explanation : 5 is an array element
which divides all numbers.
Input : arr = {9, 3, 6, 2, 15}
Output : -1
Explanation : No numbers are divisible
by any array element.
Method 1:(naive) A normal approach will be to take every element and check for division with all other elements. If all the numbers are divisible then return the number.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find an array element that// divides all numbers in the array using// naive approach#include <bits/stdc++.h>using namespace std; // function to find smallest numint findSmallest(int a[], int n){ // traverse for all elements for (int i = 0; i < n; i++) { int j; for (j = 0; j < n; j++) if (a[j] % a[i]) break; // stores the minimum if // it divides all if (j == n) return a[i]; } return -1;} // driver codeint main(){ int a[] = { 25, 20, 5, 10, 100 }; int n = sizeof(a) / sizeof(int); cout << findSmallest(a, n); return 0;}
// Java program to find an array element// that divides all numbers in the array// using naive approachimport java.io.*; class GFG { // function to find smallest num static int findSmallest(int a[], int n) { // traverse for all elements for (int i = 0; i < n; i++) { int j; for (j = 0; j < n; j++) if (a[j] % a[i]>=1) break; // stores the minimum if // it divides all if (j == n) return a[i]; } return -1; } // driver code public static void main(String args[]) { int a[] = { 25, 20, 5, 10, 100 }; int n = a.length; System.out.println(findSmallest(a, n)); }} // This code is contributed by Nikita Tiwari.
# Python 3 program to find an array# element that divides all numbers# in the array using naive approach # Function to find smallest numdef findSmallest(a, n) : # Traverse for all elements for i in range(0, n ) : for j in range(0, n) : if ((a[j] % a[i]) >= 1) : break # Stores the minimum # if it divides all if (j == n - 1) : return a[i] return -1 # Driver codea = [ 25, 20, 5, 10, 100 ]n = len(a)print(findSmallest(a, n)) # This code is contributed by Nikita Tiwari.
// C# program to find an array element// that divides all numbers in the array// using naive approachusing System; class GFG { // function to find smallest num static int findSmallest(int []a, int n) { // traverse for all elements for (int i = 0; i < n; i++) { int j; for (j = 0; j < n; j++) if (a[j] % a[i] >= 1) break; // stores the minimum if // it divides all if (j == n) return a[i]; } return -1; } // Driver code public static void Main() { int []a = { 25, 20, 5, 10, 100 }; int n = a.Length; Console.WriteLine(findSmallest(a, n)); }} // This code is contributed by vt_m.
<?php// PHP program to find an array// element that divides all// numbers in the array using// naive approach // function to find smallest numfunction findSmallest($a, $n){ // traverse for all elements for ($i = 0; $i < $n; $i++) { $j; for ($j = 0; $j < $n; $j++) if ($a[$j] % $a[$i]) break; // stores the minimum if // it divides all if ($j == $n) return $a[$i]; } return -1;} // Driver Code $a = array( 25, 20, 5, 10, 100 ); $n = sizeof($a); echo findSmallest($a, $n); // This code is contributed by nitin mittal?>
<script> // JavaScript program to find an array element// that divides all numbers in the array// using naive approach // function to find smallest num function findSmallest(a, n) { // traverse for all elements for (let i = 0; i < n; i++) { let j; for (j = 0; j < n; j++) if (a[j] % a[i]>=1) break; // stores the minimum if // it divides all if (j == n) return a[i]; } return -1; } // Driver code let a = [ 25, 20, 5, 10, 100 ]; let n = a.length; document.write(findSmallest(a, n)); </script>
Output :
5
Time Complexity: O(n2)
Auxiliary Space: O(1)
Method 2 : (Efficient) An efficient approach is to find smallest of all numbers, and check if it divides all the other numbers, if yes then the smallest number will be the required number.
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to find the smallest number// that divides all numbers in an array#include <bits/stdc++.h>using namespace std; // function to find smallest numint findSmallest(int a[], int n){ // Find the smallest element int smallest = *min_element(a, a+n); // Check if all array elements // are divisible by smallest. for (int i = 1; i < n; i++) if (a[i] % smallest) return -1; return smallest;} // Driver codeint main(){ int a[] = { 25, 20, 5, 10, 100 }; int n = sizeof(a) / sizeof(int); cout << findSmallest(a, n); return 0;}
// Java Program to find the// smallest number that divides// all numbers in an arrayimport java.io.*; class GFG { // function to find the smallest element static int min_element(int a[]) { int min = Integer.MAX_VALUE, i; for (i = 0; i < a.length; i++) { if (a[i] < min) min = a[i]; } return min; } // function to find smallest num static int findSmallest(int a[], int n) { // Find the smallest element int smallest = min_element(a); // Check if all array elements // are divisible by smallest. for (int i = 1; i < n; i++) if (a[i] % smallest >= 1) return -1; return smallest; } // Driver code public static void main(String args[]) { int a[] = {25, 20, 5, 10, 100}; int n = a.length; System.out.println(findSmallest(a, n)); }} // This code is contributed by Nikita Tiwari.
# Python3 Program to find the# smallest number that divides# all numbers in an array # Function to find the smallest elementdef min_element(a) : m = 10000000 for i in range(0, len(a)) : if (a[i] < m) : m = a[i] return m # Function to find smallest numdef findSmallest(a, n) : # Find the smallest element smallest = min_element(a) # Check if all array elements # are divisible by smallest. for i in range(1, n) : if (a[i] % smallest >= 1) : return -1 return smallest # Driver code a = [ 25, 20, 5, 10, 100 ]n = len(a)print(findSmallest(a, n)) # This code is contributed by Nikita Tiwari.
// C# Program to find the// smallest number that divides// all numbers in an arrayusing System; class GFG { // function to find the smallest element static int min_element(int []a) { int min = int.MaxValue; int i; for (i = 0; i < a.Length; i++) { if (a[i] < min) min = a[i]; } return min; } // function to find smallest num static int findSmallest(int []a, int n) { // Find the smallest element int smallest = min_element(a); // Check if all array elements // are divisible by smallest. for (int i = 1; i < n; i++) if (a[i] % smallest >= 1) return -1; return smallest; } // Driver code public static void Main() { int []a = {25, 20, 5, 10, 100}; int n = a.Length; Console.WriteLine(findSmallest(a, n)); }} // This code is contributed by vt_m.
<?php// PHP Program to find the smallest number// that divides all numbers in an array // function to find smallest numfunction findSmallest($a, $n){ // Find the smallest element $smallest = min($a); // Check if all array elements // are divisible by smallest. for ($i = 1; $i < $n; $i++) if ($a[$i] % $smallest) return -1; return $smallest;} // Driver Code $a = array(25, 20, 5, 10, 100); $n =count($a); echo findSmallest($a, $n); // This code is contributed by anuj_67.?>
<script> // Javascript Program to find the // smallest number that divides // all numbers in an array // function to find the smallest element function min_element(a) { let min = Number.MAX_VALUE; let i; for (i = 0; i < a.length; i++) { if (a[i] < min) min = a[i]; } return min; } // function to find smallest num function findSmallest(a, n) { // Find the smallest element let smallest = min_element(a); // Check if all array elements // are divisible by smallest. for (let i = 1; i < n; i++) if (a[i] % smallest >= 1) return -1; return smallest; } let a = [25, 20, 5, 10, 100]; let n = a.length; document.write(findSmallest(a, n)); // This code is contributed by divyeshrabadiya07.</script>
Output :
5
Time Complexity: O(n)
Auxiliary Space: O(1)
Find an array element such that all elements are divisible by it | GeeksforGeeks - YouTubeGeeksforGeeks528K subscribersFind an array element such that all elements are divisible by it | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:51•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=RglGlzkliNM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySEQDk2MDfbwEdjd2svVJH9p
nitin mittal
vt_m
sanjoy_62
divyeshrabadiya07
_shinchancode
Arrays
Searching
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Find Second largest element in an array
Introduction to Data Structures
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Binary Search
Search an element in a sorted and rotated array
Search, insert and delete in an unsorted array
Find the Missing Number
Median of two sorted arrays of different sizes
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 187,
"s": 53,
"text": "Given an array of numbers, find the number among them such that all numbers are divisible by it. If not possible print -1.Examples: "
},
{
"code": null,
"e": 406,
"s": 187,
"text": "Input : arr = {25, 20, 5, 10, 100} \nOutput : 5 \nExplanation : 5 is an array element\n which divides all numbers.\n\nInput : arr = {9, 3, 6, 2, 15} \nOutput : -1 \nExplanation : No numbers are divisible\nby any array element."
},
{
"code": null,
"e": 580,
"s": 408,
"text": "Method 1:(naive) A normal approach will be to take every element and check for division with all other elements. If all the numbers are divisible then return the number. "
},
{
"code": null,
"e": 584,
"s": 580,
"text": "C++"
},
{
"code": null,
"e": 589,
"s": 584,
"text": "Java"
},
{
"code": null,
"e": 597,
"s": 589,
"text": "Python3"
},
{
"code": null,
"e": 600,
"s": 597,
"text": "C#"
},
{
"code": null,
"e": 604,
"s": 600,
"text": "PHP"
},
{
"code": null,
"e": 615,
"s": 604,
"text": "Javascript"
},
{
"code": "// CPP program to find an array element that// divides all numbers in the array using// naive approach#include <bits/stdc++.h>using namespace std; // function to find smallest numint findSmallest(int a[], int n){ // traverse for all elements for (int i = 0; i < n; i++) { int j; for (j = 0; j < n; j++) if (a[j] % a[i]) break; // stores the minimum if // it divides all if (j == n) return a[i]; } return -1;} // driver codeint main(){ int a[] = { 25, 20, 5, 10, 100 }; int n = sizeof(a) / sizeof(int); cout << findSmallest(a, n); return 0;}",
"e": 1263,
"s": 615,
"text": null
},
{
"code": "// Java program to find an array element// that divides all numbers in the array// using naive approachimport java.io.*; class GFG { // function to find smallest num static int findSmallest(int a[], int n) { // traverse for all elements for (int i = 0; i < n; i++) { int j; for (j = 0; j < n; j++) if (a[j] % a[i]>=1) break; // stores the minimum if // it divides all if (j == n) return a[i]; } return -1; } // driver code public static void main(String args[]) { int a[] = { 25, 20, 5, 10, 100 }; int n = a.length; System.out.println(findSmallest(a, n)); }} // This code is contributed by Nikita Tiwari.",
"e": 2086,
"s": 1263,
"text": null
},
{
"code": "# Python 3 program to find an array# element that divides all numbers# in the array using naive approach # Function to find smallest numdef findSmallest(a, n) : # Traverse for all elements for i in range(0, n ) : for j in range(0, n) : if ((a[j] % a[i]) >= 1) : break # Stores the minimum # if it divides all if (j == n - 1) : return a[i] return -1 # Driver codea = [ 25, 20, 5, 10, 100 ]n = len(a)print(findSmallest(a, n)) # This code is contributed by Nikita Tiwari.",
"e": 2676,
"s": 2086,
"text": null
},
{
"code": "// C# program to find an array element// that divides all numbers in the array// using naive approachusing System; class GFG { // function to find smallest num static int findSmallest(int []a, int n) { // traverse for all elements for (int i = 0; i < n; i++) { int j; for (j = 0; j < n; j++) if (a[j] % a[i] >= 1) break; // stores the minimum if // it divides all if (j == n) return a[i]; } return -1; } // Driver code public static void Main() { int []a = { 25, 20, 5, 10, 100 }; int n = a.Length; Console.WriteLine(findSmallest(a, n)); }} // This code is contributed by vt_m.",
"e": 3472,
"s": 2676,
"text": null
},
{
"code": "<?php// PHP program to find an array// element that divides all// numbers in the array using// naive approach // function to find smallest numfunction findSmallest($a, $n){ // traverse for all elements for ($i = 0; $i < $n; $i++) { $j; for ($j = 0; $j < $n; $j++) if ($a[$j] % $a[$i]) break; // stores the minimum if // it divides all if ($j == $n) return $a[$i]; } return -1;} // Driver Code $a = array( 25, 20, 5, 10, 100 ); $n = sizeof($a); echo findSmallest($a, $n); // This code is contributed by nitin mittal?>",
"e": 4096,
"s": 3472,
"text": null
},
{
"code": "<script> // JavaScript program to find an array element// that divides all numbers in the array// using naive approach // function to find smallest num function findSmallest(a, n) { // traverse for all elements for (let i = 0; i < n; i++) { let j; for (j = 0; j < n; j++) if (a[j] % a[i]>=1) break; // stores the minimum if // it divides all if (j == n) return a[i]; } return -1; } // Driver code let a = [ 25, 20, 5, 10, 100 ]; let n = a.length; document.write(findSmallest(a, n)); </script>",
"e": 4793,
"s": 4096,
"text": null
},
{
"code": null,
"e": 4803,
"s": 4793,
"text": "Output : "
},
{
"code": null,
"e": 4805,
"s": 4803,
"text": "5"
},
{
"code": null,
"e": 4828,
"s": 4805,
"text": "Time Complexity: O(n2)"
},
{
"code": null,
"e": 4850,
"s": 4828,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5041,
"s": 4850,
"text": "Method 2 : (Efficient) An efficient approach is to find smallest of all numbers, and check if it divides all the other numbers, if yes then the smallest number will be the required number. "
},
{
"code": null,
"e": 5045,
"s": 5041,
"text": "C++"
},
{
"code": null,
"e": 5050,
"s": 5045,
"text": "Java"
},
{
"code": null,
"e": 5058,
"s": 5050,
"text": "Python3"
},
{
"code": null,
"e": 5061,
"s": 5058,
"text": "C#"
},
{
"code": null,
"e": 5065,
"s": 5061,
"text": "PHP"
},
{
"code": null,
"e": 5076,
"s": 5065,
"text": "Javascript"
},
{
"code": "// CPP Program to find the smallest number// that divides all numbers in an array#include <bits/stdc++.h>using namespace std; // function to find smallest numint findSmallest(int a[], int n){ // Find the smallest element int smallest = *min_element(a, a+n); // Check if all array elements // are divisible by smallest. for (int i = 1; i < n; i++) if (a[i] % smallest) return -1; return smallest;} // Driver codeint main(){ int a[] = { 25, 20, 5, 10, 100 }; int n = sizeof(a) / sizeof(int); cout << findSmallest(a, n); return 0;}",
"e": 5669,
"s": 5076,
"text": null
},
{
"code": "// Java Program to find the// smallest number that divides// all numbers in an arrayimport java.io.*; class GFG { // function to find the smallest element static int min_element(int a[]) { int min = Integer.MAX_VALUE, i; for (i = 0; i < a.length; i++) { if (a[i] < min) min = a[i]; } return min; } // function to find smallest num static int findSmallest(int a[], int n) { // Find the smallest element int smallest = min_element(a); // Check if all array elements // are divisible by smallest. for (int i = 1; i < n; i++) if (a[i] % smallest >= 1) return -1; return smallest; } // Driver code public static void main(String args[]) { int a[] = {25, 20, 5, 10, 100}; int n = a.length; System.out.println(findSmallest(a, n)); }} // This code is contributed by Nikita Tiwari.",
"e": 6650,
"s": 5669,
"text": null
},
{
"code": "# Python3 Program to find the# smallest number that divides# all numbers in an array # Function to find the smallest elementdef min_element(a) : m = 10000000 for i in range(0, len(a)) : if (a[i] < m) : m = a[i] return m # Function to find smallest numdef findSmallest(a, n) : # Find the smallest element smallest = min_element(a) # Check if all array elements # are divisible by smallest. for i in range(1, n) : if (a[i] % smallest >= 1) : return -1 return smallest # Driver code a = [ 25, 20, 5, 10, 100 ]n = len(a)print(findSmallest(a, n)) # This code is contributed by Nikita Tiwari.",
"e": 7346,
"s": 6650,
"text": null
},
{
"code": "// C# Program to find the// smallest number that divides// all numbers in an arrayusing System; class GFG { // function to find the smallest element static int min_element(int []a) { int min = int.MaxValue; int i; for (i = 0; i < a.Length; i++) { if (a[i] < min) min = a[i]; } return min; } // function to find smallest num static int findSmallest(int []a, int n) { // Find the smallest element int smallest = min_element(a); // Check if all array elements // are divisible by smallest. for (int i = 1; i < n; i++) if (a[i] % smallest >= 1) return -1; return smallest; } // Driver code public static void Main() { int []a = {25, 20, 5, 10, 100}; int n = a.Length; Console.WriteLine(findSmallest(a, n)); }} // This code is contributed by vt_m.",
"e": 8304,
"s": 7346,
"text": null
},
{
"code": "<?php// PHP Program to find the smallest number// that divides all numbers in an array // function to find smallest numfunction findSmallest($a, $n){ // Find the smallest element $smallest = min($a); // Check if all array elements // are divisible by smallest. for ($i = 1; $i < $n; $i++) if ($a[$i] % $smallest) return -1; return $smallest;} // Driver Code $a = array(25, 20, 5, 10, 100); $n =count($a); echo findSmallest($a, $n); // This code is contributed by anuj_67.?>",
"e": 8838,
"s": 8304,
"text": null
},
{
"code": "<script> // Javascript Program to find the // smallest number that divides // all numbers in an array // function to find the smallest element function min_element(a) { let min = Number.MAX_VALUE; let i; for (i = 0; i < a.length; i++) { if (a[i] < min) min = a[i]; } return min; } // function to find smallest num function findSmallest(a, n) { // Find the smallest element let smallest = min_element(a); // Check if all array elements // are divisible by smallest. for (let i = 1; i < n; i++) if (a[i] % smallest >= 1) return -1; return smallest; } let a = [25, 20, 5, 10, 100]; let n = a.length; document.write(findSmallest(a, n)); // This code is contributed by divyeshrabadiya07.</script>",
"e": 9746,
"s": 8838,
"text": null
},
{
"code": null,
"e": 9757,
"s": 9746,
"text": "Output : "
},
{
"code": null,
"e": 9759,
"s": 9757,
"text": "5"
},
{
"code": null,
"e": 9782,
"s": 9759,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 9805,
"s": 9782,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 10751,
"s": 9805,
"text": "Find an array element such that all elements are divisible by it | GeeksforGeeks - YouTubeGeeksforGeeks528K subscribersFind an array element such that all elements are divisible by it | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:51•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=RglGlzkliNM\" 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": 10793,
"s": 10751,
"text": "?list=PLqM7alHXFySEQDk2MDfbwEdjd2svVJH9p "
},
{
"code": null,
"e": 10806,
"s": 10793,
"text": "nitin mittal"
},
{
"code": null,
"e": 10811,
"s": 10806,
"text": "vt_m"
},
{
"code": null,
"e": 10821,
"s": 10811,
"text": "sanjoy_62"
},
{
"code": null,
"e": 10839,
"s": 10821,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 10853,
"s": 10839,
"text": "_shinchancode"
},
{
"code": null,
"e": 10860,
"s": 10853,
"text": "Arrays"
},
{
"code": null,
"e": 10870,
"s": 10860,
"text": "Searching"
},
{
"code": null,
"e": 10877,
"s": 10870,
"text": "Arrays"
},
{
"code": null,
"e": 10887,
"s": 10877,
"text": "Searching"
},
{
"code": null,
"e": 10985,
"s": 10887,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11008,
"s": 10985,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 11048,
"s": 11008,
"text": "Find Second largest element in an array"
},
{
"code": null,
"e": 11080,
"s": 11048,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 11125,
"s": 11080,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 11173,
"s": 11125,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 11187,
"s": 11173,
"text": "Binary Search"
},
{
"code": null,
"e": 11235,
"s": 11187,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 11282,
"s": 11235,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 11306,
"s": 11282,
"text": "Find the Missing Number"
}
] |
java.nio.file.Paths Class in Java
|
12 Mar, 2021
java.nio.file.Paths class contains static methods for converting path string or URI into Path.
Class declaration :
public final class Paths
extends Object
Methods:
get(String first, String... more)
This method converts a path string, or a sequence of strings that when joined form a path string, to a Path.
get(URI uri)
This method converts the given URI to a Path object.
1. public static Path get(String first, String... more):
Returns a Path by converting given strings into a Path. If “more” doesn’t specify any strings than “first” is the only string to convert. If “more” specify extra strings then “first” is the initial part of the sequence and the extra strings will be appended to the sequence after “first” separated by “/”.
Parameters:
first – initial part of the Path.more – extra strings to be joined to the Path.
first – initial part of the Path.
more – extra strings to be joined to the Path.
Returns: resulting Path
Throws:
InvalidPathException – if a given string cannot be converted to a Path
Java
// Java program to demonstrate// java.nio.file.Path.get(String first,String... more)// method import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths; public class GFG { public static void main(String[] args) throws IOException { // create object of Path Path path = (Path)Paths.get("/usr", "local", "bin"); // print Path System.out.println(path); }}
/usr/local/bin
2.public static Path get(URI uri): Returns a Path by converting given Uri into a Path.
Parameters:
uri – to be converted
Returns: resulting Path
Throws:
IllegalArgumentException – if the parameter of URI is not appropriateFileSystemNotFoundException – if the file system, which is identified by URI does not existSecurityException – if security manager denies access to file system
IllegalArgumentException – if the parameter of URI is not appropriate
FileSystemNotFoundException – if the file system, which is identified by URI does not exist
SecurityException – if security manager denies access to file system
Java
// Java program to demonstrate// java.nio.file.Path.get(URI uri) method import java.io.IOException;import java.net.URI;import java.net.URISyntaxException;import java.nio.file.Paths; public class Path { public static void main(String[] args) throws IOException, URISyntaxException { String uribase = "https://www.geeksforgeeks.org/"; // Constructor to create a new URI // by parsing the string URI uri = new URI(uribase); // create object of Path Path path = (Path)Paths.get(uri); // print ParentPath System.out.println(path); }}
Output:
https://www.geeksforgeeks.org/
Java-NIO package
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Multidimensional Arrays in Java
Collections in Java
Stream In Java
Set in Java
Singleton Class in Java
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n12 Mar, 2021"
},
{
"code": null,
"e": 148,
"s": 53,
"text": "java.nio.file.Paths class contains static methods for converting path string or URI into Path."
},
{
"code": null,
"e": 168,
"s": 148,
"text": "Class declaration :"
},
{
"code": null,
"e": 208,
"s": 168,
"text": "public final class Paths\nextends Object"
},
{
"code": null,
"e": 217,
"s": 208,
"text": "Methods:"
},
{
"code": null,
"e": 252,
"s": 217,
"text": "get(String first, String... more) "
},
{
"code": null,
"e": 361,
"s": 252,
"text": "This method converts a path string, or a sequence of strings that when joined form a path string, to a Path."
},
{
"code": null,
"e": 374,
"s": 361,
"text": "get(URI uri)"
},
{
"code": null,
"e": 427,
"s": 374,
"text": "This method converts the given URI to a Path object."
},
{
"code": null,
"e": 485,
"s": 427,
"text": "1. public static Path get(String first, String... more): "
},
{
"code": null,
"e": 791,
"s": 485,
"text": "Returns a Path by converting given strings into a Path. If “more” doesn’t specify any strings than “first” is the only string to convert. If “more” specify extra strings then “first” is the initial part of the sequence and the extra strings will be appended to the sequence after “first” separated by “/”."
},
{
"code": null,
"e": 803,
"s": 791,
"text": "Parameters:"
},
{
"code": null,
"e": 883,
"s": 803,
"text": "first – initial part of the Path.more – extra strings to be joined to the Path."
},
{
"code": null,
"e": 917,
"s": 883,
"text": "first – initial part of the Path."
},
{
"code": null,
"e": 964,
"s": 917,
"text": "more – extra strings to be joined to the Path."
},
{
"code": null,
"e": 988,
"s": 964,
"text": "Returns: resulting Path"
},
{
"code": null,
"e": 997,
"s": 988,
"text": "Throws: "
},
{
"code": null,
"e": 1068,
"s": 997,
"text": "InvalidPathException – if a given string cannot be converted to a Path"
},
{
"code": null,
"e": 1073,
"s": 1068,
"text": "Java"
},
{
"code": "// Java program to demonstrate// java.nio.file.Path.get(String first,String... more)// method import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths; public class GFG { public static void main(String[] args) throws IOException { // create object of Path Path path = (Path)Paths.get(\"/usr\", \"local\", \"bin\"); // print Path System.out.println(path); }}",
"e": 1498,
"s": 1073,
"text": null
},
{
"code": null,
"e": 1514,
"s": 1498,
"text": "/usr/local/bin\n"
},
{
"code": null,
"e": 1601,
"s": 1514,
"text": "2.public static Path get(URI uri): Returns a Path by converting given Uri into a Path."
},
{
"code": null,
"e": 1614,
"s": 1601,
"text": "Parameters: "
},
{
"code": null,
"e": 1636,
"s": 1614,
"text": "uri – to be converted"
},
{
"code": null,
"e": 1660,
"s": 1636,
"text": "Returns: resulting Path"
},
{
"code": null,
"e": 1668,
"s": 1660,
"text": "Throws:"
},
{
"code": null,
"e": 1897,
"s": 1668,
"text": "IllegalArgumentException – if the parameter of URI is not appropriateFileSystemNotFoundException – if the file system, which is identified by URI does not existSecurityException – if security manager denies access to file system"
},
{
"code": null,
"e": 1967,
"s": 1897,
"text": "IllegalArgumentException – if the parameter of URI is not appropriate"
},
{
"code": null,
"e": 2059,
"s": 1967,
"text": "FileSystemNotFoundException – if the file system, which is identified by URI does not exist"
},
{
"code": null,
"e": 2128,
"s": 2059,
"text": "SecurityException – if security manager denies access to file system"
},
{
"code": null,
"e": 2133,
"s": 2128,
"text": "Java"
},
{
"code": "// Java program to demonstrate// java.nio.file.Path.get(URI uri) method import java.io.IOException;import java.net.URI;import java.net.URISyntaxException;import java.nio.file.Paths; public class Path { public static void main(String[] args) throws IOException, URISyntaxException { String uribase = \"https://www.geeksforgeeks.org/\"; // Constructor to create a new URI // by parsing the string URI uri = new URI(uribase); // create object of Path Path path = (Path)Paths.get(uri); // print ParentPath System.out.println(path); }}",
"e": 2740,
"s": 2133,
"text": null
},
{
"code": null,
"e": 2748,
"s": 2740,
"text": "Output:"
},
{
"code": null,
"e": 2779,
"s": 2748,
"text": "https://www.geeksforgeeks.org/"
},
{
"code": null,
"e": 2796,
"s": 2779,
"text": "Java-NIO package"
},
{
"code": null,
"e": 2803,
"s": 2796,
"text": "Picked"
},
{
"code": null,
"e": 2808,
"s": 2803,
"text": "Java"
},
{
"code": null,
"e": 2813,
"s": 2808,
"text": "Java"
},
{
"code": null,
"e": 2911,
"s": 2813,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2962,
"s": 2911,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2993,
"s": 2962,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3012,
"s": 2993,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3042,
"s": 3012,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3060,
"s": 3042,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3092,
"s": 3060,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3112,
"s": 3092,
"text": "Collections in Java"
},
{
"code": null,
"e": 3127,
"s": 3112,
"text": "Stream In Java"
},
{
"code": null,
"e": 3139,
"s": 3127,
"text": "Set in Java"
}
] |
Next Sentence Prediction using BERT
|
27 Jan, 2022
Pre-requisite: BERT-GFG
BERT stands for Bidirectional Representation for Transformers. It was proposed by researchers at Google Research in 2018. Although, the main aim of that was to improve the understanding of the meaning of queries related to Google Search. A study shows that Google encountered 15% of new queries every day. Therefore, it requires the Google search engine to have a much better understanding of the language in order to comprehend the search query.
However, BERT is trained on a variety of different tasks to improve the language understanding of the model. In this article, we will discuss the tasks under the next sentence prediction for BERT.
BERT is fine-tuned on 3 methods for the next sentence prediction task:
In the first type, we have sentences as input and there is only one class label output, such as for the following task:MNLI (Multi-Genre Natural Language Inference): It is a large-scale classification task. In this task, we have given a pair of sentences. The goal is to identify whether the second sentence is entailment, contradiction, or neutral with respect to the first sentence.QQP (Quora Question Pairs): In this dataset, the goal is to determine whether two questions are semantically equal.QNLI (Question Natural Language Inference): In this task, the model needs to determine whether the second sentence is the answer to the question asked in the first sentence.SWAG (Situations With Adversarial Generations): This dataset contains 113k sentence classifications. The task is to determine whether the second sentence is the continuation of the first or not.
MNLI (Multi-Genre Natural Language Inference): It is a large-scale classification task. In this task, we have given a pair of sentences. The goal is to identify whether the second sentence is entailment, contradiction, or neutral with respect to the first sentence.
QQP (Quora Question Pairs): In this dataset, the goal is to determine whether two questions are semantically equal.
QNLI (Question Natural Language Inference): In this task, the model needs to determine whether the second sentence is the answer to the question asked in the first sentence.
SWAG (Situations With Adversarial Generations): This dataset contains 113k sentence classifications. The task is to determine whether the second sentence is the continuation of the first or not.
BERT architecture first type
In the second type, we have only one sentence as input, but the output is similar to the next class label. Following are the task/datasets used for it:SST-2 (The Stanford Sentiment Treebank): It is a binary sentence classification task consisting of sentences extracted from movie reviews with annotations of their sentiment representing in the sentence. BERT generated state-of-the-art results on SST-2.CoLA: (Corpus of Linguistic Acceptability): is the binary classification task. The goal of this task to predict whether an English sentence that is provided is linguistically acceptable or not.
SST-2 (The Stanford Sentiment Treebank): It is a binary sentence classification task consisting of sentences extracted from movie reviews with annotations of their sentiment representing in the sentence. BERT generated state-of-the-art results on SST-2.
CoLA: (Corpus of Linguistic Acceptability): is the binary classification task. The goal of this task to predict whether an English sentence that is provided is linguistically acceptable or not.
BERT architecture second type
In the third type of next sentence, prediction, we have been provided with a question and paragraph and outputs a sentence from the paragraph that is the answer to that question. It is performed on SQuAD (Stanford Question Answer D) v1.1 and 2.0 datasets.
BERT architecture 3rd type.
In the above architecture, the [CLS] token is the first token in the input. This means an input sentence is coming, the [SEP] represents the separation between the different inputs. Here, the inputs sentence are tokenized according to BERT vocab, and output is also tokenized.
In this implementation, we will be using the Quora Insincere question dataset in which we have some question which may contain profanity, foul-language hatred, etc. We will be using BERT from TF-dev.
Python3
# Check if there is GPU or not!nvidia-smi# Install tensorflow 2.3.0!pip install -q tensorflow==2.3.0# Clone the TensorFlow models Repo!git clone --depth 1 -b v2.3.0 https://github.com/tensorflow/models.git!pip install -Uqr models/official/requirements.txt# Importsimport sysimport numpy as npimport tensorflow as tfimport tensorflow_hub as hubsys.path.append('models')from official.nlp.data import classifier_data_libfrom official.nlp.bert import tokenizationfrom official.nlp import optimization # keras importsfrom tf.keras.layers import Input, Dropout, Densefrom tf.keras.optimizers import Adamfrom tf.keras.metrics import BinaryAccuracyfrom tf.keras.losses import BinaryCrossentropyfrom tf.keras.utils import plot_modelfrom tf.keras.models import Model# Load the Quora Insincrere QUesrtion dataset.df = pd.read_csv( 'https://archive.org/download/fine-tune-bert-tensorflow-train.csv/train.csv.zip', compression='zip')df.head()# plot the histogram of sincere and insincere question vs sincere quesdf.target.plot(kind='hist', title='Sincere (0) vs Insincere (1) distribution')
qid question_text target
000002165364db923c7e6 How did Quebec nationalists see their province...0
1000032939017120e6e44 Do you have an adopted dog, how would you enco...0
20000412ca6e4628ce2cf Why does velocity affect time? Does velocity a...0
3000042bf85aa498cd78e How did Otto von Guericke used the Magdeburg h...0
40000455dfa3e01eae3af Can I convert montra helicon D to a mountain b...0
Sincere vs Insincere
In the code below, we will be using only 1% of data to fine-tune our Bert model (about 13,000 examples), we will be also converting the data into the format required by BERT and to use eager execution, we use a python wrapper. Before doing this, we need to tokenize the dataset using the vocabulary of BERT.
Bert Classification task
Python3
# split into train and validationtrain_df, remaining = train_test_split(df, train_size=0.01, stratify=df.target.values)valid_df, _ = train_test_split(remaining, train_size=0.001, stratify=remaining.target.values)train_df.shape, valid_df.shape # import for processing datasetfrom tf.data.Dataset import from_tensor_slicesfrom tf.data.experimental import AUTOTUNE # convert dataset into tensor sliceswith tf.device('/cpu:0'): train_data =from_tensor_slices((train_df.question_text.values, train_df.target.values)) valid_data = from_tensor_slices((valid_df.question_text.values, valid_df.target.values)) for text, label in train_data.take(2): print(text) print(label) label_list = [0, 1] # Label categoriesmax_seq_length = 128 # maximum length of input sequencestrain_batch_size = 32 # Get BERT layer and tokenizer:bert_layer = hub.KerasLayer( "https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/2", trainable=True)vocab_file = bert_layer.resolved_object.vocab_file.asset_path.numpy()do_lower_case = bert_layer.resolved_object.do_lower_case.numpy()tokenizer = tokenization.FullTokenizer(vocab_file, do_lower_case) # example# convert to tokens ids andtokenizer.convert_tokens_to_ids( tokenizer.wordpiece_tokenizer.tokenize('how are you?')) # convert the dataset into the format required by BERT i.e we convert the row into# input features (Token id, input mask, input type id ) and labels def convert_to_bert_feature(text, label, label_list=label_list, max_seq_length=max_seq_length, tokenizer=tokenizer): example = classifier_data_lib.InputExample(guid = None, text_a = text.numpy(), text_b = None, label = label.numpy()) feature = classifier_data_lib.convert_single_example(0, example, label_list, max_seq_length, tokenizer) return (feature.input_ids, feature.input_mask, feature.segment_ids, feature.label_id) # wrap the dataset around the python function in order to use the tf# datasets map functiondef to_bert_feature_map(text, label): input_ids, input_mask, segment_ids, label_id = tf.py_function( convert_to_bert_feature, inp=[text, label], Tout=[tf.int32, tf.int32, tf.int32, tf.int32]) # py_func doesn't set the shape of the returned tensors. input_ids.set_shape([max_seq_length]) input_mask.set_shape([max_seq_length]) segment_ids.set_shape([max_seq_length]) label_id.set_shape([]) x = { 'input_word_ids': input_ids, 'input_mask': input_mask, 'input_type_ids': segment_ids } return (x, label_id)with tf.device('/cpu:0'): # train train_data = (train_data.map(to_bert_feature_map, num_parallel_calls=AUTOTUNE) #.cache() .shuffle(1000) .batch(32, drop_remainder=True) .prefetch(AUTOTUNE)) # valid valid_data = (valid_data.map(to_bert_feature_map, num_parallel_calls=AUTOTUNE) .batch(32, drop_remainder=True) .prefetch(AUTOTUNE)) # example format train and valid dataprint("train data format",train_data.element_spec)print("validation data format",valid_data.element_spec)
((13061, 3), (1293, 3))
#printed an example
tf.Tensor(b'What is your experience living in Venezuela in the current crisis? (2018)', shape=(), dtype=string)
tf.Tensor(0, shape=(), dtype=int64)
# converted to tokens
['how', 'are', 'you', '?']
[2129, 2024, 2017, 29632]
# train and validation data
# train
({'input_mask': TensorSpec(shape=(32, 128), dtype=tf.int32, name=None),
'input_type_ids': TensorSpec(shape=(32, 128), dtype=tf.int32, name=None),
'input_word_ids': TensorSpec(shape=(32, 128), dtype=tf.int32, name=None)},
TensorSpec(shape=(32,), dtype=tf.int32, name=None))
# validation
({'input_mask': TensorSpec(shape=(32, 128), dtype=tf.int32, name=None),
'input_type_ids': TensorSpec(shape=(32, 128), dtype=tf.int32, name=None),
'input_word_ids': TensorSpec(shape=(32, 128), dtype=tf.int32, name=None)},
TensorSpec(shape=(32,), dtype=tf.int32, name=None))
In this step, we will wrap the BERT layer around the Keras model and fine-tune it for 4 epochs, and plot the accuracy.
Python3
# define the keras model# Building the modeldef fine_tuned_model(): input_word_ids = Input(shape=(max_seq_length,), dtype=tf.int32, name="input_word_ids") input_mask = Input(shape=(max_seq_length,), dtype=tf.int32, name="input_mask") input_type_ids = Input(shape=(max_seq_length,), dtype=tf.int32, name="input_type_ids") pooled_output, sequence_output = bert_layer([input_word_ids, input_mask, input_type_ids]) drop = Dropout(0.4)(pooled_output) output = Dense(1, activation="sigmoid", name="output")(drop) model = Model( inputs={ 'input_word_ids': input_word_ids, 'input_mask': input_mask, 'input_type_ids': input_type_ids }, outputs=output) return model #compile the modelmodel = fine_tuned_model()model.compile(optimizer=Adam(learning_rate=2e-5), loss=BinaryCrossentropy(), metrics=[BinaryAccuracy()])model.summary()#plot the modelplot_model(model=model, show_shapes=True)# Train modelepochs = 4history = model.fit(train_data, validation_data=valid_data, epochs=epochs, verbose=1)# plot the accuracydef plot_graphs(history, metric): plt.plot(history.history[metric]) plt.plot(history.history['val_'+metric], '') plt.xlabel("Epochs") plt.ylabel(metric) plt.legend([metric, 'val_'+metric]) plt.show()plot_graphs(history, 'binary_accuracy')
Model: "functional_1"
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
input_word_ids (InputLayer) [(None, 128)] 0
__________________________________________________________________________________________________
input_mask (InputLayer) [(None, 128)] 0
__________________________________________________________________________________________________
input_type_ids (InputLayer) [(None, 128)] 0
__________________________________________________________________________________________________
keras_layer (KerasLayer) [(None, 768), (None, 109482241 input_word_ids[0][0]
input_mask[0][0]
input_type_ids[0][0]
__________________________________________________________________________________________________
dropout (Dropout) (None, 768) 0 keras_layer[0][0]
__________________________________________________________________________________________________
output (Dense) (None, 1) 769 dropout[0][0]
==================================================================================================
Total params: 109,483,010
Trainable params: 109,483,009
Non-trainable params: 1
__________________________________________________________________________________________________
Keras model
Plot of Binary Accuracy
Python3
# checktest_eg=['what is the current marketprice of petroleum?', 'who is Oswald?', 'why are you here idiot ?']test_data =from_tensor_slices((test_eg, [0]*len(test_eg)))# wrap test data into BERT formattest_data = (test_data.map(to_feature_map_bert).batch(1))preds = model.predict(test_data)print(preds)['Insincere' if pred >=0.5 else 'Sincere' for pred in preds]
[[1.3862031e-05]
[6.7259348e-04]
[8.9223766e-01]]
['Sincere', 'Sincere', 'Insincere']
Coursera Fine Tune Bert Using TF
as5853535
simmytarika5
Natural-language-processing
Machine Learning
Python
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": 52,
"s": 28,
"text": "Pre-requisite: BERT-GFG"
},
{
"code": null,
"e": 500,
"s": 52,
"text": "BERT stands for Bidirectional Representation for Transformers. It was proposed by researchers at Google Research in 2018. Although, the main aim of that was to improve the understanding of the meaning of queries related to Google Search. A study shows that Google encountered 15% of new queries every day. Therefore, it requires the Google search engine to have a much better understanding of the language in order to comprehend the search query. "
},
{
"code": null,
"e": 697,
"s": 500,
"text": "However, BERT is trained on a variety of different tasks to improve the language understanding of the model. In this article, we will discuss the tasks under the next sentence prediction for BERT."
},
{
"code": null,
"e": 768,
"s": 697,
"text": "BERT is fine-tuned on 3 methods for the next sentence prediction task:"
},
{
"code": null,
"e": 1635,
"s": 768,
"text": "In the first type, we have sentences as input and there is only one class label output, such as for the following task:MNLI (Multi-Genre Natural Language Inference): It is a large-scale classification task. In this task, we have given a pair of sentences. The goal is to identify whether the second sentence is entailment, contradiction, or neutral with respect to the first sentence.QQP (Quora Question Pairs): In this dataset, the goal is to determine whether two questions are semantically equal.QNLI (Question Natural Language Inference): In this task, the model needs to determine whether the second sentence is the answer to the question asked in the first sentence.SWAG (Situations With Adversarial Generations): This dataset contains 113k sentence classifications. The task is to determine whether the second sentence is the continuation of the first or not."
},
{
"code": null,
"e": 1901,
"s": 1635,
"text": "MNLI (Multi-Genre Natural Language Inference): It is a large-scale classification task. In this task, we have given a pair of sentences. The goal is to identify whether the second sentence is entailment, contradiction, or neutral with respect to the first sentence."
},
{
"code": null,
"e": 2017,
"s": 1901,
"text": "QQP (Quora Question Pairs): In this dataset, the goal is to determine whether two questions are semantically equal."
},
{
"code": null,
"e": 2191,
"s": 2017,
"text": "QNLI (Question Natural Language Inference): In this task, the model needs to determine whether the second sentence is the answer to the question asked in the first sentence."
},
{
"code": null,
"e": 2386,
"s": 2191,
"text": "SWAG (Situations With Adversarial Generations): This dataset contains 113k sentence classifications. The task is to determine whether the second sentence is the continuation of the first or not."
},
{
"code": null,
"e": 2415,
"s": 2386,
"text": "BERT architecture first type"
},
{
"code": null,
"e": 3013,
"s": 2415,
"text": "In the second type, we have only one sentence as input, but the output is similar to the next class label. Following are the task/datasets used for it:SST-2 (The Stanford Sentiment Treebank): It is a binary sentence classification task consisting of sentences extracted from movie reviews with annotations of their sentiment representing in the sentence. BERT generated state-of-the-art results on SST-2.CoLA: (Corpus of Linguistic Acceptability): is the binary classification task. The goal of this task to predict whether an English sentence that is provided is linguistically acceptable or not."
},
{
"code": null,
"e": 3267,
"s": 3013,
"text": "SST-2 (The Stanford Sentiment Treebank): It is a binary sentence classification task consisting of sentences extracted from movie reviews with annotations of their sentiment representing in the sentence. BERT generated state-of-the-art results on SST-2."
},
{
"code": null,
"e": 3461,
"s": 3267,
"text": "CoLA: (Corpus of Linguistic Acceptability): is the binary classification task. The goal of this task to predict whether an English sentence that is provided is linguistically acceptable or not."
},
{
"code": null,
"e": 3491,
"s": 3461,
"text": "BERT architecture second type"
},
{
"code": null,
"e": 3747,
"s": 3491,
"text": "In the third type of next sentence, prediction, we have been provided with a question and paragraph and outputs a sentence from the paragraph that is the answer to that question. It is performed on SQuAD (Stanford Question Answer D) v1.1 and 2.0 datasets."
},
{
"code": null,
"e": 3775,
"s": 3747,
"text": "BERT architecture 3rd type."
},
{
"code": null,
"e": 4052,
"s": 3775,
"text": "In the above architecture, the [CLS] token is the first token in the input. This means an input sentence is coming, the [SEP] represents the separation between the different inputs. Here, the inputs sentence are tokenized according to BERT vocab, and output is also tokenized."
},
{
"code": null,
"e": 4252,
"s": 4052,
"text": "In this implementation, we will be using the Quora Insincere question dataset in which we have some question which may contain profanity, foul-language hatred, etc. We will be using BERT from TF-dev."
},
{
"code": null,
"e": 4260,
"s": 4252,
"text": "Python3"
},
{
"code": "# Check if there is GPU or not!nvidia-smi# Install tensorflow 2.3.0!pip install -q tensorflow==2.3.0# Clone the TensorFlow models Repo!git clone --depth 1 -b v2.3.0 https://github.com/tensorflow/models.git!pip install -Uqr models/official/requirements.txt# Importsimport sysimport numpy as npimport tensorflow as tfimport tensorflow_hub as hubsys.path.append('models')from official.nlp.data import classifier_data_libfrom official.nlp.bert import tokenizationfrom official.nlp import optimization # keras importsfrom tf.keras.layers import Input, Dropout, Densefrom tf.keras.optimizers import Adamfrom tf.keras.metrics import BinaryAccuracyfrom tf.keras.losses import BinaryCrossentropyfrom tf.keras.utils import plot_modelfrom tf.keras.models import Model# Load the Quora Insincrere QUesrtion dataset.df = pd.read_csv( 'https://archive.org/download/fine-tune-bert-tensorflow-train.csv/train.csv.zip', compression='zip')df.head()# plot the histogram of sincere and insincere question vs sincere quesdf.target.plot(kind='hist', title='Sincere (0) vs Insincere (1) distribution')",
"e": 5355,
"s": 4260,
"text": null
},
{
"code": null,
"e": 5745,
"s": 5355,
"text": "qid question_text target\n000002165364db923c7e6 How did Quebec nationalists see their province...0\n1000032939017120e6e44 Do you have an adopted dog, how would you enco...0\n20000412ca6e4628ce2cf Why does velocity affect time? Does velocity a...0\n3000042bf85aa498cd78e How did Otto von Guericke used the Magdeburg h...0\n40000455dfa3e01eae3af Can I convert montra helicon D to a mountain b...0"
},
{
"code": null,
"e": 5766,
"s": 5745,
"text": "Sincere vs Insincere"
},
{
"code": null,
"e": 6074,
"s": 5766,
"text": "In the code below, we will be using only 1% of data to fine-tune our Bert model (about 13,000 examples), we will be also converting the data into the format required by BERT and to use eager execution, we use a python wrapper. Before doing this, we need to tokenize the dataset using the vocabulary of BERT."
},
{
"code": null,
"e": 6099,
"s": 6074,
"text": "Bert Classification task"
},
{
"code": null,
"e": 6107,
"s": 6099,
"text": "Python3"
},
{
"code": "# split into train and validationtrain_df, remaining = train_test_split(df, train_size=0.01, stratify=df.target.values)valid_df, _ = train_test_split(remaining, train_size=0.001, stratify=remaining.target.values)train_df.shape, valid_df.shape # import for processing datasetfrom tf.data.Dataset import from_tensor_slicesfrom tf.data.experimental import AUTOTUNE # convert dataset into tensor sliceswith tf.device('/cpu:0'): train_data =from_tensor_slices((train_df.question_text.values, train_df.target.values)) valid_data = from_tensor_slices((valid_df.question_text.values, valid_df.target.values)) for text, label in train_data.take(2): print(text) print(label) label_list = [0, 1] # Label categoriesmax_seq_length = 128 # maximum length of input sequencestrain_batch_size = 32 # Get BERT layer and tokenizer:bert_layer = hub.KerasLayer( \"https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/2\", trainable=True)vocab_file = bert_layer.resolved_object.vocab_file.asset_path.numpy()do_lower_case = bert_layer.resolved_object.do_lower_case.numpy()tokenizer = tokenization.FullTokenizer(vocab_file, do_lower_case) # example# convert to tokens ids andtokenizer.convert_tokens_to_ids( tokenizer.wordpiece_tokenizer.tokenize('how are you?')) # convert the dataset into the format required by BERT i.e we convert the row into# input features (Token id, input mask, input type id ) and labels def convert_to_bert_feature(text, label, label_list=label_list, max_seq_length=max_seq_length, tokenizer=tokenizer): example = classifier_data_lib.InputExample(guid = None, text_a = text.numpy(), text_b = None, label = label.numpy()) feature = classifier_data_lib.convert_single_example(0, example, label_list, max_seq_length, tokenizer) return (feature.input_ids, feature.input_mask, feature.segment_ids, feature.label_id) # wrap the dataset around the python function in order to use the tf# datasets map functiondef to_bert_feature_map(text, label): input_ids, input_mask, segment_ids, label_id = tf.py_function( convert_to_bert_feature, inp=[text, label], Tout=[tf.int32, tf.int32, tf.int32, tf.int32]) # py_func doesn't set the shape of the returned tensors. input_ids.set_shape([max_seq_length]) input_mask.set_shape([max_seq_length]) segment_ids.set_shape([max_seq_length]) label_id.set_shape([]) x = { 'input_word_ids': input_ids, 'input_mask': input_mask, 'input_type_ids': segment_ids } return (x, label_id)with tf.device('/cpu:0'): # train train_data = (train_data.map(to_bert_feature_map, num_parallel_calls=AUTOTUNE) #.cache() .shuffle(1000) .batch(32, drop_remainder=True) .prefetch(AUTOTUNE)) # valid valid_data = (valid_data.map(to_bert_feature_map, num_parallel_calls=AUTOTUNE) .batch(32, drop_remainder=True) .prefetch(AUTOTUNE)) # example format train and valid dataprint(\"train data format\",train_data.element_spec)print(\"validation data format\",valid_data.element_spec)",
"e": 9659,
"s": 6107,
"text": null
},
{
"code": null,
"e": 10535,
"s": 9659,
"text": "((13061, 3), (1293, 3))\n\n#printed an example\ntf.Tensor(b'What is your experience living in Venezuela in the current crisis? (2018)', shape=(), dtype=string)\ntf.Tensor(0, shape=(), dtype=int64)\n\n# converted to tokens\n['how', 'are', 'you', '?']\n[2129, 2024, 2017, 29632]\n\n# train and validation data\n# train\n({'input_mask': TensorSpec(shape=(32, 128), dtype=tf.int32, name=None),\n 'input_type_ids': TensorSpec(shape=(32, 128), dtype=tf.int32, name=None),\n 'input_word_ids': TensorSpec(shape=(32, 128), dtype=tf.int32, name=None)},\n TensorSpec(shape=(32,), dtype=tf.int32, name=None))\n\n# validation\n({'input_mask': TensorSpec(shape=(32, 128), dtype=tf.int32, name=None),\n 'input_type_ids': TensorSpec(shape=(32, 128), dtype=tf.int32, name=None),\n 'input_word_ids': TensorSpec(shape=(32, 128), dtype=tf.int32, name=None)},\n TensorSpec(shape=(32,), dtype=tf.int32, name=None))"
},
{
"code": null,
"e": 10654,
"s": 10535,
"text": "In this step, we will wrap the BERT layer around the Keras model and fine-tune it for 4 epochs, and plot the accuracy."
},
{
"code": null,
"e": 10662,
"s": 10654,
"text": "Python3"
},
{
"code": "# define the keras model# Building the modeldef fine_tuned_model(): input_word_ids = Input(shape=(max_seq_length,), dtype=tf.int32, name=\"input_word_ids\") input_mask = Input(shape=(max_seq_length,), dtype=tf.int32, name=\"input_mask\") input_type_ids = Input(shape=(max_seq_length,), dtype=tf.int32, name=\"input_type_ids\") pooled_output, sequence_output = bert_layer([input_word_ids, input_mask, input_type_ids]) drop = Dropout(0.4)(pooled_output) output = Dense(1, activation=\"sigmoid\", name=\"output\")(drop) model = Model( inputs={ 'input_word_ids': input_word_ids, 'input_mask': input_mask, 'input_type_ids': input_type_ids }, outputs=output) return model #compile the modelmodel = fine_tuned_model()model.compile(optimizer=Adam(learning_rate=2e-5), loss=BinaryCrossentropy(), metrics=[BinaryAccuracy()])model.summary()#plot the modelplot_model(model=model, show_shapes=True)# Train modelepochs = 4history = model.fit(train_data, validation_data=valid_data, epochs=epochs, verbose=1)# plot the accuracydef plot_graphs(history, metric): plt.plot(history.history[metric]) plt.plot(history.history['val_'+metric], '') plt.xlabel(\"Epochs\") plt.ylabel(metric) plt.legend([metric, 'val_'+metric]) plt.show()plot_graphs(history, 'binary_accuracy')",
"e": 12182,
"s": 10662,
"text": null
},
{
"code": null,
"e": 14066,
"s": 12182,
"text": "Model: \"functional_1\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_word_ids (InputLayer) [(None, 128)] 0 \n__________________________________________________________________________________________________\ninput_mask (InputLayer) [(None, 128)] 0 \n__________________________________________________________________________________________________\ninput_type_ids (InputLayer) [(None, 128)] 0 \n__________________________________________________________________________________________________\nkeras_layer (KerasLayer) [(None, 768), (None, 109482241 input_word_ids[0][0] \n input_mask[0][0] \n input_type_ids[0][0] \n__________________________________________________________________________________________________\ndropout (Dropout) (None, 768) 0 keras_layer[0][0] \n__________________________________________________________________________________________________\noutput (Dense) (None, 1) 769 dropout[0][0] \n==================================================================================================\nTotal params: 109,483,010\nTrainable params: 109,483,009\nNon-trainable params: 1\n__________________________________________________________________________________________________"
},
{
"code": null,
"e": 14078,
"s": 14066,
"text": "Keras model"
},
{
"code": null,
"e": 14102,
"s": 14078,
"text": "Plot of Binary Accuracy"
},
{
"code": null,
"e": 14110,
"s": 14102,
"text": "Python3"
},
{
"code": "# checktest_eg=['what is the current marketprice of petroleum?', 'who is Oswald?', 'why are you here idiot ?']test_data =from_tensor_slices((test_eg, [0]*len(test_eg)))# wrap test data into BERT formattest_data = (test_data.map(to_feature_map_bert).batch(1))preds = model.predict(test_data)print(preds)['Insincere' if pred >=0.5 else 'Sincere' for pred in preds]",
"e": 14481,
"s": 14110,
"text": null
},
{
"code": null,
"e": 14572,
"s": 14484,
"text": "[[1.3862031e-05]\n [6.7259348e-04]\n [8.9223766e-01]]\n['Sincere', 'Sincere', 'Insincere']"
},
{
"code": null,
"e": 14605,
"s": 14572,
"text": "Coursera Fine Tune Bert Using TF"
},
{
"code": null,
"e": 14617,
"s": 14607,
"text": "as5853535"
},
{
"code": null,
"e": 14630,
"s": 14617,
"text": "simmytarika5"
},
{
"code": null,
"e": 14658,
"s": 14630,
"text": "Natural-language-processing"
},
{
"code": null,
"e": 14675,
"s": 14658,
"text": "Machine Learning"
},
{
"code": null,
"e": 14682,
"s": 14675,
"text": "Python"
},
{
"code": null,
"e": 14699,
"s": 14682,
"text": "Machine Learning"
}
] |
Find the k-th smallest divisor of a natural number N
|
27 May, 2021
You’re given a number N and a number K. Our task is to find the kth smallest divisor of N.Examples:
Input : N = 12, K = 5
Output : 6
The divisors of 12 after sorting are 1, 2, 3, 4, 6 and 12.
Where the value of 5th divisor is equal to 6.
Input : N = 16, K 2
Output : 2
Simple Approach: A simple approach is to run a loop from 1 to √N and find all factors of N and push them into a vector. Finally, sort the vector and print the K-th value from the vector.Note: Elements in the vector will not be sorted initially as we are pushing both factors (i) and (n/i). That is why it is needed to sort the vector before printing the K-th factor.Below is the implementation of the above approach :
C++
Java
Python3
C#
Javascript
// C++ program to find K-th smallest factor #include <bits/stdc++.h>using namespace std; // function to find the k'th divisorvoid findkth(int n, int k){ // initialize a vector v vector<long long> v; // store all the divisors // so the loop will needs to run till sqrt ( n ) for (int i = 1; i <= sqrt(n); i++) { if (n % i == 0) { v.push_back(i); if (i != sqrt(n)) v.push_back(n / i); } } // sort the vector in an increasing order sort(v.begin(), v.end()); // if k is greater than the size of vector // then no divisor can be possible if (k > v.size()) cout << "Doesn't Exist"; // else print the ( k - 1 )th value of vector else cout << v[k - 1];} // Driver codeint main(){ int n = 15, k = 2; findkth(n, k); return 0;}
// Java program to find K-th smallest factorimport java.util.*; class GFG{ // function to find the k'th divisorstatic void findkth(int n, int k){ // initialize a vector v Vector<Integer> v = new Vector<Integer>(); // store all the divisors // so the loop will needs to run till sqrt ( n ) for (int i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { v.add(i); if (i != Math.sqrt(n)) v.add(n / i); } } // sort the vector in an increasing order Collections.sort(v); // if k is greater than the size of vector // then no divisor can be possible if (k > v.size()) System.out.print("Doesn't Exist"); // else print the ( k - 1 )th value of vector else System.out.print(v.get(k - 1));} // Driver codepublic static void main(String[] args){ int n = 15, k = 2; findkth(n, k);}} // This code is contributed by 29AjayKumar
# Python3 program to find K-th smallest factorfrom math import sqrt # function to find the k'th divisordef findkth(n, k): # initialize a vector v v = [] # store all the divisors so the loop # will needs to run till sqrt ( n ) p = int(sqrt(n)) + 1 for i in range(1, p, 1): if (n % i == 0): v.append(i) if (i != sqrt(n)): v.append(n / i); # sort the vector in an increasing order v.sort(reverse = False) # if k is greater than the size of vector # then no divisor can be possible if (k > len(v)): print("Doesn't Exist") # else print the (k - 1)th # value of vector else: print(v[k - 1]) # Driver codeif __name__ == '__main__': n = 15 k = 2 findkth(n, k) # This code is contributed by# Surendra_Gangwar
// C# program to find K-th smallest factorusing System;using System.Collections.Generic; class GFG{ // function to find the k'th divisorstatic void findkth(int n, int k){ // initialize a vector v List<int> v = new List<int>(); // store all the divisors // so the loop will needs to run till sqrt ( n ) for (int i = 1; i <= Math.Sqrt(n); i++) { if (n % i == 0) { v.Add(i); if (i != Math.Sqrt(n)) v.Add(n / i); } } // sort the vector in an increasing order v.Sort(); // if k is greater than the size of vector // then no divisor can be possible if (k > v.Count) Console.Write("Doesn't Exist"); // else print the ( k - 1 )th value of vector else Console.Write(v[k - 1]);} // Driver codepublic static void Main(String[] args){ int n = 15, k = 2; findkth(n, k);}} // This code is contributed by PrinciRaj1992
<script>function findkth( n, k){ // initialize a vector v var v=[]; // store all the divisors // so the loop will needs to run till sqrt ( n ) for (var i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { v.push(i); if (i != Math.sqrt(n)) v.push(n / i); } } // sort the vector in an increasing order v.sort(function fun(a,b){ return a-b }); // if k is greater than the size of vector // then no divisor can be possible if (k > v.length) document.write("Doesn't Exist"); // else print the ( k - 1 )th value of vector else document.write( v[k - 1]);} var n = 15, k = 2; findkth(n, k); </script>
3
Time Complexity: √N log( √N )Efficient Approach: An efficient approach will be to store the factors in two separate vectors. That is, factors i will be stored in a separate vector and N/i will be stored in a separate vector for all i from 1 to √N. Now, if observed carefully, it can be seen that the first vector is already sorted in increasing order and the second vector is sorted in decreasing order. So, reverse the second vector and print the K-th element from either of the vectors in which it is lying.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the K-th smallest factor #include <bits/stdc++.h>using namespace std; // Function to find the k'th divisorvoid findkth ( int n, int k){ // initialize vectors v1 and v2 vector <int> v1; vector <int> v2; // store all the divisors in the two vectors // accordingly for( int i = 1 ; i <= sqrt( n ); i++ ) { if ( n % i == 0 ) { v1.push_back ( i ); if ( i != sqrt ( n ) ) v2.push_back ( n / i ); } } // reverse the vector v2 to sort it // in increasing order reverse(v2.begin(), v2.end()); // if k is greater than the size of vectors // then no divisor can be possible if ( k > (v1.size() + v2.size())) cout << "Doesn't Exist" ; // else print the ( k - 1 )th value of vector else { // If K is lying in first vector if(k <= v1.size()) cout<<v1[k-1]; // If K is lying in second vector else cout<<v2[k-v1.size()-1]; }} // Driver codeint main(){ int n = 15, k = 2; findkth ( n, k) ; return 0;}
// Java program to find the K-th smallest factorimport java.util.*; class GFG{ // Function to find the k'th divisorstatic void findkth ( int n, int k){ // initialize vectors v1 and v2 Vector<Integer> v1 = new Vector<Integer>(); Vector <Integer> v2 = new Vector<Integer>(); // store all the divisors in the two vectors // accordingly for( int i = 1 ; i <= Math.sqrt( n ); i++ ) { if ( n % i == 0 ) { v1.add ( i ); if ( i != Math.sqrt ( n ) ) v2.add ( n / i ); } } // reverse the vector v2 to sort it // in increasing order Collections.reverse(v2); // if k is greater than the size of vectors // then no divisor can be possible if ( k > (v1.size() + v2.size())) System.out.print("Doesn't Exist"); // else print the ( k - 1 )th value of vector else { // If K is lying in first vector if(k <= v1.size()) System.out.print(v1.get(k - 1)); // If K is lying in second vector else System.out.print(v2.get(k-v1.size() - 1)); }} // Driver codepublic static void main(String[] args){ int n = 15, k = 2; findkth ( n, k) ;}} // This code is contributed by PrinciRaj1992
# Python3 program to find the K-th# smallest factorimport math as mt # Function to find the k'th divisordef findkth (n, k): # initialize vectors v1 and v2 v1 = list() v2 = list() # store all the divisors in the # two vectors accordingly for i in range(1, mt.ceil(n**(.5))): if (n % i == 0): v1.append(i) if (i != mt.ceil(mt.sqrt(n))): v2.append(n // i) # reverse the vector v2 to sort it # in increasing order v2[::-1] # if k is greater than the size of vectors # then no divisor can be possible if ( k > (len(v1) + len(v2))): print("Doesn't Exist", end = "") # else print the ( k - 1 )th value of vector else: # If K is lying in first vector if(k <= len(v1)): print(v1[k - 1]) # If K is lying in second vector else: print(v2[k - len(v1) - 1]) # Driver coden = 15k = 2findkth (n, k) # This code is contributed by Mohit kumar
// C# program to find// the K-th smallest factorusing System;using System.Collections.Generic;class GFG{ // Function to find the k'th divisorstatic void findkth (int n, int k){ // initialize vectors v1 and v2 List<int> v1 = new List<int>(); List <int> v2 = new List<int>(); // store all the divisors in the // two vectors accordingly for(int i = 1; i <= Math.Sqrt(n); i++) { if (n % i == 0) { v1.Add (i); if (i != Math.Sqrt (n)) v2.Add (n / i); } } // reverse the vector v2 to sort it // in increasing order v2.Reverse(); // if k is greater than the // size of vectors then no // divisor can be possible if (k > (v1.Count + v2.Count)) Console.Write("Doesn't Exist"); // else print the (k - 1)th // value of vector else { // If K is lying in first vector if(k <= v1.Count) Console.Write(v1[k - 1]); // If K is lying in second vector else Console.Write(v2[k - v1.Count - 1]); }} // Driver codepublic static void Main(String[] args){ int n = 15, k = 2; findkth (n, k);}} // This code is contributed by gauravrajput1
<script>// Javascript program to find the K-th smallest factor // Function to find the k'th divisorfunction findkth ( n,k){ // initialize vectors v1 and v2 let v1 = []; let v2 = []; // store all the divisors in the two vectors // accordingly for( let i = 1 ; i <= Math.sqrt( n ); i++ ) { if ( n % i == 0 ) { v1.push ( i ); if ( i != Math.sqrt ( n ) ) v2.push ( n / i ); } } // reverse the vector v2 to sort it // in increasing order v2.reverse(); // if k is greater than the size of vectors // then no divisor can be possible if ( k > (v1.length + v2.length)) document.write("Doesn't Exist"); // else print the ( k - 1 )th value of vector else { // If K is lying in first vector if(k <= v1.length) document.write(v1[k - 1]); // If K is lying in second vector else document.write(v2[k-v1.length - 1]); }} // Driver codelet n = 15, k = 2;findkth ( n, k) ; // This code is contributed by unknown2108</script>
3
Time Complexity: √N
SURENDRA_GANGWAR
mohit kumar 29
princiraj1992
GauravRajput1
akshitsaxenaa09
unknown2108
cpp-vector
divisors
factor
number-theory
Sorting Quiz
Mathematical
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 May, 2021"
},
{
"code": null,
"e": 153,
"s": 52,
"text": "You’re given a number N and a number K. Our task is to find the kth smallest divisor of N.Examples: "
},
{
"code": null,
"e": 324,
"s": 153,
"text": "Input : N = 12, K = 5\nOutput : 6\nThe divisors of 12 after sorting are 1, 2, 3, 4, 6 and 12. \nWhere the value of 5th divisor is equal to 6.\n\nInput : N = 16, K 2\nOutput : 2"
},
{
"code": null,
"e": 744,
"s": 324,
"text": "Simple Approach: A simple approach is to run a loop from 1 to √N and find all factors of N and push them into a vector. Finally, sort the vector and print the K-th value from the vector.Note: Elements in the vector will not be sorted initially as we are pushing both factors (i) and (n/i). That is why it is needed to sort the vector before printing the K-th factor.Below is the implementation of the above approach : "
},
{
"code": null,
"e": 748,
"s": 744,
"text": "C++"
},
{
"code": null,
"e": 753,
"s": 748,
"text": "Java"
},
{
"code": null,
"e": 761,
"s": 753,
"text": "Python3"
},
{
"code": null,
"e": 764,
"s": 761,
"text": "C#"
},
{
"code": null,
"e": 775,
"s": 764,
"text": "Javascript"
},
{
"code": "// C++ program to find K-th smallest factor #include <bits/stdc++.h>using namespace std; // function to find the k'th divisorvoid findkth(int n, int k){ // initialize a vector v vector<long long> v; // store all the divisors // so the loop will needs to run till sqrt ( n ) for (int i = 1; i <= sqrt(n); i++) { if (n % i == 0) { v.push_back(i); if (i != sqrt(n)) v.push_back(n / i); } } // sort the vector in an increasing order sort(v.begin(), v.end()); // if k is greater than the size of vector // then no divisor can be possible if (k > v.size()) cout << \"Doesn't Exist\"; // else print the ( k - 1 )th value of vector else cout << v[k - 1];} // Driver codeint main(){ int n = 15, k = 2; findkth(n, k); return 0;}",
"e": 1610,
"s": 775,
"text": null
},
{
"code": "// Java program to find K-th smallest factorimport java.util.*; class GFG{ // function to find the k'th divisorstatic void findkth(int n, int k){ // initialize a vector v Vector<Integer> v = new Vector<Integer>(); // store all the divisors // so the loop will needs to run till sqrt ( n ) for (int i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { v.add(i); if (i != Math.sqrt(n)) v.add(n / i); } } // sort the vector in an increasing order Collections.sort(v); // if k is greater than the size of vector // then no divisor can be possible if (k > v.size()) System.out.print(\"Doesn't Exist\"); // else print the ( k - 1 )th value of vector else System.out.print(v.get(k - 1));} // Driver codepublic static void main(String[] args){ int n = 15, k = 2; findkth(n, k);}} // This code is contributed by 29AjayKumar",
"e": 2540,
"s": 1610,
"text": null
},
{
"code": "# Python3 program to find K-th smallest factorfrom math import sqrt # function to find the k'th divisordef findkth(n, k): # initialize a vector v v = [] # store all the divisors so the loop # will needs to run till sqrt ( n ) p = int(sqrt(n)) + 1 for i in range(1, p, 1): if (n % i == 0): v.append(i) if (i != sqrt(n)): v.append(n / i); # sort the vector in an increasing order v.sort(reverse = False) # if k is greater than the size of vector # then no divisor can be possible if (k > len(v)): print(\"Doesn't Exist\") # else print the (k - 1)th # value of vector else: print(v[k - 1]) # Driver codeif __name__ == '__main__': n = 15 k = 2 findkth(n, k) # This code is contributed by# Surendra_Gangwar",
"e": 3375,
"s": 2540,
"text": null
},
{
"code": "// C# program to find K-th smallest factorusing System;using System.Collections.Generic; class GFG{ // function to find the k'th divisorstatic void findkth(int n, int k){ // initialize a vector v List<int> v = new List<int>(); // store all the divisors // so the loop will needs to run till sqrt ( n ) for (int i = 1; i <= Math.Sqrt(n); i++) { if (n % i == 0) { v.Add(i); if (i != Math.Sqrt(n)) v.Add(n / i); } } // sort the vector in an increasing order v.Sort(); // if k is greater than the size of vector // then no divisor can be possible if (k > v.Count) Console.Write(\"Doesn't Exist\"); // else print the ( k - 1 )th value of vector else Console.Write(v[k - 1]);} // Driver codepublic static void Main(String[] args){ int n = 15, k = 2; findkth(n, k);}} // This code is contributed by PrinciRaj1992",
"e": 4305,
"s": 3375,
"text": null
},
{
"code": "<script>function findkth( n, k){ // initialize a vector v var v=[]; // store all the divisors // so the loop will needs to run till sqrt ( n ) for (var i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { v.push(i); if (i != Math.sqrt(n)) v.push(n / i); } } // sort the vector in an increasing order v.sort(function fun(a,b){ return a-b }); // if k is greater than the size of vector // then no divisor can be possible if (k > v.length) document.write(\"Doesn't Exist\"); // else print the ( k - 1 )th value of vector else document.write( v[k - 1]);} var n = 15, k = 2; findkth(n, k); </script>",
"e": 5006,
"s": 4305,
"text": null
},
{
"code": null,
"e": 5008,
"s": 5006,
"text": "3"
},
{
"code": null,
"e": 5570,
"s": 5008,
"text": "Time Complexity: √N log( √N )Efficient Approach: An efficient approach will be to store the factors in two separate vectors. That is, factors i will be stored in a separate vector and N/i will be stored in a separate vector for all i from 1 to √N. Now, if observed carefully, it can be seen that the first vector is already sorted in increasing order and the second vector is sorted in decreasing order. So, reverse the second vector and print the K-th element from either of the vectors in which it is lying.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 5574,
"s": 5570,
"text": "C++"
},
{
"code": null,
"e": 5579,
"s": 5574,
"text": "Java"
},
{
"code": null,
"e": 5587,
"s": 5579,
"text": "Python3"
},
{
"code": null,
"e": 5590,
"s": 5587,
"text": "C#"
},
{
"code": null,
"e": 5601,
"s": 5590,
"text": "Javascript"
},
{
"code": "// C++ program to find the K-th smallest factor #include <bits/stdc++.h>using namespace std; // Function to find the k'th divisorvoid findkth ( int n, int k){ // initialize vectors v1 and v2 vector <int> v1; vector <int> v2; // store all the divisors in the two vectors // accordingly for( int i = 1 ; i <= sqrt( n ); i++ ) { if ( n % i == 0 ) { v1.push_back ( i ); if ( i != sqrt ( n ) ) v2.push_back ( n / i ); } } // reverse the vector v2 to sort it // in increasing order reverse(v2.begin(), v2.end()); // if k is greater than the size of vectors // then no divisor can be possible if ( k > (v1.size() + v2.size())) cout << \"Doesn't Exist\" ; // else print the ( k - 1 )th value of vector else { // If K is lying in first vector if(k <= v1.size()) cout<<v1[k-1]; // If K is lying in second vector else cout<<v2[k-v1.size()-1]; }} // Driver codeint main(){ int n = 15, k = 2; findkth ( n, k) ; return 0;}",
"e": 6720,
"s": 5601,
"text": null
},
{
"code": "// Java program to find the K-th smallest factorimport java.util.*; class GFG{ // Function to find the k'th divisorstatic void findkth ( int n, int k){ // initialize vectors v1 and v2 Vector<Integer> v1 = new Vector<Integer>(); Vector <Integer> v2 = new Vector<Integer>(); // store all the divisors in the two vectors // accordingly for( int i = 1 ; i <= Math.sqrt( n ); i++ ) { if ( n % i == 0 ) { v1.add ( i ); if ( i != Math.sqrt ( n ) ) v2.add ( n / i ); } } // reverse the vector v2 to sort it // in increasing order Collections.reverse(v2); // if k is greater than the size of vectors // then no divisor can be possible if ( k > (v1.size() + v2.size())) System.out.print(\"Doesn't Exist\"); // else print the ( k - 1 )th value of vector else { // If K is lying in first vector if(k <= v1.size()) System.out.print(v1.get(k - 1)); // If K is lying in second vector else System.out.print(v2.get(k-v1.size() - 1)); }} // Driver codepublic static void main(String[] args){ int n = 15, k = 2; findkth ( n, k) ;}} // This code is contributed by PrinciRaj1992",
"e": 7998,
"s": 6720,
"text": null
},
{
"code": "# Python3 program to find the K-th# smallest factorimport math as mt # Function to find the k'th divisordef findkth (n, k): # initialize vectors v1 and v2 v1 = list() v2 = list() # store all the divisors in the # two vectors accordingly for i in range(1, mt.ceil(n**(.5))): if (n % i == 0): v1.append(i) if (i != mt.ceil(mt.sqrt(n))): v2.append(n // i) # reverse the vector v2 to sort it # in increasing order v2[::-1] # if k is greater than the size of vectors # then no divisor can be possible if ( k > (len(v1) + len(v2))): print(\"Doesn't Exist\", end = \"\") # else print the ( k - 1 )th value of vector else: # If K is lying in first vector if(k <= len(v1)): print(v1[k - 1]) # If K is lying in second vector else: print(v2[k - len(v1) - 1]) # Driver coden = 15k = 2findkth (n, k) # This code is contributed by Mohit kumar",
"e": 9044,
"s": 7998,
"text": null
},
{
"code": "// C# program to find// the K-th smallest factorusing System;using System.Collections.Generic;class GFG{ // Function to find the k'th divisorstatic void findkth (int n, int k){ // initialize vectors v1 and v2 List<int> v1 = new List<int>(); List <int> v2 = new List<int>(); // store all the divisors in the // two vectors accordingly for(int i = 1; i <= Math.Sqrt(n); i++) { if (n % i == 0) { v1.Add (i); if (i != Math.Sqrt (n)) v2.Add (n / i); } } // reverse the vector v2 to sort it // in increasing order v2.Reverse(); // if k is greater than the // size of vectors then no // divisor can be possible if (k > (v1.Count + v2.Count)) Console.Write(\"Doesn't Exist\"); // else print the (k - 1)th // value of vector else { // If K is lying in first vector if(k <= v1.Count) Console.Write(v1[k - 1]); // If K is lying in second vector else Console.Write(v2[k - v1.Count - 1]); }} // Driver codepublic static void Main(String[] args){ int n = 15, k = 2; findkth (n, k);}} // This code is contributed by gauravrajput1",
"e": 10136,
"s": 9044,
"text": null
},
{
"code": "<script>// Javascript program to find the K-th smallest factor // Function to find the k'th divisorfunction findkth ( n,k){ // initialize vectors v1 and v2 let v1 = []; let v2 = []; // store all the divisors in the two vectors // accordingly for( let i = 1 ; i <= Math.sqrt( n ); i++ ) { if ( n % i == 0 ) { v1.push ( i ); if ( i != Math.sqrt ( n ) ) v2.push ( n / i ); } } // reverse the vector v2 to sort it // in increasing order v2.reverse(); // if k is greater than the size of vectors // then no divisor can be possible if ( k > (v1.length + v2.length)) document.write(\"Doesn't Exist\"); // else print the ( k - 1 )th value of vector else { // If K is lying in first vector if(k <= v1.length) document.write(v1[k - 1]); // If K is lying in second vector else document.write(v2[k-v1.length - 1]); }} // Driver codelet n = 15, k = 2;findkth ( n, k) ; // This code is contributed by unknown2108</script>",
"e": 11261,
"s": 10136,
"text": null
},
{
"code": null,
"e": 11263,
"s": 11261,
"text": "3"
},
{
"code": null,
"e": 11286,
"s": 11265,
"text": "Time Complexity: √N "
},
{
"code": null,
"e": 11303,
"s": 11286,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 11318,
"s": 11303,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 11332,
"s": 11318,
"text": "princiraj1992"
},
{
"code": null,
"e": 11346,
"s": 11332,
"text": "GauravRajput1"
},
{
"code": null,
"e": 11362,
"s": 11346,
"text": "akshitsaxenaa09"
},
{
"code": null,
"e": 11374,
"s": 11362,
"text": "unknown2108"
},
{
"code": null,
"e": 11385,
"s": 11374,
"text": "cpp-vector"
},
{
"code": null,
"e": 11394,
"s": 11385,
"text": "divisors"
},
{
"code": null,
"e": 11401,
"s": 11394,
"text": "factor"
},
{
"code": null,
"e": 11415,
"s": 11401,
"text": "number-theory"
},
{
"code": null,
"e": 11428,
"s": 11415,
"text": "Sorting Quiz"
},
{
"code": null,
"e": 11441,
"s": 11428,
"text": "Mathematical"
},
{
"code": null,
"e": 11455,
"s": 11441,
"text": "number-theory"
},
{
"code": null,
"e": 11468,
"s": 11455,
"text": "Mathematical"
}
] |
Python | os.nice() method
|
27 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.
os.nice() method in Python is used to increment the process’s niceness by specified value.
Niceness or nice value is set of guidelines for the CPU to follow when a process wants to get CPU time in order to executes its job. The niceness of process range between -20 to 19 (both inclusive). A process with a lower niceness or nice value is given higher priority and more CPU time while a process with a higher nice value is given a lower priority and less CPU time.
Note: os.nice() method is only available on UNIX platforms. Any user can increase the niceness of the process but only a superuser can decrease the niceness of a process.Superuser means a root user or an administrative user who has all the permissions to run or execute any program in the operating system.
Syntax: os.nice(value)
Parameters:value: An integer value.The new niceness of the process will be calculated as new niceness = previous niceness + specified value
Return Type: This method returns an integer value which represents the new niceness of the process.
# Python program to explain os.nice() method # importing os module import os # Get the current nice value# of the processniceValue = os.nice(0) # Print the current nice value # of the processprint("Current nice value of the process:", niceValue) # Increase the niceness # of the processvalue = 5niceValue = os.nice(value)print("\nNiceness of the process increased") # Print the current nice value # of the processprint("\nCurrent nice value of the process:", niceValue) # Increase the niceness # of the processvalue = 10niceValue = os.nice(value)print("\nNiceness of the process increased") # Print the current nice value # of the processprint("\nCurrent nice value of the process:", niceValue) # Increase the niceness # of the processvalue = 10niceValue = os.nice(value)print("\nNiceness of the process increased") # Print the current nice value # of the processprint("\nCurrent nice value of the process:", niceValue) # The maximum possible niceness of a process# can be 19 so if niceness to be set exceeds# the maximum limit then it will set to # the maximum possible niceness i.e 19
Current nice value of the process: 0
Niceness of the process increased
Current nice value of the process: 5
Niceness of the process increased
Current nice value of the process: 15
Niceness of the process increased
Current nice value of the process: 19
# Python program to explain os.nice() method # importing os module import os # Note : Only a superuser can# decrease a process's niceness# so run the program as superuser# to avoid permission related error # Get the current nice value# of the processniceValue = os.nice(0) # Print the Current nice value # of the processprint("Current nice value of the process:", niceValue) # Decrease the niceness # of the processvalue = -5niceValue = os.nice(value)print("\nNiceness of the process decreased") # Print the current nice value # of the processprint("\nCurrent nice value of the process:", niceValue) # Decrease the niceness # of the current processvalue = -10niceValue = os.nice(value)print("\nNiceness of the process decreased") # Print the current nice value # of the processprint("\nCurrent nice value of the process:", niceValue) # Decrease the niceness # of the current processvalue = -15niceValue = os.nice(value)print("\nNiceness of the process decreased") # Print the current nice value # of the processprint("\nCurrent nice value of the process:", niceValue) # The minimum possible niceness of a process# can be -20 so if niceness to be set is # lower than the minimum limit then# it will set to the minimum possible# niceness i.e -20
Current nice value of the process: 0
Niceness of the process decreased
Current nice value of the process: -5
Niceness of the process decreased
Current nice value of the process: -15
Niceness of the process decreased
Current nice value of the process: -20
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jun, 2019"
},
{
"code": null,
"e": 247,
"s": 28,
"text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality."
},
{
"code": null,
"e": 442,
"s": 247,
"text": "All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system."
},
{
"code": null,
"e": 533,
"s": 442,
"text": "os.nice() method in Python is used to increment the process’s niceness by specified value."
},
{
"code": null,
"e": 907,
"s": 533,
"text": "Niceness or nice value is set of guidelines for the CPU to follow when a process wants to get CPU time in order to executes its job. The niceness of process range between -20 to 19 (both inclusive). A process with a lower niceness or nice value is given higher priority and more CPU time while a process with a higher nice value is given a lower priority and less CPU time."
},
{
"code": null,
"e": 1214,
"s": 907,
"text": "Note: os.nice() method is only available on UNIX platforms. Any user can increase the niceness of the process but only a superuser can decrease the niceness of a process.Superuser means a root user or an administrative user who has all the permissions to run or execute any program in the operating system."
},
{
"code": null,
"e": 1237,
"s": 1214,
"text": "Syntax: os.nice(value)"
},
{
"code": null,
"e": 1377,
"s": 1237,
"text": "Parameters:value: An integer value.The new niceness of the process will be calculated as new niceness = previous niceness + specified value"
},
{
"code": null,
"e": 1477,
"s": 1377,
"text": "Return Type: This method returns an integer value which represents the new niceness of the process."
},
{
"code": "# Python program to explain os.nice() method # importing os module import os # Get the current nice value# of the processniceValue = os.nice(0) # Print the current nice value # of the processprint(\"Current nice value of the process:\", niceValue) # Increase the niceness # of the processvalue = 5niceValue = os.nice(value)print(\"\\nNiceness of the process increased\") # Print the current nice value # of the processprint(\"\\nCurrent nice value of the process:\", niceValue) # Increase the niceness # of the processvalue = 10niceValue = os.nice(value)print(\"\\nNiceness of the process increased\") # Print the current nice value # of the processprint(\"\\nCurrent nice value of the process:\", niceValue) # Increase the niceness # of the processvalue = 10niceValue = os.nice(value)print(\"\\nNiceness of the process increased\") # Print the current nice value # of the processprint(\"\\nCurrent nice value of the process:\", niceValue) # The maximum possible niceness of a process# can be 19 so if niceness to be set exceeds# the maximum limit then it will set to # the maximum possible niceness i.e 19 ",
"e": 2584,
"s": 1477,
"text": null
},
{
"code": null,
"e": 2843,
"s": 2584,
"text": "Current nice value of the process: 0\n\nNiceness of the process increased\n\nCurrent nice value of the process: 5\n\nNiceness of the process increased\n\nCurrent nice value of the process: 15\n\nNiceness of the process increased\n\nCurrent nice value of the process: 19\n"
},
{
"code": "# Python program to explain os.nice() method # importing os module import os # Note : Only a superuser can# decrease a process's niceness# so run the program as superuser# to avoid permission related error # Get the current nice value# of the processniceValue = os.nice(0) # Print the Current nice value # of the processprint(\"Current nice value of the process:\", niceValue) # Decrease the niceness # of the processvalue = -5niceValue = os.nice(value)print(\"\\nNiceness of the process decreased\") # Print the current nice value # of the processprint(\"\\nCurrent nice value of the process:\", niceValue) # Decrease the niceness # of the current processvalue = -10niceValue = os.nice(value)print(\"\\nNiceness of the process decreased\") # Print the current nice value # of the processprint(\"\\nCurrent nice value of the process:\", niceValue) # Decrease the niceness # of the current processvalue = -15niceValue = os.nice(value)print(\"\\nNiceness of the process decreased\") # Print the current nice value # of the processprint(\"\\nCurrent nice value of the process:\", niceValue) # The minimum possible niceness of a process# can be -20 so if niceness to be set is # lower than the minimum limit then# it will set to the minimum possible# niceness i.e -20",
"e": 4105,
"s": 2843,
"text": null
},
{
"code": null,
"e": 4367,
"s": 4105,
"text": "Current nice value of the process: 0\n\nNiceness of the process decreased\n\nCurrent nice value of the process: -5\n\nNiceness of the process decreased\n\nCurrent nice value of the process: -15\n\nNiceness of the process decreased\n\nCurrent nice value of the process: -20\n"
},
{
"code": null,
"e": 4384,
"s": 4367,
"text": "python-os-module"
},
{
"code": null,
"e": 4391,
"s": 4384,
"text": "Python"
}
] |
Tailwind CSS Rotate
|
23 Mar, 2022
This class accepts lots of value in tailwind CSS in which all the properties are covered in class form. This class is used to rotate an element based on the given angle as an argument. The angle can be set in terms of degrees, radians, or turns. In CSS, we can do that by using the CSS rotate() function.
Rotate classes:
rotate-0: This class is for no rotation.
rotate-1: This class is used to rotate 1 degree clockwise.
rotate-2: This class is used to rotate 2 degrees clockwise.
rotate-3: This class is used to rotate 3 degrees clockwise.
rotate-6: This class is used to rotate 6 degrees clockwise.
rotate-12: This class is used to rotate 12 degrees clockwise.
rotate-45: This class is used to rotate 45 degrees clockwise.
rotate-90: This class is used to rotate 90 degrees clockwise.
rotate-180: This class is used to rotate 180 degrees clockwise.
-rotate-1: This class is used to rotate 1 degree anti-clockwise.
-rotate-2: This class is used to rotate 2 degrees anti-clockwise.
-rotate-3: This class is used to rotate 3 degrees anti-clockwise.
-rotate-6: This class is used to rotate 6 degrees anti-clockwise.
-rotate-12: This class is used to rotate 12 degrees anti-clockwise.
-rotate-45: This class is used to rotate 45 degrees anti-clockwise.
-rotate-90: This class is used to rotate 90 degrees anti-clockwise.
-rotate-180: This class is used to rotate 180 degrees anti-clockwise.
Syntax:
<element class="rotate-{degree}">...</element>
Example:
HTML
<!DOCTYPE html> <html> <head> <link href= "https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Rotate Class</b> <div class="bg-green-300 mx-16 p-4 justify-between grid grid-flow-col"> <div class="bg-no-repeat w-16 h-16 transform rotate-0" style= "background-image:url( https://media.geeksforgeeks.org/wp-content/uploads/20210222211217/Screenshot20210222211207.png)"> </div> <div class="bg-no-repeat w-16 h-16 transform rotate-45" style= "background-image:url( https://media.geeksforgeeks.org/wp-content/uploads/20210222211217/Screenshot20210222211207.png)"> </div> <div class="bg-no-repeat w-16 h-16 transform rotate-90" style="background-image:url( https://media.geeksforgeeks.org/wp-content/uploads/20210222211217/Screenshot20210222211207.png)"> </div> <div class="bg-no-repeat w-16 h-16 transform rotate-180" style="background-image:url( https://media.geeksforgeeks.org/wp-content/uploads/20210222211217/Screenshot20210222211207.png)"> </div> </div> </body> </html>
Output:
Tailwind CSS
Tailwind-Transforms
CSS
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": "\n23 Mar, 2022"
},
{
"code": null,
"e": 333,
"s": 28,
"text": "This class accepts lots of value in tailwind CSS in which all the properties are covered in class form. This class is used to rotate an element based on the given angle as an argument. The angle can be set in terms of degrees, radians, or turns. In CSS, we can do that by using the CSS rotate() function."
},
{
"code": null,
"e": 349,
"s": 333,
"text": "Rotate classes:"
},
{
"code": null,
"e": 390,
"s": 349,
"text": "rotate-0: This class is for no rotation."
},
{
"code": null,
"e": 449,
"s": 390,
"text": "rotate-1: This class is used to rotate 1 degree clockwise."
},
{
"code": null,
"e": 509,
"s": 449,
"text": "rotate-2: This class is used to rotate 2 degrees clockwise."
},
{
"code": null,
"e": 569,
"s": 509,
"text": "rotate-3: This class is used to rotate 3 degrees clockwise."
},
{
"code": null,
"e": 629,
"s": 569,
"text": "rotate-6: This class is used to rotate 6 degrees clockwise."
},
{
"code": null,
"e": 691,
"s": 629,
"text": "rotate-12: This class is used to rotate 12 degrees clockwise."
},
{
"code": null,
"e": 753,
"s": 691,
"text": "rotate-45: This class is used to rotate 45 degrees clockwise."
},
{
"code": null,
"e": 815,
"s": 753,
"text": "rotate-90: This class is used to rotate 90 degrees clockwise."
},
{
"code": null,
"e": 879,
"s": 815,
"text": "rotate-180: This class is used to rotate 180 degrees clockwise."
},
{
"code": null,
"e": 944,
"s": 879,
"text": "-rotate-1: This class is used to rotate 1 degree anti-clockwise."
},
{
"code": null,
"e": 1010,
"s": 944,
"text": "-rotate-2: This class is used to rotate 2 degrees anti-clockwise."
},
{
"code": null,
"e": 1076,
"s": 1010,
"text": "-rotate-3: This class is used to rotate 3 degrees anti-clockwise."
},
{
"code": null,
"e": 1142,
"s": 1076,
"text": "-rotate-6: This class is used to rotate 6 degrees anti-clockwise."
},
{
"code": null,
"e": 1210,
"s": 1142,
"text": "-rotate-12: This class is used to rotate 12 degrees anti-clockwise."
},
{
"code": null,
"e": 1278,
"s": 1210,
"text": "-rotate-45: This class is used to rotate 45 degrees anti-clockwise."
},
{
"code": null,
"e": 1346,
"s": 1278,
"text": "-rotate-90: This class is used to rotate 90 degrees anti-clockwise."
},
{
"code": null,
"e": 1416,
"s": 1346,
"text": "-rotate-180: This class is used to rotate 180 degrees anti-clockwise."
},
{
"code": null,
"e": 1424,
"s": 1416,
"text": "Syntax:"
},
{
"code": null,
"e": 1471,
"s": 1424,
"text": "<element class=\"rotate-{degree}\">...</element>"
},
{
"code": null,
"e": 1480,
"s": 1471,
"text": "Example:"
},
{
"code": null,
"e": 1485,
"s": 1480,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <link href= \"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Rotate Class</b> <div class=\"bg-green-300 mx-16 p-4 justify-between grid grid-flow-col\"> <div class=\"bg-no-repeat w-16 h-16 transform rotate-0\" style= \"background-image:url( https://media.geeksforgeeks.org/wp-content/uploads/20210222211217/Screenshot20210222211207.png)\"> </div> <div class=\"bg-no-repeat w-16 h-16 transform rotate-45\" style= \"background-image:url( https://media.geeksforgeeks.org/wp-content/uploads/20210222211217/Screenshot20210222211207.png)\"> </div> <div class=\"bg-no-repeat w-16 h-16 transform rotate-90\" style=\"background-image:url( https://media.geeksforgeeks.org/wp-content/uploads/20210222211217/Screenshot20210222211207.png)\"> </div> <div class=\"bg-no-repeat w-16 h-16 transform rotate-180\" style=\"background-image:url( https://media.geeksforgeeks.org/wp-content/uploads/20210222211217/Screenshot20210222211207.png)\"> </div> </div> </body> </html> ",
"e": 2836,
"s": 1485,
"text": null
},
{
"code": null,
"e": 2844,
"s": 2836,
"text": "Output:"
},
{
"code": null,
"e": 2857,
"s": 2844,
"text": "Tailwind CSS"
},
{
"code": null,
"e": 2877,
"s": 2857,
"text": "Tailwind-Transforms"
},
{
"code": null,
"e": 2881,
"s": 2877,
"text": "CSS"
},
{
"code": null,
"e": 2898,
"s": 2881,
"text": "Web Technologies"
}
] |
Machine Learning : Decision Tree using Spark For Layman | by Sandeep Khurana | Towards Data Science
|
We will go over the definition, intuition and algorithm of a Decision Tree in this article.
Then we will write our own code, without using any ML library (like tensorflow etc). This will give good understanding and hands on experience for implementing decision tree.
Definition from study.com
A decision tree is a graphical representation of possible solutions to a decision based on certain conditions. It’s called a decision tree because it starts with a single box (or root), which then branches off into a number of solutions, just like a tree.
Lets consider this data of some users visiting ecom website. Lets assume we know the profile of the users visiting the site like their age, job , credit_limit etc.
This table contains some sales records and the schema of the data is
First column is city where the purchaser was from.
The second column job indicates the job purchaser was doing.
Third column is credit limit of the person
Fourth column is the age of the purchaser
The last most important column indicates if the user ended up purchasing any item or not. ‘yes’ means the user bought an item and ‘no’ means user did not buy.
What we want to do it that based upon this data, we want to build a decision tree to further predict if any new user will end up buying any item or not on the website.
Lets look at the data and see which of the four factors (city, occupation, cc_limit and age) might be influencing the decision of user to buy or not.
Consider ‘age’, this property has different value for each row. Even for unique outputs — ‘yes’ and ‘no’ the values of this property are very random. So we can say age for sure is not the determining factor for user to buy the product.
But how can we prove mathematically that age is not a factor at least not a major factor in determining the outcome? Lets look at entropy.
Entropy is measure of randomness (or impurity). In the above sample, age is most random attribute.
But how do we measure the entropy? The formula to measure entropy is. This is also called Shannon Entropy
n is the number of values and
p is number of elements in the class divided by total elements.
Lets dig into details. Consider the column of our sample data above having the outcome values
The number of ‘yes’ (‘yes’ class) for this property (i.e. y) are = 4
The number of ‘no’ (‘no’ class ) are = 3
Total number of elements are = 7
p(0) is = number of elements in ‘yes’ class / Total number of elements = 4/7
p(1) is = number of elements in ‘no’ class / Total number of elements = 3/7
Entropy = ( — 4/7 * log2(4/7) — 3/7 * log2(3/7)) = ( — 0.57* — 0.81–0.43 * -1.22) = ( 0.4617 + 0.5246) = 0.9863
0.9863 is the entropy of the data.
Now we know the entropy of the dataset based upon the outcome, how do we mathematically find out most influential top level attribute which contributes to the decision. This will be root of the decision tree we are trying to build.
As discussed above, ‘age’ can not be the factor for any customer to decide buy decision as we are seeing people age is varying with almost each record. Too much varying’ness of the age makes it least factor in decision making so conversely the attribute whose varying ness is least would be the most influential attribute or rather the attribute which varies more inline with the outcome? Hint, its the latter. Lets see.
We already have entropy (impurity) of dataset which for above example is 0.9863. So, we do below to get the information gain for an attribute
Find out the entropy of each class in each attribute. Eg city has 2 classes in — Bangalore and Chennai in our example
Proportionate the entropy for each class wrt datasets classes.
For city attribute
(total records with Bangalore city / Total records) * Bangalore Entropy
(total records with Chennai city / Total records) * Chennai Entropy
Sum up above values for each class and subtract it from dataset’s entropy
Lets find out Bangalore city entropy. Check the records for Bangalore. 2 of these have ‘yes’ output and 1 has ‘no’ output. So, Bangalore entropy would be
Bangalore Entropy = -2/3log2(2⁄3) — 1/3log2(1⁄3) = 0.39 + 0.53 = 0.92
Similarly, Chennai Entropy = -2/2log2(2/2) — 2/2log2(2/2) = 0 (its fully uniform property, equal numbers of it belong to ‘yes’ and ‘no’ outcomes)
So, information gain of the city would be as discussed above = 0.9863 — { (3/7)*0.92 + 0 } = 0.592
Information gain for ‘job’ — 0.9863 — { 4/7 * Entropy of Employed + 2/7 * Entropy of the unemployed + }
Similarly we get the information gain for ‘credit_limit’ as well.
Lets add another attribute called ‘ownshouse’ which whose values are varying exactly the way output varies. So the dataset now looks like
‘owns house’ indicates if the customer owns a house or not. It has same values as the outcome attribute ‘y’. Lets fine the Info Gain for this attribute.
It has 2 classes ‘yes’ and ‘no’.
Entropy for ‘yes’ = — 4/4log2(4/4) — 0 (no item belonging to ‘no’ class) = 0
Entropy for ‘no’ = — 0–3/3log2(3/3) = 0
Information Gain for ‘ownshouse’ attribute = 0.9863–0 = 9.9863
What did just happen? Since this attribute’s ‘ownshouse’ values are varying exactly same as of the outcome then its information gain is same as the entropy of the dataset.
Once we have the information gain for attributes then
We get the attribute which has maximum information gain
Make that attribute as head of the tree
Get the values of that attribute and make these branches of this head e.g. lets assume “city” has maximum info gain (actually it does not max gain in out example but assume it for discussion sake).
Head will be city and its branches will be Bangalore and Chennai
In next iteration — remove city from the list of attributes.
For pending attributes, get the records which belong to city = Bangalore for each attribute for branch under Bangalore.
Calculate the Info Gain for attributes under Bangalore city , get the attribute with max gain and that becomes the node under Bangalore.
Keep doing it till either we exhaust all attributes or get entropy zero.
I have another example with code at the end which implements this logic for other dataset, so you can go over that to see how its implemented.
As mentioned above we stop when either
We have gone thru all the attributes or
Found attribute whose entropy is zero.
Actually in our sepecial case example, we had met the attribute which has entropy zero in the first iteration itself. That attribute was ‘ownshouse’.
We start hands on exercise from here. If you are not keen on coding then the article concludes for you here.
Tools used — pySpark, networkx python lib to visualize the decision tree
The code is on github as well at https://github.com/skhurana333/ml/blob/master/decision_tree/decision_tree_model_complex.py
Basically this datasets lists the conditions which impacts if a game of tennis can be played outside or not. The values of outlook, temperature, humidity and wind are described and outcome that the game was played or not under these conditions. We will build the decision tree now.
outlook;temp;humidity;wind;ySunny;Hot;High;Weak;noSunny;Hot;High;Strong;noOvercast;Hot;High;Weak;yesRain;Mild;High;Weak;yesRain;Cool;Normal;Weak;yesRain;Cool;Normal;Strong;noOvercast;Cool;Normal;Strong;yesSunny;Mild;High;Weak;noSunny;Cool;Normal;Weak;yesRain;Mild;Normal;Weak;yesSunny;Mild;Normal;Strong;yesOvercast;Mild;High;Strong;yesOvercast;Hot;Normal;Weak;yesRain;Mild;High;Strong;no
Lets assume the file having above data is saved at the location = /home/me/ml/practice/decision_tree/datasets/simple_dataset
We will go over the flow and the algorithm
Lets load the dataset.
data = sqlContext.read.format('com.databricks.spark.csv').option('header', 'true')\ .option('delimiter', ';') \ .load("/home/me/ml/practice/decision_tree/datasets/simple_dataset")
Since it contains header, we have set header as true in the option.
The delimiter is ;
And its in csv format.
We will register this as table as we will need to query this dataset with different where conditions.
data.registerTempTable('data')
Calculate the entropy of the dataset
Get the count of rows having outcome as ‘yes’ and ‘no’ . Below are pyspark queries
played = sqlContext.sql("select * from data WHERE y like '%y%' ").count()notplayed = sqlContext.sql("select * from data WHERE y like '%n%' ").count()
Since we need to get the information gain for each attribute and find the attribute with max info gain, so we will be applying same logic for info gain calculation for all attributes. Create ‘process_dataset’ function.
def process_dataset(excludedAttrs, data, played, notplayed, where_condition):
excludedAtttts will contain the list of attributes which are already processed so that we dont need to process again.
data is the spark dataframe for this file
played — count when match was played
notplayed — count when match was not played
Where_condition — condition used to select the data, as and when attributes are processed we will keep chaging this condition
Lets call this function from main function,
def main(): data = sqlContext.read.format('com.databricks.spark.csv').option('header', 'true')\ .option('delimiter', ';').load("/home/me/ml/practice/decision_tree/datasets/simple_dataset") data.registerTempTable('data') played = sqlContext.sql("select * from data WHERE y like '%y%' ").count() notplayed = sqlContext.sql("select * from data WHERE y like '%n%' ").count() process_dataset([], data, played, notplayed, '')
2) Processing Data
Process_dataset will calculate the entropy of dataset first and then get info gain for each attribute.
We will declare global level variable to store attributes’s info gain. And also will create directed graph to visualize the decision tree.
attr_name_info_gain = {}G = nx.DiGraph()
Lets also declare schema of the dataset. I have created 2 variables for storing the schema and types. You can create one if you wish and modify subsequent code accordingly.
attrs = ["outlook","temp","humidity","wind"]attrs_type = {"outlook":"string","temp":"string","humidity":"string","wind":"string"}
process_dataset function
def process_dataset(excludedAttrs, data, played, notplayed, where_condition): total_elements = played + notplayed subs_info = {"played" : played, "notplayed" : notplayed} entropy = calculate_entropy(total_elements, subs_info) print "entropy is " + str(entropy) global attr_name_info_gain attr_name_info_gain = dict() for attr in attrs: if attr not in excludedAttrs: get_attr_info_gain_data_prep(attr, data, entropy, total_elements, where_condition)
It calls calculate_entropy function and then for each attribute it calls get_attr_info_gain function.
3) Calculate_entropy function
def calculate_entropy(total_elements, elements_in_each_class): # for target set S having 2 class 0 and 1, the entropy is -p0logp0 -p1logp1 # here the log is of base 2 # elements_in_each_class is a dictionary where the key is class label and the # value is number of elements in that class keysInMap = list(elements_in_each_class.keys()) entropy = 0.0 for aKey in keysInMap: number_of_elements_in_class = elements_in_each_class.get(aKey) if number_of_elements_in_class == 0: continue ratio = number_of_elements_in_class/total_elements entropy = entropy - ratio * np.log2(ratio) return entropy
4) Attr info gain data preparation function
def get_attr_info_gain_data_prep(attr_name, data, entropy, total_elements, where_condition): if not where_condition: attr_grp_y = data.where(col('y') == 'yes').groupBy(attr_name).agg({"y": 'count'})\ .withColumnRenamed('count(y)','played_count') else: attr_grp_y = data.where(" y like '%yes%' " + where_condition).groupBy(attr_name).agg({"y": 'count'})\ .withColumnRenamed('count(y)','played_count') if not where_condition: attr_grp_n = data.where(col('y') == 'no').groupBy(attr_name).agg({"y": 'count'})\ .withColumnRenamed(attr_name,'n_' + attr_name)\ .withColumnRenamed('count(y)','not_played_count') else: attr_grp_n = data.where(" y like '%no%' " + where_condition).groupBy(attr_name).agg({"y": 'count'})\ .withColumnRenamed(attr_name,'n_' + attr_name)\ .withColumnRenamed('count(y)','not_played_count') joined_df = attr_grp_y.join(attr_grp_n, on = [col(attr_grp_y.columns[0]) == col(attr_grp_n.columns[0])], how='outer' )\ .withColumn("total", col(attr_grp_y.columns[0]) + col(attr_grp_n.columns[0]))\ .select(attr_grp_y.columns[0], attr_grp_y.columns[1],\ attr_grp_n.columns[1]) \ gain_for_attribute = calculate_info_gain(entropy, joined_df, total_elements) attr_name_info_gain[attr_name] = gain_for_attribute
Explanation of the function
It reads data from the file. As we build the tree, we will need to get data corresponding to that branch of the tree only. The ‘where_condition’ attribute will contain these predicates.
We group the records in the file which have outcome as ‘yes’ for the attribute names passed
For first time, the where_condition will be blank,
Second iteration onwards, after root of the tree is found, we will have where_condition
if not where_condition: attr_grp_y = data.where(col('y') == 'yes').groupBy(attr_name).agg({"y": 'count'})\ .withColumnRenamed('count(y)','played_count')else: attr_grp_y = data.where(" y like '%yes%' " + where_condition).groupBy(attr_name).agg({"y": 'count'})\ .withColumnRenamed('count(y)','played_count')
Similarly It groups the records in the file which have outcome as ‘no’ for the attribute names passed.
if not where_condition: attr_grp_n = data.where(col('y') == 'no').groupBy(attr_name).agg({"y": 'count'})\ .withColumnRenamed(attr_name,'n_' + attr_name)\ .withColumnRenamed('count(y)','not_played_count')else: attr_grp_n = data.where(" y like '%no%' " + where_condition).groupBy(attr_name).agg({"y": 'count'})\ .withColumnRenamed(attr_name,'n_' + attr_name)\ .withColumnRenamed('count(y)','not_played_count')
We rename the columns count(y) to played_count and count(n) to not_played_count
Rename the attr_name column for n
.withColumnRenamed(attr_name,'n_' + attr_name)\
Now we join these 2 dataframes, one having the count of ‘yes’ outcomes for this attribute and other having count of ‘no’ outcomes for same attribute
joined_df = attr_grp_y.join(attr_grp_n, on = [col(attr_grp_y.columns[0]) == col(attr_grp_n.columns[0])], how='outer' )\
We join on the attribute name. We need outer join as if an attribute does not has record for either ‘yes’ or ‘no’ outcome then we still want the present ‘yes or ‘no’ count.
Also, since we have the count of yes and no outcomes, we will need the total count also (total # of records having yes and no) to calculate the entropy. Hence we added a new column which has the total
.withColumn("total", col(attr_grp_y.columns[0]) + col(attr_grp_n.columns[0]))\
And we are not selecting the join column twice
.select(attr_grp_y.columns[0], attr_grp_y.columns[1],\ attr_grp_n.columns[1])
We did all this exercise to calculate the info gain for this particular attribute, so lets calculate that
gain_for_attribute = calculate_info_gain(entropy, joined_df, total_elements)
We will save info gain for this attribute in a global variable, attr_name_info_gain. We will later sort this dict to get the attr having max info gain. INvoked Calculate_info_gain function is described next.
gain_for_attribute = calculate_info_gain(entropy, joined_df, total_elements) # attr_name_info_gain[attr_name] = gain_for_attribute
5) Info gain function
def calculate_info_gain(entropy, joined_df, total_elements): attr_entropy = 0.0 for anAttributeData in joined_df.rdd.collect(): yes_class_count = anAttributeData[1] no_class_count = anAttributeData[2] if yes_class_count is None: yes_class_count = 0 elif no_class_count is None: no_class_count = 0 count_of_class = yes_class_count + no_class_count # do the summation part e.g. if age is 56, 60, 45 then its sum of entropy for each of these element classmap = {'y' : yes_class_count, 'n' : no_class_count} attr_entropy = attr_entropy + ((count_of_class / total_elements) *\ calculate_entropy(count_of_class, classmap)) gain = entropy - attr_entropy return gain
If you have read the earlier sections then this function is self explanatory
6) Coming back to main function again
We had done processing till this code line — ->”process_dataset([], data, played, notplayed, ‘’)”
def main(): data = sqlContext.read.format('com.databricks.spark.csv').option('header', 'true')\ .option('delimiter', ';').load("/home/me/ml/practice/decision_tree/datasets/simple_dataset") data.registerTempTable('data') played = sqlContext.sql("select * from data WHERE y like '%y%' ").count() notplayed = sqlContext.sql("select * from data WHERE y like '%n%' ").count() process_dataset([], data, played, notplayed, '') # sort by info gain sorted_by_info_gain = sorted(attr_name_info_gain.items(), key=operator.itemgetter(1), reverse=True) processed_attrs = [] max_gain_attr = sorted_by_info_gain[0][0] processed_attrs.append(max_gain_attr) build_tree(max_gain_attr, processed_attrs, data, '') nx.draw(G, with_labels=True) plt.show()
We sort the info gain function and get the attr having max gain, make that as root node. Now we call build tree function. This is last and important function.
The input to this method is name of the attribute having max info gain. This becomes root node for the tree. We want to get the distinct values of this attribute. These values will become branches of this node.
This function will build complete tree recursively.
def build_tree(max_gain_attr, processed_attrs, data, where_condition): attrValues = sqlContext.sql("select distinct " + max_gain_attr + " from data where 1==1 " + where_condition) orig_where_condition = where_condition for aValueForMaxGainAttr in attrValues.rdd.collect(): adistinct_value_for_attr = aValueForMaxGainAttr[0] G.add_edges_from([(max_gain_attr, adistinct_value_for_attr)]) if attrs_type[max_gain_attr] == "string": where_condition = str(orig_where_condition + " and " + max_gain_attr + "=='" + adistinct_value_for_attr + "'") else: where_condition = str(orig_where_condition + " and " + max_gain_attr + "==" + adistinct_value_for_attr) played_for_attr = sqlContext.sql("select * from data where y like '%yes%' " + where_condition).count() notplayed_for_attr = sqlContext.sql("select * from data where y like '%no%' " + where_condition).count() # if either has zero value then entropy for this attr will be zero and its the last attr in the tree leaf_values = [] if played_for_attr == 0 or notplayed_for_attr == 0: leaf_node = sqlContext.sql("select distinct y from data where 1==1 " + where_condition) for leaf_node_data in leaf_node.rdd.collect(): G.add_edges_from([(adistinct_value_for_attr, str(leaf_node_data[0]))]) continue process_dataset(processed_attrs, data, played_for_attr, notplayed_for_attr, where_condition) if not attr_name_info_gain: # we processed all attributes # attach leaf node leaf_node = sqlContext.sql("select distinct y from data where 1==1 " + where_condition) for leaf_node_data in leaf_node.rdd.collect(): G.add_edges_from([(adistinct_value_for_attr, str(leaf_node_data[0]))]) continue # we are done for this branch of tree # get the attr with max info gain under aValueForMaxGainAttr # sort by info gain sorted_by_info_gain = sorted(attr_name_info_gain.items(), key=operator.itemgetter(1), reverse=True) new_max_gain_attr = sorted_by_info_gain[0][0] if sorted_by_info_gain[0][1] == 0: # under this where condition, records dont have entropy leaf_node = sqlContext.sql("select distinct y from data where 1==1 " + where_condition) # there might be more than one leaf node for leaf_node_data in leaf_node.rdd.collect(): G.add_edges_from([(adistinct_value_for_attr, str(leaf_node_data[0]))]) continue # we are done for this branch of tree G.add_edges_from([(adistinct_value_for_attr, new_max_gain_attr)]) processed_attrs.append(new_max_gain_attr) build_tree(new_max_gain_attr, processed_attrs, data, where_condition)
Explanation
We want distinct values for the node.
attrValues = sqlContext.sql("select distinct " + max_gain_attr + " from data where 1==1 " + where_condition)
For each value for this node
for aValueForMaxGainAttr in attrValues.rdd.collect():
Get the attribute value under this iteration
adistinct_value_for_attr = aValueForMaxGainAttr[0]
Add this value as branch of the node
G.add_edges_from([(max_gain_attr, adistinct_value_for_attr)])
We need to get the data under this attribute value. If the tree is
And we are processing ‘Sunny’ value of the parent node then to proceed under same branch ( outlook -> sunny) we need to get data where outlook = sunny. So we add this as new where condition.
Also, if the attribute type is string when we need to add value under quotes and it is int type then we dont add quotes.
if attrs_type[max_gain_attr] == "string": where_condition = str(orig_where_condition + " and " + max_gain_attr + "=='" + adistinct_value_for_attr + "'") else: where_condition = str(orig_where_condition + " and " + max_gain_attr + "==" + adistinct_value_for_attr)
We will again find out the attr having max info gain from the list of attributes excluding the attributes which are already processed. So for this value of the parent attr we want to know how many records outcome as ‘yes’ and ‘no’
played_for_attr = sqlContext.sql("select * from data where y like '%yes%' " + where_condition).count()notplayed_for_attr = sqlContext.sql("select * from data where y like '%no%' " + where_condition).count()
As the comment states, if we get zero entropy value then we have reached the leaf node of this branch, we will just add the outcomes to the tree under this node.
# if either has zero value then entropy for this attr will be zero and its the last attr in the tree leaf_values = [] if played_for_attr == 0 or notplayed_for_attr == 0: leaf_node = sqlContext.sql("select distinct y from data where 1==1 " + where_condition) for leaf_node_data in leaf_node.rdd.collect(): G.add_edges_from([(adistinct_value_for_attr, str(leaf_node_data[0]))]) continue
If not then we keep processing. Code similar to below was already was processed in main function and explained. Maybe we should put that one iteration also as part of this recursion, let this be exercise for you.
process_dataset(processed_attrs, data, subscribed_for_attr, unsubscribed_for_attr, where_condition)if not attr_name_info_gain: # we processed all attributes # attach leaf node leaf_node = sqlContext.sql("select distinct y from data where 1==1 " + where_condition) for leaf_node_data in leaf_node.rdd.collect(): G.add_edges_from([(adistinct_value_for_attr, str(leaf_node_data[0]))]) continue # we are done for this branch of tree# get the attr with max info gain under aValueForMaxGainAttr# sort by info gainsorted_by_info_gain = sorted(attr_name_info_gain.items(), key=operator.itemgetter(1), reverse=True)new_max_gain_attr = sorted_by_info_gain[0][0]if sorted_by_info_gain[0][1] == 0: # under this where condition, records dont have entropy leaf_node = sqlContext.sql("select distinct y from data where 1==1 " + where_condition) # there might be more than one leaf node for leaf_node_data in leaf_node.rdd.collect(): G.add_edges_from([(adistinct_value_for_attr, str(leaf_node_data[0]))]) continue # we are done for this branch of treeG.add_edges_from([(adistinct_value_for_attr, new_max_gain_attr)])processed_attrs.append(new_max_gain_attr)build_tree(new_max_gain_attr, processed_attrs, data, where_condition)
Now if we last 2 lines of main function are executed then you can visually see the decision tree built :-)
nx.draw(G, with_labels=True)plt.show()
Enjoy !!! And if possible, provide the feedback about wrong spelling or any other such edit (have not done any review or proof reading), about algo, optimization etc.
|
[
{
"code": null,
"e": 264,
"s": 172,
"text": "We will go over the definition, intuition and algorithm of a Decision Tree in this article."
},
{
"code": null,
"e": 439,
"s": 264,
"text": "Then we will write our own code, without using any ML library (like tensorflow etc). This will give good understanding and hands on experience for implementing decision tree."
},
{
"code": null,
"e": 465,
"s": 439,
"text": "Definition from study.com"
},
{
"code": null,
"e": 721,
"s": 465,
"text": "A decision tree is a graphical representation of possible solutions to a decision based on certain conditions. It’s called a decision tree because it starts with a single box (or root), which then branches off into a number of solutions, just like a tree."
},
{
"code": null,
"e": 885,
"s": 721,
"text": "Lets consider this data of some users visiting ecom website. Lets assume we know the profile of the users visiting the site like their age, job , credit_limit etc."
},
{
"code": null,
"e": 954,
"s": 885,
"text": "This table contains some sales records and the schema of the data is"
},
{
"code": null,
"e": 1005,
"s": 954,
"text": "First column is city where the purchaser was from."
},
{
"code": null,
"e": 1066,
"s": 1005,
"text": "The second column job indicates the job purchaser was doing."
},
{
"code": null,
"e": 1109,
"s": 1066,
"text": "Third column is credit limit of the person"
},
{
"code": null,
"e": 1151,
"s": 1109,
"text": "Fourth column is the age of the purchaser"
},
{
"code": null,
"e": 1310,
"s": 1151,
"text": "The last most important column indicates if the user ended up purchasing any item or not. ‘yes’ means the user bought an item and ‘no’ means user did not buy."
},
{
"code": null,
"e": 1478,
"s": 1310,
"text": "What we want to do it that based upon this data, we want to build a decision tree to further predict if any new user will end up buying any item or not on the website."
},
{
"code": null,
"e": 1628,
"s": 1478,
"text": "Lets look at the data and see which of the four factors (city, occupation, cc_limit and age) might be influencing the decision of user to buy or not."
},
{
"code": null,
"e": 1864,
"s": 1628,
"text": "Consider ‘age’, this property has different value for each row. Even for unique outputs — ‘yes’ and ‘no’ the values of this property are very random. So we can say age for sure is not the determining factor for user to buy the product."
},
{
"code": null,
"e": 2003,
"s": 1864,
"text": "But how can we prove mathematically that age is not a factor at least not a major factor in determining the outcome? Lets look at entropy."
},
{
"code": null,
"e": 2102,
"s": 2003,
"text": "Entropy is measure of randomness (or impurity). In the above sample, age is most random attribute."
},
{
"code": null,
"e": 2208,
"s": 2102,
"text": "But how do we measure the entropy? The formula to measure entropy is. This is also called Shannon Entropy"
},
{
"code": null,
"e": 2238,
"s": 2208,
"text": "n is the number of values and"
},
{
"code": null,
"e": 2302,
"s": 2238,
"text": "p is number of elements in the class divided by total elements."
},
{
"code": null,
"e": 2396,
"s": 2302,
"text": "Lets dig into details. Consider the column of our sample data above having the outcome values"
},
{
"code": null,
"e": 2465,
"s": 2396,
"text": "The number of ‘yes’ (‘yes’ class) for this property (i.e. y) are = 4"
},
{
"code": null,
"e": 2506,
"s": 2465,
"text": "The number of ‘no’ (‘no’ class ) are = 3"
},
{
"code": null,
"e": 2539,
"s": 2506,
"text": "Total number of elements are = 7"
},
{
"code": null,
"e": 2616,
"s": 2539,
"text": "p(0) is = number of elements in ‘yes’ class / Total number of elements = 4/7"
},
{
"code": null,
"e": 2692,
"s": 2616,
"text": "p(1) is = number of elements in ‘no’ class / Total number of elements = 3/7"
},
{
"code": null,
"e": 2804,
"s": 2692,
"text": "Entropy = ( — 4/7 * log2(4/7) — 3/7 * log2(3/7)) = ( — 0.57* — 0.81–0.43 * -1.22) = ( 0.4617 + 0.5246) = 0.9863"
},
{
"code": null,
"e": 2839,
"s": 2804,
"text": "0.9863 is the entropy of the data."
},
{
"code": null,
"e": 3071,
"s": 2839,
"text": "Now we know the entropy of the dataset based upon the outcome, how do we mathematically find out most influential top level attribute which contributes to the decision. This will be root of the decision tree we are trying to build."
},
{
"code": null,
"e": 3492,
"s": 3071,
"text": "As discussed above, ‘age’ can not be the factor for any customer to decide buy decision as we are seeing people age is varying with almost each record. Too much varying’ness of the age makes it least factor in decision making so conversely the attribute whose varying ness is least would be the most influential attribute or rather the attribute which varies more inline with the outcome? Hint, its the latter. Lets see."
},
{
"code": null,
"e": 3634,
"s": 3492,
"text": "We already have entropy (impurity) of dataset which for above example is 0.9863. So, we do below to get the information gain for an attribute"
},
{
"code": null,
"e": 3752,
"s": 3634,
"text": "Find out the entropy of each class in each attribute. Eg city has 2 classes in — Bangalore and Chennai in our example"
},
{
"code": null,
"e": 3815,
"s": 3752,
"text": "Proportionate the entropy for each class wrt datasets classes."
},
{
"code": null,
"e": 3834,
"s": 3815,
"text": "For city attribute"
},
{
"code": null,
"e": 3906,
"s": 3834,
"text": "(total records with Bangalore city / Total records) * Bangalore Entropy"
},
{
"code": null,
"e": 3974,
"s": 3906,
"text": "(total records with Chennai city / Total records) * Chennai Entropy"
},
{
"code": null,
"e": 4048,
"s": 3974,
"text": "Sum up above values for each class and subtract it from dataset’s entropy"
},
{
"code": null,
"e": 4202,
"s": 4048,
"text": "Lets find out Bangalore city entropy. Check the records for Bangalore. 2 of these have ‘yes’ output and 1 has ‘no’ output. So, Bangalore entropy would be"
},
{
"code": null,
"e": 4272,
"s": 4202,
"text": "Bangalore Entropy = -2/3log2(2⁄3) — 1/3log2(1⁄3) = 0.39 + 0.53 = 0.92"
},
{
"code": null,
"e": 4418,
"s": 4272,
"text": "Similarly, Chennai Entropy = -2/2log2(2/2) — 2/2log2(2/2) = 0 (its fully uniform property, equal numbers of it belong to ‘yes’ and ‘no’ outcomes)"
},
{
"code": null,
"e": 4517,
"s": 4418,
"text": "So, information gain of the city would be as discussed above = 0.9863 — { (3/7)*0.92 + 0 } = 0.592"
},
{
"code": null,
"e": 4621,
"s": 4517,
"text": "Information gain for ‘job’ — 0.9863 — { 4/7 * Entropy of Employed + 2/7 * Entropy of the unemployed + }"
},
{
"code": null,
"e": 4687,
"s": 4621,
"text": "Similarly we get the information gain for ‘credit_limit’ as well."
},
{
"code": null,
"e": 4825,
"s": 4687,
"text": "Lets add another attribute called ‘ownshouse’ which whose values are varying exactly the way output varies. So the dataset now looks like"
},
{
"code": null,
"e": 4978,
"s": 4825,
"text": "‘owns house’ indicates if the customer owns a house or not. It has same values as the outcome attribute ‘y’. Lets fine the Info Gain for this attribute."
},
{
"code": null,
"e": 5011,
"s": 4978,
"text": "It has 2 classes ‘yes’ and ‘no’."
},
{
"code": null,
"e": 5088,
"s": 5011,
"text": "Entropy for ‘yes’ = — 4/4log2(4/4) — 0 (no item belonging to ‘no’ class) = 0"
},
{
"code": null,
"e": 5128,
"s": 5088,
"text": "Entropy for ‘no’ = — 0–3/3log2(3/3) = 0"
},
{
"code": null,
"e": 5191,
"s": 5128,
"text": "Information Gain for ‘ownshouse’ attribute = 0.9863–0 = 9.9863"
},
{
"code": null,
"e": 5363,
"s": 5191,
"text": "What did just happen? Since this attribute’s ‘ownshouse’ values are varying exactly same as of the outcome then its information gain is same as the entropy of the dataset."
},
{
"code": null,
"e": 5417,
"s": 5363,
"text": "Once we have the information gain for attributes then"
},
{
"code": null,
"e": 5473,
"s": 5417,
"text": "We get the attribute which has maximum information gain"
},
{
"code": null,
"e": 5513,
"s": 5473,
"text": "Make that attribute as head of the tree"
},
{
"code": null,
"e": 5711,
"s": 5513,
"text": "Get the values of that attribute and make these branches of this head e.g. lets assume “city” has maximum info gain (actually it does not max gain in out example but assume it for discussion sake)."
},
{
"code": null,
"e": 5776,
"s": 5711,
"text": "Head will be city and its branches will be Bangalore and Chennai"
},
{
"code": null,
"e": 5837,
"s": 5776,
"text": "In next iteration — remove city from the list of attributes."
},
{
"code": null,
"e": 5957,
"s": 5837,
"text": "For pending attributes, get the records which belong to city = Bangalore for each attribute for branch under Bangalore."
},
{
"code": null,
"e": 6094,
"s": 5957,
"text": "Calculate the Info Gain for attributes under Bangalore city , get the attribute with max gain and that becomes the node under Bangalore."
},
{
"code": null,
"e": 6167,
"s": 6094,
"text": "Keep doing it till either we exhaust all attributes or get entropy zero."
},
{
"code": null,
"e": 6310,
"s": 6167,
"text": "I have another example with code at the end which implements this logic for other dataset, so you can go over that to see how its implemented."
},
{
"code": null,
"e": 6349,
"s": 6310,
"text": "As mentioned above we stop when either"
},
{
"code": null,
"e": 6389,
"s": 6349,
"text": "We have gone thru all the attributes or"
},
{
"code": null,
"e": 6428,
"s": 6389,
"text": "Found attribute whose entropy is zero."
},
{
"code": null,
"e": 6578,
"s": 6428,
"text": "Actually in our sepecial case example, we had met the attribute which has entropy zero in the first iteration itself. That attribute was ‘ownshouse’."
},
{
"code": null,
"e": 6687,
"s": 6578,
"text": "We start hands on exercise from here. If you are not keen on coding then the article concludes for you here."
},
{
"code": null,
"e": 6760,
"s": 6687,
"text": "Tools used — pySpark, networkx python lib to visualize the decision tree"
},
{
"code": null,
"e": 6884,
"s": 6760,
"text": "The code is on github as well at https://github.com/skhurana333/ml/blob/master/decision_tree/decision_tree_model_complex.py"
},
{
"code": null,
"e": 7166,
"s": 6884,
"text": "Basically this datasets lists the conditions which impacts if a game of tennis can be played outside or not. The values of outlook, temperature, humidity and wind are described and outcome that the game was played or not under these conditions. We will build the decision tree now."
},
{
"code": null,
"e": 7555,
"s": 7166,
"text": "outlook;temp;humidity;wind;ySunny;Hot;High;Weak;noSunny;Hot;High;Strong;noOvercast;Hot;High;Weak;yesRain;Mild;High;Weak;yesRain;Cool;Normal;Weak;yesRain;Cool;Normal;Strong;noOvercast;Cool;Normal;Strong;yesSunny;Mild;High;Weak;noSunny;Cool;Normal;Weak;yesRain;Mild;Normal;Weak;yesSunny;Mild;Normal;Strong;yesOvercast;Mild;High;Strong;yesOvercast;Hot;Normal;Weak;yesRain;Mild;High;Strong;no"
},
{
"code": null,
"e": 7680,
"s": 7555,
"text": "Lets assume the file having above data is saved at the location = /home/me/ml/practice/decision_tree/datasets/simple_dataset"
},
{
"code": null,
"e": 7723,
"s": 7680,
"text": "We will go over the flow and the algorithm"
},
{
"code": null,
"e": 7746,
"s": 7723,
"text": "Lets load the dataset."
},
{
"code": null,
"e": 7926,
"s": 7746,
"text": "data = sqlContext.read.format('com.databricks.spark.csv').option('header', 'true')\\ .option('delimiter', ';') \\ .load(\"/home/me/ml/practice/decision_tree/datasets/simple_dataset\")"
},
{
"code": null,
"e": 7994,
"s": 7926,
"text": "Since it contains header, we have set header as true in the option."
},
{
"code": null,
"e": 8013,
"s": 7994,
"text": "The delimiter is ;"
},
{
"code": null,
"e": 8036,
"s": 8013,
"text": "And its in csv format."
},
{
"code": null,
"e": 8138,
"s": 8036,
"text": "We will register this as table as we will need to query this dataset with different where conditions."
},
{
"code": null,
"e": 8169,
"s": 8138,
"text": "data.registerTempTable('data')"
},
{
"code": null,
"e": 8206,
"s": 8169,
"text": "Calculate the entropy of the dataset"
},
{
"code": null,
"e": 8289,
"s": 8206,
"text": "Get the count of rows having outcome as ‘yes’ and ‘no’ . Below are pyspark queries"
},
{
"code": null,
"e": 8439,
"s": 8289,
"text": "played = sqlContext.sql(\"select * from data WHERE y like '%y%' \").count()notplayed = sqlContext.sql(\"select * from data WHERE y like '%n%' \").count()"
},
{
"code": null,
"e": 8658,
"s": 8439,
"text": "Since we need to get the information gain for each attribute and find the attribute with max info gain, so we will be applying same logic for info gain calculation for all attributes. Create ‘process_dataset’ function."
},
{
"code": null,
"e": 8736,
"s": 8658,
"text": "def process_dataset(excludedAttrs, data, played, notplayed, where_condition):"
},
{
"code": null,
"e": 8854,
"s": 8736,
"text": "excludedAtttts will contain the list of attributes which are already processed so that we dont need to process again."
},
{
"code": null,
"e": 8896,
"s": 8854,
"text": "data is the spark dataframe for this file"
},
{
"code": null,
"e": 8933,
"s": 8896,
"text": "played — count when match was played"
},
{
"code": null,
"e": 8977,
"s": 8933,
"text": "notplayed — count when match was not played"
},
{
"code": null,
"e": 9103,
"s": 8977,
"text": "Where_condition — condition used to select the data, as and when attributes are processed we will keep chaging this condition"
},
{
"code": null,
"e": 9147,
"s": 9103,
"text": "Lets call this function from main function,"
},
{
"code": null,
"e": 9585,
"s": 9147,
"text": "def main(): data = sqlContext.read.format('com.databricks.spark.csv').option('header', 'true')\\ .option('delimiter', ';').load(\"/home/me/ml/practice/decision_tree/datasets/simple_dataset\") data.registerTempTable('data') played = sqlContext.sql(\"select * from data WHERE y like '%y%' \").count() notplayed = sqlContext.sql(\"select * from data WHERE y like '%n%' \").count() process_dataset([], data, played, notplayed, '')"
},
{
"code": null,
"e": 9604,
"s": 9585,
"text": "2) Processing Data"
},
{
"code": null,
"e": 9707,
"s": 9604,
"text": "Process_dataset will calculate the entropy of dataset first and then get info gain for each attribute."
},
{
"code": null,
"e": 9846,
"s": 9707,
"text": "We will declare global level variable to store attributes’s info gain. And also will create directed graph to visualize the decision tree."
},
{
"code": null,
"e": 9887,
"s": 9846,
"text": "attr_name_info_gain = {}G = nx.DiGraph()"
},
{
"code": null,
"e": 10060,
"s": 9887,
"text": "Lets also declare schema of the dataset. I have created 2 variables for storing the schema and types. You can create one if you wish and modify subsequent code accordingly."
},
{
"code": null,
"e": 10190,
"s": 10060,
"text": "attrs = [\"outlook\",\"temp\",\"humidity\",\"wind\"]attrs_type = {\"outlook\":\"string\",\"temp\":\"string\",\"humidity\":\"string\",\"wind\":\"string\"}"
},
{
"code": null,
"e": 10215,
"s": 10190,
"text": "process_dataset function"
},
{
"code": null,
"e": 10694,
"s": 10215,
"text": "def process_dataset(excludedAttrs, data, played, notplayed, where_condition): total_elements = played + notplayed subs_info = {\"played\" : played, \"notplayed\" : notplayed} entropy = calculate_entropy(total_elements, subs_info) print \"entropy is \" + str(entropy) global attr_name_info_gain attr_name_info_gain = dict() for attr in attrs: if attr not in excludedAttrs: get_attr_info_gain_data_prep(attr, data, entropy, total_elements, where_condition)"
},
{
"code": null,
"e": 10796,
"s": 10694,
"text": "It calls calculate_entropy function and then for each attribute it calls get_attr_info_gain function."
},
{
"code": null,
"e": 10826,
"s": 10796,
"text": "3) Calculate_entropy function"
},
{
"code": null,
"e": 11468,
"s": 10826,
"text": "def calculate_entropy(total_elements, elements_in_each_class): # for target set S having 2 class 0 and 1, the entropy is -p0logp0 -p1logp1 # here the log is of base 2 # elements_in_each_class is a dictionary where the key is class label and the # value is number of elements in that class keysInMap = list(elements_in_each_class.keys()) entropy = 0.0 for aKey in keysInMap: number_of_elements_in_class = elements_in_each_class.get(aKey) if number_of_elements_in_class == 0: continue ratio = number_of_elements_in_class/total_elements entropy = entropy - ratio * np.log2(ratio) return entropy"
},
{
"code": null,
"e": 11512,
"s": 11468,
"text": "4) Attr info gain data preparation function"
},
{
"code": null,
"e": 12856,
"s": 11512,
"text": "def get_attr_info_gain_data_prep(attr_name, data, entropy, total_elements, where_condition): if not where_condition: attr_grp_y = data.where(col('y') == 'yes').groupBy(attr_name).agg({\"y\": 'count'})\\ .withColumnRenamed('count(y)','played_count') else: attr_grp_y = data.where(\" y like '%yes%' \" + where_condition).groupBy(attr_name).agg({\"y\": 'count'})\\ .withColumnRenamed('count(y)','played_count') if not where_condition: attr_grp_n = data.where(col('y') == 'no').groupBy(attr_name).agg({\"y\": 'count'})\\ .withColumnRenamed(attr_name,'n_' + attr_name)\\ .withColumnRenamed('count(y)','not_played_count') else: attr_grp_n = data.where(\" y like '%no%' \" + where_condition).groupBy(attr_name).agg({\"y\": 'count'})\\ .withColumnRenamed(attr_name,'n_' + attr_name)\\ .withColumnRenamed('count(y)','not_played_count') joined_df = attr_grp_y.join(attr_grp_n, on = [col(attr_grp_y.columns[0]) == col(attr_grp_n.columns[0])], how='outer' )\\ .withColumn(\"total\", col(attr_grp_y.columns[0]) + col(attr_grp_n.columns[0]))\\ .select(attr_grp_y.columns[0], attr_grp_y.columns[1],\\ attr_grp_n.columns[1]) \\ gain_for_attribute = calculate_info_gain(entropy, joined_df, total_elements) attr_name_info_gain[attr_name] = gain_for_attribute"
},
{
"code": null,
"e": 12884,
"s": 12856,
"text": "Explanation of the function"
},
{
"code": null,
"e": 13070,
"s": 12884,
"text": "It reads data from the file. As we build the tree, we will need to get data corresponding to that branch of the tree only. The ‘where_condition’ attribute will contain these predicates."
},
{
"code": null,
"e": 13162,
"s": 13070,
"text": "We group the records in the file which have outcome as ‘yes’ for the attribute names passed"
},
{
"code": null,
"e": 13213,
"s": 13162,
"text": "For first time, the where_condition will be blank,"
},
{
"code": null,
"e": 13301,
"s": 13213,
"text": "Second iteration onwards, after root of the tree is found, we will have where_condition"
},
{
"code": null,
"e": 13624,
"s": 13301,
"text": "if not where_condition: attr_grp_y = data.where(col('y') == 'yes').groupBy(attr_name).agg({\"y\": 'count'})\\ .withColumnRenamed('count(y)','played_count')else: attr_grp_y = data.where(\" y like '%yes%' \" + where_condition).groupBy(attr_name).agg({\"y\": 'count'})\\ .withColumnRenamed('count(y)','played_count')"
},
{
"code": null,
"e": 13727,
"s": 13624,
"text": "Similarly It groups the records in the file which have outcome as ‘no’ for the attribute names passed."
},
{
"code": null,
"e": 14164,
"s": 13727,
"text": "if not where_condition: attr_grp_n = data.where(col('y') == 'no').groupBy(attr_name).agg({\"y\": 'count'})\\ .withColumnRenamed(attr_name,'n_' + attr_name)\\ .withColumnRenamed('count(y)','not_played_count')else: attr_grp_n = data.where(\" y like '%no%' \" + where_condition).groupBy(attr_name).agg({\"y\": 'count'})\\ .withColumnRenamed(attr_name,'n_' + attr_name)\\ .withColumnRenamed('count(y)','not_played_count')"
},
{
"code": null,
"e": 14244,
"s": 14164,
"text": "We rename the columns count(y) to played_count and count(n) to not_played_count"
},
{
"code": null,
"e": 14278,
"s": 14244,
"text": "Rename the attr_name column for n"
},
{
"code": null,
"e": 14326,
"s": 14278,
"text": ".withColumnRenamed(attr_name,'n_' + attr_name)\\"
},
{
"code": null,
"e": 14475,
"s": 14326,
"text": "Now we join these 2 dataframes, one having the count of ‘yes’ outcomes for this attribute and other having count of ‘no’ outcomes for same attribute"
},
{
"code": null,
"e": 14595,
"s": 14475,
"text": "joined_df = attr_grp_y.join(attr_grp_n, on = [col(attr_grp_y.columns[0]) == col(attr_grp_n.columns[0])], how='outer' )\\"
},
{
"code": null,
"e": 14768,
"s": 14595,
"text": "We join on the attribute name. We need outer join as if an attribute does not has record for either ‘yes’ or ‘no’ outcome then we still want the present ‘yes or ‘no’ count."
},
{
"code": null,
"e": 14969,
"s": 14768,
"text": "Also, since we have the count of yes and no outcomes, we will need the total count also (total # of records having yes and no) to calculate the entropy. Hence we added a new column which has the total"
},
{
"code": null,
"e": 15048,
"s": 14969,
"text": ".withColumn(\"total\", col(attr_grp_y.columns[0]) + col(attr_grp_n.columns[0]))\\"
},
{
"code": null,
"e": 15095,
"s": 15048,
"text": "And we are not selecting the join column twice"
},
{
"code": null,
"e": 15180,
"s": 15095,
"text": ".select(attr_grp_y.columns[0], attr_grp_y.columns[1],\\ attr_grp_n.columns[1])"
},
{
"code": null,
"e": 15286,
"s": 15180,
"text": "We did all this exercise to calculate the info gain for this particular attribute, so lets calculate that"
},
{
"code": null,
"e": 15363,
"s": 15286,
"text": "gain_for_attribute = calculate_info_gain(entropy, joined_df, total_elements)"
},
{
"code": null,
"e": 15571,
"s": 15363,
"text": "We will save info gain for this attribute in a global variable, attr_name_info_gain. We will later sort this dict to get the attr having max info gain. INvoked Calculate_info_gain function is described next."
},
{
"code": null,
"e": 15703,
"s": 15571,
"text": "gain_for_attribute = calculate_info_gain(entropy, joined_df, total_elements) # attr_name_info_gain[attr_name] = gain_for_attribute"
},
{
"code": null,
"e": 15725,
"s": 15703,
"text": "5) Info gain function"
},
{
"code": null,
"e": 16497,
"s": 15725,
"text": "def calculate_info_gain(entropy, joined_df, total_elements): attr_entropy = 0.0 for anAttributeData in joined_df.rdd.collect(): yes_class_count = anAttributeData[1] no_class_count = anAttributeData[2] if yes_class_count is None: yes_class_count = 0 elif no_class_count is None: no_class_count = 0 count_of_class = yes_class_count + no_class_count # do the summation part e.g. if age is 56, 60, 45 then its sum of entropy for each of these element classmap = {'y' : yes_class_count, 'n' : no_class_count} attr_entropy = attr_entropy + ((count_of_class / total_elements) *\\ calculate_entropy(count_of_class, classmap)) gain = entropy - attr_entropy return gain"
},
{
"code": null,
"e": 16574,
"s": 16497,
"text": "If you have read the earlier sections then this function is self explanatory"
},
{
"code": null,
"e": 16612,
"s": 16574,
"text": "6) Coming back to main function again"
},
{
"code": null,
"e": 16710,
"s": 16612,
"text": "We had done processing till this code line — ->”process_dataset([], data, played, notplayed, ‘’)”"
},
{
"code": null,
"e": 17478,
"s": 16710,
"text": "def main(): data = sqlContext.read.format('com.databricks.spark.csv').option('header', 'true')\\ .option('delimiter', ';').load(\"/home/me/ml/practice/decision_tree/datasets/simple_dataset\") data.registerTempTable('data') played = sqlContext.sql(\"select * from data WHERE y like '%y%' \").count() notplayed = sqlContext.sql(\"select * from data WHERE y like '%n%' \").count() process_dataset([], data, played, notplayed, '') # sort by info gain sorted_by_info_gain = sorted(attr_name_info_gain.items(), key=operator.itemgetter(1), reverse=True) processed_attrs = [] max_gain_attr = sorted_by_info_gain[0][0] processed_attrs.append(max_gain_attr) build_tree(max_gain_attr, processed_attrs, data, '') nx.draw(G, with_labels=True) plt.show()"
},
{
"code": null,
"e": 17637,
"s": 17478,
"text": "We sort the info gain function and get the attr having max gain, make that as root node. Now we call build tree function. This is last and important function."
},
{
"code": null,
"e": 17848,
"s": 17637,
"text": "The input to this method is name of the attribute having max info gain. This becomes root node for the tree. We want to get the distinct values of this attribute. These values will become branches of this node."
},
{
"code": null,
"e": 17900,
"s": 17848,
"text": "This function will build complete tree recursively."
},
{
"code": null,
"e": 20658,
"s": 17900,
"text": "def build_tree(max_gain_attr, processed_attrs, data, where_condition): attrValues = sqlContext.sql(\"select distinct \" + max_gain_attr + \" from data where 1==1 \" + where_condition) orig_where_condition = where_condition for aValueForMaxGainAttr in attrValues.rdd.collect(): adistinct_value_for_attr = aValueForMaxGainAttr[0] G.add_edges_from([(max_gain_attr, adistinct_value_for_attr)]) if attrs_type[max_gain_attr] == \"string\": where_condition = str(orig_where_condition + \" and \" + max_gain_attr + \"=='\" + adistinct_value_for_attr + \"'\") else: where_condition = str(orig_where_condition + \" and \" + max_gain_attr + \"==\" + adistinct_value_for_attr) played_for_attr = sqlContext.sql(\"select * from data where y like '%yes%' \" + where_condition).count() notplayed_for_attr = sqlContext.sql(\"select * from data where y like '%no%' \" + where_condition).count() # if either has zero value then entropy for this attr will be zero and its the last attr in the tree leaf_values = [] if played_for_attr == 0 or notplayed_for_attr == 0: leaf_node = sqlContext.sql(\"select distinct y from data where 1==1 \" + where_condition) for leaf_node_data in leaf_node.rdd.collect(): G.add_edges_from([(adistinct_value_for_attr, str(leaf_node_data[0]))]) continue process_dataset(processed_attrs, data, played_for_attr, notplayed_for_attr, where_condition) if not attr_name_info_gain: # we processed all attributes # attach leaf node leaf_node = sqlContext.sql(\"select distinct y from data where 1==1 \" + where_condition) for leaf_node_data in leaf_node.rdd.collect(): G.add_edges_from([(adistinct_value_for_attr, str(leaf_node_data[0]))]) continue # we are done for this branch of tree # get the attr with max info gain under aValueForMaxGainAttr # sort by info gain sorted_by_info_gain = sorted(attr_name_info_gain.items(), key=operator.itemgetter(1), reverse=True) new_max_gain_attr = sorted_by_info_gain[0][0] if sorted_by_info_gain[0][1] == 0: # under this where condition, records dont have entropy leaf_node = sqlContext.sql(\"select distinct y from data where 1==1 \" + where_condition) # there might be more than one leaf node for leaf_node_data in leaf_node.rdd.collect(): G.add_edges_from([(adistinct_value_for_attr, str(leaf_node_data[0]))]) continue # we are done for this branch of tree G.add_edges_from([(adistinct_value_for_attr, new_max_gain_attr)]) processed_attrs.append(new_max_gain_attr) build_tree(new_max_gain_attr, processed_attrs, data, where_condition)"
},
{
"code": null,
"e": 20670,
"s": 20658,
"text": "Explanation"
},
{
"code": null,
"e": 20708,
"s": 20670,
"text": "We want distinct values for the node."
},
{
"code": null,
"e": 20818,
"s": 20708,
"text": "attrValues = sqlContext.sql(\"select distinct \" + max_gain_attr + \" from data where 1==1 \" + where_condition)"
},
{
"code": null,
"e": 20847,
"s": 20818,
"text": "For each value for this node"
},
{
"code": null,
"e": 20901,
"s": 20847,
"text": "for aValueForMaxGainAttr in attrValues.rdd.collect():"
},
{
"code": null,
"e": 20946,
"s": 20901,
"text": "Get the attribute value under this iteration"
},
{
"code": null,
"e": 20997,
"s": 20946,
"text": "adistinct_value_for_attr = aValueForMaxGainAttr[0]"
},
{
"code": null,
"e": 21034,
"s": 20997,
"text": "Add this value as branch of the node"
},
{
"code": null,
"e": 21096,
"s": 21034,
"text": "G.add_edges_from([(max_gain_attr, adistinct_value_for_attr)])"
},
{
"code": null,
"e": 21163,
"s": 21096,
"text": "We need to get the data under this attribute value. If the tree is"
},
{
"code": null,
"e": 21354,
"s": 21163,
"text": "And we are processing ‘Sunny’ value of the parent node then to proceed under same branch ( outlook -> sunny) we need to get data where outlook = sunny. So we add this as new where condition."
},
{
"code": null,
"e": 21475,
"s": 21354,
"text": "Also, if the attribute type is string when we need to add value under quotes and it is int type then we dont add quotes."
},
{
"code": null,
"e": 21764,
"s": 21475,
"text": "if attrs_type[max_gain_attr] == \"string\": where_condition = str(orig_where_condition + \" and \" + max_gain_attr + \"=='\" + adistinct_value_for_attr + \"'\") else: where_condition = str(orig_where_condition + \" and \" + max_gain_attr + \"==\" + adistinct_value_for_attr)"
},
{
"code": null,
"e": 21995,
"s": 21764,
"text": "We will again find out the attr having max info gain from the list of attributes excluding the attributes which are already processed. So for this value of the parent attr we want to know how many records outcome as ‘yes’ and ‘no’"
},
{
"code": null,
"e": 22202,
"s": 21995,
"text": "played_for_attr = sqlContext.sql(\"select * from data where y like '%yes%' \" + where_condition).count()notplayed_for_attr = sqlContext.sql(\"select * from data where y like '%no%' \" + where_condition).count()"
},
{
"code": null,
"e": 22364,
"s": 22202,
"text": "As the comment states, if we get zero entropy value then we have reached the leaf node of this branch, we will just add the outcomes to the tree under this node."
},
{
"code": null,
"e": 22805,
"s": 22364,
"text": "# if either has zero value then entropy for this attr will be zero and its the last attr in the tree leaf_values = [] if played_for_attr == 0 or notplayed_for_attr == 0: leaf_node = sqlContext.sql(\"select distinct y from data where 1==1 \" + where_condition) for leaf_node_data in leaf_node.rdd.collect(): G.add_edges_from([(adistinct_value_for_attr, str(leaf_node_data[0]))]) continue"
},
{
"code": null,
"e": 23018,
"s": 22805,
"text": "If not then we keep processing. Code similar to below was already was processed in main function and explained. Maybe we should put that one iteration also as part of this recursion, let this be exercise for you."
},
{
"code": null,
"e": 24259,
"s": 23018,
"text": "process_dataset(processed_attrs, data, subscribed_for_attr, unsubscribed_for_attr, where_condition)if not attr_name_info_gain: # we processed all attributes # attach leaf node leaf_node = sqlContext.sql(\"select distinct y from data where 1==1 \" + where_condition) for leaf_node_data in leaf_node.rdd.collect(): G.add_edges_from([(adistinct_value_for_attr, str(leaf_node_data[0]))]) continue # we are done for this branch of tree# get the attr with max info gain under aValueForMaxGainAttr# sort by info gainsorted_by_info_gain = sorted(attr_name_info_gain.items(), key=operator.itemgetter(1), reverse=True)new_max_gain_attr = sorted_by_info_gain[0][0]if sorted_by_info_gain[0][1] == 0: # under this where condition, records dont have entropy leaf_node = sqlContext.sql(\"select distinct y from data where 1==1 \" + where_condition) # there might be more than one leaf node for leaf_node_data in leaf_node.rdd.collect(): G.add_edges_from([(adistinct_value_for_attr, str(leaf_node_data[0]))]) continue # we are done for this branch of treeG.add_edges_from([(adistinct_value_for_attr, new_max_gain_attr)])processed_attrs.append(new_max_gain_attr)build_tree(new_max_gain_attr, processed_attrs, data, where_condition)"
},
{
"code": null,
"e": 24366,
"s": 24259,
"text": "Now if we last 2 lines of main function are executed then you can visually see the decision tree built :-)"
},
{
"code": null,
"e": 24405,
"s": 24366,
"text": "nx.draw(G, with_labels=True)plt.show()"
}
] |
Create a Donut Chart using Recharts in ReactJS - GeeksforGeeks
|
27 Jul, 2021
Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents).
To create Donut Chart using Recharts, we create a dataset that contains actual data. Then we define the slices using donaut element with data property which will have the data of the dataset created and with datakey property which is the property name with a value for the slices.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd 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 modules using the following command.
npm install --save recharts
Step 3: After creating the ReactJS application, Install the required modules using the following command.
npm install --save recharts
Project Structure: It will look like the following.
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 { PieChart, Pie} from 'recharts';
const App = () => {
// Sample data
const data = [
{name: 'Geeksforgeeks', students: 400},
{name: 'Technical scripter', students: 700},
{name: 'Geek-i-knack', students: 200},
{name: 'Geek-o-mania', students: 1000}
];
return (
<PieChart width={700} height={700}>
<Pie data={data} dataKey="students" outerRadius={250} innerRadius={150} fill="green" />
</PieChart>
);
}
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:
Output
React-Questions
Recharts
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to filter object array based on attributes?
How to get selected value in dropdown list using JavaScript ?
How to remove duplicate elements from JavaScript Array ?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
|
[
{
"code": null,
"e": 25304,
"s": 25273,
"text": " \n27 Jul, 2021\n"
},
{
"code": null,
"e": 25522,
"s": 25304,
"text": "Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents). "
},
{
"code": null,
"e": 25803,
"s": 25522,
"text": "To create Donut Chart using Recharts, we create a dataset that contains actual data. Then we define the slices using donaut element with data property which will have the data of the dataset created and with datakey property which is the property name with a value for the slices."
},
{
"code": null,
"e": 25853,
"s": 25803,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 25951,
"s": 25853,
"text": "\nStep 1: Create a React application using the following command.\nnpx create-react-app foldername\n"
},
{
"code": null,
"e": 26015,
"s": 25951,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 26047,
"s": 26015,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 26163,
"s": 26047,
"text": "\nStep 2: After creating your project folder i.e. foldername, move to it using the following command.\ncd foldername\n"
},
{
"code": null,
"e": 26263,
"s": 26163,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command."
},
{
"code": null,
"e": 26277,
"s": 26263,
"text": "cd foldername"
},
{
"code": null,
"e": 26413,
"s": 26277,
"text": "\nStep 3: After creating the ReactJS application, Install the required modules using the following command.\nnpm install --save recharts\n"
},
{
"code": null,
"e": 26519,
"s": 26413,
"text": "Step 3: After creating the ReactJS application, Install the required modules using the following command."
},
{
"code": null,
"e": 26547,
"s": 26519,
"text": "npm install --save recharts"
},
{
"code": null,
"e": 26599,
"s": 26547,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 26729,
"s": 26599,
"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": 26736,
"s": 26729,
"text": "App.js"
},
{
"code": "\n\n\n\n\n\n\nimport React from 'react'; \nimport { PieChart, Pie} from 'recharts'; \n \n \nconst App = () => { \n \n// Sample data \nconst data = [ \n {name: 'Geeksforgeeks', students: 400}, \n {name: 'Technical scripter', students: 700}, \n {name: 'Geek-i-knack', students: 200}, \n {name: 'Geek-o-mania', students: 1000} \n]; \n \n \nreturn ( \n <PieChart width={700} height={700}> \n <Pie data={data} dataKey=\"students\" outerRadius={250} innerRadius={150} fill=\"green\" /> \n </PieChart> \n); \n} \n \nexport default App; \n\n\n\n\n\n",
"e": 27282,
"s": 26746,
"text": null
},
{
"code": null,
"e": 27395,
"s": 27282,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 27405,
"s": 27395,
"text": "npm start"
},
{
"code": null,
"e": 27504,
"s": 27405,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 27511,
"s": 27504,
"text": "Output"
},
{
"code": null,
"e": 27529,
"s": 27511,
"text": "\nReact-Questions\n"
},
{
"code": null,
"e": 27540,
"s": 27529,
"text": "\nRecharts\n"
},
{
"code": null,
"e": 27553,
"s": 27540,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 27563,
"s": 27553,
"text": "\nReactJS\n"
},
{
"code": null,
"e": 27582,
"s": 27563,
"text": "\nWeb Technologies\n"
},
{
"code": null,
"e": 27787,
"s": 27582,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 27848,
"s": 27787,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27889,
"s": 27848,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27937,
"s": 27889,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 27999,
"s": 27937,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 28056,
"s": 27999,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 28099,
"s": 28056,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28144,
"s": 28099,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 28209,
"s": 28144,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 28277,
"s": 28209,
"text": "How to pass data from one component to other component in ReactJS ?"
}
] |
Which Evaluation Metric Should You Use in Machine Learning Regression Problems? | by Jeff Hale | Towards Data Science
|
If you’re like me, you might have used R-Squared (R2), Root Mean Squared Error (RMSE), and Mean Absolute Error (MAE )evaluation metrics in your regression problems without giving them a lot of thought. 🤔
Although all of them are common metrics, it’s not obvious which one to use when. After writing this article I have a new favorite and a new plan for reporting them going forward. 😀
I’ll share those conclusions with you in a bit. First, we’ll dig into each metric. You’ll learn the pros and cons of each for model selection and reporting. Let’s get to it! 🚀
R2 represents the proportion of variance explained by your model.
R2 is a relative metric, so you can use it to compare with other models trained on the same data. And you can use it to get a rough a feel for how well a model performs, in general.
Disclaimer: This article isn’t a review of machine learning methods, but make sure you use different data for training, validation, and testing. You always want to hold out some data that your model has not seen to evaluate its performance. Also, it’s a good idea to look at plot of your model’s predictions vs. the actual values to see how well your model fit the data.
Let’s see how R2 is computed. Onward! ➡️
Here is one way to formulate R2.
1 - (SSE/SST)
SSE is the sum of squared errors; the sum of the squared differences between the actual values and predicted values.
SST is the total sum of squares (shown sometimes as TSS); the sum of the squared differences between the actual values and the mean of the actual values.
With more mathy notation:
1 - (∑(y - ŷ)2 / ∑(y - y̅)2)
Here’s what the code looks like —adapted from scikit-learn, the primary Python machine learning library.
numerator = ((y_true - y_pred) ** 2).sum()denominator = ((y_true - np.average(y_true)) ** 2).sum()r2_score = 1 - (numerator / denominator)
subtract the predicted values from the actual y valuessquare the resultssum them
subtract the predicted values from the actual y values
square the results
sum them
That’s the numerator.
subtract the mean of the actual y values from each actual y valuesquare the resultssum them
subtract the mean of the actual y values from each actual y value
square the results
sum them
That’s the denominator.
1 - the numerator/denominator is the R2. 🎉
R2 is the default metric for scikit-learn regression problems. If you want to use it explicitly you can import it and then use it like this:
from sklearn.metrics import r2_scorer2_score(y_true, y_pred)
A model that explains no variance would have an R2 of 0. A model with an R2 of 1 would explain all of the variance. Higher scores are better.
However, if your R2 is 1 on your test set you are probably leaking information or the problem is fairly simple for your model to learn. 👍
In some fields, such as the social sciences, there are lots of factors that influence human behavior. Say you have a model with just a few independent variables that results in an R2 close to .5. Your model is able to account for half of the variance in your data, and that’s quite good. 😀
It is possible to have an R2 that is negative. Negative scores occur when the predictions the model makes fit that data worse than the mean of the output values. Predicting the mean each time is a null model. See more here.
Say you have the following small toy test dataset:
All code is available on GitHub in this Jupyter notebook.
Here’s a plot of the actual and predicted y values.
The R2 of the model is 0.71. The model is accounting for 71% of the variance in the data. That’s not too shabby, although we’d like more test data. 😀
As another example, let’s say the true values for y are [55, 2, 3]. The mean is 20. Predicting 20 for each y value results in an R2 of 0.
A model that predicts [1 , 2, 2] for the true values above results in an R2 of -0.59. Bottom line, you can do far worse than the null model! In fact, you can predict infinitely worse, resulting in an infinitely low R2. 😲
As a brief aside, let’s look at the Adjusted R2 and machine learning vs. statistics.
The Adjusted R2 accounts for the addition of more predictor variables (features).
Adjusted R2 will only increase with a new predictor variable when that variable improves the model performance more than would be expect by chance. Adjusted R2 helps you focus on using the most parsimonious model possible. 😉
The Adjusted R2 is more common in statistical inference than in machine learning. Scikit-learn, the primary Python library for machine learning, doesn’t even have an Adjusted R2 metric. Statsmodels, the primary statistical library for Python does. If you want to learn more about when to use which Python library for data science, I wrote a guide here.
You can compute the Adjusted R2 if you know the number of feature columns (p) and the number of observations (n). Here’s the code:
adjusted_r2 = 1 — ((1 — r2) * (n — 1)) / ( n — p — 1)
n-1 is the degrees of freedom. Whenever you hear that term, you know you are in statistics land. In machine learning we generally care most about predictive ability, so R2 is favored over Adjusted R2.
Another note on statistics vs. machine learning: our focus is on machine learning, so prediction rather than causality. R2 — and the other metrics that we’ll see, don’t say anything about causality by themselves.
R2 tells you how much variance your model accounts for. It’s handy because the R2 for any regression problem will immediately provide some (limited) understanding of how well the model is performing. 😀
R2 is a relative metric. Let’s see a few absolute metrics now.
RMSE is a very common evaluation metric. It can range between 0 and infinity. Lower values are better. To keep this straight, remember that it has error in the name and you want errors to be low. ☝️
The RMSE can be formulated like this:
square root of mean SSE
We saw SSE in the R2 score metric. It’s the sum of squared errors; the sum of the squared differences between the actual values and predicted values.
More mathy formula:
square root of (1/n * (∑(y -ŷ)2))
In Python code:
np.sqrt(np.mean((y_true - y_pred) ** 2))
subtract the predicted values from the actual y valuessquare the resultssum themtake the averagetake the square root
subtract the predicted values from the actual y values
square the results
sum them
take the average
take the square root
Here’s how to get the RMSE with a function in scikit-learn:
from sklearn.model_selection import mean_squared_errormean_squared_error(y_true, y_pred, squared=False)
You can use the squared=False argument as of scikit-learn version 0.22.0. Prior to that you had to take the square root yourself like this: np.sqrt(mean_squared_error(y_actual, y_predicted). ☝️
Use RMSE if you want to:
penalize large errors
have the result be in the same units as the outcome variable
use a loss function for validation that can be quickly computed
You could use the Mean Squared Error (MSE) with no Root, but then the units are not as easily comprehensible. Just take the square root of the MSE and you’ve got the RMSE. 👍
In this excellent article JJ points out some issues with RMSE. Namely, that “RMSE does not necessarily increase with the variance of the errors. RMSE increases with the variance of the frequency distribution of error magnitudes.”
Also, the RMSE is not so easily interpreted. The units might look familiar, but you are squaring differences. You can’t just say that an RMSE of 10 means you are off by 10 units on average, although that’s kind of how most folks think of the result. At least, it’s how I used to. 😉
Turning to our example dataset again:
The RMSE is 0.48. The mean of the actual y values is 2.2. Together, that information tells us that the model is probably somewhere between great and terrible. It’s hard to do too much with this RMSE statistic without more context. 😐
RMSE is an imperfect statistic for evaluation, but it’s very common. If you care a lot about penalizing large errors, it’s not a bad choice. It’s a great choice for a loss metric when hyperparameter tuning or batch training a deep neural network.
Mean Absolute Error (MAE) is the average of the absolute value of the errors.
Let’s get right to math equation:
(1 / n) * (∑ |y - ŷ|)
In code:
np.average(np.abs(y_true - y_pred))
subtract the predicted values from the actual y valuestake the absolute value of each errorsum themtake the average
subtract the predicted values from the actual y values
take the absolute value of each error
sum them
take the average
Here’s how to get the MAE with a scikit-learn function:
from sklearn.model_selection import mean_absolute_errormean_absolute_error(y_actual, y_predicted, squared=False)
The MAE is conceptually the easiest evaluation metric for regression problems. It answers the question, “How far were you off in your predictions, on average?”
The units make intuitive sense. Yes! 🎉
For example, say you are predicting house sale prices and the mean actual sale price in the test set is $500,000. An MAE of $10,000 means the model was off by an average of $10k in its predictions. That’s not bad! 😀
Unlike RMSE scores, bad predictions don’t result in disproportionately high MAE scores.
The MAE will always be closer to 0 than the RMSE (or the same).
Note that computing the RMSE as an optimization metric for a model with a training loop is faster than computing MAE.
Turning to our example dataset for a final time:
The MAE is 0.37. The predictions were off from the mean of 2.2 by an average of 0.37. I can quickly understand that statement. 😀
The RMSE was 0.48 and the R2 was 0.71.
MAE is the simplest evaluation metric and most easily interpreted. It’s a great metric to use if you don’t want a few far off predictions to overwhelm a lot of close ones. It’s a less good choice if you want to penalize predictions that were really far off the mark.
So which metric should you use? In general, I suggest you report all three! 🚀
R2 gives people evaluating the performance an at-a-glance understanding of how well your model performs. It’s definitely worth report it.
RMSE is less intuitive to understand, but extremely common. It penalizes really bad predictions. It also make a great loss metric for a model to optimize because it can be computed quickly. It merits reporting.
I came out of this article with new respect for MAE. It’s straightforward to understand and treats all prediction errors proportionately. I would emphasize it in most regression problem evaluations.
Disagree? Let me know on Twitter. 👍
If you want to learn about metrics for classification problems, I wrote about them here.
I hope you enjoyed this guide to popular Python data science packages. If you did, please share it on your favorite social media so other folks can find it, too. 😀
I write about Python, SQL, Docker, and other tech topics. If any of that’s of interest to you, sign up for my mailing list of awesome data science resources and read more to help you grow your skills here. 👍
Happy reporting! ⚖️
|
[
{
"code": null,
"e": 375,
"s": 171,
"text": "If you’re like me, you might have used R-Squared (R2), Root Mean Squared Error (RMSE), and Mean Absolute Error (MAE )evaluation metrics in your regression problems without giving them a lot of thought. 🤔"
},
{
"code": null,
"e": 556,
"s": 375,
"text": "Although all of them are common metrics, it’s not obvious which one to use when. After writing this article I have a new favorite and a new plan for reporting them going forward. 😀"
},
{
"code": null,
"e": 732,
"s": 556,
"text": "I’ll share those conclusions with you in a bit. First, we’ll dig into each metric. You’ll learn the pros and cons of each for model selection and reporting. Let’s get to it! 🚀"
},
{
"code": null,
"e": 798,
"s": 732,
"text": "R2 represents the proportion of variance explained by your model."
},
{
"code": null,
"e": 980,
"s": 798,
"text": "R2 is a relative metric, so you can use it to compare with other models trained on the same data. And you can use it to get a rough a feel for how well a model performs, in general."
},
{
"code": null,
"e": 1351,
"s": 980,
"text": "Disclaimer: This article isn’t a review of machine learning methods, but make sure you use different data for training, validation, and testing. You always want to hold out some data that your model has not seen to evaluate its performance. Also, it’s a good idea to look at plot of your model’s predictions vs. the actual values to see how well your model fit the data."
},
{
"code": null,
"e": 1392,
"s": 1351,
"text": "Let’s see how R2 is computed. Onward! ➡️"
},
{
"code": null,
"e": 1425,
"s": 1392,
"text": "Here is one way to formulate R2."
},
{
"code": null,
"e": 1439,
"s": 1425,
"text": "1 - (SSE/SST)"
},
{
"code": null,
"e": 1556,
"s": 1439,
"text": "SSE is the sum of squared errors; the sum of the squared differences between the actual values and predicted values."
},
{
"code": null,
"e": 1710,
"s": 1556,
"text": "SST is the total sum of squares (shown sometimes as TSS); the sum of the squared differences between the actual values and the mean of the actual values."
},
{
"code": null,
"e": 1736,
"s": 1710,
"text": "With more mathy notation:"
},
{
"code": null,
"e": 1766,
"s": 1736,
"text": "1 - (∑(y - ŷ)2 / ∑(y - y̅)2)"
},
{
"code": null,
"e": 1871,
"s": 1766,
"text": "Here’s what the code looks like —adapted from scikit-learn, the primary Python machine learning library."
},
{
"code": null,
"e": 2010,
"s": 1871,
"text": "numerator = ((y_true - y_pred) ** 2).sum()denominator = ((y_true - np.average(y_true)) ** 2).sum()r2_score = 1 - (numerator / denominator)"
},
{
"code": null,
"e": 2091,
"s": 2010,
"text": "subtract the predicted values from the actual y valuessquare the resultssum them"
},
{
"code": null,
"e": 2146,
"s": 2091,
"text": "subtract the predicted values from the actual y values"
},
{
"code": null,
"e": 2165,
"s": 2146,
"text": "square the results"
},
{
"code": null,
"e": 2174,
"s": 2165,
"text": "sum them"
},
{
"code": null,
"e": 2196,
"s": 2174,
"text": "That’s the numerator."
},
{
"code": null,
"e": 2288,
"s": 2196,
"text": "subtract the mean of the actual y values from each actual y valuesquare the resultssum them"
},
{
"code": null,
"e": 2354,
"s": 2288,
"text": "subtract the mean of the actual y values from each actual y value"
},
{
"code": null,
"e": 2373,
"s": 2354,
"text": "square the results"
},
{
"code": null,
"e": 2382,
"s": 2373,
"text": "sum them"
},
{
"code": null,
"e": 2406,
"s": 2382,
"text": "That’s the denominator."
},
{
"code": null,
"e": 2449,
"s": 2406,
"text": "1 - the numerator/denominator is the R2. 🎉"
},
{
"code": null,
"e": 2590,
"s": 2449,
"text": "R2 is the default metric for scikit-learn regression problems. If you want to use it explicitly you can import it and then use it like this:"
},
{
"code": null,
"e": 2651,
"s": 2590,
"text": "from sklearn.metrics import r2_scorer2_score(y_true, y_pred)"
},
{
"code": null,
"e": 2793,
"s": 2651,
"text": "A model that explains no variance would have an R2 of 0. A model with an R2 of 1 would explain all of the variance. Higher scores are better."
},
{
"code": null,
"e": 2931,
"s": 2793,
"text": "However, if your R2 is 1 on your test set you are probably leaking information or the problem is fairly simple for your model to learn. 👍"
},
{
"code": null,
"e": 3221,
"s": 2931,
"text": "In some fields, such as the social sciences, there are lots of factors that influence human behavior. Say you have a model with just a few independent variables that results in an R2 close to .5. Your model is able to account for half of the variance in your data, and that’s quite good. 😀"
},
{
"code": null,
"e": 3445,
"s": 3221,
"text": "It is possible to have an R2 that is negative. Negative scores occur when the predictions the model makes fit that data worse than the mean of the output values. Predicting the mean each time is a null model. See more here."
},
{
"code": null,
"e": 3496,
"s": 3445,
"text": "Say you have the following small toy test dataset:"
},
{
"code": null,
"e": 3554,
"s": 3496,
"text": "All code is available on GitHub in this Jupyter notebook."
},
{
"code": null,
"e": 3606,
"s": 3554,
"text": "Here’s a plot of the actual and predicted y values."
},
{
"code": null,
"e": 3756,
"s": 3606,
"text": "The R2 of the model is 0.71. The model is accounting for 71% of the variance in the data. That’s not too shabby, although we’d like more test data. 😀"
},
{
"code": null,
"e": 3894,
"s": 3756,
"text": "As another example, let’s say the true values for y are [55, 2, 3]. The mean is 20. Predicting 20 for each y value results in an R2 of 0."
},
{
"code": null,
"e": 4115,
"s": 3894,
"text": "A model that predicts [1 , 2, 2] for the true values above results in an R2 of -0.59. Bottom line, you can do far worse than the null model! In fact, you can predict infinitely worse, resulting in an infinitely low R2. 😲"
},
{
"code": null,
"e": 4200,
"s": 4115,
"text": "As a brief aside, let’s look at the Adjusted R2 and machine learning vs. statistics."
},
{
"code": null,
"e": 4282,
"s": 4200,
"text": "The Adjusted R2 accounts for the addition of more predictor variables (features)."
},
{
"code": null,
"e": 4507,
"s": 4282,
"text": "Adjusted R2 will only increase with a new predictor variable when that variable improves the model performance more than would be expect by chance. Adjusted R2 helps you focus on using the most parsimonious model possible. 😉"
},
{
"code": null,
"e": 4860,
"s": 4507,
"text": "The Adjusted R2 is more common in statistical inference than in machine learning. Scikit-learn, the primary Python library for machine learning, doesn’t even have an Adjusted R2 metric. Statsmodels, the primary statistical library for Python does. If you want to learn more about when to use which Python library for data science, I wrote a guide here."
},
{
"code": null,
"e": 4991,
"s": 4860,
"text": "You can compute the Adjusted R2 if you know the number of feature columns (p) and the number of observations (n). Here’s the code:"
},
{
"code": null,
"e": 5045,
"s": 4991,
"text": "adjusted_r2 = 1 — ((1 — r2) * (n — 1)) / ( n — p — 1)"
},
{
"code": null,
"e": 5246,
"s": 5045,
"text": "n-1 is the degrees of freedom. Whenever you hear that term, you know you are in statistics land. In machine learning we generally care most about predictive ability, so R2 is favored over Adjusted R2."
},
{
"code": null,
"e": 5459,
"s": 5246,
"text": "Another note on statistics vs. machine learning: our focus is on machine learning, so prediction rather than causality. R2 — and the other metrics that we’ll see, don’t say anything about causality by themselves."
},
{
"code": null,
"e": 5661,
"s": 5459,
"text": "R2 tells you how much variance your model accounts for. It’s handy because the R2 for any regression problem will immediately provide some (limited) understanding of how well the model is performing. 😀"
},
{
"code": null,
"e": 5724,
"s": 5661,
"text": "R2 is a relative metric. Let’s see a few absolute metrics now."
},
{
"code": null,
"e": 5923,
"s": 5724,
"text": "RMSE is a very common evaluation metric. It can range between 0 and infinity. Lower values are better. To keep this straight, remember that it has error in the name and you want errors to be low. ☝️"
},
{
"code": null,
"e": 5961,
"s": 5923,
"text": "The RMSE can be formulated like this:"
},
{
"code": null,
"e": 5985,
"s": 5961,
"text": "square root of mean SSE"
},
{
"code": null,
"e": 6135,
"s": 5985,
"text": "We saw SSE in the R2 score metric. It’s the sum of squared errors; the sum of the squared differences between the actual values and predicted values."
},
{
"code": null,
"e": 6155,
"s": 6135,
"text": "More mathy formula:"
},
{
"code": null,
"e": 6190,
"s": 6155,
"text": "square root of (1/n * (∑(y -ŷ)2))"
},
{
"code": null,
"e": 6206,
"s": 6190,
"text": "In Python code:"
},
{
"code": null,
"e": 6247,
"s": 6206,
"text": "np.sqrt(np.mean((y_true - y_pred) ** 2))"
},
{
"code": null,
"e": 6364,
"s": 6247,
"text": "subtract the predicted values from the actual y valuessquare the resultssum themtake the averagetake the square root"
},
{
"code": null,
"e": 6419,
"s": 6364,
"text": "subtract the predicted values from the actual y values"
},
{
"code": null,
"e": 6438,
"s": 6419,
"text": "square the results"
},
{
"code": null,
"e": 6447,
"s": 6438,
"text": "sum them"
},
{
"code": null,
"e": 6464,
"s": 6447,
"text": "take the average"
},
{
"code": null,
"e": 6485,
"s": 6464,
"text": "take the square root"
},
{
"code": null,
"e": 6545,
"s": 6485,
"text": "Here’s how to get the RMSE with a function in scikit-learn:"
},
{
"code": null,
"e": 6649,
"s": 6545,
"text": "from sklearn.model_selection import mean_squared_errormean_squared_error(y_true, y_pred, squared=False)"
},
{
"code": null,
"e": 6843,
"s": 6649,
"text": "You can use the squared=False argument as of scikit-learn version 0.22.0. Prior to that you had to take the square root yourself like this: np.sqrt(mean_squared_error(y_actual, y_predicted). ☝️"
},
{
"code": null,
"e": 6868,
"s": 6843,
"text": "Use RMSE if you want to:"
},
{
"code": null,
"e": 6890,
"s": 6868,
"text": "penalize large errors"
},
{
"code": null,
"e": 6951,
"s": 6890,
"text": "have the result be in the same units as the outcome variable"
},
{
"code": null,
"e": 7015,
"s": 6951,
"text": "use a loss function for validation that can be quickly computed"
},
{
"code": null,
"e": 7189,
"s": 7015,
"text": "You could use the Mean Squared Error (MSE) with no Root, but then the units are not as easily comprehensible. Just take the square root of the MSE and you’ve got the RMSE. 👍"
},
{
"code": null,
"e": 7419,
"s": 7189,
"text": "In this excellent article JJ points out some issues with RMSE. Namely, that “RMSE does not necessarily increase with the variance of the errors. RMSE increases with the variance of the frequency distribution of error magnitudes.”"
},
{
"code": null,
"e": 7701,
"s": 7419,
"text": "Also, the RMSE is not so easily interpreted. The units might look familiar, but you are squaring differences. You can’t just say that an RMSE of 10 means you are off by 10 units on average, although that’s kind of how most folks think of the result. At least, it’s how I used to. 😉"
},
{
"code": null,
"e": 7739,
"s": 7701,
"text": "Turning to our example dataset again:"
},
{
"code": null,
"e": 7972,
"s": 7739,
"text": "The RMSE is 0.48. The mean of the actual y values is 2.2. Together, that information tells us that the model is probably somewhere between great and terrible. It’s hard to do too much with this RMSE statistic without more context. 😐"
},
{
"code": null,
"e": 8219,
"s": 7972,
"text": "RMSE is an imperfect statistic for evaluation, but it’s very common. If you care a lot about penalizing large errors, it’s not a bad choice. It’s a great choice for a loss metric when hyperparameter tuning or batch training a deep neural network."
},
{
"code": null,
"e": 8297,
"s": 8219,
"text": "Mean Absolute Error (MAE) is the average of the absolute value of the errors."
},
{
"code": null,
"e": 8331,
"s": 8297,
"text": "Let’s get right to math equation:"
},
{
"code": null,
"e": 8354,
"s": 8331,
"text": "(1 / n) * (∑ |y - ŷ|)"
},
{
"code": null,
"e": 8363,
"s": 8354,
"text": "In code:"
},
{
"code": null,
"e": 8399,
"s": 8363,
"text": "np.average(np.abs(y_true - y_pred))"
},
{
"code": null,
"e": 8515,
"s": 8399,
"text": "subtract the predicted values from the actual y valuestake the absolute value of each errorsum themtake the average"
},
{
"code": null,
"e": 8570,
"s": 8515,
"text": "subtract the predicted values from the actual y values"
},
{
"code": null,
"e": 8608,
"s": 8570,
"text": "take the absolute value of each error"
},
{
"code": null,
"e": 8617,
"s": 8608,
"text": "sum them"
},
{
"code": null,
"e": 8634,
"s": 8617,
"text": "take the average"
},
{
"code": null,
"e": 8690,
"s": 8634,
"text": "Here’s how to get the MAE with a scikit-learn function:"
},
{
"code": null,
"e": 8803,
"s": 8690,
"text": "from sklearn.model_selection import mean_absolute_errormean_absolute_error(y_actual, y_predicted, squared=False)"
},
{
"code": null,
"e": 8963,
"s": 8803,
"text": "The MAE is conceptually the easiest evaluation metric for regression problems. It answers the question, “How far were you off in your predictions, on average?”"
},
{
"code": null,
"e": 9002,
"s": 8963,
"text": "The units make intuitive sense. Yes! 🎉"
},
{
"code": null,
"e": 9218,
"s": 9002,
"text": "For example, say you are predicting house sale prices and the mean actual sale price in the test set is $500,000. An MAE of $10,000 means the model was off by an average of $10k in its predictions. That’s not bad! 😀"
},
{
"code": null,
"e": 9306,
"s": 9218,
"text": "Unlike RMSE scores, bad predictions don’t result in disproportionately high MAE scores."
},
{
"code": null,
"e": 9370,
"s": 9306,
"text": "The MAE will always be closer to 0 than the RMSE (or the same)."
},
{
"code": null,
"e": 9488,
"s": 9370,
"text": "Note that computing the RMSE as an optimization metric for a model with a training loop is faster than computing MAE."
},
{
"code": null,
"e": 9537,
"s": 9488,
"text": "Turning to our example dataset for a final time:"
},
{
"code": null,
"e": 9666,
"s": 9537,
"text": "The MAE is 0.37. The predictions were off from the mean of 2.2 by an average of 0.37. I can quickly understand that statement. 😀"
},
{
"code": null,
"e": 9705,
"s": 9666,
"text": "The RMSE was 0.48 and the R2 was 0.71."
},
{
"code": null,
"e": 9972,
"s": 9705,
"text": "MAE is the simplest evaluation metric and most easily interpreted. It’s a great metric to use if you don’t want a few far off predictions to overwhelm a lot of close ones. It’s a less good choice if you want to penalize predictions that were really far off the mark."
},
{
"code": null,
"e": 10050,
"s": 9972,
"text": "So which metric should you use? In general, I suggest you report all three! 🚀"
},
{
"code": null,
"e": 10188,
"s": 10050,
"text": "R2 gives people evaluating the performance an at-a-glance understanding of how well your model performs. It’s definitely worth report it."
},
{
"code": null,
"e": 10399,
"s": 10188,
"text": "RMSE is less intuitive to understand, but extremely common. It penalizes really bad predictions. It also make a great loss metric for a model to optimize because it can be computed quickly. It merits reporting."
},
{
"code": null,
"e": 10598,
"s": 10399,
"text": "I came out of this article with new respect for MAE. It’s straightforward to understand and treats all prediction errors proportionately. I would emphasize it in most regression problem evaluations."
},
{
"code": null,
"e": 10634,
"s": 10598,
"text": "Disagree? Let me know on Twitter. 👍"
},
{
"code": null,
"e": 10723,
"s": 10634,
"text": "If you want to learn about metrics for classification problems, I wrote about them here."
},
{
"code": null,
"e": 10887,
"s": 10723,
"text": "I hope you enjoyed this guide to popular Python data science packages. If you did, please share it on your favorite social media so other folks can find it, too. 😀"
},
{
"code": null,
"e": 11095,
"s": 10887,
"text": "I write about Python, SQL, Docker, and other tech topics. If any of that’s of interest to you, sign up for my mailing list of awesome data science resources and read more to help you grow your skills here. 👍"
}
] |
How to make photo sliding effect using HTML and CSS ? - GeeksforGeeks
|
22 Jun, 2021
It is an easy and amazing animation effect created with HTML and CSS, where the photos are moving horizontally one by one like a roller. When the mouse pointer comes upon the photo then the specific photo stops moving.
Approach: The basic idea of these animation comes from the hover effect of CSS animation. Let us see how the code works.
HTML code: The photos will be moving in a circular ring using HTML. To create the animation, we have taken a “div” and a section to maintain the area of the photos properly and the class name is used in the CSS code. We used HTML figure and img tag for the photos which will be shown in the page.
HTML
<!DOCTYPE html><html> <body> <div class="addition"> <section class="slideshow"> <div class="content"> <div class="content-carrousel"> <figure class="shadow"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201105170558/geeks112.png"> </figure> <figure class="shadow"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201105170611/geeks28.png"> </figure> <figure class="shadow"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201105170619/geeks33.png"> </figure> <figure class="shadow"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201105170627/geeks41.jpg"> </figure> <figure class="shadow"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201105170635/geeks51.jpg"> </figure> <figure class="shadow"> <img src="https://media.geeksforgeeks.org/wp-contentuploads/20201105170644/geeks61.jpg"> </figure> </div> </div> </section> </div></body> </html>
CSS Code: Let us talk about the CSS part of the code. Some basic attributes are used like margin, padding, position, float, border, animation, etc which will help the photos giving them the right position. It helps to rotate the photos in 2D. First it rotates around its own axis. Then the whole “div” rotates around its axis.
To create this animation, figure:nth-child(“no. of child”) property is used. The transform:rotateY(amount of deg) and translateZ(–px) are the two attributes of CSS which helps to rotate the object.
CSS
<style> body { background-color: #000000; } .addition { margin-left: 35%; margin-top: 10%; } .slideshow { position: centre; margin: 0 auto; padding-top: 50px; height: 250px; background-color: rgb(10, 10, 10); box-sizing: border-box; } .content { margin: auto; width: 190px; perspective: 1000px; position: relative; padding-top 80px; } .content-carrousel { padding-left: 40px; /* This helps to rotate the photo div with respest to axis of an another circle */ width: 100%; position: absolute; float: right; animation: rotar 15s infinite linear; transform-style: preserve-3d; } .content-carrousel:hover { /* This is a hover effect. when the mouse will reach on the photo, the photo will stop moving */ animation-play-state: paused; cursor: pointer; } .content-carrousel figure { /* width of the full image div*/ width: 100%; /* height of the full image div*/ height: 120px; border: 1px solid #4d444d; overflow: hidden; position: absolute; } /* The calculation part starts for the angle. first, take the number of photos and then divide by 360 and write it in the position of degree */ .content-carrousel figure:nth-child(1) { transform: rotateY(0deg) translateZ(300px); } .content-carrousel figure:nth-child(2) { transform: rotateY(60deg) translateZ(300px); } .content-carrousel figure:nth-child(3) { transform: rotateY(120deg) translateZ(300px); } .content-carrousel figure:nth-child(4) { transform: rotateY(180deg) translateZ(300px); } .content-carrousel figure:nth-child(5) { transform: rotateY(240deg) translateZ(300px); } .content-carrousel figure:nth-child(6) { transform: rotateY(300deg) translateZ(300px); } .content-carrousel figure:nth-child(7) { transform: rotateY(360deg) translateZ(300px); } .slideshow { position: absolute; box-shadow: 0px 0pz 20px 0px #000; border-radius: 2px; } .content-carrousel img { image-rendering: auto; /* The photo will move with this velocity */ transition: all 300ms; /* width of the photo */ width: 100%; /* height of the photo */ height: 100%; } .content-carrousel img:hover { transform: scale(1.2); transition: all 300ms; } @keyframes rotar { from { transform: rotateY(0deg); } to { transform: rotateY(360deg); } }</style>
Final code: In this section, we will combine the above two sections (HTML and CSS) of code.
HTML
<!DOCTYPE html><html> <head> <style> body { background-color: #000000; } .addition { margin-left: 35%; margin-top: 10%; } .slideshow { position: centre; margin: 0 auto; padding-top: 50px; height: 250px; background-color: rgb(10, 10, 10); box-sizing: border-box; } .content { margin: auto; width: 190px; perspective: 1000px; position: relative; padding-top 80px; } .content-carrousel { padding-left: 40px; width: 100%; position: absolute; float: right; animation: rotar 15s infinite linear; transform-style: preserve-3d; } .content-carrousel:hover { animation-play-state: paused; cursor: pointer; } .content-carrousel figure { width: 100%; height: 120px; border: 1px solid #4d444d; overflow: hidden; position: absolute; } .content-carrousel figure:nth-child(1) { transform: rotateY(0deg) translateZ(300px); } .content-carrousel figure:nth-child(2) { transform: rotateY(60deg) translateZ(300px); } .content-carrousel figure:nth-child(3) { transform: rotateY(120deg) translateZ(300px); } .content-carrousel figure:nth-child(4) { transform: rotateY(180deg) translateZ(300px); } .content-carrousel figure:nth-child(5) { transform: rotateY(240deg) translateZ(300px); } .content-carrousel figure:nth-child(6) { transform: rotateY(300deg) translateZ(300px); } .content-carrousel figure:nth-child(7) { transform: rotateY(360deg) translateZ(300px); } .slideshow { position: absolute; box-shadow: 0px 0pz 20px 0px #000; border-radius: 2px; } .content-carrousel img { image-rendering: auto; transition: all 300ms; width: 100%; height: 100%; } .content-carrousel img:hover { transform: scale(1.2); transition: all 300ms; } @keyframes rotar { from { transform: rotateY(0deg); } to { transform: rotateY(360deg); } } </style> </head> <body> <div class="addition"> <section class="slideshow"> <div class="content"> <div class="content-carrousel"> <figure class="shadow"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201105170558/geeks112.png"> </figure> <figure class="shadow"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201105170611/geeks28.png"> </figure> <figure class="shadow"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201105170619/geeks33.png"> </figure> <figure class="shadow"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201105170627/geeks41.jpg"> </figure> <figure class="shadow"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201105170635/geeks51.jpg"> </figure> <figure class="shadow"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20201105170644/geeks61.jpg"> </figure> </div> </div> </section> </div></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
sagar0719kumar
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to fetch data from localserver database and display on HTML table using PHP ?
How to Create Time-Table schedule using HTML ?
Search Bar using HTML, CSS and JavaScript
How to Insert Form Data into Database using PHP ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
Form validation using HTML and JavaScript
|
[
{
"code": null,
"e": 25296,
"s": 25268,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 25515,
"s": 25296,
"text": "It is an easy and amazing animation effect created with HTML and CSS, where the photos are moving horizontally one by one like a roller. When the mouse pointer comes upon the photo then the specific photo stops moving."
},
{
"code": null,
"e": 25636,
"s": 25515,
"text": "Approach: The basic idea of these animation comes from the hover effect of CSS animation. Let us see how the code works."
},
{
"code": null,
"e": 25933,
"s": 25636,
"text": "HTML code: The photos will be moving in a circular ring using HTML. To create the animation, we have taken a “div” and a section to maintain the area of the photos properly and the class name is used in the CSS code. We used HTML figure and img tag for the photos which will be shown in the page."
},
{
"code": null,
"e": 25938,
"s": 25933,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <div class=\"addition\"> <section class=\"slideshow\"> <div class=\"content\"> <div class=\"content-carrousel\"> <figure class=\"shadow\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201105170558/geeks112.png\"> </figure> <figure class=\"shadow\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201105170611/geeks28.png\"> </figure> <figure class=\"shadow\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201105170619/geeks33.png\"> </figure> <figure class=\"shadow\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201105170627/geeks41.jpg\"> </figure> <figure class=\"shadow\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201105170635/geeks51.jpg\"> </figure> <figure class=\"shadow\"> <img src=\"https://media.geeksforgeeks.org/wp-contentuploads/20201105170644/geeks61.jpg\"> </figure> </div> </div> </section> </div></body> </html>",
"e": 27301,
"s": 25938,
"text": null
},
{
"code": null,
"e": 27628,
"s": 27301,
"text": "CSS Code: Let us talk about the CSS part of the code. Some basic attributes are used like margin, padding, position, float, border, animation, etc which will help the photos giving them the right position. It helps to rotate the photos in 2D. First it rotates around its own axis. Then the whole “div” rotates around its axis."
},
{
"code": null,
"e": 27826,
"s": 27628,
"text": "To create this animation, figure:nth-child(“no. of child”) property is used. The transform:rotateY(amount of deg) and translateZ(–px) are the two attributes of CSS which helps to rotate the object."
},
{
"code": null,
"e": 27830,
"s": 27826,
"text": "CSS"
},
{
"code": "<style> body { background-color: #000000; } .addition { margin-left: 35%; margin-top: 10%; } .slideshow { position: centre; margin: 0 auto; padding-top: 50px; height: 250px; background-color: rgb(10, 10, 10); box-sizing: border-box; } .content { margin: auto; width: 190px; perspective: 1000px; position: relative; padding-top 80px; } .content-carrousel { padding-left: 40px; /* This helps to rotate the photo div with respest to axis of an another circle */ width: 100%; position: absolute; float: right; animation: rotar 15s infinite linear; transform-style: preserve-3d; } .content-carrousel:hover { /* This is a hover effect. when the mouse will reach on the photo, the photo will stop moving */ animation-play-state: paused; cursor: pointer; } .content-carrousel figure { /* width of the full image div*/ width: 100%; /* height of the full image div*/ height: 120px; border: 1px solid #4d444d; overflow: hidden; position: absolute; } /* The calculation part starts for the angle. first, take the number of photos and then divide by 360 and write it in the position of degree */ .content-carrousel figure:nth-child(1) { transform: rotateY(0deg) translateZ(300px); } .content-carrousel figure:nth-child(2) { transform: rotateY(60deg) translateZ(300px); } .content-carrousel figure:nth-child(3) { transform: rotateY(120deg) translateZ(300px); } .content-carrousel figure:nth-child(4) { transform: rotateY(180deg) translateZ(300px); } .content-carrousel figure:nth-child(5) { transform: rotateY(240deg) translateZ(300px); } .content-carrousel figure:nth-child(6) { transform: rotateY(300deg) translateZ(300px); } .content-carrousel figure:nth-child(7) { transform: rotateY(360deg) translateZ(300px); } .slideshow { position: absolute; box-shadow: 0px 0pz 20px 0px #000; border-radius: 2px; } .content-carrousel img { image-rendering: auto; /* The photo will move with this velocity */ transition: all 300ms; /* width of the photo */ width: 100%; /* height of the photo */ height: 100%; } .content-carrousel img:hover { transform: scale(1.2); transition: all 300ms; } @keyframes rotar { from { transform: rotateY(0deg); } to { transform: rotateY(360deg); } }</style>",
"e": 30598,
"s": 27830,
"text": null
},
{
"code": null,
"e": 30690,
"s": 30598,
"text": "Final code: In this section, we will combine the above two sections (HTML and CSS) of code."
},
{
"code": null,
"e": 30695,
"s": 30690,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> body { background-color: #000000; } .addition { margin-left: 35%; margin-top: 10%; } .slideshow { position: centre; margin: 0 auto; padding-top: 50px; height: 250px; background-color: rgb(10, 10, 10); box-sizing: border-box; } .content { margin: auto; width: 190px; perspective: 1000px; position: relative; padding-top 80px; } .content-carrousel { padding-left: 40px; width: 100%; position: absolute; float: right; animation: rotar 15s infinite linear; transform-style: preserve-3d; } .content-carrousel:hover { animation-play-state: paused; cursor: pointer; } .content-carrousel figure { width: 100%; height: 120px; border: 1px solid #4d444d; overflow: hidden; position: absolute; } .content-carrousel figure:nth-child(1) { transform: rotateY(0deg) translateZ(300px); } .content-carrousel figure:nth-child(2) { transform: rotateY(60deg) translateZ(300px); } .content-carrousel figure:nth-child(3) { transform: rotateY(120deg) translateZ(300px); } .content-carrousel figure:nth-child(4) { transform: rotateY(180deg) translateZ(300px); } .content-carrousel figure:nth-child(5) { transform: rotateY(240deg) translateZ(300px); } .content-carrousel figure:nth-child(6) { transform: rotateY(300deg) translateZ(300px); } .content-carrousel figure:nth-child(7) { transform: rotateY(360deg) translateZ(300px); } .slideshow { position: absolute; box-shadow: 0px 0pz 20px 0px #000; border-radius: 2px; } .content-carrousel img { image-rendering: auto; transition: all 300ms; width: 100%; height: 100%; } .content-carrousel img:hover { transform: scale(1.2); transition: all 300ms; } @keyframes rotar { from { transform: rotateY(0deg); } to { transform: rotateY(360deg); } } </style> </head> <body> <div class=\"addition\"> <section class=\"slideshow\"> <div class=\"content\"> <div class=\"content-carrousel\"> <figure class=\"shadow\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201105170558/geeks112.png\"> </figure> <figure class=\"shadow\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201105170611/geeks28.png\"> </figure> <figure class=\"shadow\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201105170619/geeks33.png\"> </figure> <figure class=\"shadow\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201105170627/geeks41.jpg\"> </figure> <figure class=\"shadow\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201105170635/geeks51.jpg\"> </figure> <figure class=\"shadow\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20201105170644/geeks61.jpg\"> </figure> </div> </div> </section> </div></body> </html>",
"e": 34578,
"s": 30695,
"text": null
},
{
"code": null,
"e": 34586,
"s": 34578,
"text": "Output:"
},
{
"code": null,
"e": 34723,
"s": 34586,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 34738,
"s": 34723,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 34747,
"s": 34738,
"text": "CSS-Misc"
},
{
"code": null,
"e": 34757,
"s": 34747,
"text": "HTML-Misc"
},
{
"code": null,
"e": 34761,
"s": 34757,
"text": "CSS"
},
{
"code": null,
"e": 34766,
"s": 34761,
"text": "HTML"
},
{
"code": null,
"e": 34783,
"s": 34766,
"text": "Web Technologies"
},
{
"code": null,
"e": 34810,
"s": 34783,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 34815,
"s": 34810,
"text": "HTML"
},
{
"code": null,
"e": 34913,
"s": 34815,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34922,
"s": 34913,
"text": "Comments"
},
{
"code": null,
"e": 34935,
"s": 34922,
"text": "Old Comments"
},
{
"code": null,
"e": 34972,
"s": 34935,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 35001,
"s": 34972,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 35083,
"s": 35001,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 35130,
"s": 35083,
"text": "How to Create Time-Table schedule using HTML ?"
},
{
"code": null,
"e": 35172,
"s": 35130,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 35222,
"s": 35172,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 35282,
"s": 35222,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 35343,
"s": 35282,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 35367,
"s": 35343,
"text": "REST API (Introduction)"
}
] |
Find last index of a character in a string - GeeksforGeeks
|
30 Apr, 2021
Given a string str and a character x, find last index of x in str.Examples :
Input : str = "geeks", x = 'e'
Output : 2
Last index of 'e' in "geeks" is: 2
Input : str = "Hello world!", x = 'o'
Output : 7
Last index of 'o' is: 7
Method 1 (Simple : Traverse from left) : Traverse given string from left to right and keep updating index whenever x matches with current character.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find last index of// character x in given string.#include <iostream>using namespace std; // Returns last index of x if it is present.// Else returns -1.int findLastIndex(string& str, char x){ int index = -1; for (int i = 0; i < str.length(); i++) if (str[i] == x) index = i; return index;} // Driver codeint main(){ // String in which char is to be found string str = "geeksforgeeks"; // char whose index is to be found char x = 'e'; int index = findLastIndex(str, x); if (index == -1) cout << "Character not found"; else cout << "Last index is " << index; return 0;}
// Java program to find last index// of character x in given string.import java.io.*; class GFG { // Returns last index of x if// it is present Else returns -1.static int findLastIndex(String str, Character x){ int index = -1; for (int i = 0; i < str.length(); i++) if (str.charAt(i) == x) index = i; return index;} // Driver codepublic static void main(String[] args){ // String in which char is to be found String str = "geeksforgeeks"; // char whose index is to be found Character x = 'e'; int index = findLastIndex(str, x); if (index == -1) System.out.println("Character not found"); else System.out.println("Last index is " + index);}} /* This code is contributed by Prerna Saini */
# A Python program to find last# index of character x in given# string. # Returns last index of x if it# is present. Else returns -1.def findLastIndex(str, x): index = -1 for i in range(0, len(str)): if str[i] == x: index = i return index # Driver program # String in which char is to be foundstr = "geeksforgeeks" # char whose index is to be foundx = 'e' index = findLastIndex(str, x) if index == -1: print("Character not found")else: print('Last index is', index) # This code is contributed by shrikant13.
// C# program to find last index// of character x in given string.using System; class GFG { // Returns last index of x if // it is present Else returns -1. static int findLastIndex(string str, char x) { int index = -1; for (int i = 0; i < str.Length; i++) if (str[i] == x) index = i; return index; } // Driver code public static void Main() { // String in which char is to be found string str = "geeksforgeeks"; // char whose index is to be found char x = 'e'; int index = findLastIndex(str, x); if (index == -1) Console.WriteLine("Character not found"); else Console.WriteLine("Last index is " + index); }} /* This code is contributed by vt_m */
<?php// PHP program to find last index of// character x in given string. // Returns last index of// x if it is present.// Else returns -1.function findLastIndex($str, $x){ $index = -1; for ($i = 0; $i < strlen($str); $i++) if ($str[$i] == $x) $index = $i; return $index;} // Driver code// String in which// char is to be found$str = "geeksforgeeks"; // char whose index// is to be found$x = 'e';$index = findLastIndex($str, $x);if ($index == -1) echo("Character not found");else echo("Last index is " . $index); // This code is contributed by Ajit.?>
<script>// javascript program to find last index// of character x in given string. // Returns last index of x if// it is present Else returns -1.function findLastIndex(str, x){ let index = -1; for (let i = 0; i < str.length; i++) if (str[i] == x) index = i; return index;} // Driver code // String in which char is to be found let str = "geeksforgeeks"; // char whose index is to be found let x = 'e'; let index = findLastIndex(str, x); if (index == -1) document.write("Character not found"); else document.write("Last index is " + index); // This code is contributed by sanjoy_62.</script>
Output:
Last index is 10
Time Complexity : Θ(n)Method 2 (Efficient : Traverse from right) : In above method 1, we always traverse complete string. In this method, we can avoid complete traversal in all those cases when x is present. The idea is to traverse from right side and stop as soon as we find character.
CPP
Java
Python3
C#
PHP
Javascript
// Simple CPP program to find last index of// character x in given string.#include <iostream>using namespace std; // Returns last index of x if it is present.// Else returns -1.int findLastIndex(string& str, char x){ // Traverse from right for (int i = str.length() - 1; i >= 0; i--) if (str[i] == x) return i; return -1;} // Driver codeint main(){ string str = "geeksforgeeks"; char x = 'e'; int index = findLastIndex(str, x); if (index == -1) cout << "Character not found"; else cout << "Last index is " << index; return 0;}
// Java code to find last index// character x in given string.import java.io.*;class GFG { // Returns last index of x if// it is present. Else returns -1.static int findLastIndex(String str, Character x){ // Traverse from right for (int i = str.length() - 1; i >= 0; i--) if (str.charAt(i) == x) return i; return -1;} // Driver codepublic static void main(String[] args){ String str = "geeksforgeeks"; Character x = 'e'; int index = findLastIndex(str, x); if (index == -1) System.out.println("Character not found"); else System.out.println("Last index is " + index);}}// This code is contributed by Prerna Saini
# Simple Python3 program to find last# index of character x in given string. # Returns last index of x if it is# present. Else returns -1.def findLastIndex(str, x): # Traverse from right for i in range(len(str) - 1, -1,-1): if (str[i] == x): return i return -1 # Driver codestr = "geeksforgeeks"x = 'e'index = findLastIndex(str, x) if (index == -1): print("Character not found")else: print("Last index is " ,index) # This code is contributed by Smitha
// C# code to find last index// character x in given string.using System; class GFG { // Returns last index of x if // it is present. Else returns -1. static int findLastIndex(string str, char x) { // Traverse from right for (int i = str.Length - 1; i >= 0; i--) if (str[i] == x) return i; return -1; } // Driver code public static void Main() { string str = "geeksforgeeks"; char x = 'e'; int index = findLastIndex(str, x); if (index == -1) Console.WriteLine("Character not found"); else Console.WriteLine("Last index is " + index); }}// This code is contributed by vt_m
<?php// Simple PHP program to find last index// of character x in given string. // Returns last index of x if it// is present. Else returns -1.function findLastIndex($str, $x){ // Traverse from right for ($i = strlen($str) - 1; $i >= 0; $i--) if ($str[$i] == $x) return $i; return -1;} // Driver code$str = "geeksforgeeks";$x = 'e';$index = findLastIndex($str, $x);if ($index == -1) echo("Character not found");else echo("Last index is " . $index); // This code is contributed by Ajit.?>
<script> // Javascript code to find last index character x in given string. // Returns last index of x if // it is present. Else returns -1. function findLastIndex(str, x) { // Traverse from right for (let i = str.length - 1; i >= 0; i--) if (str[i] == x) return i; return -1; } let str = "geeksforgeeks"; let x = 'e'; let index = findLastIndex(str, x); if (index == -1) document.write("Character not found"); else document.write("Last index is " + index); </script>
Output:
Last index is 10
Time Complexity : O(n)
YouTubeGeeksforGeeks500K subscribersFind last index of a character in a string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:09•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Ih9YswsVyn0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
shrikanth13
jit_t
Smitha Dinesh Semwal
sanjoy_62
mukesh07
Searching
Strings
Technical Scripter
Searching
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Split the given array into K sub-arrays such that maximum sum of all sub arrays is minimum
Best First Search (Informed Search)
3 Different ways to print Fibonacci series in Java
Find whether an array is subset of another array | Added Method 5
Program to remove vowels from a String
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
|
[
{
"code": null,
"e": 24616,
"s": 24588,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 24695,
"s": 24616,
"text": "Given a string str and a character x, find last index of x in str.Examples : "
},
{
"code": null,
"e": 24848,
"s": 24695,
"text": "Input : str = \"geeks\", x = 'e'\nOutput : 2\nLast index of 'e' in \"geeks\" is: 2 \n\nInput : str = \"Hello world!\", x = 'o'\nOutput : 7\nLast index of 'o' is: 7 "
},
{
"code": null,
"e": 25001,
"s": 24850,
"text": "Method 1 (Simple : Traverse from left) : Traverse given string from left to right and keep updating index whenever x matches with current character. "
},
{
"code": null,
"e": 25005,
"s": 25001,
"text": "C++"
},
{
"code": null,
"e": 25010,
"s": 25005,
"text": "Java"
},
{
"code": null,
"e": 25018,
"s": 25010,
"text": "Python3"
},
{
"code": null,
"e": 25021,
"s": 25018,
"text": "C#"
},
{
"code": null,
"e": 25025,
"s": 25021,
"text": "PHP"
},
{
"code": null,
"e": 25036,
"s": 25025,
"text": "Javascript"
},
{
"code": "// CPP program to find last index of// character x in given string.#include <iostream>using namespace std; // Returns last index of x if it is present.// Else returns -1.int findLastIndex(string& str, char x){ int index = -1; for (int i = 0; i < str.length(); i++) if (str[i] == x) index = i; return index;} // Driver codeint main(){ // String in which char is to be found string str = \"geeksforgeeks\"; // char whose index is to be found char x = 'e'; int index = findLastIndex(str, x); if (index == -1) cout << \"Character not found\"; else cout << \"Last index is \" << index; return 0;}",
"e": 25688,
"s": 25036,
"text": null
},
{
"code": "// Java program to find last index// of character x in given string.import java.io.*; class GFG { // Returns last index of x if// it is present Else returns -1.static int findLastIndex(String str, Character x){ int index = -1; for (int i = 0; i < str.length(); i++) if (str.charAt(i) == x) index = i; return index;} // Driver codepublic static void main(String[] args){ // String in which char is to be found String str = \"geeksforgeeks\"; // char whose index is to be found Character x = 'e'; int index = findLastIndex(str, x); if (index == -1) System.out.println(\"Character not found\"); else System.out.println(\"Last index is \" + index);}} /* This code is contributed by Prerna Saini */",
"e": 26442,
"s": 25688,
"text": null
},
{
"code": "# A Python program to find last# index of character x in given# string. # Returns last index of x if it# is present. Else returns -1.def findLastIndex(str, x): index = -1 for i in range(0, len(str)): if str[i] == x: index = i return index # Driver program # String in which char is to be foundstr = \"geeksforgeeks\" # char whose index is to be foundx = 'e' index = findLastIndex(str, x) if index == -1: print(\"Character not found\")else: print('Last index is', index) # This code is contributed by shrikant13.",
"e": 26983,
"s": 26442,
"text": null
},
{
"code": "// C# program to find last index// of character x in given string.using System; class GFG { // Returns last index of x if // it is present Else returns -1. static int findLastIndex(string str, char x) { int index = -1; for (int i = 0; i < str.Length; i++) if (str[i] == x) index = i; return index; } // Driver code public static void Main() { // String in which char is to be found string str = \"geeksforgeeks\"; // char whose index is to be found char x = 'e'; int index = findLastIndex(str, x); if (index == -1) Console.WriteLine(\"Character not found\"); else Console.WriteLine(\"Last index is \" + index); }} /* This code is contributed by vt_m */",
"e": 27791,
"s": 26983,
"text": null
},
{
"code": "<?php// PHP program to find last index of// character x in given string. // Returns last index of// x if it is present.// Else returns -1.function findLastIndex($str, $x){ $index = -1; for ($i = 0; $i < strlen($str); $i++) if ($str[$i] == $x) $index = $i; return $index;} // Driver code// String in which// char is to be found$str = \"geeksforgeeks\"; // char whose index// is to be found$x = 'e';$index = findLastIndex($str, $x);if ($index == -1) echo(\"Character not found\");else echo(\"Last index is \" . $index); // This code is contributed by Ajit.?>",
"e": 28375,
"s": 27791,
"text": null
},
{
"code": "<script>// javascript program to find last index// of character x in given string. // Returns last index of x if// it is present Else returns -1.function findLastIndex(str, x){ let index = -1; for (let i = 0; i < str.length; i++) if (str[i] == x) index = i; return index;} // Driver code // String in which char is to be found let str = \"geeksforgeeks\"; // char whose index is to be found let x = 'e'; let index = findLastIndex(str, x); if (index == -1) document.write(\"Character not found\"); else document.write(\"Last index is \" + index); // This code is contributed by sanjoy_62.</script>",
"e": 29047,
"s": 28375,
"text": null
},
{
"code": null,
"e": 29057,
"s": 29047,
"text": "Output: "
},
{
"code": null,
"e": 29074,
"s": 29057,
"text": "Last index is 10"
},
{
"code": null,
"e": 29362,
"s": 29074,
"text": "Time Complexity : Θ(n)Method 2 (Efficient : Traverse from right) : In above method 1, we always traverse complete string. In this method, we can avoid complete traversal in all those cases when x is present. The idea is to traverse from right side and stop as soon as we find character. "
},
{
"code": null,
"e": 29366,
"s": 29362,
"text": "CPP"
},
{
"code": null,
"e": 29371,
"s": 29366,
"text": "Java"
},
{
"code": null,
"e": 29379,
"s": 29371,
"text": "Python3"
},
{
"code": null,
"e": 29382,
"s": 29379,
"text": "C#"
},
{
"code": null,
"e": 29386,
"s": 29382,
"text": "PHP"
},
{
"code": null,
"e": 29397,
"s": 29386,
"text": "Javascript"
},
{
"code": "// Simple CPP program to find last index of// character x in given string.#include <iostream>using namespace std; // Returns last index of x if it is present.// Else returns -1.int findLastIndex(string& str, char x){ // Traverse from right for (int i = str.length() - 1; i >= 0; i--) if (str[i] == x) return i; return -1;} // Driver codeint main(){ string str = \"geeksforgeeks\"; char x = 'e'; int index = findLastIndex(str, x); if (index == -1) cout << \"Character not found\"; else cout << \"Last index is \" << index; return 0;}",
"e": 29984,
"s": 29397,
"text": null
},
{
"code": "// Java code to find last index// character x in given string.import java.io.*;class GFG { // Returns last index of x if// it is present. Else returns -1.static int findLastIndex(String str, Character x){ // Traverse from right for (int i = str.length() - 1; i >= 0; i--) if (str.charAt(i) == x) return i; return -1;} // Driver codepublic static void main(String[] args){ String str = \"geeksforgeeks\"; Character x = 'e'; int index = findLastIndex(str, x); if (index == -1) System.out.println(\"Character not found\"); else System.out.println(\"Last index is \" + index);}}// This code is contributed by Prerna Saini",
"e": 30655,
"s": 29984,
"text": null
},
{
"code": "# Simple Python3 program to find last# index of character x in given string. # Returns last index of x if it is# present. Else returns -1.def findLastIndex(str, x): # Traverse from right for i in range(len(str) - 1, -1,-1): if (str[i] == x): return i return -1 # Driver codestr = \"geeksforgeeks\"x = 'e'index = findLastIndex(str, x) if (index == -1): print(\"Character not found\")else: print(\"Last index is \" ,index) # This code is contributed by Smitha",
"e": 31142,
"s": 30655,
"text": null
},
{
"code": "// C# code to find last index// character x in given string.using System; class GFG { // Returns last index of x if // it is present. Else returns -1. static int findLastIndex(string str, char x) { // Traverse from right for (int i = str.Length - 1; i >= 0; i--) if (str[i] == x) return i; return -1; } // Driver code public static void Main() { string str = \"geeksforgeeks\"; char x = 'e'; int index = findLastIndex(str, x); if (index == -1) Console.WriteLine(\"Character not found\"); else Console.WriteLine(\"Last index is \" + index); }}// This code is contributed by vt_m",
"e": 31856,
"s": 31142,
"text": null
},
{
"code": "<?php// Simple PHP program to find last index// of character x in given string. // Returns last index of x if it// is present. Else returns -1.function findLastIndex($str, $x){ // Traverse from right for ($i = strlen($str) - 1; $i >= 0; $i--) if ($str[$i] == $x) return $i; return -1;} // Driver code$str = \"geeksforgeeks\";$x = 'e';$index = findLastIndex($str, $x);if ($index == -1) echo(\"Character not found\");else echo(\"Last index is \" . $index); // This code is contributed by Ajit.?>",
"e": 32383,
"s": 31856,
"text": null
},
{
"code": "<script> // Javascript code to find last index character x in given string. // Returns last index of x if // it is present. Else returns -1. function findLastIndex(str, x) { // Traverse from right for (let i = str.length - 1; i >= 0; i--) if (str[i] == x) return i; return -1; } let str = \"geeksforgeeks\"; let x = 'e'; let index = findLastIndex(str, x); if (index == -1) document.write(\"Character not found\"); else document.write(\"Last index is \" + index); </script>",
"e": 32968,
"s": 32383,
"text": null
},
{
"code": null,
"e": 32978,
"s": 32968,
"text": "Output: "
},
{
"code": null,
"e": 32995,
"s": 32978,
"text": "Last index is 10"
},
{
"code": null,
"e": 33020,
"s": 32995,
"text": "Time Complexity : O(n) "
},
{
"code": null,
"e": 33861,
"s": 33020,
"text": "YouTubeGeeksforGeeks500K subscribersFind last index of a character in a string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:09•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Ih9YswsVyn0\" 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": 33875,
"s": 33863,
"text": "shrikanth13"
},
{
"code": null,
"e": 33881,
"s": 33875,
"text": "jit_t"
},
{
"code": null,
"e": 33902,
"s": 33881,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 33912,
"s": 33902,
"text": "sanjoy_62"
},
{
"code": null,
"e": 33921,
"s": 33912,
"text": "mukesh07"
},
{
"code": null,
"e": 33931,
"s": 33921,
"text": "Searching"
},
{
"code": null,
"e": 33939,
"s": 33931,
"text": "Strings"
},
{
"code": null,
"e": 33958,
"s": 33939,
"text": "Technical Scripter"
},
{
"code": null,
"e": 33968,
"s": 33958,
"text": "Searching"
},
{
"code": null,
"e": 33976,
"s": 33968,
"text": "Strings"
},
{
"code": null,
"e": 34074,
"s": 33976,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34083,
"s": 34074,
"text": "Comments"
},
{
"code": null,
"e": 34096,
"s": 34083,
"text": "Old Comments"
},
{
"code": null,
"e": 34187,
"s": 34096,
"text": "Split the given array into K sub-arrays such that maximum sum of all sub arrays is minimum"
},
{
"code": null,
"e": 34223,
"s": 34187,
"text": "Best First Search (Informed Search)"
},
{
"code": null,
"e": 34274,
"s": 34223,
"text": "3 Different ways to print Fibonacci series in Java"
},
{
"code": null,
"e": 34340,
"s": 34274,
"text": "Find whether an array is subset of another array | Added Method 5"
},
{
"code": null,
"e": 34379,
"s": 34340,
"text": "Program to remove vowels from a String"
},
{
"code": null,
"e": 34404,
"s": 34379,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 34450,
"s": 34404,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 34484,
"s": 34450,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 34544,
"s": 34484,
"text": "Write a program to print all permutations of a given string"
}
] |
PHP - Function MySQLi Fetch Object
|
mysqli_fetch_object(result,classname,params);
It returns the current row of a result set, as an object.
It returns string properties for the fetched row or NULL if there are no more rows in the result set
result
It specifies the result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()
classname
It specifies the name of the class to instantiate
params
It specifies an array of parameters to pass to the constructor for classname objects
Try out the following example
<?php
$connection_mysql = mysqli_connect("localhost","user","password","db");
if (mysqli_connect_errno($connection_mysql)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT name FROM emp";
if ($result = mysqli_query($connection_mysql,$sql)){
while ($obj = mysqli_fetch_object($result)){
print $obj->name;
print "\n";
}
mysqli_free_result($result);
}
mysqli_close($connection_mysql);
?>
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": 2804,
"s": 2757,
"text": "mysqli_fetch_object(result,classname,params);\n"
},
{
"code": null,
"e": 2862,
"s": 2804,
"text": "It returns the current row of a result set, as an object."
},
{
"code": null,
"e": 2963,
"s": 2862,
"text": "It returns string properties for the fetched row or NULL if there are no more rows in the result set"
},
{
"code": null,
"e": 2970,
"s": 2963,
"text": "result"
},
{
"code": null,
"e": 3082,
"s": 2970,
"text": "It specifies the result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()"
},
{
"code": null,
"e": 3092,
"s": 3082,
"text": "classname"
},
{
"code": null,
"e": 3142,
"s": 3092,
"text": "It specifies the name of the class to instantiate"
},
{
"code": null,
"e": 3149,
"s": 3142,
"text": "params"
},
{
"code": null,
"e": 3234,
"s": 3149,
"text": "It specifies an array of parameters to pass to the constructor for classname objects"
},
{
"code": null,
"e": 3264,
"s": 3234,
"text": "Try out the following example"
},
{
"code": null,
"e": 3755,
"s": 3264,
"text": "<?php\n $connection_mysql = mysqli_connect(\"localhost\",\"user\",\"password\",\"db\");\n \n if (mysqli_connect_errno($connection_mysql)){\n echo \"Failed to connect to MySQL: \" . mysqli_connect_error();\n }\n \n $sql = \"SELECT name FROM emp\";\n \n if ($result = mysqli_query($connection_mysql,$sql)){\n while ($obj = mysqli_fetch_object($result)){\n print $obj->name;\n print \"\\n\";\n }\n mysqli_free_result($result);\n }\n mysqli_close($connection_mysql);\n?>"
},
{
"code": null,
"e": 3788,
"s": 3755,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 3804,
"s": 3788,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3837,
"s": 3804,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3848,
"s": 3837,
"text": " Syed Raza"
},
{
"code": null,
"e": 3883,
"s": 3848,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3900,
"s": 3883,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3933,
"s": 3900,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3948,
"s": 3933,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 3983,
"s": 3948,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 3995,
"s": 3983,
"text": " Azaz Patel"
},
{
"code": null,
"e": 4030,
"s": 3995,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4058,
"s": 4030,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 4065,
"s": 4058,
"text": " Print"
},
{
"code": null,
"e": 4076,
"s": 4065,
"text": " Add Notes"
}
] |
How to Use IterativeImputer and KNNImputer For Powerful Missing Data Imputation | Towards Data Science
|
Despite the massive number of MOOCs and other online resources, there are still skill gaps in dealing with certain data problems. One example is properly dealing with missing data in real-world datasets. Beginner learners might take this problem lightly, and they are not to blame. Even though it is such a pressing issue, the complexity of data missingness problems has been greatly underestimated because of the availability of small, easy-to-work-with toy datasets.
As a result, many beginner data scientists don’t go beyond simple mean, median, or mode imputation. Though these methods may suffice for simple datasets, they are in no way a competent solution to handling missing data in large datasets.
Like any other stage of data science workflow, missing data imputation is an iterative process. You should be able to use multiple methods and compare their results effectively. While the basic methods may perform well, it is rarely the case, and you have to have a few backup strategies.
This tutorial will introduce two, more robust model-based imputation algorithms native to Sklearn — KNNImputer and IterativeImputer. You will learn their basic usage, tune their parameters, and finally, see how to compare their results visually.
The first step to implementing an effective strategy is to identify why the values are missing. Even though each case is unique, missingness can be grouped into 3 broad categories:
Missing Completely At Random (MCAR): this is a genuine case of data missing randomly. Examples are sudden mistakes in data entry, temporary sensor failures, or generally missing data that is not associated with any outside factor. The amount of missingness is low.
Missing At Random (MAR): this is a broader case of MCAR. Even though missing data may seem random at first glance, it will have some systematic relationship with the other observed features—for example — data missing from observational equipment during the times of scheduled maintenance breaks. The number of null values may vary.
Missing Not At Random (MNAR): missing values may exist in large amounts, and the reason for the missingness is associated with factors beyond our control or knowledge.
Identifying which category your problem falls into can help narrow down the set of solutions you can apply.
Let’s further explore these missingness types using the Diabetes dataset:
There are 5 features with different proportions of missing values. A first step in identifying the missingness type is to plot a missingness matrix. This special plot is available through the missingno package which we can import as msno:
This matrix shows how nulls are scattered across the dataset. White segments or lines represent where missing values lie. Glucose, BMI, and blood pressure columns can be considered MCAR because of two reasons:
The proportion of missing values is small.
Missing values are scattered completely randomly in the dataset.
However, a large proportion of data points are missing in both Insulin and SkinFoldThickness. So, is there some relationship between their missingness?
To answer this, MSNO provides a missingness heatmap that shows the missingness correlation:
>>> msno.heatmap(diabetes);
From the plot, we can see a strong correlation between Skin Thickness and Insulin. We can confirm this by sorting either of them:
>>> msno.matrix(diabetes.sort_values("Insulin"));
This plot proves that we can not understand why there are missing values in these two columns leading to a conclusion that they are MNAR. We also saw a weak correlation between blood pressure and skin thickness which disproves our first assumption. Rather than being MCAR, blood pressure is missing at random (MAR).
These missingness categories can be a lot to wrap your mind around. For a deeper insight, you can refer to my other article specifically on missingness types and the MSNO package:
towardsdev.com
Apart from the SimpleImputer, Sklearn provides KNNImputer class which uses the K-Nearest-Neighbors algorithm to impute numeric values. If you are not familiar with it, I recommend reading my separate article on it:
towardsdatascience.com
For reference, here is an excerpt from the article briefly touching on how the algorithm works:
“Imagine you have a variable with 2 categories which are visualized here:
Given a new, unknown sample, how do you tell which group it belongs to? Well, naturally, you would look at the surrounding points. But the result would be really dependent on how far you look. If you look at the closest 3 (solid circle), the green dot would belong to red triangles. If you look further, (the dashed circle) dot would be classified as a blue square.
kNN works the same way. Depending on the value of k, the algorithm classifies new samples by the majority vote of the nearest k neighbors in classification. For regression, which predicts the actual numerical value of a new sample, the algorithm takes the mean of the nearest k neighbors. “
KNNImputer is a slightly modified version of the algorithm where it tries to predict the value of numeric nullity by averaging the distances between its k nearest neighbors. For folks who have been using Sklearn for a time, its syntax should not be a problem:
With this imputer, the problem is choosing the right value for k. As you cannot use GridSearch to tune it, we can take a visual approach for comparison:
In the above plot, we compare the different KNN imputations for the SkinThickness feature using Probability Density plots. The closer the imputed distribution comes to the original, the better was the imputation. Here, it seems k=2 is the best choice.
Another more robust but more computationally expensive technique would be using IterativeImputer. It takes an arbitrary Sklearn estimator and tries to impute missing values by modeling other features as a function of features with missing values. Here is a more granular, step-by-step explanation of its functionality:
A regressor is passed to the transformer.The first feature (feature_1) with missing values is chosen.The data is split into train/test sets where the train set contains all the known values for feature_1, and the test set contains the missing samples.The regressor is fit on all the other variables as inputs and with feature_1 as an output.The regressor predicts the missing values.The transformer continues this process until all features are imputed.Steps 1–6 are called a single iteration round. These steps are carried out multiple times as specified by the max_iter parameter of the transformer.
A regressor is passed to the transformer.
The first feature (feature_1) with missing values is chosen.
The data is split into train/test sets where the train set contains all the known values for feature_1, and the test set contains the missing samples.
The regressor is fit on all the other variables as inputs and with feature_1 as an output.
The regressor predicts the missing values.
The transformer continues this process until all features are imputed.
Steps 1–6 are called a single iteration round. These steps are carried out multiple times as specified by the max_iter parameter of the transformer.
This means that IterativeImputer (II) predicts not one but max_iter number of possible values for a single missing sample. This has the benefit of treating each missing data point as a random variable and associate the inherent uncertainty that comes with missing values. This is also called multiple imputation, and it is the base for most other imputation techniques out there (yes, there are so many others).
When all iterations are done, II returns only the last result of the predictions because, through each iteration, the predictions get better and better (like gradient descent). The algorithm also has an early stopping feature which can terminate the iterations if there isn’t a considerable difference between rounds.
According to Sklearn, this implementation of IterativeImputer was inspired by the more popular R MICE package (Multivariate Imputation by Chained Equations). Let’s see it in action:
IterativeImputer is still an experimental feature, so don't forget to include the second line of the above snippet.
When estimator is set to None, the algorithm chooses it on its own. But, after reading this official guide on IterativeImputer by Sklearn, I learned that BayesianRidge and ExtraTreeRegressor yield the best results.
It is time to test how well the imputations work. To accomplish this, we will be predicting if a patient has diabetes or not (outcome), so it is a binary classification task. Let’s build feature/target arrays:
We will test both KNNImputer and IterativeImputer using cross-validation. For the estimators, we will use the recommended BayesianRidge and ExtraTreesRegressor:
We can see from the final results that KNNImputer with 7 neighbors is the best choice for the dataset when trained on RandomForests. Even though I mentioned that IterativeImputer would be more robust, you can never be sure. Maybe, we could have achieved better performance by tuning its parameters more.
Missing data is a problem that should be taken seriously. There is no point in spending hours learning complex ML algorithms if you can’t even fix the prerequisite data problems. Always remember that a model is only as good as the data it was trained on. This means you have to do your best in dealing with missing data points as they are ubiquitous in real-world datasets.
In this article, you learned how to deal with missingness using two model-based techniques: KNNImputer and IterativeImputer. Below are links to their documentation, an official Sklearn guide on their usage, and related sources that will help your understanding:
Imputation of missing values, Sklearn Guide
IterativeImputer documentation
KNNImputer documentation
Imputing missing values with variants of IterativeImputer
Thanks for reading!
How to Differentiate Between Scaling, Normalization, and Log Transformations
How to Perform Operator Overloading in Python OOP
Practical Sklearn Feature Selection in 3 stages
|
[
{
"code": null,
"e": 641,
"s": 172,
"text": "Despite the massive number of MOOCs and other online resources, there are still skill gaps in dealing with certain data problems. One example is properly dealing with missing data in real-world datasets. Beginner learners might take this problem lightly, and they are not to blame. Even though it is such a pressing issue, the complexity of data missingness problems has been greatly underestimated because of the availability of small, easy-to-work-with toy datasets."
},
{
"code": null,
"e": 879,
"s": 641,
"text": "As a result, many beginner data scientists don’t go beyond simple mean, median, or mode imputation. Though these methods may suffice for simple datasets, they are in no way a competent solution to handling missing data in large datasets."
},
{
"code": null,
"e": 1168,
"s": 879,
"text": "Like any other stage of data science workflow, missing data imputation is an iterative process. You should be able to use multiple methods and compare their results effectively. While the basic methods may perform well, it is rarely the case, and you have to have a few backup strategies."
},
{
"code": null,
"e": 1414,
"s": 1168,
"text": "This tutorial will introduce two, more robust model-based imputation algorithms native to Sklearn — KNNImputer and IterativeImputer. You will learn their basic usage, tune their parameters, and finally, see how to compare their results visually."
},
{
"code": null,
"e": 1595,
"s": 1414,
"text": "The first step to implementing an effective strategy is to identify why the values are missing. Even though each case is unique, missingness can be grouped into 3 broad categories:"
},
{
"code": null,
"e": 1860,
"s": 1595,
"text": "Missing Completely At Random (MCAR): this is a genuine case of data missing randomly. Examples are sudden mistakes in data entry, temporary sensor failures, or generally missing data that is not associated with any outside factor. The amount of missingness is low."
},
{
"code": null,
"e": 2192,
"s": 1860,
"text": "Missing At Random (MAR): this is a broader case of MCAR. Even though missing data may seem random at first glance, it will have some systematic relationship with the other observed features—for example — data missing from observational equipment during the times of scheduled maintenance breaks. The number of null values may vary."
},
{
"code": null,
"e": 2360,
"s": 2192,
"text": "Missing Not At Random (MNAR): missing values may exist in large amounts, and the reason for the missingness is associated with factors beyond our control or knowledge."
},
{
"code": null,
"e": 2468,
"s": 2360,
"text": "Identifying which category your problem falls into can help narrow down the set of solutions you can apply."
},
{
"code": null,
"e": 2542,
"s": 2468,
"text": "Let’s further explore these missingness types using the Diabetes dataset:"
},
{
"code": null,
"e": 2781,
"s": 2542,
"text": "There are 5 features with different proportions of missing values. A first step in identifying the missingness type is to plot a missingness matrix. This special plot is available through the missingno package which we can import as msno:"
},
{
"code": null,
"e": 2991,
"s": 2781,
"text": "This matrix shows how nulls are scattered across the dataset. White segments or lines represent where missing values lie. Glucose, BMI, and blood pressure columns can be considered MCAR because of two reasons:"
},
{
"code": null,
"e": 3034,
"s": 2991,
"text": "The proportion of missing values is small."
},
{
"code": null,
"e": 3099,
"s": 3034,
"text": "Missing values are scattered completely randomly in the dataset."
},
{
"code": null,
"e": 3251,
"s": 3099,
"text": "However, a large proportion of data points are missing in both Insulin and SkinFoldThickness. So, is there some relationship between their missingness?"
},
{
"code": null,
"e": 3343,
"s": 3251,
"text": "To answer this, MSNO provides a missingness heatmap that shows the missingness correlation:"
},
{
"code": null,
"e": 3371,
"s": 3343,
"text": ">>> msno.heatmap(diabetes);"
},
{
"code": null,
"e": 3501,
"s": 3371,
"text": "From the plot, we can see a strong correlation between Skin Thickness and Insulin. We can confirm this by sorting either of them:"
},
{
"code": null,
"e": 3551,
"s": 3501,
"text": ">>> msno.matrix(diabetes.sort_values(\"Insulin\"));"
},
{
"code": null,
"e": 3867,
"s": 3551,
"text": "This plot proves that we can not understand why there are missing values in these two columns leading to a conclusion that they are MNAR. We also saw a weak correlation between blood pressure and skin thickness which disproves our first assumption. Rather than being MCAR, blood pressure is missing at random (MAR)."
},
{
"code": null,
"e": 4047,
"s": 3867,
"text": "These missingness categories can be a lot to wrap your mind around. For a deeper insight, you can refer to my other article specifically on missingness types and the MSNO package:"
},
{
"code": null,
"e": 4062,
"s": 4047,
"text": "towardsdev.com"
},
{
"code": null,
"e": 4277,
"s": 4062,
"text": "Apart from the SimpleImputer, Sklearn provides KNNImputer class which uses the K-Nearest-Neighbors algorithm to impute numeric values. If you are not familiar with it, I recommend reading my separate article on it:"
},
{
"code": null,
"e": 4300,
"s": 4277,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4396,
"s": 4300,
"text": "For reference, here is an excerpt from the article briefly touching on how the algorithm works:"
},
{
"code": null,
"e": 4470,
"s": 4396,
"text": "“Imagine you have a variable with 2 categories which are visualized here:"
},
{
"code": null,
"e": 4836,
"s": 4470,
"text": "Given a new, unknown sample, how do you tell which group it belongs to? Well, naturally, you would look at the surrounding points. But the result would be really dependent on how far you look. If you look at the closest 3 (solid circle), the green dot would belong to red triangles. If you look further, (the dashed circle) dot would be classified as a blue square."
},
{
"code": null,
"e": 5127,
"s": 4836,
"text": "kNN works the same way. Depending on the value of k, the algorithm classifies new samples by the majority vote of the nearest k neighbors in classification. For regression, which predicts the actual numerical value of a new sample, the algorithm takes the mean of the nearest k neighbors. “"
},
{
"code": null,
"e": 5387,
"s": 5127,
"text": "KNNImputer is a slightly modified version of the algorithm where it tries to predict the value of numeric nullity by averaging the distances between its k nearest neighbors. For folks who have been using Sklearn for a time, its syntax should not be a problem:"
},
{
"code": null,
"e": 5540,
"s": 5387,
"text": "With this imputer, the problem is choosing the right value for k. As you cannot use GridSearch to tune it, we can take a visual approach for comparison:"
},
{
"code": null,
"e": 5792,
"s": 5540,
"text": "In the above plot, we compare the different KNN imputations for the SkinThickness feature using Probability Density plots. The closer the imputed distribution comes to the original, the better was the imputation. Here, it seems k=2 is the best choice."
},
{
"code": null,
"e": 6111,
"s": 5792,
"text": "Another more robust but more computationally expensive technique would be using IterativeImputer. It takes an arbitrary Sklearn estimator and tries to impute missing values by modeling other features as a function of features with missing values. Here is a more granular, step-by-step explanation of its functionality:"
},
{
"code": null,
"e": 6713,
"s": 6111,
"text": "A regressor is passed to the transformer.The first feature (feature_1) with missing values is chosen.The data is split into train/test sets where the train set contains all the known values for feature_1, and the test set contains the missing samples.The regressor is fit on all the other variables as inputs and with feature_1 as an output.The regressor predicts the missing values.The transformer continues this process until all features are imputed.Steps 1–6 are called a single iteration round. These steps are carried out multiple times as specified by the max_iter parameter of the transformer."
},
{
"code": null,
"e": 6755,
"s": 6713,
"text": "A regressor is passed to the transformer."
},
{
"code": null,
"e": 6816,
"s": 6755,
"text": "The first feature (feature_1) with missing values is chosen."
},
{
"code": null,
"e": 6967,
"s": 6816,
"text": "The data is split into train/test sets where the train set contains all the known values for feature_1, and the test set contains the missing samples."
},
{
"code": null,
"e": 7058,
"s": 6967,
"text": "The regressor is fit on all the other variables as inputs and with feature_1 as an output."
},
{
"code": null,
"e": 7101,
"s": 7058,
"text": "The regressor predicts the missing values."
},
{
"code": null,
"e": 7172,
"s": 7101,
"text": "The transformer continues this process until all features are imputed."
},
{
"code": null,
"e": 7321,
"s": 7172,
"text": "Steps 1–6 are called a single iteration round. These steps are carried out multiple times as specified by the max_iter parameter of the transformer."
},
{
"code": null,
"e": 7733,
"s": 7321,
"text": "This means that IterativeImputer (II) predicts not one but max_iter number of possible values for a single missing sample. This has the benefit of treating each missing data point as a random variable and associate the inherent uncertainty that comes with missing values. This is also called multiple imputation, and it is the base for most other imputation techniques out there (yes, there are so many others)."
},
{
"code": null,
"e": 8051,
"s": 7733,
"text": "When all iterations are done, II returns only the last result of the predictions because, through each iteration, the predictions get better and better (like gradient descent). The algorithm also has an early stopping feature which can terminate the iterations if there isn’t a considerable difference between rounds."
},
{
"code": null,
"e": 8233,
"s": 8051,
"text": "According to Sklearn, this implementation of IterativeImputer was inspired by the more popular R MICE package (Multivariate Imputation by Chained Equations). Let’s see it in action:"
},
{
"code": null,
"e": 8349,
"s": 8233,
"text": "IterativeImputer is still an experimental feature, so don't forget to include the second line of the above snippet."
},
{
"code": null,
"e": 8564,
"s": 8349,
"text": "When estimator is set to None, the algorithm chooses it on its own. But, after reading this official guide on IterativeImputer by Sklearn, I learned that BayesianRidge and ExtraTreeRegressor yield the best results."
},
{
"code": null,
"e": 8774,
"s": 8564,
"text": "It is time to test how well the imputations work. To accomplish this, we will be predicting if a patient has diabetes or not (outcome), so it is a binary classification task. Let’s build feature/target arrays:"
},
{
"code": null,
"e": 8935,
"s": 8774,
"text": "We will test both KNNImputer and IterativeImputer using cross-validation. For the estimators, we will use the recommended BayesianRidge and ExtraTreesRegressor:"
},
{
"code": null,
"e": 9239,
"s": 8935,
"text": "We can see from the final results that KNNImputer with 7 neighbors is the best choice for the dataset when trained on RandomForests. Even though I mentioned that IterativeImputer would be more robust, you can never be sure. Maybe, we could have achieved better performance by tuning its parameters more."
},
{
"code": null,
"e": 9613,
"s": 9239,
"text": "Missing data is a problem that should be taken seriously. There is no point in spending hours learning complex ML algorithms if you can’t even fix the prerequisite data problems. Always remember that a model is only as good as the data it was trained on. This means you have to do your best in dealing with missing data points as they are ubiquitous in real-world datasets."
},
{
"code": null,
"e": 9875,
"s": 9613,
"text": "In this article, you learned how to deal with missingness using two model-based techniques: KNNImputer and IterativeImputer. Below are links to their documentation, an official Sklearn guide on their usage, and related sources that will help your understanding:"
},
{
"code": null,
"e": 9919,
"s": 9875,
"text": "Imputation of missing values, Sklearn Guide"
},
{
"code": null,
"e": 9950,
"s": 9919,
"text": "IterativeImputer documentation"
},
{
"code": null,
"e": 9975,
"s": 9950,
"text": "KNNImputer documentation"
},
{
"code": null,
"e": 10033,
"s": 9975,
"text": "Imputing missing values with variants of IterativeImputer"
},
{
"code": null,
"e": 10053,
"s": 10033,
"text": "Thanks for reading!"
},
{
"code": null,
"e": 10130,
"s": 10053,
"text": "How to Differentiate Between Scaling, Normalization, and Log Transformations"
},
{
"code": null,
"e": 10180,
"s": 10130,
"text": "How to Perform Operator Overloading in Python OOP"
}
] |
Extracting Keywords from a Text Using R Regex (Easy) | by Deborah Kewon | Towards Data Science
|
When you have a large volume of text files, extracting only relevant information is not so easy. It is complicated and time-consuming. For this reason, I want to show you how I used Regex to extract locations from U.S. job description.
Here is the structure of a job description. My goal is to extract only states from this text column.
The state has a trailing space, which is located at the end of a line without any characters following it. If you do not remove it (\\n), you will end up extracting extra words.
Also, it is important to keep the state abbreviation in capital letters (‘CA’ rather than ‘ca’ for California) because if you don’t do this, it will extract all the words that have ‘ca’ in them.
# deleting punctuationsdescription$text<-gsub("[[:punct:][:blank:]]+", " ", description$text)# deleting trailing spacedescription$text<-gsub("\\n"," ", description$text)
After cleaning, you can split the job description text by space and find the string that matches the list of state abbreviations (dictionary). Once it is done, you can assign it to the location column as below.
#creating a location columndescription$location <- NA #using for loop to extract all the states for (i in 1:length(description$text)){ #split the text by space split <- strsplit(description$text[i]," ")[[1]] #comparing split with the state abbreviation state <- match(split, stateabbreviation$Abbreviation) #if it matches, get the position of each state state <- which(!is.na(state)) #extract the state based on the position state_split <- split[state] #adding states to the new column description$location[i] <- state_split[1] }
In order to find the state abbreviations in the job description, I used the dictionary “stateabbreviation” I created.
And...Voila! Here is the result.
If you want to also extract the cities, you can simply use the same code with ‘which(!is.na(location))-1’. You use ‘-1’ because the cities come right before the states.
Now you can visualize it to have a better understanding of your finding.
library(ggplot2)state_count<-table(description$location)state_count<-as.data.frame(state_count)ggplot(state_count, aes(x = as.character(state_count$Var1), y = state_count$Freq)) + geom_bar(stat="identity") + theme(axis.text.x = element_text(angle = 60, vjust = )) + labs(y = "Frequency", x= "States")
This is part of my work to have a better understanding of the current data science job market. According to this result, California, New York, and Texas are in high need of data/tech-savvy professionals.
For more details regarding my text mining project, please feel free to visit my GitHub page. Thank you for reading!
Also, feel free to check out my other articles:
How to Get Twitter Notifications on Currency Exchange Rate: Web Scraping and Automation
Databricks: How to Save Data Frames as CSV Files on Your Local Computer
|
[
{
"code": null,
"e": 408,
"s": 172,
"text": "When you have a large volume of text files, extracting only relevant information is not so easy. It is complicated and time-consuming. For this reason, I want to show you how I used Regex to extract locations from U.S. job description."
},
{
"code": null,
"e": 509,
"s": 408,
"text": "Here is the structure of a job description. My goal is to extract only states from this text column."
},
{
"code": null,
"e": 687,
"s": 509,
"text": "The state has a trailing space, which is located at the end of a line without any characters following it. If you do not remove it (\\\\n), you will end up extracting extra words."
},
{
"code": null,
"e": 882,
"s": 687,
"text": "Also, it is important to keep the state abbreviation in capital letters (‘CA’ rather than ‘ca’ for California) because if you don’t do this, it will extract all the words that have ‘ca’ in them."
},
{
"code": null,
"e": 1052,
"s": 882,
"text": "# deleting punctuationsdescription$text<-gsub(\"[[:punct:][:blank:]]+\", \" \", description$text)# deleting trailing spacedescription$text<-gsub(\"\\\\n\",\" \", description$text)"
},
{
"code": null,
"e": 1263,
"s": 1052,
"text": "After cleaning, you can split the job description text by space and find the string that matches the list of state abbreviations (dictionary). Once it is done, you can assign it to the location column as below."
},
{
"code": null,
"e": 1817,
"s": 1263,
"text": "#creating a location columndescription$location <- NA #using for loop to extract all the states for (i in 1:length(description$text)){ #split the text by space split <- strsplit(description$text[i],\" \")[[1]] #comparing split with the state abbreviation state <- match(split, stateabbreviation$Abbreviation) #if it matches, get the position of each state state <- which(!is.na(state)) #extract the state based on the position state_split <- split[state] #adding states to the new column description$location[i] <- state_split[1] }"
},
{
"code": null,
"e": 1935,
"s": 1817,
"text": "In order to find the state abbreviations in the job description, I used the dictionary “stateabbreviation” I created."
},
{
"code": null,
"e": 1968,
"s": 1935,
"text": "And...Voila! Here is the result."
},
{
"code": null,
"e": 2137,
"s": 1968,
"text": "If you want to also extract the cities, you can simply use the same code with ‘which(!is.na(location))-1’. You use ‘-1’ because the cities come right before the states."
},
{
"code": null,
"e": 2210,
"s": 2137,
"text": "Now you can visualize it to have a better understanding of your finding."
},
{
"code": null,
"e": 2511,
"s": 2210,
"text": "library(ggplot2)state_count<-table(description$location)state_count<-as.data.frame(state_count)ggplot(state_count, aes(x = as.character(state_count$Var1), y = state_count$Freq)) + geom_bar(stat=\"identity\") + theme(axis.text.x = element_text(angle = 60, vjust = )) + labs(y = \"Frequency\", x= \"States\")"
},
{
"code": null,
"e": 2715,
"s": 2511,
"text": "This is part of my work to have a better understanding of the current data science job market. According to this result, California, New York, and Texas are in high need of data/tech-savvy professionals."
},
{
"code": null,
"e": 2831,
"s": 2715,
"text": "For more details regarding my text mining project, please feel free to visit my GitHub page. Thank you for reading!"
},
{
"code": null,
"e": 2879,
"s": 2831,
"text": "Also, feel free to check out my other articles:"
},
{
"code": null,
"e": 2967,
"s": 2879,
"text": "How to Get Twitter Notifications on Currency Exchange Rate: Web Scraping and Automation"
}
] |
Explain ValueFromPipeline in PowerShell Advanced Functions.
|
Consider the below example, we have created Advanced function to get the specific process
information like Process Name, Process ID (PID), Start Time, Responding status, etc.
function Get-ProcessInformation{
[cmdletbinding()]
param(
[Parameter(Mandatory=$True)]
[string[]]$name
)
Begin{
Write-Verbose "Program started"
}
Process{
Write-Verbose "Extracting Process Inforamtion" Get-Process $name | Select Name, ID, StartTime, Responding | ft - AutoSize
}
End{
Write-Verbose "Function ends here"
}
}
Above is the advanced function example. When we run the above command, it will give us the
Process information about the selected tables.
Output
PS C:\WINDOWS\system32> Get-ProcessInformation -name Chrome
Name Id StartTime Responding
---- -- --------- ----------
chrome 1284 24-04-2020 21:29:25 True
chrome 1316 24-04-2020 21:29:37 True
chrome 2004 25-04-2020 17:12:40 True
chrome 2676 26-04-2020 10:59:37 True
chrome 3096 24-04-2020 23:39:00 True
chrome 4660 25-04-2020 22:43:34 True
chrome 6040 24-04-2020 21:29:31 True
chrome 6548 26-04-2020 10:59:30 True
chrome 6592 26-04-2020 10:59:39 True
chrome 6644 25-04-2020 16:41:59 True
chrome 6780 26-04-2020 09:53:33 True
chrome 7392 25-04-2020 11:47:22 True
chrome 10540 26-04-2020 10:56:49 True
chrome 11288 24-04-2020 21:33:05 True
chrome 12088 26-04-2020 10:59:48 True
chrome 12100 24-04-2020 21:29:38 True
chrome 13112 26-04-2020 10:59:48 True
chrome 13460 26-04-2020 10:59:45 True
Now we will pass the above-created function as the pipeline output and check if it works?
PS C:\WINDOWS\system32> "Chrome" | Get-ProcessInformation
cmdlet Get-ProcessInformation at command pipeline position 1
Supply values for the following parameters:
name:
Get-ProcessInformation : Cannot bind argument to parameter 'name' because it
is an empty string.
At line:1 char:12
+ "Chrome" | Get-ProcessInformation
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-ProcessInformation], Param eterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAl
lowed,Get-ProcessInformation
This doesn’t work because this function is not compatible to use as the Pipeline input. It doesn’t take the “chrome” as its input and asks for the value of the Name variable because of the Mandatory parameter. We simply need to add ValueFromPipeline() parameter. As we have already used the Mandatory parameter in the function so just need to add one more pipeline parameter as shown below.
function Get-ProcessInformation{
[cmdletbinding()]
param(
[Parameter(Mandatory=$True,ValuefromPipeline=$True)]
[string[]]$name
)
Begin{
Write-Verbose "Program started"
}
Process{
Write-Verbose "Extracting Process Inforamtion" Get-Process $name | Select Name, ID, StartTime, Responding | ft - AutoSize
}
End{
Write-Verbose "Function ends here"
}
}
Now, let's check if it works or not.
PS C:\WINDOWS\system32> "Chrome" | Get-ProcessInformation
Name Id StartTime Responding
---- -- --------- ----------
chrome 1284 24-04-2020 21:29:25 True
chrome 1316 24-04-2020 21:29:37 True
chrome 2004 25-04-2020 17:12:40 True
chrome 2676 26-04-2020 10:59:37 True
chrome 3096 24-04-2020 23:39:00 True
chrome 4660 25-04-2020 22:43:34 True
chrome 6040 24-04-2020 21:29:31 True
chrome 6548 26-04-2020 10:59:30 True
chrome 6592 26-04-2020 10:59:39 True
chrome 6644 25-04-2020 16:41:59 True
chrome 6780 26-04-2020 09:53:33 True
chrome 7392 25-04-2020 11:47:22 True
chrome 10540 26-04-2020 10:56:49 True
chrome 11288 24-04-2020 21:33:05 True
chrome 12088 26-04-2020 10:59:48 True
Yes, it works. Now what if we provide the two existing process names as the input, it will not provide the desired result because the string we declared in the parameter section is not an array, it is a single string variable. We will declare it as the String array now.
function Get-ProcessInformation{
[cmdletbinding()]
param(
[Parameter(Mandatory=$True,ValuefromPipeline=$True)]
[string[]]$name
)
Begin{
Write-Verbose "Program started"
}
Process{
Write-Verbose "Extracting Process Inforamtion" Get-Process $name | Select Name, ID, StartTime, Responding | ft - AutoSize
}
End{
Write-Verbose "Function ends here"
}
}
Check the output now.
PS C:\WINDOWS\system32> "Chrome","SkypeApp" | Get-ProcessInformation
Name Id StartTime Responding
---- -- --------- ----------
chrome 1284 24-04-2020 21:29:25 True
chrome 1316 24-04-2020 21:29:37 True
chrome 2004 25-04-2020 17:12:40 True
chrome 2676 26-04-2020 10:59:37 True
chrome 3096 24-04-2020 23:39:00 True
chrome 4660 25-04-2020 22:43:34 True
chrome 6040 24-04-2020 21:29:31 True
chrome 6548 26-04-2020 10:59:30 True
chrome 6592 26-04-2020 10:59:39 True
chrome 6644 25-04-2020 16:41:59 True
chrome 6780 26-04-2020 09:53:33 True
Name Id StartTime Responding
---- -- --------- ----------
SkypeApp 2552 21-04-2020 18:31:02 True
Here, we are getting the desired output but for each new process, we are getting headers and we don’t need that. We need the combined output so we will use the foreach loop here and required to use PSCustomObject to gather the data.
function Get-ProcessInformation{
[cmdletbinding()]
param(
[Parameter(Mandatory=$True,ValuefromPipeline=$True)]
[string]$name
)
Begin{
Write-Verbose "Program started"
$out = @()
}
Process{
Write-Verbose "Extracting Process Inforamtion" $procs = Get-Process $name
foreach($proc in $procs){
$out += [PSCustomObject]@{
"Process_Name" = $proc.Name
"PID" = $proc.Id
"Start_Time" = $proc.StartTime
"Responding?" = $proc.Responding
}
}
}
End{
$out
Write-Verbose "Function ends here"
}
}
When you check the output above, the output is combined and as expected.
PS C:\WINDOWS\system32> "Chrome","SkypeApp" | Get-ProcessInformation
Process_Name PID Start_Time Responding?
------------ --- ---------- -----------
chrome 1284 24-04-2020 21:29:25 True
chrome 1316 24-04-2020 21:29:37 True
chrome 2004 25-04-2020 17:12:40 True
chrome 2676 26-04-2020 10:59:37 True
chrome 3096 24-04-2020 23:39:00 True
chrome 4660 25-04-2020 22:43:34 True
chrome 6040 24-04-2020 21:29:31 True
chrome 6548 26-04-2020 10:59:30 True
chrome 6592 26-04-2020 10:59:39 True
chrome 6644 25-04-2020 16:41:59 True
chrome 6780 26-04-2020 09:53:33 True
chrome 7392 25-04-2020 11:47:22 True
chrome 10540 26-04-2020 10:56:49 True
chrome 11288 24-04-2020 21:33:05 True
chrome 12088 26-04-2020 10:59:48 True
chrome 12100 24-04-2020 21:29:38 True
SkypeApp 2552 21-04-2020 18:31:02 True
|
[
{
"code": null,
"e": 1237,
"s": 1062,
"text": "Consider the below example, we have created Advanced function to get the specific process\ninformation like Process Name, Process ID (PID), Start Time, Responding status, etc."
},
{
"code": null,
"e": 1617,
"s": 1237,
"text": "function Get-ProcessInformation{\n [cmdletbinding()]\n param(\n [Parameter(Mandatory=$True)]\n [string[]]$name\n )\n Begin{\n Write-Verbose \"Program started\"\n }\n Process{\n Write-Verbose \"Extracting Process Inforamtion\" Get-Process $name | Select Name, ID, StartTime, Responding | ft - AutoSize\n }\n End{\n Write-Verbose \"Function ends here\"\n }\n}"
},
{
"code": null,
"e": 1755,
"s": 1617,
"text": "Above is the advanced function example. When we run the above command, it will give us the\nProcess information about the selected tables."
},
{
"code": null,
"e": 1762,
"s": 1755,
"text": "Output"
},
{
"code": null,
"e": 2690,
"s": 1762,
"text": "PS C:\\WINDOWS\\system32> Get-ProcessInformation -name Chrome\nName Id StartTime Responding\n---- -- --------- ----------\nchrome 1284 24-04-2020 21:29:25 True\nchrome 1316 24-04-2020 21:29:37 True\nchrome 2004 25-04-2020 17:12:40 True\nchrome 2676 26-04-2020 10:59:37 True\nchrome 3096 24-04-2020 23:39:00 True\nchrome 4660 25-04-2020 22:43:34 True\nchrome 6040 24-04-2020 21:29:31 True\nchrome 6548 26-04-2020 10:59:30 True\nchrome 6592 26-04-2020 10:59:39 True\nchrome 6644 25-04-2020 16:41:59 True\nchrome 6780 26-04-2020 09:53:33 True\nchrome 7392 25-04-2020 11:47:22 True\nchrome 10540 26-04-2020 10:56:49 True\nchrome 11288 24-04-2020 21:33:05 True\nchrome 12088 26-04-2020 10:59:48 True\nchrome 12100 24-04-2020 21:29:38 True\nchrome 13112 26-04-2020 10:59:48 True\nchrome 13460 26-04-2020 10:59:45 True"
},
{
"code": null,
"e": 2780,
"s": 2690,
"text": "Now we will pass the above-created function as the pipeline output and check if it works?"
},
{
"code": null,
"e": 3359,
"s": 2780,
"text": "PS C:\\WINDOWS\\system32> \"Chrome\" | Get-ProcessInformation\ncmdlet Get-ProcessInformation at command pipeline position 1\nSupply values for the following parameters:\nname:\nGet-ProcessInformation : Cannot bind argument to parameter 'name' because it\nis an empty string.\nAt line:1 char:12\n+ \"Chrome\" | Get-ProcessInformation\n+ ~~~~~~~~~~~~~~~~~~~~~~\n + CategoryInfo : InvalidData: (:) [Get-ProcessInformation], Param eterBindingValidationException\n + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAl\nlowed,Get-ProcessInformation"
},
{
"code": null,
"e": 3750,
"s": 3359,
"text": "This doesn’t work because this function is not compatible to use as the Pipeline input. It doesn’t take the “chrome” as its input and asks for the value of the Name variable because of the Mandatory parameter. We simply need to add ValueFromPipeline() parameter. As we have already used the Mandatory parameter in the function so just need to add one more pipeline parameter as shown below."
},
{
"code": null,
"e": 4154,
"s": 3750,
"text": "function Get-ProcessInformation{\n [cmdletbinding()]\n param(\n [Parameter(Mandatory=$True,ValuefromPipeline=$True)]\n [string[]]$name\n )\n Begin{\n Write-Verbose \"Program started\"\n }\n Process{\n Write-Verbose \"Extracting Process Inforamtion\" Get-Process $name | Select Name, ID, StartTime, Responding | ft - AutoSize\n }\n End{\n Write-Verbose \"Function ends here\"\n }\n}"
},
{
"code": null,
"e": 4191,
"s": 4154,
"text": "Now, let's check if it works or not."
},
{
"code": null,
"e": 4937,
"s": 4191,
"text": "PS C:\\WINDOWS\\system32> \"Chrome\" | Get-ProcessInformation\nName Id StartTime Responding\n---- -- --------- ----------\nchrome 1284 24-04-2020 21:29:25 True\nchrome 1316 24-04-2020 21:29:37 True\nchrome 2004 25-04-2020 17:12:40 True\nchrome 2676 26-04-2020 10:59:37 True\nchrome 3096 24-04-2020 23:39:00 True\nchrome 4660 25-04-2020 22:43:34 True\nchrome 6040 24-04-2020 21:29:31 True\nchrome 6548 26-04-2020 10:59:30 True\nchrome 6592 26-04-2020 10:59:39 True\nchrome 6644 25-04-2020 16:41:59 True\nchrome 6780 26-04-2020 09:53:33 True\nchrome 7392 25-04-2020 11:47:22 True\nchrome 10540 26-04-2020 10:56:49 True\nchrome 11288 24-04-2020 21:33:05 True\nchrome 12088 26-04-2020 10:59:48 True"
},
{
"code": null,
"e": 5208,
"s": 4937,
"text": "Yes, it works. Now what if we provide the two existing process names as the input, it will not provide the desired result because the string we declared in the parameter section is not an array, it is a single string variable. We will declare it as the String array now."
},
{
"code": null,
"e": 5613,
"s": 5208,
"text": "function Get-ProcessInformation{\n [cmdletbinding()]\n param(\n [Parameter(Mandatory=$True,ValuefromPipeline=$True)]\n [string[]]$name\n )\n Begin{\n Write-Verbose \"Program started\"\n }\n Process{\n Write-Verbose \"Extracting Process Inforamtion\" Get-Process $name | Select Name, ID, StartTime, Responding | ft - AutoSize\n }\n End{\n Write-Verbose \"Function ends here\"\n }\n}"
},
{
"code": null,
"e": 5635,
"s": 5613,
"text": "Check the output now."
},
{
"code": null,
"e": 6362,
"s": 5635,
"text": "PS C:\\WINDOWS\\system32> \"Chrome\",\"SkypeApp\" | Get-ProcessInformation\nName Id StartTime Responding\n---- -- --------- ----------\nchrome 1284 24-04-2020 21:29:25 True\nchrome 1316 24-04-2020 21:29:37 True\nchrome 2004 25-04-2020 17:12:40 True\nchrome 2676 26-04-2020 10:59:37 True\nchrome 3096 24-04-2020 23:39:00 True\nchrome 4660 25-04-2020 22:43:34 True\nchrome 6040 24-04-2020 21:29:31 True\nchrome 6548 26-04-2020 10:59:30 True\nchrome 6592 26-04-2020 10:59:39 True\nchrome 6644 25-04-2020 16:41:59 True\nchrome 6780 26-04-2020 09:53:33 True\nName Id StartTime Responding\n---- -- --------- ----------\nSkypeApp 2552 21-04-2020 18:31:02 True"
},
{
"code": null,
"e": 6595,
"s": 6362,
"text": "Here, we are getting the desired output but for each new process, we are getting headers and we don’t need that. We need the combined output so we will use the foreach loop here and required to use PSCustomObject to gather the data."
},
{
"code": null,
"e": 7197,
"s": 6595,
"text": "function Get-ProcessInformation{\n [cmdletbinding()]\n param(\n [Parameter(Mandatory=$True,ValuefromPipeline=$True)]\n [string]$name\n )\n Begin{\n Write-Verbose \"Program started\"\n $out = @()\n }\n Process{\n Write-Verbose \"Extracting Process Inforamtion\" $procs = Get-Process $name\n foreach($proc in $procs){\n $out += [PSCustomObject]@{\n \"Process_Name\" = $proc.Name\n \"PID\" = $proc.Id\n \"Start_Time\" = $proc.StartTime\n \"Responding?\" = $proc.Responding\n }\n }\n}\n End{\n $out\n Write-Verbose \"Function ends here\"\n }\n}"
},
{
"code": null,
"e": 7270,
"s": 7197,
"text": "When you check the output above, the output is combined and as expected."
},
{
"code": null,
"e": 8339,
"s": 7270,
"text": "PS C:\\WINDOWS\\system32> \"Chrome\",\"SkypeApp\" | Get-ProcessInformation\nProcess_Name PID Start_Time Responding?\n------------ --- ---------- -----------\nchrome 1284 24-04-2020 21:29:25 True\nchrome 1316 24-04-2020 21:29:37 True\nchrome 2004 25-04-2020 17:12:40 True\nchrome 2676 26-04-2020 10:59:37 True\nchrome 3096 24-04-2020 23:39:00 True\nchrome 4660 25-04-2020 22:43:34 True\nchrome 6040 24-04-2020 21:29:31 True\nchrome 6548 26-04-2020 10:59:30 True\nchrome 6592 26-04-2020 10:59:39 True\nchrome 6644 25-04-2020 16:41:59 True\nchrome 6780 26-04-2020 09:53:33 True\nchrome 7392 25-04-2020 11:47:22 True\nchrome 10540 26-04-2020 10:56:49 True\nchrome 11288 24-04-2020 21:33:05 True\nchrome 12088 26-04-2020 10:59:48 True\nchrome 12100 24-04-2020 21:29:38 True\nSkypeApp 2552 21-04-2020 18:31:02 True"
}
] |
5 Easy Ways of Customizing Pandas Plots and Charts | by Alan Jones | Towards Data Science
|
Perhaps you are a data journalist putting a new story together, or a data scientist preparing a paper or presentation. You’ve got a nice set of charts that are looking good but a bit of tweaking would be helpful. Maybe you want to give them all titles. Maybe some would be improved with a grid, or the ticks are in the wrong places or too small to easily read.
You know how to produce line plots, bar charts, scatter diagrams, and so on but are not an expert in all of the ins and outs of the Pandas plot function (if not see the link below).
medium.com
You don’t have to stick with what you are given. There are quite a lot of parameters that allow you to change various aspects of your diagrams. You can change labels, add grids, change colors and so on.
Using the underlying matplotlib library you can change just about every aspect of what your plots look like and it can get complicated. However, we are going to look at some of the easier things we can do just with Pandas.
Before we start you’ll need to import the appropriate libraries and get some data.
Let’s start by importing all of the libraries that you’ll need to run the examples
# The first line is only required if you are using a Jupyter Notebook %matplotlib inline import numpy as npimport pandas as pdimport matplotlib.pyplot as plt
This is all pretty standard stuff which should be familiar from my previous article. One thing to note though is the first line — if, like me, you are using a Jupyter Notebook then you may need to include this. If you are using a normal Python program, or the Python console, then you should not include it.
You need some data to work with, so we’ll use the same data set as previously: weather data from London, UK, for 2008.
Load the data like this:
weather = pd.read_csv(‘https://raw.githubusercontent.com/alanjones2/dataviz/master/london2018.csv')print(weather[:2])Year Month Tmax Tmin Rain Sun 0 2018 1 9.7 3.8 58.0 46.5 1 2018 2 6.7 0.6 29.0 92.0
The print statement prints out the first couple of lines of the table, representing January and February. You can see that there are four pieces of data (apart from the year and month), Tmax is the maximum temperature for that month, Tmin is the minimum temperature, Rain is the rainfall in millimeters and Sun is the total hours of sunshine for the month.
So let’s just draw a simple plot of how the maximum temperature changed over the year
weather.plot(x=’Month’, y=’Tmax’)plt.show()
This is the default chart and it is quite acceptable. But we can change a few things to make it more so.
The first thing that you might want to do is change the size. To do this we add the figsize parameter and give it the sizes of x, and y (in inches). The values are given a a tuple, as below.
To change the color we set the color parameter. The easiest way to do this is with a string that represents a valid web color such as ‘Red’, ‘Black’ or ‘Teal’. (Note: you can find a list of web colors in Wikipedia.)
weather.plot(x='Month', y='Tmax', figsize=(8,5), color='Red')plt.show()
It’s very likely that for and article, paper or presentation, you will want to set a title for your chart. As you’ve probably gathered, much of this is knowing what the correct parameters are and setting them properly. The parameter to set a title is title. Of course! Here’s the code:
weather.plot(x=’Month’, y=’Tmax’, title=”Maximum temperatures”)plt.show()
While the default charts are fine, sometimes you want your audience to more easily see what certain values in your chart. Drawing gridlines on your plot can help.
To draw the grid, simply set the grid parameter to True. Pandas defaults to False.
weather.plot(x=’Month’, y=’Tmax’, grid=True)plt.show()
The legend is given the name of the column that represents the y axis. If this is not a acceptably descriptive name, you can change it. Or, indeed, you can eliminate it altogether!
If we want to remove it we set the parameter legend to False. If we want to change the label we incorporate the label parameter and set it to the string that we want displayed.
weather.plot(x=’Month’, y=’Tmax’, legend=False)plt.show()
weather.plot(x=’Month’, y=’Tmax’, label=’Max Temp’)plt.show()
Ticks are the divisions on the x and y axes. You can see that on our charts they are labelled from 10 to 25 on the y axis and 2 to 12 on the y axis. Given that the bottom set are supposed to represent the months, it would be better if they went from 1 to 12. We can set the tick labels with tuples. If we want to display all twelve months we would set the parameter xticks to (1,2,3,4,5,6,7,8,9,10,11,12). You can do a similar thing with the yticks parameter. Take a look at this code:
weather.plot(x=’Month’, y=’Tmax’, xticks=range(1,13), yticks=(0,10,20,30))plt.show()
As you can see I’ve set both sets of ticks explicitly. The y ticks now start at 0 and go up in tens to 30, and the x ticks show every month. But I’ve been a bit sneaky here, rather than use the tuple I showed you, above, I’ve used the Python range function to generate a list from 1 to 12 (less typing!).
If you wanted to remove the ticks altogether, it would be a simple matter to set either parameter to an empty tuple, e.g. xticks=().
weather.plot(x=’Month’, y=’Tmax’, xticks=())plt.show()
I you want to emphasize the ticks even more you can change the font size. In the example below, you can see how.
plot = weather.plot(x=’Month’, y=’Tmax’, xticks=range(1,13), fontsize=18)plt.show()
I mean your code could get messy. What if you wanted to set the ticks, a title, labels, a grid and so on. First, the line of code to do the plot would be very long and, second, if you have several plots to make you find yourself repeating it.
Here’s a solution.
Assume that you want all of you plots to look the same. What you do is define a dictionary of all of the parameters that you want to apply to all of your charts, like this:
plot_kwargs={‘xticks’:range(1,13), ‘yticks’:(0,10,20,30), ‘grid’:True, ‘fontsize’:12}
then instead of typing in all of the parameters explicitly, you can take advantage of Python’s ** operator which will expand a dictionary into a list of keyword arguments. I’ve called the variable plot_kwargs as kwargs is the conventional name given to a variable containing keyword parameters (which is what these are).
Use them like this:
weather.plot(y=’Tmax’,x=’Month’, **plot_kwargs)plt.show()
Now, you can use the same dictionary for other plots, too, for example:
weather.plot.scatter(y=’Tmax’,x=’Month’, legend=True, label=”Min Temperature”, **plot_kwargs)plt.show()
Here, I’ve used the plot_kwargs parameter to set the default parameters but explicitly set the ones for the individual plot.
Well, no. It isn’t really. There is a lot you can do to customize your plots more both with Pandas and matplotlib. You can also make changes when you save the plots to a file. There is just far too much to cover in a single article.
Thanks, for getting to the end of the article, I hope you have found it useful.
A quick postscript about the format. All of the code is very short but some lines are little long and wrap around — so I’ve put a blank line after each line so you can see what is supposed to be on one line. The only exception in the dictionary assignment towards the end of the article, which is fine the way it looks.
|
[
{
"code": null,
"e": 533,
"s": 172,
"text": "Perhaps you are a data journalist putting a new story together, or a data scientist preparing a paper or presentation. You’ve got a nice set of charts that are looking good but a bit of tweaking would be helpful. Maybe you want to give them all titles. Maybe some would be improved with a grid, or the ticks are in the wrong places or too small to easily read."
},
{
"code": null,
"e": 715,
"s": 533,
"text": "You know how to produce line plots, bar charts, scatter diagrams, and so on but are not an expert in all of the ins and outs of the Pandas plot function (if not see the link below)."
},
{
"code": null,
"e": 726,
"s": 715,
"text": "medium.com"
},
{
"code": null,
"e": 929,
"s": 726,
"text": "You don’t have to stick with what you are given. There are quite a lot of parameters that allow you to change various aspects of your diagrams. You can change labels, add grids, change colors and so on."
},
{
"code": null,
"e": 1152,
"s": 929,
"text": "Using the underlying matplotlib library you can change just about every aspect of what your plots look like and it can get complicated. However, we are going to look at some of the easier things we can do just with Pandas."
},
{
"code": null,
"e": 1235,
"s": 1152,
"text": "Before we start you’ll need to import the appropriate libraries and get some data."
},
{
"code": null,
"e": 1318,
"s": 1235,
"text": "Let’s start by importing all of the libraries that you’ll need to run the examples"
},
{
"code": null,
"e": 1476,
"s": 1318,
"text": "# The first line is only required if you are using a Jupyter Notebook %matplotlib inline import numpy as npimport pandas as pdimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 1784,
"s": 1476,
"text": "This is all pretty standard stuff which should be familiar from my previous article. One thing to note though is the first line — if, like me, you are using a Jupyter Notebook then you may need to include this. If you are using a normal Python program, or the Python console, then you should not include it."
},
{
"code": null,
"e": 1903,
"s": 1784,
"text": "You need some data to work with, so we’ll use the same data set as previously: weather data from London, UK, for 2008."
},
{
"code": null,
"e": 1928,
"s": 1903,
"text": "Load the data like this:"
},
{
"code": null,
"e": 2129,
"s": 1928,
"text": "weather = pd.read_csv(‘https://raw.githubusercontent.com/alanjones2/dataviz/master/london2018.csv')print(weather[:2])Year Month Tmax Tmin Rain Sun 0 2018 1 9.7 3.8 58.0 46.5 1 2018 2 6.7 0.6 29.0 92.0"
},
{
"code": null,
"e": 2486,
"s": 2129,
"text": "The print statement prints out the first couple of lines of the table, representing January and February. You can see that there are four pieces of data (apart from the year and month), Tmax is the maximum temperature for that month, Tmin is the minimum temperature, Rain is the rainfall in millimeters and Sun is the total hours of sunshine for the month."
},
{
"code": null,
"e": 2572,
"s": 2486,
"text": "So let’s just draw a simple plot of how the maximum temperature changed over the year"
},
{
"code": null,
"e": 2616,
"s": 2572,
"text": "weather.plot(x=’Month’, y=’Tmax’)plt.show()"
},
{
"code": null,
"e": 2721,
"s": 2616,
"text": "This is the default chart and it is quite acceptable. But we can change a few things to make it more so."
},
{
"code": null,
"e": 2912,
"s": 2721,
"text": "The first thing that you might want to do is change the size. To do this we add the figsize parameter and give it the sizes of x, and y (in inches). The values are given a a tuple, as below."
},
{
"code": null,
"e": 3128,
"s": 2912,
"text": "To change the color we set the color parameter. The easiest way to do this is with a string that represents a valid web color such as ‘Red’, ‘Black’ or ‘Teal’. (Note: you can find a list of web colors in Wikipedia.)"
},
{
"code": null,
"e": 3200,
"s": 3128,
"text": "weather.plot(x='Month', y='Tmax', figsize=(8,5), color='Red')plt.show()"
},
{
"code": null,
"e": 3486,
"s": 3200,
"text": "It’s very likely that for and article, paper or presentation, you will want to set a title for your chart. As you’ve probably gathered, much of this is knowing what the correct parameters are and setting them properly. The parameter to set a title is title. Of course! Here’s the code:"
},
{
"code": null,
"e": 3560,
"s": 3486,
"text": "weather.plot(x=’Month’, y=’Tmax’, title=”Maximum temperatures”)plt.show()"
},
{
"code": null,
"e": 3723,
"s": 3560,
"text": "While the default charts are fine, sometimes you want your audience to more easily see what certain values in your chart. Drawing gridlines on your plot can help."
},
{
"code": null,
"e": 3806,
"s": 3723,
"text": "To draw the grid, simply set the grid parameter to True. Pandas defaults to False."
},
{
"code": null,
"e": 3861,
"s": 3806,
"text": "weather.plot(x=’Month’, y=’Tmax’, grid=True)plt.show()"
},
{
"code": null,
"e": 4042,
"s": 3861,
"text": "The legend is given the name of the column that represents the y axis. If this is not a acceptably descriptive name, you can change it. Or, indeed, you can eliminate it altogether!"
},
{
"code": null,
"e": 4219,
"s": 4042,
"text": "If we want to remove it we set the parameter legend to False. If we want to change the label we incorporate the label parameter and set it to the string that we want displayed."
},
{
"code": null,
"e": 4277,
"s": 4219,
"text": "weather.plot(x=’Month’, y=’Tmax’, legend=False)plt.show()"
},
{
"code": null,
"e": 4339,
"s": 4277,
"text": "weather.plot(x=’Month’, y=’Tmax’, label=’Max Temp’)plt.show()"
},
{
"code": null,
"e": 4825,
"s": 4339,
"text": "Ticks are the divisions on the x and y axes. You can see that on our charts they are labelled from 10 to 25 on the y axis and 2 to 12 on the y axis. Given that the bottom set are supposed to represent the months, it would be better if they went from 1 to 12. We can set the tick labels with tuples. If we want to display all twelve months we would set the parameter xticks to (1,2,3,4,5,6,7,8,9,10,11,12). You can do a similar thing with the yticks parameter. Take a look at this code:"
},
{
"code": null,
"e": 4910,
"s": 4825,
"text": "weather.plot(x=’Month’, y=’Tmax’, xticks=range(1,13), yticks=(0,10,20,30))plt.show()"
},
{
"code": null,
"e": 5215,
"s": 4910,
"text": "As you can see I’ve set both sets of ticks explicitly. The y ticks now start at 0 and go up in tens to 30, and the x ticks show every month. But I’ve been a bit sneaky here, rather than use the tuple I showed you, above, I’ve used the Python range function to generate a list from 1 to 12 (less typing!)."
},
{
"code": null,
"e": 5348,
"s": 5215,
"text": "If you wanted to remove the ticks altogether, it would be a simple matter to set either parameter to an empty tuple, e.g. xticks=()."
},
{
"code": null,
"e": 5403,
"s": 5348,
"text": "weather.plot(x=’Month’, y=’Tmax’, xticks=())plt.show()"
},
{
"code": null,
"e": 5516,
"s": 5403,
"text": "I you want to emphasize the ticks even more you can change the font size. In the example below, you can see how."
},
{
"code": null,
"e": 5600,
"s": 5516,
"text": "plot = weather.plot(x=’Month’, y=’Tmax’, xticks=range(1,13), fontsize=18)plt.show()"
},
{
"code": null,
"e": 5843,
"s": 5600,
"text": "I mean your code could get messy. What if you wanted to set the ticks, a title, labels, a grid and so on. First, the line of code to do the plot would be very long and, second, if you have several plots to make you find yourself repeating it."
},
{
"code": null,
"e": 5862,
"s": 5843,
"text": "Here’s a solution."
},
{
"code": null,
"e": 6035,
"s": 5862,
"text": "Assume that you want all of you plots to look the same. What you do is define a dictionary of all of the parameters that you want to apply to all of your charts, like this:"
},
{
"code": null,
"e": 6121,
"s": 6035,
"text": "plot_kwargs={‘xticks’:range(1,13), ‘yticks’:(0,10,20,30), ‘grid’:True, ‘fontsize’:12}"
},
{
"code": null,
"e": 6442,
"s": 6121,
"text": "then instead of typing in all of the parameters explicitly, you can take advantage of Python’s ** operator which will expand a dictionary into a list of keyword arguments. I’ve called the variable plot_kwargs as kwargs is the conventional name given to a variable containing keyword parameters (which is what these are)."
},
{
"code": null,
"e": 6462,
"s": 6442,
"text": "Use them like this:"
},
{
"code": null,
"e": 6520,
"s": 6462,
"text": "weather.plot(y=’Tmax’,x=’Month’, **plot_kwargs)plt.show()"
},
{
"code": null,
"e": 6592,
"s": 6520,
"text": "Now, you can use the same dictionary for other plots, too, for example:"
},
{
"code": null,
"e": 6696,
"s": 6592,
"text": "weather.plot.scatter(y=’Tmax’,x=’Month’, legend=True, label=”Min Temperature”, **plot_kwargs)plt.show()"
},
{
"code": null,
"e": 6821,
"s": 6696,
"text": "Here, I’ve used the plot_kwargs parameter to set the default parameters but explicitly set the ones for the individual plot."
},
{
"code": null,
"e": 7054,
"s": 6821,
"text": "Well, no. It isn’t really. There is a lot you can do to customize your plots more both with Pandas and matplotlib. You can also make changes when you save the plots to a file. There is just far too much to cover in a single article."
},
{
"code": null,
"e": 7134,
"s": 7054,
"text": "Thanks, for getting to the end of the article, I hope you have found it useful."
}
] |
Difference between grep and fgrep command - GeeksforGeeks
|
27 Dec, 2018
The grep filter searches a file for a particular pattern of characters and displays all lines that contain that pattern. The fgrep filter searches for fixed-character strings in a file or files.
Syntax of grep command:
grep [options] pattern [files]
Syntax of fgrep command:
fgrep [options] pattern [files]
The main difference between both commands is:
String matching algorithm used by them.
fgrep always uses the Aho-Corasick algorithm that worst O(m+n) complexity.
grep command always uses the modified version of Commentz-Walter algorithm which has worst case O(mn) complexity.
fgrep command interprets the PATTERN as a list of fixed strings separated by newlines. But grep always interpreted as regular expressions.
Consider the below file named as para2
Hi, are you using geeksforgeeks for learning computer science concepts.
Geeksforgeeks is best for learning.
Consider the below Words :
are
using
geeksforgeeks
learning
concepts
Using grep Command:
$grep -f word para
Output:
Hi, are you using geeksforgeeks for learning computer science concepts.
Geeksforgeeks is best for learning.
Using fgrep Command:
$fgrep -f word para
Output:
Hi, are you using geeksforgeeks for learning computer science concepts.
Geeksforgeeks is best for learning.
Consider the below File :
Hi, @re you usin.g geeks*forgeeks for learni\ng computer science con/cepts.
Geeks*forgeeks is best for learni\ng.
Consider the below Words :
@re
usin.g
geeks*forgeeks
learni\ng
con/cepts
Using grep Command:
grep -f word para
Output:
Hi, @re you usin.g geeks*forgeeks for learni\ng computer science con/cepts.
Using fgrep Command:
fgrep -f word para
Output:
Hi, @re you usin.g geeks*forgeeks for learni\ng computer science con/cepts.
Geeks*forgeeks is best for learni\ng.
linux-command
Technical Scripter 2018
Difference Between
Linux-Unix
Technical Scripter
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 Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Differences and Applications of List, Tuple, Set and Dictionary in Python
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
TCP Server-Client implementation in C
|
[
{
"code": null,
"e": 24858,
"s": 24830,
"text": "\n27 Dec, 2018"
},
{
"code": null,
"e": 25053,
"s": 24858,
"text": "The grep filter searches a file for a particular pattern of characters and displays all lines that contain that pattern. The fgrep filter searches for fixed-character strings in a file or files."
},
{
"code": null,
"e": 25077,
"s": 25053,
"text": "Syntax of grep command:"
},
{
"code": null,
"e": 25109,
"s": 25077,
"text": "grep [options] pattern [files]\n"
},
{
"code": null,
"e": 25134,
"s": 25109,
"text": "Syntax of fgrep command:"
},
{
"code": null,
"e": 25167,
"s": 25134,
"text": "fgrep [options] pattern [files]\n"
},
{
"code": null,
"e": 25213,
"s": 25167,
"text": "The main difference between both commands is:"
},
{
"code": null,
"e": 25253,
"s": 25213,
"text": "String matching algorithm used by them."
},
{
"code": null,
"e": 25328,
"s": 25253,
"text": "fgrep always uses the Aho-Corasick algorithm that worst O(m+n) complexity."
},
{
"code": null,
"e": 25442,
"s": 25328,
"text": "grep command always uses the modified version of Commentz-Walter algorithm which has worst case O(mn) complexity."
},
{
"code": null,
"e": 25581,
"s": 25442,
"text": "fgrep command interprets the PATTERN as a list of fixed strings separated by newlines. But grep always interpreted as regular expressions."
},
{
"code": null,
"e": 25620,
"s": 25581,
"text": "Consider the below file named as para2"
},
{
"code": null,
"e": 25729,
"s": 25620,
"text": "Hi, are you using geeksforgeeks for learning computer science concepts.\nGeeksforgeeks is best for learning.\n"
},
{
"code": null,
"e": 25756,
"s": 25729,
"text": "Consider the below Words :"
},
{
"code": null,
"e": 25799,
"s": 25756,
"text": "are\nusing\ngeeksforgeeks\nlearning\nconcepts\n"
},
{
"code": null,
"e": 25819,
"s": 25799,
"text": "Using grep Command:"
},
{
"code": null,
"e": 25839,
"s": 25819,
"text": "$grep -f word para\n"
},
{
"code": null,
"e": 25847,
"s": 25839,
"text": "Output:"
},
{
"code": null,
"e": 25956,
"s": 25847,
"text": "Hi, are you using geeksforgeeks for learning computer science concepts.\nGeeksforgeeks is best for learning.\n"
},
{
"code": null,
"e": 25977,
"s": 25956,
"text": "Using fgrep Command:"
},
{
"code": null,
"e": 25998,
"s": 25977,
"text": "$fgrep -f word para\n"
},
{
"code": null,
"e": 26006,
"s": 25998,
"text": "Output:"
},
{
"code": null,
"e": 26115,
"s": 26006,
"text": "Hi, are you using geeksforgeeks for learning computer science concepts.\nGeeksforgeeks is best for learning.\n"
},
{
"code": null,
"e": 26141,
"s": 26115,
"text": "Consider the below File :"
},
{
"code": null,
"e": 26256,
"s": 26141,
"text": "Hi, @re you usin.g geeks*forgeeks for learni\\ng computer science con/cepts.\nGeeks*forgeeks is best for learni\\ng.\n"
},
{
"code": null,
"e": 26283,
"s": 26256,
"text": "Consider the below Words :"
},
{
"code": null,
"e": 26330,
"s": 26283,
"text": "@re\nusin.g\ngeeks*forgeeks\nlearni\\ng\ncon/cepts\n"
},
{
"code": null,
"e": 26350,
"s": 26330,
"text": "Using grep Command:"
},
{
"code": null,
"e": 26369,
"s": 26350,
"text": "grep -f word para\n"
},
{
"code": null,
"e": 26377,
"s": 26369,
"text": "Output:"
},
{
"code": null,
"e": 26454,
"s": 26377,
"text": "Hi, @re you usin.g geeks*forgeeks for learni\\ng computer science con/cepts.\n"
},
{
"code": null,
"e": 26475,
"s": 26454,
"text": "Using fgrep Command:"
},
{
"code": null,
"e": 26495,
"s": 26475,
"text": "fgrep -f word para\n"
},
{
"code": null,
"e": 26503,
"s": 26495,
"text": "Output:"
},
{
"code": null,
"e": 26618,
"s": 26503,
"text": "Hi, @re you usin.g geeks*forgeeks for learni\\ng computer science con/cepts.\nGeeks*forgeeks is best for learni\\ng.\n"
},
{
"code": null,
"e": 26632,
"s": 26618,
"text": "linux-command"
},
{
"code": null,
"e": 26656,
"s": 26632,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 26675,
"s": 26656,
"text": "Difference Between"
},
{
"code": null,
"e": 26686,
"s": 26675,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26705,
"s": 26686,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26803,
"s": 26705,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26864,
"s": 26803,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26932,
"s": 26864,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 26990,
"s": 26932,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 27045,
"s": 26990,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 27119,
"s": 27045,
"text": "Differences and Applications of List, Tuple, Set and Dictionary in Python"
},
{
"code": null,
"e": 27159,
"s": 27119,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 27199,
"s": 27159,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 27226,
"s": 27199,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 27261,
"s": 27226,
"text": "cut command in Linux with examples"
}
] |
Scan-line Polygon filling using OPENGL in C
|
06 Jun, 2022
Figures on a computer screen can be drawn using polygons. To fill those figures with color, we need to develop some algorithm.There are two famous algorithms for this purpose: Boundary fill and Scanline fill algorithms.Boundary filling requires a lot of processing and thus encounters few problems in real time. Thus the viable alternative is scanline filling as it is very robust in nature. This article discusses how to use Scanline filling algorithm to fill colors in an image.
Scanline Polygon filling Algorithm
Scanline filling is basically filling up of polygons using horizontal lines or scanlines. The purpose of the SLPF algorithm is to fill (color) the interior pixels of a polygon given only the vertices of the figure. To understand Scanline, think of the image being drawn by a single pen starting from bottom left, continuing to the right, plotting only points where there is a point present in the image, and when the line is complete, start from the next line and continue. This algorithm works by intersecting scanline with polygon edges and fills the polygon between pairs of intersections.
Special cases of polygon vertices:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
If both lines intersecting at the vertex are on the same side of the scanline, consider it as two points.If lines intersecting at the vertex are at opposite sides of the scanline, consider it as only one point.
If both lines intersecting at the vertex are on the same side of the scanline, consider it as two points.
If lines intersecting at the vertex are at opposite sides of the scanline, consider it as only one point.
Components of Polygon fill:
Edge Buckets: It contains an edge’s information. The entries of edge bucket vary according to data structure you have used.In the example we are taking below, there are three edge buckets namely: ymax, xofymin, slopeinverse.Edge Table: It consistsof several edge lists -> holds all of the edges that compose the figure. When creating edges, the vertices of the edge need to be ordered from left to right and the edges are maintained in increasing yMin order. Filling is complete once all of the edges are removed from the ETActive List: IT maintains the current edges being used to fill in the polygon.Edges are pushed into the AL from the Edge Table when an edge’s yMin is equal to the current scan line being processed. The Active List will be re-sorted after every pass.
Edge Buckets: It contains an edge’s information. The entries of edge bucket vary according to data structure you have used.In the example we are taking below, there are three edge buckets namely: ymax, xofymin, slopeinverse.
Edge Table: It consistsof several edge lists -> holds all of the edges that compose the figure. When creating edges, the vertices of the edge need to be ordered from left to right and the edges are maintained in increasing yMin order. Filling is complete once all of the edges are removed from the ET
Active List: IT maintains the current edges being used to fill in the polygon.Edges are pushed into the AL from the Edge Table when an edge’s yMin is equal to the current scan line being processed. The Active List will be re-sorted after every pass.
Data Structure:
Algorithm:
1. We will process the polygon edge after edge, and store in the edge Table.
2. Storing is done by storing the edge in the same scanline edge tuple as
the lowermost point's y-coordinate value of the edge.
3. After addition of any edge in an edge tuple, the tuple is
sorted using insertion sort, according to its xofymin value.
4. After the whole polygon is added to the edge table,
the figure is now filled.
5. Filling is started from the first scanline at the bottom,
and continued till the top.
6. Now the active edge table is taken and the following things
are repeated for each scanline:
i. Copy all edge buckets of the designated scanline
to the active edge tuple
ii. Perform an insertion sort according
to the xofymin values
iii. Remove all edge buckets whose ymax is equal
or greater than the scanline
iv. Fillup pairs of edges in active tuple, if any vertex is got,
follow these instructions:
o If both lines intersecting at the vertex are on
the same side of the scanline, consider it as two points.
o If lines intersecting at the vertex are at
opposite sides of the scanline, consider it as only one point.
v. Update the xofymin by adding slopeinverse for each bucket.
Sample Image
We are using an example of a polygon dinosaur. Paste the following in a textfile in the same folder as the executable and rename it as PolyDino.txt . Link: PolyDino.txt
C
// CPP program to illustrate// Scanline Polygon fill Algorithm #include <stdio.h>#include <math.h>#include <GL/glut.h>#define maxHt 800#define maxWd 600#define maxVer 10000 FILE *fp; // Start from lower left cornertypedef struct edgebucket{ int ymax; //max y-coordinate of edge float xofymin; //x-coordinate of lowest edge point updated only in aet float slopeinverse;}EdgeBucket; typedef struct edgetabletup{ // the array will give the scanline number // The edge table (ET) with edges entries sorted // in increasing y and x of the lower end int countEdgeBucket; //no. of edgebuckets EdgeBucket buckets[maxVer];}EdgeTableTuple; EdgeTableTuple EdgeTable[maxHt], ActiveEdgeTuple; // Scanline Functionvoid initEdgeTable(){ int i; for (i=0; i<maxHt; i++) { EdgeTable[i].countEdgeBucket = 0; } ActiveEdgeTuple.countEdgeBucket = 0;} void printTuple(EdgeTableTuple *tup){ int j; if (tup->countEdgeBucket) printf("\nCount %d-----\n",tup->countEdgeBucket); for (j=0; j<tup->countEdgeBucket; j++) { printf(" %d+%.2f+%.2f", tup->buckets[j].ymax, tup->buckets[j].xofymin,tup->buckets[j].slopeinverse); }} void printTable(){ int i,j; for (i=0; i<maxHt; i++) { if (EdgeTable[i].countEdgeBucket) printf("\nScanline %d", i); printTuple(&EdgeTable[i]); }} /* Function to sort an array using insertion sort*/void insertionSort(EdgeTableTuple *ett){ int i,j; EdgeBucket temp; for (i = 1; i < ett->countEdgeBucket; i++) { temp.ymax = ett->buckets[i].ymax; temp.xofymin = ett->buckets[i].xofymin; temp.slopeinverse = ett->buckets[i].slopeinverse; j = i - 1; while ((temp.xofymin < ett->buckets[j].xofymin) && (j >= 0)) { ett->buckets[j + 1].ymax = ett->buckets[j].ymax; ett->buckets[j + 1].xofymin = ett->buckets[j].xofymin; ett->buckets[j + 1].slopeinverse = ett->buckets[j].slopeinverse; j = j - 1; } ett->buckets[j + 1].ymax = temp.ymax; ett->buckets[j + 1].xofymin = temp.xofymin; ett->buckets[j + 1].slopeinverse = temp.slopeinverse; }} void storeEdgeInTuple (EdgeTableTuple *receiver,int ym,int xm,float slopInv){ // both used for edgetable and active edge table.. // The edge tuple sorted in increasing ymax and x of the lower end. (receiver->buckets[(receiver)->countEdgeBucket]).ymax = ym; (receiver->buckets[(receiver)->countEdgeBucket]).xofymin = (float)xm; (receiver->buckets[(receiver)->countEdgeBucket]).slopeinverse = slopInv; // sort the buckets insertionSort(receiver); (receiver->countEdgeBucket)++; } void storeEdgeInTable (int x1,int y1, int x2, int y2){ float m,minv; int ymaxTS,xwithyminTS, scanline; //ts stands for to store if (x2==x1) { minv=0.000000; } else { m = ((float)(y2-y1))/((float)(x2-x1)); // horizontal lines are not stored in edge table if (y2==y1) return; minv = (float)1.0/m; printf("\nSlope string for %d %d & %d %d: %f",x1,y1,x2,y2,minv); } if (y1>y2) { scanline=y2; ymaxTS=y1; xwithyminTS=x2; } else { scanline=y1; ymaxTS=y2; xwithyminTS=x1; } // the assignment part is done..now storage.. storeEdgeInTuple(&EdgeTable[scanline],ymaxTS,xwithyminTS,minv); } void removeEdgeByYmax(EdgeTableTuple *Tup,int yy){ int i,j; for (i=0; i< Tup->countEdgeBucket; i++) { if (Tup->buckets[i].ymax == yy) { printf("\nRemoved at %d",yy); for ( j = i ; j < Tup->countEdgeBucket -1 ; j++ ) { Tup->buckets[j].ymax =Tup->buckets[j+1].ymax; Tup->buckets[j].xofymin =Tup->buckets[j+1].xofymin; Tup->buckets[j].slopeinverse = Tup->buckets[j+1].slopeinverse; } Tup->countEdgeBucket--; i--; } }} void updatexbyslopeinv(EdgeTableTuple *Tup){ int i; for (i=0; i<Tup->countEdgeBucket; i++) { (Tup->buckets[i]).xofymin =(Tup->buckets[i]).xofymin + (Tup->buckets[i]).slopeinverse; }} void ScanlineFill(){ /* Follow the following rules: 1. Horizontal edges: Do not include in edge table 2. Horizontal edges: Drawn either on the bottom or on the top. 3. Vertices: If local max or min, then count twice, else count once. 4. Either vertices at local minima or at local maxima are drawn.*/ int i, j, x1, ymax1, x2, ymax2, FillFlag = 0, coordCount; // we will start from scanline 0; // Repeat until last scanline: for (i=0; i<maxHt; i++)//4. Increment y by 1 (next scan line) { // 1. Move from ET bucket y to the // AET those edges whose ymin = y (entering edges) for (j=0; j<EdgeTable[i].countEdgeBucket; j++) { storeEdgeInTuple(&ActiveEdgeTuple,EdgeTable[i].buckets[j]. ymax,EdgeTable[i].buckets[j].xofymin, EdgeTable[i].buckets[j].slopeinverse); } printTuple(&ActiveEdgeTuple); // 2. Remove from AET those edges for // which y=ymax (not involved in next scan line) removeEdgeByYmax(&ActiveEdgeTuple, i); //sort AET (remember: ET is presorted) insertionSort(&ActiveEdgeTuple); printTuple(&ActiveEdgeTuple); //3. Fill lines on scan line y by using pairs of x-coords from AET j = 0; FillFlag = 0; coordCount = 0; x1 = 0; x2 = 0; ymax1 = 0; ymax2 = 0; while (j<ActiveEdgeTuple.countEdgeBucket) { if (coordCount%2==0) { x1 = (int)(ActiveEdgeTuple.buckets[j].xofymin); ymax1 = ActiveEdgeTuple.buckets[j].ymax; if (x1==x2) { /* three cases can arrive- 1. lines are towards top of the intersection 2. lines are towards bottom 3. one line is towards top and other is towards bottom */ if (((x1==ymax1)&&(x2!=ymax2))||((x1!=ymax1)&&(x2==ymax2))) { x2 = x1; ymax2 = ymax1; } else { coordCount++; } } else { coordCount++; } } else { x2 = (int)ActiveEdgeTuple.buckets[j].xofymin; ymax2 = ActiveEdgeTuple.buckets[j].ymax; FillFlag = 0; // checking for intersection... if (x1==x2) { /*three cases can arrive- 1. lines are towards top of the intersection 2. lines are towards bottom 3. one line is towards top and other is towards bottom */ if (((x1==ymax1)&&(x2!=ymax2))||((x1!=ymax1)&&(x2==ymax2))) { x1 = x2; ymax1 = ymax2; } else { coordCount++; FillFlag = 1; } } else { coordCount++; FillFlag = 1; } if(FillFlag) { //drawing actual lines... glColor3f(0.0f,0.7f,0.0f); glBegin(GL_LINES); glVertex2i(x1,i); glVertex2i(x2,i); glEnd(); glFlush(); // printf("\nLine drawn from %d,%d to %d,%d",x1,i,x2,i); } } j++; } // 5. For each nonvertical edge remaining in AET, update x for new y updatexbyslopeinv(&ActiveEdgeTuple);} printf("\nScanline filling complete"); } void myInit(void){ glClearColor(1.0,1.0,1.0,0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,maxHt,0,maxWd); glClear(GL_COLOR_BUFFER_BIT);} void drawPolyDino(){ glColor3f(1.0f,0.0f,0.0f); int count = 0,x1,y1,x2,y2; rewind(fp); while(!feof(fp) ) { count++; if (count>2) { x1 = x2; y1 = y2; count=2; } if (count==1) { fscanf(fp, "%d,%d", &x1, &y1); } else { fscanf(fp, "%d,%d", &x2, &y2); printf("\n%d,%d", x2, y2); glBegin(GL_LINES); glVertex2i( x1, y1); glVertex2i( x2, y2); glEnd(); storeEdgeInTable(x1, y1, x2, y2);//storage of edges in edge table. glFlush(); } } } void drawDino(void){ initEdgeTable(); drawPolyDino(); printf("\nTable"); printTable(); ScanlineFill();//actual calling of scanline filling..} void main(int argc, char** argv){ fp=fopen ("PolyDino.txt","r"); if ( fp == NULL ) { printf( "Could not open file" ) ; return; } glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(maxHt,maxWd); glutInitWindowPosition(100, 150); glutCreateWindow("Scanline filled dinosaur"); myInit(); glutDisplayFunc(drawDino); glutMainLoop(); fclose(fp);}
Output: Filled up dinosaur:
Note: See your output on an opengl window. Mind that you have to have glut installed. You may see this video for watching the output. This article is contributed by Suprotik Dey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
gabaa406
varshagumber28
sumitgumber28
computer-graphics
OpenGL
Algorithms
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
What is Hashing | A Complete Tutorial
Understanding Time Complexity with Simple Examples
CPU Scheduling in Operating Systems
Find if there is a path between two vertices in an undirected graph
A* Search Algorithm
What is Algorithm | Introduction to Algorithms
Analysis of Algorithms | Set 3 (Asymptotic Notations)
Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jun, 2022"
},
{
"code": null,
"e": 535,
"s": 52,
"text": "Figures on a computer screen can be drawn using polygons. To fill those figures with color, we need to develop some algorithm.There are two famous algorithms for this purpose: Boundary fill and Scanline fill algorithms.Boundary filling requires a lot of processing and thus encounters few problems in real time. Thus the viable alternative is scanline filling as it is very robust in nature. This article discusses how to use Scanline filling algorithm to fill colors in an image. "
},
{
"code": null,
"e": 570,
"s": 535,
"text": "Scanline Polygon filling Algorithm"
},
{
"code": null,
"e": 1165,
"s": 570,
"text": "Scanline filling is basically filling up of polygons using horizontal lines or scanlines. The purpose of the SLPF algorithm is to fill (color) the interior pixels of a polygon given only the vertices of the figure. To understand Scanline, think of the image being drawn by a single pen starting from bottom left, continuing to the right, plotting only points where there is a point present in the image, and when the line is complete, start from the next line and continue. This algorithm works by intersecting scanline with polygon edges and fills the polygon between pairs of intersections. "
},
{
"code": null,
"e": 1202,
"s": 1165,
"text": "Special cases of polygon vertices: "
},
{
"code": null,
"e": 1211,
"s": 1202,
"text": "Chapters"
},
{
"code": null,
"e": 1238,
"s": 1211,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1288,
"s": 1238,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1311,
"s": 1288,
"text": "captions off, selected"
},
{
"code": null,
"e": 1319,
"s": 1311,
"text": "English"
},
{
"code": null,
"e": 1343,
"s": 1319,
"text": "This is a modal window."
},
{
"code": null,
"e": 1412,
"s": 1343,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1434,
"s": 1412,
"text": "End of dialog window."
},
{
"code": null,
"e": 1645,
"s": 1434,
"text": "If both lines intersecting at the vertex are on the same side of the scanline, consider it as two points.If lines intersecting at the vertex are at opposite sides of the scanline, consider it as only one point."
},
{
"code": null,
"e": 1751,
"s": 1645,
"text": "If both lines intersecting at the vertex are on the same side of the scanline, consider it as two points."
},
{
"code": null,
"e": 1857,
"s": 1751,
"text": "If lines intersecting at the vertex are at opposite sides of the scanline, consider it as only one point."
},
{
"code": null,
"e": 1887,
"s": 1857,
"text": "Components of Polygon fill: "
},
{
"code": null,
"e": 2661,
"s": 1887,
"text": "Edge Buckets: It contains an edge’s information. The entries of edge bucket vary according to data structure you have used.In the example we are taking below, there are three edge buckets namely: ymax, xofymin, slopeinverse.Edge Table: It consistsof several edge lists -> holds all of the edges that compose the figure. When creating edges, the vertices of the edge need to be ordered from left to right and the edges are maintained in increasing yMin order. Filling is complete once all of the edges are removed from the ETActive List: IT maintains the current edges being used to fill in the polygon.Edges are pushed into the AL from the Edge Table when an edge’s yMin is equal to the current scan line being processed. The Active List will be re-sorted after every pass."
},
{
"code": null,
"e": 2886,
"s": 2661,
"text": "Edge Buckets: It contains an edge’s information. The entries of edge bucket vary according to data structure you have used.In the example we are taking below, there are three edge buckets namely: ymax, xofymin, slopeinverse."
},
{
"code": null,
"e": 3187,
"s": 2886,
"text": "Edge Table: It consistsof several edge lists -> holds all of the edges that compose the figure. When creating edges, the vertices of the edge need to be ordered from left to right and the edges are maintained in increasing yMin order. Filling is complete once all of the edges are removed from the ET"
},
{
"code": null,
"e": 3437,
"s": 3187,
"text": "Active List: IT maintains the current edges being used to fill in the polygon.Edges are pushed into the AL from the Edge Table when an edge’s yMin is equal to the current scan line being processed. The Active List will be re-sorted after every pass."
},
{
"code": null,
"e": 3455,
"s": 3437,
"text": "Data Structure: "
},
{
"code": null,
"e": 4805,
"s": 3457,
"text": "Algorithm:\n\n1. We will process the polygon edge after edge, and store in the edge Table.\n2. Storing is done by storing the edge in the same scanline edge tuple as \n the lowermost point's y-coordinate value of the edge.\n3. After addition of any edge in an edge tuple, the tuple is \n sorted using insertion sort, according to its xofymin value.\n4. After the whole polygon is added to the edge table, \n the figure is now filled.\n5. Filling is started from the first scanline at the bottom,\n and continued till the top.\n6. Now the active edge table is taken and the following things \n are repeated for each scanline:\n i. Copy all edge buckets of the designated scanline \n to the active edge tuple\n ii. Perform an insertion sort according\n to the xofymin values\n iii. Remove all edge buckets whose ymax is equal \n or greater than the scanline\n iv. Fillup pairs of edges in active tuple, if any vertex is got, \n follow these instructions:\n o If both lines intersecting at the vertex are on\n the same side of the scanline, consider it as two points.\n o If lines intersecting at the vertex are at \n opposite sides of the scanline, consider it as only one point.\n v. Update the xofymin by adding slopeinverse for each bucket.\n "
},
{
"code": null,
"e": 4820,
"s": 4807,
"text": "Sample Image"
},
{
"code": null,
"e": 4990,
"s": 4820,
"text": "We are using an example of a polygon dinosaur. Paste the following in a textfile in the same folder as the executable and rename it as PolyDino.txt . Link: PolyDino.txt "
},
{
"code": null,
"e": 4994,
"s": 4992,
"text": "C"
},
{
"code": "// CPP program to illustrate// Scanline Polygon fill Algorithm #include <stdio.h>#include <math.h>#include <GL/glut.h>#define maxHt 800#define maxWd 600#define maxVer 10000 FILE *fp; // Start from lower left cornertypedef struct edgebucket{ int ymax; //max y-coordinate of edge float xofymin; //x-coordinate of lowest edge point updated only in aet float slopeinverse;}EdgeBucket; typedef struct edgetabletup{ // the array will give the scanline number // The edge table (ET) with edges entries sorted // in increasing y and x of the lower end int countEdgeBucket; //no. of edgebuckets EdgeBucket buckets[maxVer];}EdgeTableTuple; EdgeTableTuple EdgeTable[maxHt], ActiveEdgeTuple; // Scanline Functionvoid initEdgeTable(){ int i; for (i=0; i<maxHt; i++) { EdgeTable[i].countEdgeBucket = 0; } ActiveEdgeTuple.countEdgeBucket = 0;} void printTuple(EdgeTableTuple *tup){ int j; if (tup->countEdgeBucket) printf(\"\\nCount %d-----\\n\",tup->countEdgeBucket); for (j=0; j<tup->countEdgeBucket; j++) { printf(\" %d+%.2f+%.2f\", tup->buckets[j].ymax, tup->buckets[j].xofymin,tup->buckets[j].slopeinverse); }} void printTable(){ int i,j; for (i=0; i<maxHt; i++) { if (EdgeTable[i].countEdgeBucket) printf(\"\\nScanline %d\", i); printTuple(&EdgeTable[i]); }} /* Function to sort an array using insertion sort*/void insertionSort(EdgeTableTuple *ett){ int i,j; EdgeBucket temp; for (i = 1; i < ett->countEdgeBucket; i++) { temp.ymax = ett->buckets[i].ymax; temp.xofymin = ett->buckets[i].xofymin; temp.slopeinverse = ett->buckets[i].slopeinverse; j = i - 1; while ((temp.xofymin < ett->buckets[j].xofymin) && (j >= 0)) { ett->buckets[j + 1].ymax = ett->buckets[j].ymax; ett->buckets[j + 1].xofymin = ett->buckets[j].xofymin; ett->buckets[j + 1].slopeinverse = ett->buckets[j].slopeinverse; j = j - 1; } ett->buckets[j + 1].ymax = temp.ymax; ett->buckets[j + 1].xofymin = temp.xofymin; ett->buckets[j + 1].slopeinverse = temp.slopeinverse; }} void storeEdgeInTuple (EdgeTableTuple *receiver,int ym,int xm,float slopInv){ // both used for edgetable and active edge table.. // The edge tuple sorted in increasing ymax and x of the lower end. (receiver->buckets[(receiver)->countEdgeBucket]).ymax = ym; (receiver->buckets[(receiver)->countEdgeBucket]).xofymin = (float)xm; (receiver->buckets[(receiver)->countEdgeBucket]).slopeinverse = slopInv; // sort the buckets insertionSort(receiver); (receiver->countEdgeBucket)++; } void storeEdgeInTable (int x1,int y1, int x2, int y2){ float m,minv; int ymaxTS,xwithyminTS, scanline; //ts stands for to store if (x2==x1) { minv=0.000000; } else { m = ((float)(y2-y1))/((float)(x2-x1)); // horizontal lines are not stored in edge table if (y2==y1) return; minv = (float)1.0/m; printf(\"\\nSlope string for %d %d & %d %d: %f\",x1,y1,x2,y2,minv); } if (y1>y2) { scanline=y2; ymaxTS=y1; xwithyminTS=x2; } else { scanline=y1; ymaxTS=y2; xwithyminTS=x1; } // the assignment part is done..now storage.. storeEdgeInTuple(&EdgeTable[scanline],ymaxTS,xwithyminTS,minv); } void removeEdgeByYmax(EdgeTableTuple *Tup,int yy){ int i,j; for (i=0; i< Tup->countEdgeBucket; i++) { if (Tup->buckets[i].ymax == yy) { printf(\"\\nRemoved at %d\",yy); for ( j = i ; j < Tup->countEdgeBucket -1 ; j++ ) { Tup->buckets[j].ymax =Tup->buckets[j+1].ymax; Tup->buckets[j].xofymin =Tup->buckets[j+1].xofymin; Tup->buckets[j].slopeinverse = Tup->buckets[j+1].slopeinverse; } Tup->countEdgeBucket--; i--; } }} void updatexbyslopeinv(EdgeTableTuple *Tup){ int i; for (i=0; i<Tup->countEdgeBucket; i++) { (Tup->buckets[i]).xofymin =(Tup->buckets[i]).xofymin + (Tup->buckets[i]).slopeinverse; }} void ScanlineFill(){ /* Follow the following rules: 1. Horizontal edges: Do not include in edge table 2. Horizontal edges: Drawn either on the bottom or on the top. 3. Vertices: If local max or min, then count twice, else count once. 4. Either vertices at local minima or at local maxima are drawn.*/ int i, j, x1, ymax1, x2, ymax2, FillFlag = 0, coordCount; // we will start from scanline 0; // Repeat until last scanline: for (i=0; i<maxHt; i++)//4. Increment y by 1 (next scan line) { // 1. Move from ET bucket y to the // AET those edges whose ymin = y (entering edges) for (j=0; j<EdgeTable[i].countEdgeBucket; j++) { storeEdgeInTuple(&ActiveEdgeTuple,EdgeTable[i].buckets[j]. ymax,EdgeTable[i].buckets[j].xofymin, EdgeTable[i].buckets[j].slopeinverse); } printTuple(&ActiveEdgeTuple); // 2. Remove from AET those edges for // which y=ymax (not involved in next scan line) removeEdgeByYmax(&ActiveEdgeTuple, i); //sort AET (remember: ET is presorted) insertionSort(&ActiveEdgeTuple); printTuple(&ActiveEdgeTuple); //3. Fill lines on scan line y by using pairs of x-coords from AET j = 0; FillFlag = 0; coordCount = 0; x1 = 0; x2 = 0; ymax1 = 0; ymax2 = 0; while (j<ActiveEdgeTuple.countEdgeBucket) { if (coordCount%2==0) { x1 = (int)(ActiveEdgeTuple.buckets[j].xofymin); ymax1 = ActiveEdgeTuple.buckets[j].ymax; if (x1==x2) { /* three cases can arrive- 1. lines are towards top of the intersection 2. lines are towards bottom 3. one line is towards top and other is towards bottom */ if (((x1==ymax1)&&(x2!=ymax2))||((x1!=ymax1)&&(x2==ymax2))) { x2 = x1; ymax2 = ymax1; } else { coordCount++; } } else { coordCount++; } } else { x2 = (int)ActiveEdgeTuple.buckets[j].xofymin; ymax2 = ActiveEdgeTuple.buckets[j].ymax; FillFlag = 0; // checking for intersection... if (x1==x2) { /*three cases can arrive- 1. lines are towards top of the intersection 2. lines are towards bottom 3. one line is towards top and other is towards bottom */ if (((x1==ymax1)&&(x2!=ymax2))||((x1!=ymax1)&&(x2==ymax2))) { x1 = x2; ymax1 = ymax2; } else { coordCount++; FillFlag = 1; } } else { coordCount++; FillFlag = 1; } if(FillFlag) { //drawing actual lines... glColor3f(0.0f,0.7f,0.0f); glBegin(GL_LINES); glVertex2i(x1,i); glVertex2i(x2,i); glEnd(); glFlush(); // printf(\"\\nLine drawn from %d,%d to %d,%d\",x1,i,x2,i); } } j++; } // 5. For each nonvertical edge remaining in AET, update x for new y updatexbyslopeinv(&ActiveEdgeTuple);} printf(\"\\nScanline filling complete\"); } void myInit(void){ glClearColor(1.0,1.0,1.0,0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,maxHt,0,maxWd); glClear(GL_COLOR_BUFFER_BIT);} void drawPolyDino(){ glColor3f(1.0f,0.0f,0.0f); int count = 0,x1,y1,x2,y2; rewind(fp); while(!feof(fp) ) { count++; if (count>2) { x1 = x2; y1 = y2; count=2; } if (count==1) { fscanf(fp, \"%d,%d\", &x1, &y1); } else { fscanf(fp, \"%d,%d\", &x2, &y2); printf(\"\\n%d,%d\", x2, y2); glBegin(GL_LINES); glVertex2i( x1, y1); glVertex2i( x2, y2); glEnd(); storeEdgeInTable(x1, y1, x2, y2);//storage of edges in edge table. glFlush(); } } } void drawDino(void){ initEdgeTable(); drawPolyDino(); printf(\"\\nTable\"); printTable(); ScanlineFill();//actual calling of scanline filling..} void main(int argc, char** argv){ fp=fopen (\"PolyDino.txt\",\"r\"); if ( fp == NULL ) { printf( \"Could not open file\" ) ; return; } glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(maxHt,maxWd); glutInitWindowPosition(100, 150); glutCreateWindow(\"Scanline filled dinosaur\"); myInit(); glutDisplayFunc(drawDino); glutMainLoop(); fclose(fp);}",
"e": 14806,
"s": 4994,
"text": null
},
{
"code": null,
"e": 14836,
"s": 14806,
"text": "Output: Filled up dinosaur: "
},
{
"code": null,
"e": 15391,
"s": 14836,
"text": "Note: See your output on an opengl window. Mind that you have to have glut installed. You may see this video for watching the output. This article is contributed by Suprotik Dey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 15400,
"s": 15391,
"text": "gabaa406"
},
{
"code": null,
"e": 15415,
"s": 15400,
"text": "varshagumber28"
},
{
"code": null,
"e": 15429,
"s": 15415,
"text": "sumitgumber28"
},
{
"code": null,
"e": 15447,
"s": 15429,
"text": "computer-graphics"
},
{
"code": null,
"e": 15454,
"s": 15447,
"text": "OpenGL"
},
{
"code": null,
"e": 15465,
"s": 15454,
"text": "Algorithms"
},
{
"code": null,
"e": 15476,
"s": 15465,
"text": "Algorithms"
},
{
"code": null,
"e": 15574,
"s": 15476,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15599,
"s": 15574,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 15648,
"s": 15599,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 15686,
"s": 15648,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 15737,
"s": 15686,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 15773,
"s": 15737,
"text": "CPU Scheduling in Operating Systems"
},
{
"code": null,
"e": 15841,
"s": 15773,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 15861,
"s": 15841,
"text": "A* Search Algorithm"
},
{
"code": null,
"e": 15908,
"s": 15861,
"text": "What is Algorithm | Introduction to Algorithms"
},
{
"code": null,
"e": 15962,
"s": 15908,
"text": "Analysis of Algorithms | Set 3 (Asymptotic Notations)"
}
] |
How to Replace specific values in column in R DataFrame ?
|
01 Jun, 2021
In this article, we will see how to replace specific values in a column of DataFrame in R Programming Language.
Method 1: Using Replace() function.
replace() function in R Language is used to replace the values in the specified string vector x with indices given in list by those given in values.
Syntax: replace(list , position , replacement_value)
It takes on three parameters first is the list name, then the index at which the element needs to be replaced, and the third parameter is the replacement values.
Example:
R
# List of NamesNames<-c("Suresh","Sita","Anu","Manasa", "Riya","Ramesh","Roopa","Neha") # Roll numbersRoll_No<-1:8 # Marks obtainedMarks<-c(15, 20, 3, -1, 14, -2 , 10, 13)Full_Marks<-c(20, 10, 44, 21, 24, 36, 20, 13) # df name of data frame# Converting the list into dataframedf<-data.frame(Roll_No,Names, Marks, Full_Marks) print("Original DF")print(df) print("Replaced Value") #replaces the negative numbers with zerosdata<-replace(df$Marks, df$Marks<0, 0)print(data)
Output:
[1] "Original DF"
Roll_No Names Marks Full_Marks
1 1 Suresh 15 20
2 2 Sita 20 10
3 3 Anu 3 44
4 4 Manasa -1 21
5 5 Riya 14 24
6 6 Ramesh -2 36
7 7 Roopa 10 20
8 8 Neha 13 13
[1] "Replaced Value"
15 20 3 0 14 0 10 13
You can see in the above code we have replaced the 2nd element from “Sonam” to “Harish”.
Method 2: Using the logical condition.
Now let us see how we can replace values of specific values in the column using logical conditions. First, let us create the data frame in R
R
# List of NamesNames<-c("Suresh","Sita","Anu","Manasa", "Riya","Ramesh","Roopa","Neha") # Roll numbersRoll_No<-1:8 # Marks obtainedMarks<-c(15, 20, 3, 11, 14, 16, 10, 13) # df name of data frame# Converting the list into dataframedf<-data.frame(Roll_No,Names,Marks) print(df)
Output:
Data Frame
Now, let’s see how can we replace specific values in the column.
Example 1: In our data frame “Sita” marks are given as 20 let us replace it with 25.
Syntax: dataframe_name$column_name1[dataframe_name$column_name2==y]<-x
Parameters:
y:It is the value which help us to fetch the data location the column
x: It is the value which needs to be replaced
Code:
R
# List of NamesNames<-c("Suresh","Sita","Anu","Manasa", "Riya","Ramesh","Roopa","Neha") # Roll numbersRoll_No<-1:8 # Marks obtainedMarks<-c(15, 20, 3, 11, 14, 16, 10, 13) # df name of data frame# Converting the list into dataframedf<-data.frame(Roll_No,Names, Marks) df$Marks[df$Names == "Sita"] <- 25# Column_name1 is Marks which we need to replace # Print the modified data frameprint(df)
Output:
Sita marks are replaced
In the above code, you can see that we have used two columns(Marks, Names) in our data frame “df”. First, we fetch the data that need to be replaced, In our case, we need to replace the marks of a person whose name is “Sita”. So, We go through the Marks column and stop Where the name connected to those marks is “Sita”. After we find that location we replace the marks with 25
Example 2:
Let us replace the name of “Ramesh” with “Vikas”.
R
# List of NamesNames<-c("Suresh","Sita","Anu","Manasa", "Riya","Ramesh","Roopa","Neha") # Roll numbersRoll_No<-1:8 # Marks obtainedMarks<-c(15, 20, 3, 11, 14, 16, 10, 13) # df name of data frame# Converting the list into dataframedf<-data.frame(Roll_No,Names,Marks) df$Names[df$Names=="Ramesh"]<-"Vikas" # Prints the modified data frameprint(df)
Output:
Ramesh is replaced by Vikas
In the above code you can see that we are fetching a row where name is “Ramesh”, So it is like a linear search in a list to find the location of a given element After we find that location we replace the name with “Vikas”.
arorakashish0911
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
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 Split Column Into Multiple Columns in R DataFrame?
How to change Row Names of DataFrame in R ?
How to filter R DataFrame by values in a column?
Remove rows with NA in one column of R DataFrame
Replace Specific Characters in String in R
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Jun, 2021"
},
{
"code": null,
"e": 141,
"s": 28,
"text": "In this article, we will see how to replace specific values in a column of DataFrame in R Programming Language. "
},
{
"code": null,
"e": 177,
"s": 141,
"text": "Method 1: Using Replace() function."
},
{
"code": null,
"e": 326,
"s": 177,
"text": "replace() function in R Language is used to replace the values in the specified string vector x with indices given in list by those given in values."
},
{
"code": null,
"e": 379,
"s": 326,
"text": "Syntax: replace(list , position , replacement_value)"
},
{
"code": null,
"e": 541,
"s": 379,
"text": "It takes on three parameters first is the list name, then the index at which the element needs to be replaced, and the third parameter is the replacement values."
},
{
"code": null,
"e": 550,
"s": 541,
"text": "Example:"
},
{
"code": null,
"e": 552,
"s": 550,
"text": "R"
},
{
"code": "# List of NamesNames<-c(\"Suresh\",\"Sita\",\"Anu\",\"Manasa\", \"Riya\",\"Ramesh\",\"Roopa\",\"Neha\") # Roll numbersRoll_No<-1:8 # Marks obtainedMarks<-c(15, 20, 3, -1, 14, -2 , 10, 13)Full_Marks<-c(20, 10, 44, 21, 24, 36, 20, 13) # df name of data frame# Converting the list into dataframedf<-data.frame(Roll_No,Names, Marks, Full_Marks) print(\"Original DF\")print(df) print(\"Replaced Value\") #replaces the negative numbers with zerosdata<-replace(df$Marks, df$Marks<0, 0)print(data)",
"e": 1030,
"s": 552,
"text": null
},
{
"code": null,
"e": 1038,
"s": 1030,
"text": "Output:"
},
{
"code": null,
"e": 1404,
"s": 1038,
"text": "[1] \"Original DF\"\n Roll_No Names Marks Full_Marks\n1 1 Suresh 15 20\n2 2 Sita 20 10\n3 3 Anu 3 44\n4 4 Manasa -1 21\n5 5 Riya 14 24\n6 6 Ramesh -2 36\n7 7 Roopa 10 20\n8 8 Neha 13 13\n[1] \"Replaced Value\"\n15 20 3 0 14 0 10 13"
},
{
"code": null,
"e": 1493,
"s": 1404,
"text": "You can see in the above code we have replaced the 2nd element from “Sonam” to “Harish”."
},
{
"code": null,
"e": 1532,
"s": 1493,
"text": "Method 2: Using the logical condition."
},
{
"code": null,
"e": 1675,
"s": 1532,
"text": "Now let us see how we can replace values of specific values in the column using logical conditions. First, let us create the data frame in R "
},
{
"code": null,
"e": 1677,
"s": 1675,
"text": "R"
},
{
"code": "# List of NamesNames<-c(\"Suresh\",\"Sita\",\"Anu\",\"Manasa\", \"Riya\",\"Ramesh\",\"Roopa\",\"Neha\") # Roll numbersRoll_No<-1:8 # Marks obtainedMarks<-c(15, 20, 3, 11, 14, 16, 10, 13) # df name of data frame# Converting the list into dataframedf<-data.frame(Roll_No,Names,Marks) print(df)",
"e": 1962,
"s": 1677,
"text": null
},
{
"code": null,
"e": 1971,
"s": 1962,
"text": "Output: "
},
{
"code": null,
"e": 1982,
"s": 1971,
"text": "Data Frame"
},
{
"code": null,
"e": 2047,
"s": 1982,
"text": "Now, let’s see how can we replace specific values in the column."
},
{
"code": null,
"e": 2132,
"s": 2047,
"text": "Example 1: In our data frame “Sita” marks are given as 20 let us replace it with 25."
},
{
"code": null,
"e": 2203,
"s": 2132,
"text": "Syntax: dataframe_name$column_name1[dataframe_name$column_name2==y]<-x"
},
{
"code": null,
"e": 2215,
"s": 2203,
"text": "Parameters:"
},
{
"code": null,
"e": 2285,
"s": 2215,
"text": "y:It is the value which help us to fetch the data location the column"
},
{
"code": null,
"e": 2331,
"s": 2285,
"text": "x: It is the value which needs to be replaced"
},
{
"code": null,
"e": 2337,
"s": 2331,
"text": "Code:"
},
{
"code": null,
"e": 2339,
"s": 2337,
"text": "R"
},
{
"code": "# List of NamesNames<-c(\"Suresh\",\"Sita\",\"Anu\",\"Manasa\", \"Riya\",\"Ramesh\",\"Roopa\",\"Neha\") # Roll numbersRoll_No<-1:8 # Marks obtainedMarks<-c(15, 20, 3, 11, 14, 16, 10, 13) # df name of data frame# Converting the list into dataframedf<-data.frame(Roll_No,Names, Marks) df$Marks[df$Names == \"Sita\"] <- 25# Column_name1 is Marks which we need to replace # Print the modified data frameprint(df)",
"e": 2739,
"s": 2339,
"text": null
},
{
"code": null,
"e": 2747,
"s": 2739,
"text": "Output:"
},
{
"code": null,
"e": 2771,
"s": 2747,
"text": "Sita marks are replaced"
},
{
"code": null,
"e": 3149,
"s": 2771,
"text": "In the above code, you can see that we have used two columns(Marks, Names) in our data frame “df”. First, we fetch the data that need to be replaced, In our case, we need to replace the marks of a person whose name is “Sita”. So, We go through the Marks column and stop Where the name connected to those marks is “Sita”. After we find that location we replace the marks with 25"
},
{
"code": null,
"e": 3160,
"s": 3149,
"text": "Example 2:"
},
{
"code": null,
"e": 3211,
"s": 3160,
"text": "Let us replace the name of “Ramesh” with “Vikas”. "
},
{
"code": null,
"e": 3213,
"s": 3211,
"text": "R"
},
{
"code": "# List of NamesNames<-c(\"Suresh\",\"Sita\",\"Anu\",\"Manasa\", \"Riya\",\"Ramesh\",\"Roopa\",\"Neha\") # Roll numbersRoll_No<-1:8 # Marks obtainedMarks<-c(15, 20, 3, 11, 14, 16, 10, 13) # df name of data frame# Converting the list into dataframedf<-data.frame(Roll_No,Names,Marks) df$Names[df$Names==\"Ramesh\"]<-\"Vikas\" # Prints the modified data frameprint(df)",
"e": 3568,
"s": 3213,
"text": null
},
{
"code": null,
"e": 3576,
"s": 3568,
"text": "Output:"
},
{
"code": null,
"e": 3604,
"s": 3576,
"text": "Ramesh is replaced by Vikas"
},
{
"code": null,
"e": 3827,
"s": 3604,
"text": "In the above code you can see that we are fetching a row where name is “Ramesh”, So it is like a linear search in a list to find the location of a given element After we find that location we replace the name with “Vikas”."
},
{
"code": null,
"e": 3844,
"s": 3827,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3851,
"s": 3844,
"text": "Picked"
},
{
"code": null,
"e": 3872,
"s": 3851,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 3884,
"s": 3872,
"text": "R-DataFrame"
},
{
"code": null,
"e": 3895,
"s": 3884,
"text": "R Language"
},
{
"code": null,
"e": 3906,
"s": 3895,
"text": "R Programs"
},
{
"code": null,
"e": 4004,
"s": 3906,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4056,
"s": 4004,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 4108,
"s": 4056,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 4166,
"s": 4108,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 4198,
"s": 4166,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 4233,
"s": 4198,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 4291,
"s": 4233,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 4335,
"s": 4291,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 4384,
"s": 4335,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 4433,
"s": 4384,
"text": "Remove rows with NA in one column of R DataFrame"
}
] |
Python | Pandas Series.ix
|
28 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.ix attribute is a primarily label-location based indexer, with integer position fallback. It takes the label as input and returns the value corresponding to that label.
Syntax:Series.ix
Parameter : None
Returns : value
Example #1: Use Series.ix attribute to return a value lying at the specified label in the given Series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4'] # Print the seriesprint(sr)
Output :
Now we will use Series.ix attribute to return the value lying corresponding to the ‘City 4’ label.
# return the valuesr.ix['City 4']
Output :
As we can see in the output, the Series.ix attribute has returned ‘Lisbon’ as the value corresponding to the ‘City 4’ label in the given Series object. Example #2 : Use Series.ix attribute to return a value lying at the specified label in the given Series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr)
Output :
Now we will use Series.ix attribute to return the value lying corresponding to the ‘Day 3’ label.
# return the valuesr.ix['Day 3']
Output :As we can see in the output, the Series.ix attribute has returned ‘3/1/2018’ as the value corresponding to the ‘Day 3’ label in the given Series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 499,
"s": 242,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 682,
"s": 499,
"text": "Pandas Series.ix attribute is a primarily label-location based indexer, with integer position fallback. It takes the label as input and returns the value corresponding to that label."
},
{
"code": null,
"e": 699,
"s": 682,
"text": "Syntax:Series.ix"
},
{
"code": null,
"e": 716,
"s": 699,
"text": "Parameter : None"
},
{
"code": null,
"e": 732,
"s": 716,
"text": "Returns : value"
},
{
"code": null,
"e": 843,
"s": 732,
"text": "Example #1: Use Series.ix attribute to return a value lying at the specified label in the given Series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4'] # Print the seriesprint(sr)",
"e": 1083,
"s": 843,
"text": null
},
{
"code": null,
"e": 1092,
"s": 1083,
"text": "Output :"
},
{
"code": null,
"e": 1191,
"s": 1092,
"text": "Now we will use Series.ix attribute to return the value lying corresponding to the ‘City 4’ label."
},
{
"code": "# return the valuesr.ix['City 4']",
"e": 1225,
"s": 1191,
"text": null
},
{
"code": null,
"e": 1234,
"s": 1225,
"text": "Output :"
},
{
"code": null,
"e": 1498,
"s": 1234,
"text": "As we can see in the output, the Series.ix attribute has returned ‘Lisbon’ as the value corresponding to the ‘City 4’ label in the given Series object. Example #2 : Use Series.ix attribute to return a value lying at the specified label in the given Series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr)",
"e": 1737,
"s": 1498,
"text": null
},
{
"code": null,
"e": 1746,
"s": 1737,
"text": "Output :"
},
{
"code": null,
"e": 1844,
"s": 1746,
"text": "Now we will use Series.ix attribute to return the value lying corresponding to the ‘Day 3’ label."
},
{
"code": "# return the valuesr.ix['Day 3']",
"e": 1877,
"s": 1844,
"text": null
},
{
"code": null,
"e": 2038,
"s": 1877,
"text": "Output :As we can see in the output, the Series.ix attribute has returned ‘3/1/2018’ as the value corresponding to the ‘Day 3’ label in the given Series object."
},
{
"code": null,
"e": 2059,
"s": 2038,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2088,
"s": 2059,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2102,
"s": 2088,
"text": "Python-pandas"
},
{
"code": null,
"e": 2109,
"s": 2102,
"text": "Python"
},
{
"code": null,
"e": 2207,
"s": 2109,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2239,
"s": 2207,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2266,
"s": 2239,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2297,
"s": 2266,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2318,
"s": 2297,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2341,
"s": 2318,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2397,
"s": 2341,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2439,
"s": 2397,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2481,
"s": 2439,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2520,
"s": 2481,
"text": "Python | Get unique values from a list"
}
] |
Matplotlib.axes.Axes.axvline() in Python
|
21 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.axvline() function in axes module of matplotlib library is used to add a vertical line across the axis.
Syntax: Axes.axvline(self, x=0, ymin=0, ymax=1, **kwargs)
Parameters: This method accept the following parameters that are described below:
x: This parameter is the x position in data coordinates of the vertical line with default value of 0.
ymin: This parameter should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot.Its default value of 0.
ymax: This parameter should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot. Its default value of 1.
Returns: This returns the following:
lines:This returns the list of Line2D objects representing the plotted data.
Below examples illustrate the matplotlib.axes.Axes.axhline() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npimport matplotlib.collections as collections t = np.arange(0.0, 5, 0.01)s1 = np.sin(4 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s1, color ='black', alpha = 0.75, lw = 1)ax.axvline(3, color ='green', lw = 2, alpha = 0.75)ax.set_title('matplotlib.axes.Axes.axvline() Example')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np t = np.linspace(-10, 10, 100)sig = 1 / t**2fig, ax = plt.subplots() plt.axvline(color ="green", alpha = 0.8, lw = 1.5)plt.plot(t, sig, linewidth = 1.5, color ="black", alpha = 0.6, label = r"$\sigma(t) = \frac{1}{x ^ 2}$") plt.xlim(-10, 10)plt.xlabel("t")plt.legend(fontsize = 14) ax.set_title('matplotlib.axes.Axes.axvline() Example')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 441,
"s": 328,
"text": "The Axes.axvline() function in axes module of matplotlib library is used to add a vertical line across the axis."
},
{
"code": null,
"e": 499,
"s": 441,
"text": "Syntax: Axes.axvline(self, x=0, ymin=0, ymax=1, **kwargs)"
},
{
"code": null,
"e": 581,
"s": 499,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 683,
"s": 581,
"text": "x: This parameter is the x position in data coordinates of the vertical line with default value of 0."
},
{
"code": null,
"e": 809,
"s": 683,
"text": "ymin: This parameter should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot.Its default value of 0."
},
{
"code": null,
"e": 936,
"s": 809,
"text": "ymax: This parameter should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot. Its default value of 1."
},
{
"code": null,
"e": 973,
"s": 936,
"text": "Returns: This returns the following:"
},
{
"code": null,
"e": 1050,
"s": 973,
"text": "lines:This returns the list of Line2D objects representing the plotted data."
},
{
"code": null,
"e": 1140,
"s": 1050,
"text": "Below examples illustrate the matplotlib.axes.Axes.axhline() function in matplotlib.axes:"
},
{
"code": null,
"e": 1151,
"s": 1140,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npimport matplotlib.collections as collections t = np.arange(0.0, 5, 0.01)s1 = np.sin(4 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s1, color ='black', alpha = 0.75, lw = 1)ax.axvline(3, color ='green', lw = 2, alpha = 0.75)ax.set_title('matplotlib.axes.Axes.axvline() Example')plt.show()",
"e": 1534,
"s": 1151,
"text": null
},
{
"code": null,
"e": 1542,
"s": 1534,
"text": "Output:"
},
{
"code": null,
"e": 1553,
"s": 1542,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np t = np.linspace(-10, 10, 100)sig = 1 / t**2fig, ax = plt.subplots() plt.axvline(color =\"green\", alpha = 0.8, lw = 1.5)plt.plot(t, sig, linewidth = 1.5, color =\"black\", alpha = 0.6, label = r\"$\\sigma(t) = \\frac{1}{x ^ 2}$\") plt.xlim(-10, 10)plt.xlabel(\"t\")plt.legend(fontsize = 14) ax.set_title('matplotlib.axes.Axes.axvline() Example')plt.show()",
"e": 2008,
"s": 1553,
"text": null
},
{
"code": null,
"e": 2016,
"s": 2008,
"text": "Output:"
},
{
"code": null,
"e": 2034,
"s": 2016,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2041,
"s": 2034,
"text": "Python"
}
] |
Matplotlib – Animate Multiple Lines
|
07 Jul, 2021
In this article, we are going to learn about how to make an animated chart of multiple lines using matplotlib. Animating the charts can make things more attractive and also help others to visualize the data more appropriately rather than static charts. Animations make even more sense when we are working with projects(stock markets, ECG Anomaly Detection, Internet Traffic Forecasting) that depicts the time series data.
The matplotlib.animation.FuncAnimation class is used to make animation calls recursively. You must store the created Animation in a variable that lives as long as the animation should run. Otherwise, the Animation object will be garbage-collected and the animation stops.
Syntax: class matplotlib.animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True, **kwargs)
Example 1:
For matplotlib there are two important modules we need primarily: pyplot and animation(Funcanimation). Below is a step-wise approach on how to animate lines in matplotlib. We are going to make our first example with 4 manually built plots using the random numbers in a certain range.
Import all necessary libraries for creating charts and animation.
Python3
# importing all necessary librariesimport randomimport matplotlibfrom matplotlib import animationimport matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimation%matplotlib qt
Now make 4 different sets of y i.e y1,y2,y3,y4 which are going to share with the same x-axis values. While taking the random values we are going to divide each random value because these will help us to get different exponential lines.
Python3
# add random points for each linel1 = [random.randint(-20, 4)+(points**1.88)/(random.randint(13, 14)) for points in range(0, 160, 2)]l2 = [random.randint(0, 9)+(points**1.9)/(random.randint(9, 11)) for points in range(0, 160, 2)]l3 = [random.randint(-10, 10)-(points**1.4)/(random.randint(9, 12)) for points in range(0, 160, 2)]l4 = [random.randint(-5, 10)-(points**1.1)/(random.randint(7, 12)) for points in range(0, 160, 2)]
Now use itertools to iterate. This module works fast, it is a memory-efficient tool that is used either by itself or in combination to form iterator algebra. You can also use for loop to iterate just create one list and start storing the variables of y w.r.t x.
Python3
from itertools import countmyvar = count(0, 3)
Create 3 extra empty lists for new lines (y2 ,y3, and y4) total of 5 empty lists when we include x1 and y1. Inside the animation function, we will fill those containers at each iteration step. In each iteration single frame created animation. Also, add colors for 4 different lines.
Python3
# subplots() function you can draw# multiple plots in one figurefig, axes = plt.subplots(nrows=1, ncols=1, figsize=(10, 5)) # set limit for x and y axisaxes.set_ylim(-100, 500)axes.set_xlim(0, 250) # style for plotting lineplt.style.use("ggplot") # create 5 list to get store element# after every iterationx1, y1, y2, y3, y4 = [], [], [], [], []myvar = count(0, 3) def animate(i): x1.append(next(myvar)) y1.append((l1[i])) y2.append((l2[i])) y3.append((l3[i])) y4.append((l4[i])) axes.plot(x1, y1, color="red") axes.plot(x1, y2, color="gray") axes.plot(x1, y3, color="blue") axes.plot(x1, y4, color="green") # set ani variable to call the# function recursivelyanim = FuncAnimation(fig, animate, interval=30)
Below is the complete program:
Python3
# importing all necessary librariesfrom itertools import countimport randomimport matplotlibfrom matplotlib import animationimport matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimation%matplotlib qt # add random points for each linel1 = [random.randint(-20, 4)+(points**1.88)/(random.randint(13, 14)) for points in range(0, 160, 2)]l2 = [random.randint(0, 9)+(points**1.9)/(random.randint(9, 11)) for points in range(0, 160, 2)]l3 = [random.randint(-10, 10)-(points**1.4)/(random.randint(9, 12)) for points in range(0, 160, 2)]l4 = [random.randint(-5, 10)-(points**1.1)/(random.randint(7, 12)) for points in range(0, 160, 2)] myvar = count(0, 3) # subplots() function you can draw# multiple plots in one figurefig, axes = plt.subplots(nrows=1, ncols=1, figsize=(10, 5)) # set limit for x and y axisaxes.set_ylim(-100, 500)axes.set_xlim(0, 250) # style for plotting lineplt.style.use("ggplot") # create 5 list to get store element# after every iterationx1, y1, y2, y3, y4 = [], [], [], [], []myvar = count(0, 3) def animate(i): x1.append(next(myvar)) y1.append((l1[i])) y2.append((l2[i])) y3.append((l3[i])) y4.append((l4[i])) axes.plot(x1, y1, color="red") axes.plot(x1, y2, color="gray") axes.plot(x1, y3, color="blue") axes.plot(x1, y4, color="green") # set ani variable to call the# function recursivelyanim = FuncAnimation(fig, animate, interval=30)
Output :
Example 2:
Here is another example to animate multiple lines in matplotlib.
Import all necessary Libraries.
Python3
# import modulesimport numpy as npimport matplotlibimport matplotlib.pyplot as pltimport matplotlib.animation as animation
Create a function update line to get a new value for each iteration.
Python3
def updateline(num, data, line1, data2, line2): line1.set_data(data[..., :num]) line2.set_data(data2[..., :num]) time_text.set_text("Points: %.0f" % int(num)) return line1, line2 # generating data of 100 elements# each for line 1x = np.linspace(0, 2*np.pi, 100)y = np.sin(x)data = np.array([x, y]) # generating data of 100 elements# each for line 2x2 = np.linspace(0, 2*np.pi, 100)y2 = np.cos(x2)data2 = np.array([x2, y2]) # setup the formating for moving filesWriter = animation.writers['ffmpeg']Writer = Writer(fps=10, metadata=dict(artist="Me"), bitrate=-1) fig = plt.figure()ax = fig.add_subplot(111)l, = ax.plot([], [], 'r-', label="Sin")ax2 = ax.twinx()k = ax2.plot([], [], 'b-', label="Cos")[0] ax.legend([l, k], [l.get_label(), k.get_label()], loc=0) ax.set_xlabel("X") # axis 1ax.set_ylim(-1.5, 1.5)ax.set_xlim(0, 7) # axis 2ax2.set_ylim(-1.5, 1.5)ax2.set_xlim(0, 7) plt.title('Sin and Cos')time_text = ax.text(0.1, 0.95, "", transform=ax.transAxes, fontsize=15, color='red')
Save mp4 file [By default files saved in your present directory].
Python3
# set line_animation variable to call# the function recursivelyline_animation = animation.FuncAnimation( fig, updateline, frames=100, fargs=(data, l, data2, k)) line_animation.save("lines.mp4", writer=Writer)
Below is the complete program:
Python3
# import required modulesimport numpy as npimport matplotlibimport matplotlib.pyplot as pltimport matplotlib.animation as animation def updateline(num, data, line1, data2, line2): line1.set_data(data[..., :num]) line2.set_data(data2[..., :num]) time_text.set_text("Points: %.0f" % int(num)) return line1, line2 # generating data of 100 elements# each for line 1x = np.linspace(0, 2*np.pi, 100)y = np.sin(x)data = np.array([x, y]) # generating data of 100 elements# each for line 2x2 = np.linspace(0, 2*np.pi, 100)y2 = np.cos(x2)data2 = np.array([x2, y2]) # setup the formating for moving filesWriter = animation.writers['ffmpeg']Writer = Writer(fps=10, metadata=dict(artist="Me"), bitrate=-1) fig = plt.figure()ax = fig.add_subplot(111)l, = ax.plot([], [], 'r-', label="Sin")ax2 = ax.twinx()k = ax2.plot([], [], 'b-', label="Cos")[0] ax.legend([l, k], [l.get_label(), k.get_label()], loc=0) ax.set_xlabel("X") # axis 1ax.set_ylim(-1.5, 1.5)ax.set_xlim(0, 7) # axis 2ax2.set_ylim(-1.5, 1.5)ax2.set_xlim(0, 7) plt.title('Sin and Cos')time_text = ax.text(0.1, 0.95, "", transform=ax.transAxes, fontsize=15, color='red') # set line_animation variable to call# the function recursivelyline_animation = animation.FuncAnimation( fig, updateline, frames=100, fargs=(data, l, data2, k))line_animation.save("lines.mp4", writer=Writer)
Output :
akshaysingh98088
Picked
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Jul, 2021"
},
{
"code": null,
"e": 476,
"s": 54,
"text": "In this article, we are going to learn about how to make an animated chart of multiple lines using matplotlib. Animating the charts can make things more attractive and also help others to visualize the data more appropriately rather than static charts. Animations make even more sense when we are working with projects(stock markets, ECG Anomaly Detection, Internet Traffic Forecasting) that depicts the time series data."
},
{
"code": null,
"e": 749,
"s": 476,
"text": "The matplotlib.animation.FuncAnimation class is used to make animation calls recursively. You must store the created Animation in a variable that lives as long as the animation should run. Otherwise, the Animation object will be garbage-collected and the animation stops. "
},
{
"code": null,
"e": 903,
"s": 749,
"text": "Syntax: class matplotlib.animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True, **kwargs)"
},
{
"code": null,
"e": 914,
"s": 903,
"text": "Example 1:"
},
{
"code": null,
"e": 1198,
"s": 914,
"text": "For matplotlib there are two important modules we need primarily: pyplot and animation(Funcanimation). Below is a step-wise approach on how to animate lines in matplotlib. We are going to make our first example with 4 manually built plots using the random numbers in a certain range."
},
{
"code": null,
"e": 1264,
"s": 1198,
"text": "Import all necessary libraries for creating charts and animation."
},
{
"code": null,
"e": 1272,
"s": 1264,
"text": "Python3"
},
{
"code": "# importing all necessary librariesimport randomimport matplotlibfrom matplotlib import animationimport matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimation%matplotlib qt",
"e": 1461,
"s": 1272,
"text": null
},
{
"code": null,
"e": 1698,
"s": 1461,
"text": "Now make 4 different sets of y i.e y1,y2,y3,y4 which are going to share with the same x-axis values. While taking the random values we are going to divide each random value because these will help us to get different exponential lines."
},
{
"code": null,
"e": 1706,
"s": 1698,
"text": "Python3"
},
{
"code": "# add random points for each linel1 = [random.randint(-20, 4)+(points**1.88)/(random.randint(13, 14)) for points in range(0, 160, 2)]l2 = [random.randint(0, 9)+(points**1.9)/(random.randint(9, 11)) for points in range(0, 160, 2)]l3 = [random.randint(-10, 10)-(points**1.4)/(random.randint(9, 12)) for points in range(0, 160, 2)]l4 = [random.randint(-5, 10)-(points**1.1)/(random.randint(7, 12)) for points in range(0, 160, 2)]",
"e": 2153,
"s": 1706,
"text": null
},
{
"code": null,
"e": 2415,
"s": 2153,
"text": "Now use itertools to iterate. This module works fast, it is a memory-efficient tool that is used either by itself or in combination to form iterator algebra. You can also use for loop to iterate just create one list and start storing the variables of y w.r.t x."
},
{
"code": null,
"e": 2423,
"s": 2415,
"text": "Python3"
},
{
"code": "from itertools import countmyvar = count(0, 3)",
"e": 2470,
"s": 2423,
"text": null
},
{
"code": null,
"e": 2753,
"s": 2470,
"text": "Create 3 extra empty lists for new lines (y2 ,y3, and y4) total of 5 empty lists when we include x1 and y1. Inside the animation function, we will fill those containers at each iteration step. In each iteration single frame created animation. Also, add colors for 4 different lines."
},
{
"code": null,
"e": 2761,
"s": 2753,
"text": "Python3"
},
{
"code": "# subplots() function you can draw# multiple plots in one figurefig, axes = plt.subplots(nrows=1, ncols=1, figsize=(10, 5)) # set limit for x and y axisaxes.set_ylim(-100, 500)axes.set_xlim(0, 250) # style for plotting lineplt.style.use(\"ggplot\") # create 5 list to get store element# after every iterationx1, y1, y2, y3, y4 = [], [], [], [], []myvar = count(0, 3) def animate(i): x1.append(next(myvar)) y1.append((l1[i])) y2.append((l2[i])) y3.append((l3[i])) y4.append((l4[i])) axes.plot(x1, y1, color=\"red\") axes.plot(x1, y2, color=\"gray\") axes.plot(x1, y3, color=\"blue\") axes.plot(x1, y4, color=\"green\") # set ani variable to call the# function recursivelyanim = FuncAnimation(fig, animate, interval=30)",
"e": 3498,
"s": 2761,
"text": null
},
{
"code": null,
"e": 3529,
"s": 3498,
"text": "Below is the complete program:"
},
{
"code": null,
"e": 3537,
"s": 3529,
"text": "Python3"
},
{
"code": "# importing all necessary librariesfrom itertools import countimport randomimport matplotlibfrom matplotlib import animationimport matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimation%matplotlib qt # add random points for each linel1 = [random.randint(-20, 4)+(points**1.88)/(random.randint(13, 14)) for points in range(0, 160, 2)]l2 = [random.randint(0, 9)+(points**1.9)/(random.randint(9, 11)) for points in range(0, 160, 2)]l3 = [random.randint(-10, 10)-(points**1.4)/(random.randint(9, 12)) for points in range(0, 160, 2)]l4 = [random.randint(-5, 10)-(points**1.1)/(random.randint(7, 12)) for points in range(0, 160, 2)] myvar = count(0, 3) # subplots() function you can draw# multiple plots in one figurefig, axes = plt.subplots(nrows=1, ncols=1, figsize=(10, 5)) # set limit for x and y axisaxes.set_ylim(-100, 500)axes.set_xlim(0, 250) # style for plotting lineplt.style.use(\"ggplot\") # create 5 list to get store element# after every iterationx1, y1, y2, y3, y4 = [], [], [], [], []myvar = count(0, 3) def animate(i): x1.append(next(myvar)) y1.append((l1[i])) y2.append((l2[i])) y3.append((l3[i])) y4.append((l4[i])) axes.plot(x1, y1, color=\"red\") axes.plot(x1, y2, color=\"gray\") axes.plot(x1, y3, color=\"blue\") axes.plot(x1, y4, color=\"green\") # set ani variable to call the# function recursivelyanim = FuncAnimation(fig, animate, interval=30)",
"e": 4957,
"s": 3537,
"text": null
},
{
"code": null,
"e": 4966,
"s": 4957,
"text": "Output :"
},
{
"code": null,
"e": 4978,
"s": 4966,
"text": "Example 2: "
},
{
"code": null,
"e": 5043,
"s": 4978,
"text": "Here is another example to animate multiple lines in matplotlib."
},
{
"code": null,
"e": 5075,
"s": 5043,
"text": "Import all necessary Libraries."
},
{
"code": null,
"e": 5083,
"s": 5075,
"text": "Python3"
},
{
"code": "# import modulesimport numpy as npimport matplotlibimport matplotlib.pyplot as pltimport matplotlib.animation as animation",
"e": 5206,
"s": 5083,
"text": null
},
{
"code": null,
"e": 5278,
"s": 5209,
"text": "Create a function update line to get a new value for each iteration."
},
{
"code": null,
"e": 5288,
"s": 5280,
"text": "Python3"
},
{
"code": "def updateline(num, data, line1, data2, line2): line1.set_data(data[..., :num]) line2.set_data(data2[..., :num]) time_text.set_text(\"Points: %.0f\" % int(num)) return line1, line2 # generating data of 100 elements# each for line 1x = np.linspace(0, 2*np.pi, 100)y = np.sin(x)data = np.array([x, y]) # generating data of 100 elements# each for line 2x2 = np.linspace(0, 2*np.pi, 100)y2 = np.cos(x2)data2 = np.array([x2, y2]) # setup the formating for moving filesWriter = animation.writers['ffmpeg']Writer = Writer(fps=10, metadata=dict(artist=\"Me\"), bitrate=-1) fig = plt.figure()ax = fig.add_subplot(111)l, = ax.plot([], [], 'r-', label=\"Sin\")ax2 = ax.twinx()k = ax2.plot([], [], 'b-', label=\"Cos\")[0] ax.legend([l, k], [l.get_label(), k.get_label()], loc=0) ax.set_xlabel(\"X\") # axis 1ax.set_ylim(-1.5, 1.5)ax.set_xlim(0, 7) # axis 2ax2.set_ylim(-1.5, 1.5)ax2.set_xlim(0, 7) plt.title('Sin and Cos')time_text = ax.text(0.1, 0.95, \"\", transform=ax.transAxes, fontsize=15, color='red')",
"e": 6316,
"s": 5288,
"text": null
},
{
"code": null,
"e": 6382,
"s": 6316,
"text": "Save mp4 file [By default files saved in your present directory]."
},
{
"code": null,
"e": 6390,
"s": 6382,
"text": "Python3"
},
{
"code": "# set line_animation variable to call# the function recursivelyline_animation = animation.FuncAnimation( fig, updateline, frames=100, fargs=(data, l, data2, k)) line_animation.save(\"lines.mp4\", writer=Writer)",
"e": 6602,
"s": 6390,
"text": null
},
{
"code": null,
"e": 6633,
"s": 6602,
"text": "Below is the complete program:"
},
{
"code": null,
"e": 6641,
"s": 6633,
"text": "Python3"
},
{
"code": "# import required modulesimport numpy as npimport matplotlibimport matplotlib.pyplot as pltimport matplotlib.animation as animation def updateline(num, data, line1, data2, line2): line1.set_data(data[..., :num]) line2.set_data(data2[..., :num]) time_text.set_text(\"Points: %.0f\" % int(num)) return line1, line2 # generating data of 100 elements# each for line 1x = np.linspace(0, 2*np.pi, 100)y = np.sin(x)data = np.array([x, y]) # generating data of 100 elements# each for line 2x2 = np.linspace(0, 2*np.pi, 100)y2 = np.cos(x2)data2 = np.array([x2, y2]) # setup the formating for moving filesWriter = animation.writers['ffmpeg']Writer = Writer(fps=10, metadata=dict(artist=\"Me\"), bitrate=-1) fig = plt.figure()ax = fig.add_subplot(111)l, = ax.plot([], [], 'r-', label=\"Sin\")ax2 = ax.twinx()k = ax2.plot([], [], 'b-', label=\"Cos\")[0] ax.legend([l, k], [l.get_label(), k.get_label()], loc=0) ax.set_xlabel(\"X\") # axis 1ax.set_ylim(-1.5, 1.5)ax.set_xlim(0, 7) # axis 2ax2.set_ylim(-1.5, 1.5)ax2.set_xlim(0, 7) plt.title('Sin and Cos')time_text = ax.text(0.1, 0.95, \"\", transform=ax.transAxes, fontsize=15, color='red') # set line_animation variable to call# the function recursivelyline_animation = animation.FuncAnimation( fig, updateline, frames=100, fargs=(data, l, data2, k))line_animation.save(\"lines.mp4\", writer=Writer)",
"e": 8013,
"s": 6641,
"text": null
},
{
"code": null,
"e": 8022,
"s": 8013,
"text": "Output :"
},
{
"code": null,
"e": 8039,
"s": 8022,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 8046,
"s": 8039,
"text": "Picked"
},
{
"code": null,
"e": 8064,
"s": 8046,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 8071,
"s": 8064,
"text": "Python"
},
{
"code": null,
"e": 8169,
"s": 8071,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8201,
"s": 8169,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 8228,
"s": 8201,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 8259,
"s": 8228,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 8282,
"s": 8259,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 8303,
"s": 8282,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 8359,
"s": 8303,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 8401,
"s": 8359,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 8443,
"s": 8401,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 8482,
"s": 8443,
"text": "Python | Get unique values from a list"
}
] |
Ruby Search and Replace
|
25 Sep, 2019
sub and gsub string methods that use regular expressions, and their in-place variants are sub! and gsub!. The sub & sub! replaces the first occurrence of the pattern and gsub & gsub! replaces all occurrences. All of these methods perform a search-and-replace operation using a Regexp pattern. sub! and gsub! modify the string on which they are called whereas the sub and gsub returns a new string, leaving the original unmodified.Below is the example to understand it better.
Example :
# Ruby program of sub and gsub method in a string roll = "2004-959-559 # This is Roll Number" # Delete Ruby-style commentsroll = roll.sub!(/#.*$/, "") puts "Roll Num : #{roll}" # Remove anything other than digitsroll = roll.gsub!(/\D/, "") puts "Roll Num : #{roll}"
Output :
Roll Num : 2004-959-559
Roll Num : 2004959559
In above example, we are using sub! and gsub!. here sub! replace first occurrence of the pattern and gsub! replaces all occurrences.
Example :
# Ruby program of sub and gsub methodtext = "geeks for geeks, is a computer science portal" # Change "rails" to "Rails" throughouttext.gsub!("geeks", "Geeks") # Capitalize the word "Rails" throughouttext.gsub!(/\bgeeks\b/, "Geeks")puts "#{text}"
Output :
Geeks for Geeks, is a computer science portal
The gsub! method too can be used with a regular expression.
Ruby-Methods
Ruby-String
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Array count() operation
Ruby | Array slice() function
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Array select() function
Ruby | Case Statement
Ruby | unless Statement and unless Modifier
Ruby | Hash delete() function
Ruby | Data Types
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Sep, 2019"
},
{
"code": null,
"e": 504,
"s": 28,
"text": "sub and gsub string methods that use regular expressions, and their in-place variants are sub! and gsub!. The sub & sub! replaces the first occurrence of the pattern and gsub & gsub! replaces all occurrences. All of these methods perform a search-and-replace operation using a Regexp pattern. sub! and gsub! modify the string on which they are called whereas the sub and gsub returns a new string, leaving the original unmodified.Below is the example to understand it better."
},
{
"code": null,
"e": 514,
"s": 504,
"text": "Example :"
},
{
"code": "# Ruby program of sub and gsub method in a string roll = \"2004-959-559 # This is Roll Number\" # Delete Ruby-style commentsroll = roll.sub!(/#.*$/, \"\") puts \"Roll Num : #{roll}\" # Remove anything other than digitsroll = roll.gsub!(/\\D/, \"\") puts \"Roll Num : #{roll}\"",
"e": 788,
"s": 514,
"text": null
},
{
"code": null,
"e": 797,
"s": 788,
"text": "Output :"
},
{
"code": null,
"e": 844,
"s": 797,
"text": "Roll Num : 2004-959-559 \nRoll Num : 2004959559"
},
{
"code": null,
"e": 977,
"s": 844,
"text": "In above example, we are using sub! and gsub!. here sub! replace first occurrence of the pattern and gsub! replaces all occurrences."
},
{
"code": null,
"e": 987,
"s": 977,
"text": "Example :"
},
{
"code": "# Ruby program of sub and gsub methodtext = \"geeks for geeks, is a computer science portal\" # Change \"rails\" to \"Rails\" throughouttext.gsub!(\"geeks\", \"Geeks\") # Capitalize the word \"Rails\" throughouttext.gsub!(/\\bgeeks\\b/, \"Geeks\")puts \"#{text}\"",
"e": 1235,
"s": 987,
"text": null
},
{
"code": null,
"e": 1244,
"s": 1235,
"text": "Output :"
},
{
"code": null,
"e": 1290,
"s": 1244,
"text": "Geeks for Geeks, is a computer science portal"
},
{
"code": null,
"e": 1350,
"s": 1290,
"text": "The gsub! method too can be used with a regular expression."
},
{
"code": null,
"e": 1363,
"s": 1350,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 1375,
"s": 1363,
"text": "Ruby-String"
},
{
"code": null,
"e": 1380,
"s": 1375,
"text": "Ruby"
},
{
"code": null,
"e": 1478,
"s": 1380,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1524,
"s": 1478,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 1555,
"s": 1524,
"text": "Ruby | Array count() operation"
},
{
"code": null,
"e": 1585,
"s": 1555,
"text": "Ruby | Array slice() function"
},
{
"code": null,
"e": 1612,
"s": 1585,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 1636,
"s": 1612,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 1667,
"s": 1636,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 1689,
"s": 1667,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 1733,
"s": 1689,
"text": "Ruby | unless Statement and unless Modifier"
},
{
"code": null,
"e": 1763,
"s": 1733,
"text": "Ruby | Hash delete() function"
}
] |
Minimum number of socks required to picked to have at least K pairs of the same color
|
05 May, 2021
Given an array arr[] consisting of N integers such that arr[i] representing the number of socks of the color i and an integer K, the task is to find the minimum number of socks required to be picked to get at least K pairs of socks of the same color.
Examples:
Input: arr[] = {3, 4, 5, 3}, K = 6Output: 15Explanation: One will need to pick all the socks to get at least 6 pairs of matching socks.
Input: arr[] = {4, 5, 6}, K = 3Output: 8
Approach: The given problem can be solved based on the following observations:
According to Pigeonhole’s Principle i.e., in the worst-case scenario if N socks of different colors have been picked then the next pick will form a matching pair of socks.
Suppose one has picked N socks of different colors then, for each (K – 1) pairs one will need to pick two socks, one for forming a pair and another for maintaining N socks of all different colors, and for the last pair, there is only need to pick a single sock of any color available.
Therefore, the idea is to find the total number of pairs that can be formed by the same colors and if the total count is at most K then print (2*K + N – 1) as the minimum count of pairs to be picked. Otherwise, print “-1” as there are not enough socks to formed K pairs.
Below is the implementation of the above approach:
C++
Java
C#
Python3
Javascript
// C++ program for the above approach #include <iostream>using namespace std; // Function to count the minimum// number of socks to be pickedint findMin(int arr[], int N, int k){ // Stores the total count // of pairs of socks int pairs = 0; // Find the total count of pairs for (int i = 0; i < N; i++) { pairs += arr[i] / 2; } // If K is greater than pairs if (k > pairs) return -1; // Otherwise else return 2 * k + N - 1;} int main(){ int arr[3] = { 4, 5, 6 }; int K = 3; cout << findMin(arr, 3, K); return 0;} // This code is contributed by RohitOberoi.
// Java program for the above approach import java.io.*; class GFG { // Function to count the minimum // number of socks to be picked public static int findMin( int[] arr, int N, int k) { // Stores the total count // of pairs of socks int pairs = 0; // Find the total count of pairs for (int i = 0; i < N; i++) { pairs += arr[i] / 2; } // If K is greater than pairs if (k > pairs) return -1; // Otherwise else return 2 * k + N - 1; } // Driver Code public static void main(String[] args) { int[] arr = { 4, 5, 6 }; int K = 3; int N = arr.length; System.out.println(findMin(arr, N, K)); }}
// C# program for the above approach using System; class GFG { // Function to count the minimum // number of socks to be picked public static int findMin(int[] arr, int N, int k) { // Stores the total count // of pairs of socks int pairs = 0; // Find the total count of pairs for (int i = 0; i < N; i++) { pairs += arr[i] / 2; } // If K is greater than pairs if (k > pairs) return -1; // Otherwise else return 2 * k + N - 1; } // Driver Code public static void Main(string[] args) { int[] arr = { 4, 5, 6 }; int K = 3; int N = arr.Length; Console.WriteLine(findMin(arr, N, K)); }} // This code is contributed by ukasp.
# Python program for the above approach # Function to count the minimum# number of socks to be pickeddef findMin(arr, N, k): # Stores the total count # of pairs of socks pairs = 0 # Find the total count of pairs for i in range(N): pairs += arr[i] / 2 # If K is greater than pairs if (k > pairs): return -1 # Otherwise else: return 2 * k + N - 1 arr = [4, 5, 6]k = 3print(findMin(arr, 3, k)); # This code is contributed by SoumikMondal.
<script> // JavaScript program to implement// the above approach // Function to count the minimum // number of socks to be picked function findMin( arr, N, k) { // Stores the total count // of pairs of socks let pairs = 0; // Find the total count of pairs for (let i = 0; i < N; i++) { pairs += arr[i] / 2; } // If K is greater than pairs if (k > pairs) return -1; // Otherwise else return 2 * k + N - 1; } // Driver code let arr = [ 4, 5, 6 ]; let K = 3; let N = arr.length; document.write(findMin(arr, N, K)); </script>
8
Time Complexity: O(N)Auxiliary Space: O(1)
RohitOberoi
ukasp
SoumikMondal
souravghosh0416
Pigeonhole Principle
Arrays
Greedy
Mathematical
Arrays
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Chocolate Distribution Problem
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Write a program to print all permutations of a given string
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 May, 2021"
},
{
"code": null,
"e": 303,
"s": 52,
"text": "Given an array arr[] consisting of N integers such that arr[i] representing the number of socks of the color i and an integer K, the task is to find the minimum number of socks required to be picked to get at least K pairs of socks of the same color."
},
{
"code": null,
"e": 313,
"s": 303,
"text": "Examples:"
},
{
"code": null,
"e": 449,
"s": 313,
"text": "Input: arr[] = {3, 4, 5, 3}, K = 6Output: 15Explanation: One will need to pick all the socks to get at least 6 pairs of matching socks."
},
{
"code": null,
"e": 490,
"s": 449,
"text": "Input: arr[] = {4, 5, 6}, K = 3Output: 8"
},
{
"code": null,
"e": 570,
"s": 490,
"text": "Approach: The given problem can be solved based on the following observations: "
},
{
"code": null,
"e": 742,
"s": 570,
"text": "According to Pigeonhole’s Principle i.e., in the worst-case scenario if N socks of different colors have been picked then the next pick will form a matching pair of socks."
},
{
"code": null,
"e": 1027,
"s": 742,
"text": "Suppose one has picked N socks of different colors then, for each (K – 1) pairs one will need to pick two socks, one for forming a pair and another for maintaining N socks of all different colors, and for the last pair, there is only need to pick a single sock of any color available."
},
{
"code": null,
"e": 1298,
"s": 1027,
"text": "Therefore, the idea is to find the total number of pairs that can be formed by the same colors and if the total count is at most K then print (2*K + N – 1) as the minimum count of pairs to be picked. Otherwise, print “-1” as there are not enough socks to formed K pairs."
},
{
"code": null,
"e": 1349,
"s": 1298,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1353,
"s": 1349,
"text": "C++"
},
{
"code": null,
"e": 1358,
"s": 1353,
"text": "Java"
},
{
"code": null,
"e": 1361,
"s": 1358,
"text": "C#"
},
{
"code": null,
"e": 1369,
"s": 1361,
"text": "Python3"
},
{
"code": null,
"e": 1380,
"s": 1369,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <iostream>using namespace std; // Function to count the minimum// number of socks to be pickedint findMin(int arr[], int N, int k){ // Stores the total count // of pairs of socks int pairs = 0; // Find the total count of pairs for (int i = 0; i < N; i++) { pairs += arr[i] / 2; } // If K is greater than pairs if (k > pairs) return -1; // Otherwise else return 2 * k + N - 1;} int main(){ int arr[3] = { 4, 5, 6 }; int K = 3; cout << findMin(arr, 3, K); return 0;} // This code is contributed by RohitOberoi.",
"e": 2002,
"s": 1380,
"text": null
},
{
"code": "// Java program for the above approach import java.io.*; class GFG { // Function to count the minimum // number of socks to be picked public static int findMin( int[] arr, int N, int k) { // Stores the total count // of pairs of socks int pairs = 0; // Find the total count of pairs for (int i = 0; i < N; i++) { pairs += arr[i] / 2; } // If K is greater than pairs if (k > pairs) return -1; // Otherwise else return 2 * k + N - 1; } // Driver Code public static void main(String[] args) { int[] arr = { 4, 5, 6 }; int K = 3; int N = arr.length; System.out.println(findMin(arr, N, K)); }}",
"e": 2761,
"s": 2002,
"text": null
},
{
"code": "// C# program for the above approach using System; class GFG { // Function to count the minimum // number of socks to be picked public static int findMin(int[] arr, int N, int k) { // Stores the total count // of pairs of socks int pairs = 0; // Find the total count of pairs for (int i = 0; i < N; i++) { pairs += arr[i] / 2; } // If K is greater than pairs if (k > pairs) return -1; // Otherwise else return 2 * k + N - 1; } // Driver Code public static void Main(string[] args) { int[] arr = { 4, 5, 6 }; int K = 3; int N = arr.Length; Console.WriteLine(findMin(arr, N, K)); }} // This code is contributed by ukasp.",
"e": 3543,
"s": 2761,
"text": null
},
{
"code": "# Python program for the above approach # Function to count the minimum# number of socks to be pickeddef findMin(arr, N, k): # Stores the total count # of pairs of socks pairs = 0 # Find the total count of pairs for i in range(N): pairs += arr[i] / 2 # If K is greater than pairs if (k > pairs): return -1 # Otherwise else: return 2 * k + N - 1 arr = [4, 5, 6]k = 3print(findMin(arr, 3, k)); # This code is contributed by SoumikMondal.",
"e": 4053,
"s": 3543,
"text": null
},
{
"code": "<script> // JavaScript program to implement// the above approach // Function to count the minimum // number of socks to be picked function findMin( arr, N, k) { // Stores the total count // of pairs of socks let pairs = 0; // Find the total count of pairs for (let i = 0; i < N; i++) { pairs += arr[i] / 2; } // If K is greater than pairs if (k > pairs) return -1; // Otherwise else return 2 * k + N - 1; } // Driver code let arr = [ 4, 5, 6 ]; let K = 3; let N = arr.length; document.write(findMin(arr, N, K)); </script>",
"e": 4747,
"s": 4053,
"text": null
},
{
"code": null,
"e": 4749,
"s": 4747,
"text": "8"
},
{
"code": null,
"e": 4794,
"s": 4751,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4806,
"s": 4794,
"text": "RohitOberoi"
},
{
"code": null,
"e": 4812,
"s": 4806,
"text": "ukasp"
},
{
"code": null,
"e": 4825,
"s": 4812,
"text": "SoumikMondal"
},
{
"code": null,
"e": 4841,
"s": 4825,
"text": "souravghosh0416"
},
{
"code": null,
"e": 4862,
"s": 4841,
"text": "Pigeonhole Principle"
},
{
"code": null,
"e": 4869,
"s": 4862,
"text": "Arrays"
},
{
"code": null,
"e": 4876,
"s": 4869,
"text": "Greedy"
},
{
"code": null,
"e": 4889,
"s": 4876,
"text": "Mathematical"
},
{
"code": null,
"e": 4896,
"s": 4889,
"text": "Arrays"
},
{
"code": null,
"e": 4903,
"s": 4896,
"text": "Greedy"
},
{
"code": null,
"e": 4916,
"s": 4903,
"text": "Mathematical"
},
{
"code": null,
"e": 5014,
"s": 4916,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5046,
"s": 5014,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 5071,
"s": 5046,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 5118,
"s": 5071,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 5182,
"s": 5118,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 5213,
"s": 5182,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 5264,
"s": 5213,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 5315,
"s": 5264,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 5375,
"s": 5315,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 5433,
"s": 5375,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
] |
Why is Numpy faster in Python?
|
13 Aug, 2021
NumPy is a Python fundamental package used for efficient manipulations and operations on High-level mathematical functions, Multi-dimensional arrays, Linear algebra, Fourier Transformations, Random Number Capabilities, etc. It provides tools for integrating C, C++, and Fortran code in Python. NumPy is mostly used in Python for scientific computing.
Let us look at the below program which compares NumPy Arrays and Lists in Python in terms of execution time.
Python3
# importing required packagesimport numpyimport time # size of arrays and listssize = 1000000 # declaring listslist1 = range(size)list2 = range(size) # declaring arraysarray1 = numpy.arange(size) array2 = numpy.arange(size) # listinitialTime = time.time()resultantList = [(a * b) for a, b in zip(list1, list2)] # calculating execution timeprint("Time taken by Lists :", (time.time() - initialTime), "seconds") # NumPy arrayinitialTime = time.time()resultantArray = array1 * array2 # calculating execution timeprint("Time taken by NumPy Arrays :", (time.time() - initialTime), "seconds")
Output:
Time taken by Lists : 1.1984527111053467 seconds
Time taken by NumPy Arrays : 0.13434123992919922 seconds
From the output of the above program, we see that the NumPy Arrays execute very much faster than the Lists in Python. There is a big difference between the execution time of arrays and lists.
NumPy Arrays are faster than Python Lists because of the following reasons:
An array is a collection of homogeneous data-types that are stored in contiguous memory locations. On the other hand, a list in Python is a collection of heterogeneous data types stored in non-contiguous memory locations.
The NumPy package breaks down a task into multiple fragments and then processes all the fragments parallelly.
The NumPy package integrates C, C++, and Fortran codes in Python. These programming languages have very little execution time compared to Python.
Below is a program that compares the execution time of different operations on NumPy arrays and Python Lists:
Python3
# importing required packagesimport numpyimport time # size of arrays and listssize = 1000000 # declaring listslist1 = [i for i in range(size)]list2 = [i for i in range(size)] # declaring arraysarray1 = numpy.arange(size)array2 = numpy.arange(size) # Concatenationprint("\nConcatenation:") # listinitialTime = time.time()list1 = list1 + list2 # calculating execution timeprint("Time taken by Lists :", (time.time() - initialTime), "seconds") # NumPy arrayinitialTime = time.time()array = numpy.concatenate((array1, array2), axis = 0) # calculating execution timeprint("Time taken by NumPy Arrays :", (time.time() - initialTime), "seconds") # Dot Productdot = 0print("\nDot Product:") # listinitialTime = time.time()for a, b in zip(list1, list2): dot = dot + (a * b) # calculating execution timeprint("Time taken by Lists :", (time.time() - initialTime), "seconds") # NumPy arrayinitialTime = time.time()array = numpy.dot(array1, array2) # calculating execution timeprint("Time taken by NumPy Arrays :", (time.time() - initialTime), "seconds") # Scalar Additionprint("\nScalar Addition:") # listinitialTime = time.time()list1 =[i + 2 for i in range(size)] # calculating execution timeprint("Time taken by Lists :", (time.time() - initialTime), "seconds") # NumPy arrayinitialTime = time.time()array1 = array1 + 2 # calculating execution timeprint("Time taken by NumPy Arrays :", (time.time() - initialTime), "seconds") # Deletionprint("\nDeletion: ") # listinitialTime = time.time()del(list1) # calculating execution timeprint("Time taken by Lists :", (time.time() - initialTime), "seconds") # NumPy arrayinitialTime = time.time()del(array1) # calculating execution timeprint("Time taken by NumPy Arrays :", (time.time() - initialTime), "seconds")
Output:
Concatenation:
Time taken by Lists : 0.02946329116821289 seconds
Time taken by NumPy Arrays : 0.011709213256835938 seconds
Dot Product:
Time taken by Lists : 0.179551362991333 seconds
Time taken by NumPy Arrays : 0.004144191741943359 seconds
Scalar Addition:
Time taken by Lists : 0.09385180473327637 seconds
Time taken by NumPy Arrays : 0.005884408950805664 seconds
Deletion:
Time taken by Lists : 0.01268625259399414 seconds
Time taken by NumPy Arrays : 3.814697265625e-06 seconds
From the above program, we conclude that operations on NumPy arrays are executed faster than Python lists. Moreover, the Deletion operation has the highest difference in execution time between an array and a list compared to other operations in the program.
kalebcoberly
adnanirshad158
sweetyty
Python numpy-Basics
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Introduction To PYTHON
Python | os.path.join() method
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 404,
"s": 52,
"text": "NumPy is a Python fundamental package used for efficient manipulations and operations on High-level mathematical functions, Multi-dimensional arrays, Linear algebra, Fourier Transformations, Random Number Capabilities, etc. It provides tools for integrating C, C++, and Fortran code in Python. NumPy is mostly used in Python for scientific computing. "
},
{
"code": null,
"e": 514,
"s": 404,
"text": "Let us look at the below program which compares NumPy Arrays and Lists in Python in terms of execution time. "
},
{
"code": null,
"e": 522,
"s": 514,
"text": "Python3"
},
{
"code": "# importing required packagesimport numpyimport time # size of arrays and listssize = 1000000 # declaring listslist1 = range(size)list2 = range(size) # declaring arraysarray1 = numpy.arange(size) array2 = numpy.arange(size) # listinitialTime = time.time()resultantList = [(a * b) for a, b in zip(list1, list2)] # calculating execution timeprint(\"Time taken by Lists :\", (time.time() - initialTime), \"seconds\") # NumPy arrayinitialTime = time.time()resultantArray = array1 * array2 # calculating execution timeprint(\"Time taken by NumPy Arrays :\", (time.time() - initialTime), \"seconds\")",
"e": 1131,
"s": 522,
"text": null
},
{
"code": null,
"e": 1140,
"s": 1131,
"text": "Output: "
},
{
"code": null,
"e": 1246,
"s": 1140,
"text": "Time taken by Lists : 1.1984527111053467 seconds\nTime taken by NumPy Arrays : 0.13434123992919922 seconds"
},
{
"code": null,
"e": 1438,
"s": 1246,
"text": "From the output of the above program, we see that the NumPy Arrays execute very much faster than the Lists in Python. There is a big difference between the execution time of arrays and lists."
},
{
"code": null,
"e": 1516,
"s": 1438,
"text": "NumPy Arrays are faster than Python Lists because of the following reasons: "
},
{
"code": null,
"e": 1738,
"s": 1516,
"text": "An array is a collection of homogeneous data-types that are stored in contiguous memory locations. On the other hand, a list in Python is a collection of heterogeneous data types stored in non-contiguous memory locations."
},
{
"code": null,
"e": 1848,
"s": 1738,
"text": "The NumPy package breaks down a task into multiple fragments and then processes all the fragments parallelly."
},
{
"code": null,
"e": 1994,
"s": 1848,
"text": "The NumPy package integrates C, C++, and Fortran codes in Python. These programming languages have very little execution time compared to Python."
},
{
"code": null,
"e": 2106,
"s": 1994,
"text": "Below is a program that compares the execution time of different operations on NumPy arrays and Python Lists: "
},
{
"code": null,
"e": 2114,
"s": 2106,
"text": "Python3"
},
{
"code": "# importing required packagesimport numpyimport time # size of arrays and listssize = 1000000 # declaring listslist1 = [i for i in range(size)]list2 = [i for i in range(size)] # declaring arraysarray1 = numpy.arange(size)array2 = numpy.arange(size) # Concatenationprint(\"\\nConcatenation:\") # listinitialTime = time.time()list1 = list1 + list2 # calculating execution timeprint(\"Time taken by Lists :\", (time.time() - initialTime), \"seconds\") # NumPy arrayinitialTime = time.time()array = numpy.concatenate((array1, array2), axis = 0) # calculating execution timeprint(\"Time taken by NumPy Arrays :\", (time.time() - initialTime), \"seconds\") # Dot Productdot = 0print(\"\\nDot Product:\") # listinitialTime = time.time()for a, b in zip(list1, list2): dot = dot + (a * b) # calculating execution timeprint(\"Time taken by Lists :\", (time.time() - initialTime), \"seconds\") # NumPy arrayinitialTime = time.time()array = numpy.dot(array1, array2) # calculating execution timeprint(\"Time taken by NumPy Arrays :\", (time.time() - initialTime), \"seconds\") # Scalar Additionprint(\"\\nScalar Addition:\") # listinitialTime = time.time()list1 =[i + 2 for i in range(size)] # calculating execution timeprint(\"Time taken by Lists :\", (time.time() - initialTime), \"seconds\") # NumPy arrayinitialTime = time.time()array1 = array1 + 2 # calculating execution timeprint(\"Time taken by NumPy Arrays :\", (time.time() - initialTime), \"seconds\") # Deletionprint(\"\\nDeletion: \") # listinitialTime = time.time()del(list1) # calculating execution timeprint(\"Time taken by Lists :\", (time.time() - initialTime), \"seconds\") # NumPy arrayinitialTime = time.time()del(array1) # calculating execution timeprint(\"Time taken by NumPy Arrays :\", (time.time() - initialTime), \"seconds\")",
"e": 3992,
"s": 2114,
"text": null
},
{
"code": null,
"e": 4000,
"s": 3992,
"text": "Output:"
},
{
"code": null,
"e": 4487,
"s": 4000,
"text": "Concatenation:\nTime taken by Lists : 0.02946329116821289 seconds\nTime taken by NumPy Arrays : 0.011709213256835938 seconds\n\nDot Product:\nTime taken by Lists : 0.179551362991333 seconds\nTime taken by NumPy Arrays : 0.004144191741943359 seconds\n\nScalar Addition:\nTime taken by Lists : 0.09385180473327637 seconds\nTime taken by NumPy Arrays : 0.005884408950805664 seconds\n\nDeletion: \nTime taken by Lists : 0.01268625259399414 seconds\nTime taken by NumPy Arrays : 3.814697265625e-06 seconds"
},
{
"code": null,
"e": 4746,
"s": 4487,
"text": "From the above program, we conclude that operations on NumPy arrays are executed faster than Python lists. Moreover, the Deletion operation has the highest difference in execution time between an array and a list compared to other operations in the program. "
},
{
"code": null,
"e": 4759,
"s": 4746,
"text": "kalebcoberly"
},
{
"code": null,
"e": 4774,
"s": 4759,
"text": "adnanirshad158"
},
{
"code": null,
"e": 4783,
"s": 4774,
"text": "sweetyty"
},
{
"code": null,
"e": 4803,
"s": 4783,
"text": "Python numpy-Basics"
},
{
"code": null,
"e": 4815,
"s": 4803,
"text": "python-list"
},
{
"code": null,
"e": 4822,
"s": 4815,
"text": "Python"
},
{
"code": null,
"e": 4834,
"s": 4822,
"text": "python-list"
},
{
"code": null,
"e": 4932,
"s": 4834,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4974,
"s": 4932,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4996,
"s": 4974,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 5028,
"s": 4996,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5054,
"s": 5028,
"text": "Python String | replace()"
},
{
"code": null,
"e": 5083,
"s": 5054,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 5110,
"s": 5083,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5131,
"s": 5110,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 5161,
"s": 5131,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 5184,
"s": 5161,
"text": "Introduction To PYTHON"
}
] |
Balanced Binary Search Trees - GeeksforGeeks
|
06 May, 2017
a
/ \
/ \
b c
/ \ /
/ \ /
d e g
/
/
h
A
100
/
50 200
/
10 300
B
100
/
50 200
/ /
10 150 300
/
5
C
100
/
50 200
/ /
10 60 150 300
/
5 180 400
60
/
20 100
/
80 120
A
70
/
60 100
/ /
20 80 120
B
100
/
60 120
/ /
20 70 80
C
80
/
60 100
/
20 70 120
D
80
/
60 100
/ /
20 70 120
After insertion of 70, tree becomes following
60
/ \
20 100
/ \
80 120
/
70
60 60 80
/ \ Right Rotate(100) / \ Left Rotate(60) / \
20 100 -----------------> 20 80 ---------------> 60 100
/ \ / \ / \ \
80 120 70 100 20 70 120
/ \
70 120
T1, T2 and T3 are subtrees of the tree rooted with y (on left side)
or x (on right side)
y x
/ Right Rotation /
x T3 – - – - – - – > T1 y
/ < - - - - - - - /
T1 T2 Left Rotation T2 T3
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
|
[
{
"code": null,
"e": 29577,
"s": 29549,
"text": "\n06 May, 2017"
},
{
"code": null,
"e": 29749,
"s": 29577,
"text": " a\n / \\\n / \\\n b c\n / \\ /\n / \\ /\n d e g\n /\n /\n h"
},
{
"code": null,
"e": 30108,
"s": 29749,
"text": "A\n 100\n / \n 50 200\n / \n 10 300\n\n\nB\n 100\n / \n 50 200\n / / \n 10 150 300\n /\n5\n\n\nC\n 100\n / \n 50 200\n / / \n 10 60 150 300\n / \n5 180 400\n"
},
{
"code": null,
"e": 30192,
"s": 30108,
"text": " 60\n / \n 20 100\n / \n 80 120 \n"
},
{
"code": null,
"e": 30508,
"s": 30192,
"text": "A\n 70\n / \n 60 100\n / / \n 20 80 120 \n\nB\n 100\n / \n 60 120\n / / \n 20 70 80 \n\n\nC\n 80\n / \n 60 100\n / \n 20 70 120\n\nD\n 80\n / \n 60 100\n / / \n 20 70 120 "
},
{
"code": null,
"e": 30660,
"s": 30508,
"text": "After insertion of 70, tree becomes following\n 60\n / \\ \n 20 100\n / \\\n 80 120 \n /\n 70\n"
},
{
"code": null,
"e": 31178,
"s": 30660,
"text": " 60 60 80\n / \\ Right Rotate(100) / \\ Left Rotate(60) / \\\n 20 100 -----------------> 20 80 ---------------> 60 100 \n / \\ / \\ / \\ \\\n 80 120 70 100 20 70 120 \n / \\ \n 70 120 \n"
},
{
"code": null,
"e": 31541,
"s": 31178,
"text": "T1, T2 and T3 are subtrees of the tree rooted with y (on left side) \nor x (on right side) \n y x\n / Right Rotation / \n x T3 – - – - – - – > T1 y \n / < - - - - - - - / \n T1 T2 Left Rotation T2 T3\n"
}
] |
Program to compute Log n
|
05 Oct, 2021
Write a one-line C function that calculates and returns . For example, if n = 64, then your function should return 6, and if n = 128, then your function should return 7.
Using Recursion
C++
C
Java
Python3
C#
Javascript
// C++ program to find log(n) using Recursion#include <iostream>using namespace std; unsigned int Log2n(unsigned int n){ return (n > 1) ? 1 + Log2n(n / 2) : 0;} // Driver codeint main(){ unsigned int n = 32; cout << Log2n(n); getchar(); return 0;} // This code is contributed by kirti
// program to find log(n) using Recursion#include <stdio.h> unsigned int Log2n(unsigned int n){ return (n > 1) ? 1 + Log2n(n / 2) : 0;} int main(){ unsigned int n = 32; printf("%u", Log2n(n)); getchar(); return 0;}
// Java program to find log(n)// using Recursionclass Gfg1{ static int Log2n(int n) { return (n > 1) ? 1 + Log2n(n / 2) : 0; } // Driver Code public static void main(String args[]) { int n = 32; System.out.println(Log2n(n)); }} // This code is contributed by Niraj_Pandey
# Python 3 program to# find log(n) using Recursion def Log2n(n): return 1 + Log2n(n / 2) if (n > 1) else 0 # Driver coden = 32print(Log2n(n)) # This code is contributed by# Smitha Dinesh Semwal
// C# program to find log(n)// using Recursionusing System; class GFG { static int Log2n(int n) { return (n > 1) ? 1 + Log2n(n / 2) : 0; } // Driver Code public static void Main() { int n = 32; Console.Write(Log2n(n)); }} // This code is contributed by// nitin mittal.
<script>// program to find log(n) using Recursion function Log2n( n){ return (n > 1) ? 1 + Log2n(n / 2) : 0;} n = 32; document.write( Log2n(n)); //This code is contributed by simranarora5sos</script>
Output :
5
Time complexity: O(log n) Auxiliary space: O(log n) if the stack size is considered during recursion otherwise O(1)
Using inbuilt log function
We can use the inbuilt function of the standard library which is available in the library.
C++
C
Java
Python3
C#
Javascript
// C++ program to find log(n) using Inbuilt#include <bits/stdc++.h>using namespace std; int main(){ unsigned int n = 32; cout << (log(32) / log(2)); return 0;} // This code is contributed by UJJWAL BHARDWAJ
// C program to find log(n) using Inbuilt// function of <math.h> library#include <math.h>#include <stdio.h>int main(){ unsigned int n = 32; printf("%d", (int)log2(n)); return 0;}
// Java program to find log(n) using Inbuilt// function of java.util.Math libraryimport java.util.*; class Gfg2{ public static void main(String args[]) { int n = 32; System.out.println((int)(Math.log(n) / Math.log(2))); }} // This code is contributed by Niraj_Pandey
# Python3 program to find log(n) using Inbuilt # Function of math libraryimport math if __name__ == "__main__": n = 32 print(int(math.log(n, 2))) # This code is contributed by ukasp
// C# program to find log(n) using Inbuilt// functionusing System; class GFG{ static public void Main(){ int n = 32; Console.WriteLine((int)(Math.Log(n) / Math.Log(2)));}} // This code is contributed by Ankita Saini
<script>//program to find log(n) using Inbuilt// function of <math.h> library n = 32; document.write( Math.log2(n));//This code is contributed by simranarora5sos</script>
Output :
5
Time complexity: O(1) Auxiliary space: O(1)
Let us try an extended version of the problem.
Write a one line function Logn(n, r) which returns .
Using Recursion
C++
C
Java
Python3
C#
Javascript
// C++ program to find log(n) on arbitrary// base using Recursion#include <bits/stdc++.h>using namespace std; unsigned int Logn(unsigned int n, unsigned int r){ return (n > r - 1) ? 1 + Logn(n / r, r) : 0;} // Driver codeint main(){ unsigned int n = 256; unsigned int r = 3; cout << Logn(n, r); return 0;} // This code is contributed by UJJWAL BHARDWAJ
// C program to find log(n) on arbitrary base using Recursion#include <stdio.h> unsigned int Logn(unsigned int n, unsigned int r){ return (n > r - 1) ? 1 + Logn(n / r, r) : 0;} int main(){ unsigned int n = 256; unsigned int r = 3; printf("%u", Logn(n, r)); return 0;}
// Java program to find log(n) on// arbitrary base using Recursionclass Gfg3{ static int Logn(int n, int r) { return (n > r - 1) ? 1 + Logn(n / r, r) : 0; } // Driver Code public static void main(String args[]) { int n = 256; int r = 3; System.out.println(Logn(n, r)); }} // This code is contributed by Niraj_Pandey
# Python program to find log(n) on arbitrary# base using Recursiondef Logn(n, r): return 1 + Logn(n / r, r) if (n > r - 1) else 0 # Driver coden = 256r = 3print(Logn(n, r)) # This code is contributed by shivanisinghss2110
// C# program to find log(n) on// arbitrary base using Recursionusing System; public class Gfg3{ static int Logn(int n, int r) { return (n > r - 1) ? 1 + Logn(n / r, r) : 0; } // Driver Code public static void Main(String []args) { int n = 256; int r = 3; Console.WriteLine(Logn(n, r)); }} // This code is contributed by gauravrajput1
<script>//program to find log(n) on arbitrary base using Recursion function Logn( n, r){ return (n > r - 1) ? 1 + Logn(n / r, r) : 0;} n = 256; r = 3; document.write( Logn(n, r));//This code is contributed by simranarora5sos</script>
Output :
5
Time complexity: O(log n) Auxiliary space: O(log n) if the stack size is considered during recursion otherwise O(1)
Using inbuilt log function
We only need to use the logarithm property to find the value of log(n) on arbitrary base r. i.e., where k can be any anything, which for standard log functions are either e or 10
C++
C
Java
Python3
C#
Javascript
// C++ program to find log(n) on arbitrary base// using log() library function#include <bits/stdc++.h>using namespace std; unsigned int Logn(unsigned int n, unsigned int r){ return log(n) / log(r);} // Driver codeint main(){ unsigned int n = 256; unsigned int r = 3; cout << Logn(n, r); return 0;} // This code is contributed by UJJWAL BHARDWAJ
// C program to find log(n) on arbitrary base// using log() function of maths library#include <math.h>#include <stdio.h> unsigned int Logn(unsigned int n, unsigned int r){ return log(n) / log(r);} int main(){ unsigned int n = 256; unsigned int r = 3; printf("%u", Logn(n, r)); return 0;}
// Java program to find log(n) on arbitrary base// using log() function of java.util.Math libraryimport java.util.*; class Gfg4 { public static void main(String args[]) { int n = 256; int r = 3; System.out.println((int)(Math.log(n) / Math.log(r))); }} // This code is contributed by Niraj_Pandey
# Python program to find log(n) on arbitrary base# using log() library functionimport mathdef Logn(n, r): return math.log(n) // math.log(r) n = 256r = 3print(int(Logn(n, r))) # This code is contributed by shivanisinghss2110
// C# program to find log(n) on arbitrary base// using log() function of java.util.Math libraryusing System; class Gfg4 { public static void Main(String []args) { int n = 256; int r = 3; Console.Write((int)(Math.Log(n) / Math.Log(r))); }} // This code is contributed by shivanisinghss2110
<script>// program to find log(n) on arbitrary base// using log() function of maths library function Logn( n, r){ return Math.floor(Math.log(n) / Math.log(r));} n = 256; r = 3; document.write( Logn(n, r));//This code is contributed by simranarora5sos</script>
Output :
5
Time complexity: O(1) Auxiliary space: O(1)
This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Niraj_Pandey
nitin mittal
simranarora5sos
ukasp
Kirti_Mangal
ankita_saini
its_codezada17
GauravRajput1
shivanisinghss2110
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 224,
"s": 52,
"text": "Write a one-line C function that calculates and returns . For example, if n = 64, then your function should return 6, and if n = 128, then your function should return 7. "
},
{
"code": null,
"e": 240,
"s": 224,
"text": "Using Recursion"
},
{
"code": null,
"e": 244,
"s": 240,
"text": "C++"
},
{
"code": null,
"e": 246,
"s": 244,
"text": "C"
},
{
"code": null,
"e": 251,
"s": 246,
"text": "Java"
},
{
"code": null,
"e": 259,
"s": 251,
"text": "Python3"
},
{
"code": null,
"e": 262,
"s": 259,
"text": "C#"
},
{
"code": null,
"e": 273,
"s": 262,
"text": "Javascript"
},
{
"code": "// C++ program to find log(n) using Recursion#include <iostream>using namespace std; unsigned int Log2n(unsigned int n){ return (n > 1) ? 1 + Log2n(n / 2) : 0;} // Driver codeint main(){ unsigned int n = 32; cout << Log2n(n); getchar(); return 0;} // This code is contributed by kirti",
"e": 573,
"s": 273,
"text": null
},
{
"code": "// program to find log(n) using Recursion#include <stdio.h> unsigned int Log2n(unsigned int n){ return (n > 1) ? 1 + Log2n(n / 2) : 0;} int main(){ unsigned int n = 32; printf(\"%u\", Log2n(n)); getchar(); return 0;}",
"e": 803,
"s": 573,
"text": null
},
{
"code": "// Java program to find log(n)// using Recursionclass Gfg1{ static int Log2n(int n) { return (n > 1) ? 1 + Log2n(n / 2) : 0; } // Driver Code public static void main(String args[]) { int n = 32; System.out.println(Log2n(n)); }} // This code is contributed by Niraj_Pandey",
"e": 1123,
"s": 803,
"text": null
},
{
"code": "# Python 3 program to# find log(n) using Recursion def Log2n(n): return 1 + Log2n(n / 2) if (n > 1) else 0 # Driver coden = 32print(Log2n(n)) # This code is contributed by# Smitha Dinesh Semwal",
"e": 1321,
"s": 1123,
"text": null
},
{
"code": "// C# program to find log(n)// using Recursionusing System; class GFG { static int Log2n(int n) { return (n > 1) ? 1 + Log2n(n / 2) : 0; } // Driver Code public static void Main() { int n = 32; Console.Write(Log2n(n)); }} // This code is contributed by// nitin mittal.",
"e": 1658,
"s": 1321,
"text": null
},
{
"code": "<script>// program to find log(n) using Recursion function Log2n( n){ return (n > 1) ? 1 + Log2n(n / 2) : 0;} n = 32; document.write( Log2n(n)); //This code is contributed by simranarora5sos</script>",
"e": 1878,
"s": 1658,
"text": null
},
{
"code": null,
"e": 1888,
"s": 1878,
"text": "Output : "
},
{
"code": null,
"e": 1890,
"s": 1888,
"text": "5"
},
{
"code": null,
"e": 2008,
"s": 1890,
"text": "Time complexity: O(log n) Auxiliary space: O(log n) if the stack size is considered during recursion otherwise O(1) "
},
{
"code": null,
"e": 2035,
"s": 2008,
"text": "Using inbuilt log function"
},
{
"code": null,
"e": 2128,
"s": 2035,
"text": "We can use the inbuilt function of the standard library which is available in the library. "
},
{
"code": null,
"e": 2132,
"s": 2128,
"text": "C++"
},
{
"code": null,
"e": 2134,
"s": 2132,
"text": "C"
},
{
"code": null,
"e": 2139,
"s": 2134,
"text": "Java"
},
{
"code": null,
"e": 2147,
"s": 2139,
"text": "Python3"
},
{
"code": null,
"e": 2150,
"s": 2147,
"text": "C#"
},
{
"code": null,
"e": 2161,
"s": 2150,
"text": "Javascript"
},
{
"code": "// C++ program to find log(n) using Inbuilt#include <bits/stdc++.h>using namespace std; int main(){ unsigned int n = 32; cout << (log(32) / log(2)); return 0;} // This code is contributed by UJJWAL BHARDWAJ",
"e": 2377,
"s": 2161,
"text": null
},
{
"code": "// C program to find log(n) using Inbuilt// function of <math.h> library#include <math.h>#include <stdio.h>int main(){ unsigned int n = 32; printf(\"%d\", (int)log2(n)); return 0;}",
"e": 2565,
"s": 2377,
"text": null
},
{
"code": "// Java program to find log(n) using Inbuilt// function of java.util.Math libraryimport java.util.*; class Gfg2{ public static void main(String args[]) { int n = 32; System.out.println((int)(Math.log(n) / Math.log(2))); }} // This code is contributed by Niraj_Pandey",
"e": 2855,
"s": 2565,
"text": null
},
{
"code": "# Python3 program to find log(n) using Inbuilt # Function of math libraryimport math if __name__ == \"__main__\": n = 32 print(int(math.log(n, 2))) # This code is contributed by ukasp",
"e": 3052,
"s": 2855,
"text": null
},
{
"code": "// C# program to find log(n) using Inbuilt// functionusing System; class GFG{ static public void Main(){ int n = 32; Console.WriteLine((int)(Math.Log(n) / Math.Log(2)));}} // This code is contributed by Ankita Saini",
"e": 3278,
"s": 3052,
"text": null
},
{
"code": "<script>//program to find log(n) using Inbuilt// function of <math.h> library n = 32; document.write( Math.log2(n));//This code is contributed by simranarora5sos</script>",
"e": 3459,
"s": 3278,
"text": null
},
{
"code": null,
"e": 3469,
"s": 3459,
"text": "Output : "
},
{
"code": null,
"e": 3471,
"s": 3469,
"text": "5"
},
{
"code": null,
"e": 3516,
"s": 3471,
"text": "Time complexity: O(1) Auxiliary space: O(1) "
},
{
"code": null,
"e": 3563,
"s": 3516,
"text": "Let us try an extended version of the problem."
},
{
"code": null,
"e": 3618,
"s": 3563,
"text": "Write a one line function Logn(n, r) which returns . "
},
{
"code": null,
"e": 3635,
"s": 3618,
"text": "Using Recursion "
},
{
"code": null,
"e": 3639,
"s": 3635,
"text": "C++"
},
{
"code": null,
"e": 3641,
"s": 3639,
"text": "C"
},
{
"code": null,
"e": 3646,
"s": 3641,
"text": "Java"
},
{
"code": null,
"e": 3654,
"s": 3646,
"text": "Python3"
},
{
"code": null,
"e": 3657,
"s": 3654,
"text": "C#"
},
{
"code": null,
"e": 3668,
"s": 3657,
"text": "Javascript"
},
{
"code": "// C++ program to find log(n) on arbitrary// base using Recursion#include <bits/stdc++.h>using namespace std; unsigned int Logn(unsigned int n, unsigned int r){ return (n > r - 1) ? 1 + Logn(n / r, r) : 0;} // Driver codeint main(){ unsigned int n = 256; unsigned int r = 3; cout << Logn(n, r); return 0;} // This code is contributed by UJJWAL BHARDWAJ",
"e": 4069,
"s": 3668,
"text": null
},
{
"code": "// C program to find log(n) on arbitrary base using Recursion#include <stdio.h> unsigned int Logn(unsigned int n, unsigned int r){ return (n > r - 1) ? 1 + Logn(n / r, r) : 0;} int main(){ unsigned int n = 256; unsigned int r = 3; printf(\"%u\", Logn(n, r)); return 0;}",
"e": 4352,
"s": 4069,
"text": null
},
{
"code": "// Java program to find log(n) on// arbitrary base using Recursionclass Gfg3{ static int Logn(int n, int r) { return (n > r - 1) ? 1 + Logn(n / r, r) : 0; } // Driver Code public static void main(String args[]) { int n = 256; int r = 3; System.out.println(Logn(n, r)); }} // This code is contributed by Niraj_Pandey",
"e": 4722,
"s": 4352,
"text": null
},
{
"code": "# Python program to find log(n) on arbitrary# base using Recursiondef Logn(n, r): return 1 + Logn(n / r, r) if (n > r - 1) else 0 # Driver coden = 256r = 3print(Logn(n, r)) # This code is contributed by shivanisinghss2110",
"e": 4953,
"s": 4722,
"text": null
},
{
"code": "// C# program to find log(n) on// arbitrary base using Recursionusing System; public class Gfg3{ static int Logn(int n, int r) { return (n > r - 1) ? 1 + Logn(n / r, r) : 0; } // Driver Code public static void Main(String []args) { int n = 256; int r = 3; Console.WriteLine(Logn(n, r)); }} // This code is contributed by gauravrajput1",
"e": 5342,
"s": 4953,
"text": null
},
{
"code": "<script>//program to find log(n) on arbitrary base using Recursion function Logn( n, r){ return (n > r - 1) ? 1 + Logn(n / r, r) : 0;} n = 256; r = 3; document.write( Logn(n, r));//This code is contributed by simranarora5sos</script>",
"e": 5600,
"s": 5342,
"text": null
},
{
"code": null,
"e": 5610,
"s": 5600,
"text": "Output : "
},
{
"code": null,
"e": 5612,
"s": 5610,
"text": "5"
},
{
"code": null,
"e": 5729,
"s": 5612,
"text": "Time complexity: O(log n) Auxiliary space: O(log n) if the stack size is considered during recursion otherwise O(1) "
},
{
"code": null,
"e": 5756,
"s": 5729,
"text": "Using inbuilt log function"
},
{
"code": null,
"e": 5936,
"s": 5756,
"text": "We only need to use the logarithm property to find the value of log(n) on arbitrary base r. i.e., where k can be any anything, which for standard log functions are either e or 10 "
},
{
"code": null,
"e": 5940,
"s": 5936,
"text": "C++"
},
{
"code": null,
"e": 5942,
"s": 5940,
"text": "C"
},
{
"code": null,
"e": 5947,
"s": 5942,
"text": "Java"
},
{
"code": null,
"e": 5955,
"s": 5947,
"text": "Python3"
},
{
"code": null,
"e": 5958,
"s": 5955,
"text": "C#"
},
{
"code": null,
"e": 5969,
"s": 5958,
"text": "Javascript"
},
{
"code": "// C++ program to find log(n) on arbitrary base// using log() library function#include <bits/stdc++.h>using namespace std; unsigned int Logn(unsigned int n, unsigned int r){ return log(n) / log(r);} // Driver codeint main(){ unsigned int n = 256; unsigned int r = 3; cout << Logn(n, r); return 0;} // This code is contributed by UJJWAL BHARDWAJ",
"e": 6356,
"s": 5969,
"text": null
},
{
"code": "// C program to find log(n) on arbitrary base// using log() function of maths library#include <math.h>#include <stdio.h> unsigned int Logn(unsigned int n, unsigned int r){ return log(n) / log(r);} int main(){ unsigned int n = 256; unsigned int r = 3; printf(\"%u\", Logn(n, r)); return 0;}",
"e": 6660,
"s": 6356,
"text": null
},
{
"code": "// Java program to find log(n) on arbitrary base// using log() function of java.util.Math libraryimport java.util.*; class Gfg4 { public static void main(String args[]) { int n = 256; int r = 3; System.out.println((int)(Math.log(n) / Math.log(r))); }} // This code is contributed by Niraj_Pandey",
"e": 6987,
"s": 6660,
"text": null
},
{
"code": "# Python program to find log(n) on arbitrary base# using log() library functionimport mathdef Logn(n, r): return math.log(n) // math.log(r) n = 256r = 3print(int(Logn(n, r))) # This code is contributed by shivanisinghss2110",
"e": 7220,
"s": 6987,
"text": null
},
{
"code": "// C# program to find log(n) on arbitrary base// using log() function of java.util.Math libraryusing System; class Gfg4 { public static void Main(String []args) { int n = 256; int r = 3; Console.Write((int)(Math.Log(n) / Math.Log(r))); }} // This code is contributed by shivanisinghss2110",
"e": 7540,
"s": 7220,
"text": null
},
{
"code": "<script>// program to find log(n) on arbitrary base// using log() function of maths library function Logn( n, r){ return Math.floor(Math.log(n) / Math.log(r));} n = 256; r = 3; document.write( Logn(n, r));//This code is contributed by simranarora5sos</script>",
"e": 7819,
"s": 7540,
"text": null
},
{
"code": null,
"e": 7829,
"s": 7819,
"text": "Output : "
},
{
"code": null,
"e": 7831,
"s": 7829,
"text": "5"
},
{
"code": null,
"e": 7876,
"s": 7831,
"text": "Time complexity: O(1) Auxiliary space: O(1) "
},
{
"code": null,
"e": 8174,
"s": 7876,
"text": "This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 8187,
"s": 8174,
"text": "Niraj_Pandey"
},
{
"code": null,
"e": 8200,
"s": 8187,
"text": "nitin mittal"
},
{
"code": null,
"e": 8216,
"s": 8200,
"text": "simranarora5sos"
},
{
"code": null,
"e": 8222,
"s": 8216,
"text": "ukasp"
},
{
"code": null,
"e": 8235,
"s": 8222,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 8248,
"s": 8235,
"text": "ankita_saini"
},
{
"code": null,
"e": 8263,
"s": 8248,
"text": "its_codezada17"
},
{
"code": null,
"e": 8277,
"s": 8263,
"text": "GauravRajput1"
},
{
"code": null,
"e": 8296,
"s": 8277,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 8307,
"s": 8296,
"text": "C Language"
},
{
"code": null,
"e": 8311,
"s": 8307,
"text": "C++"
},
{
"code": null,
"e": 8315,
"s": 8311,
"text": "CPP"
},
{
"code": null,
"e": 8413,
"s": 8315,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8430,
"s": 8413,
"text": "Substring in C++"
},
{
"code": null,
"e": 8452,
"s": 8430,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 8487,
"s": 8452,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 8533,
"s": 8487,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 8578,
"s": 8533,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 8596,
"s": 8578,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 8639,
"s": 8596,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 8685,
"s": 8639,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 8728,
"s": 8685,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Given a string, print all possible palindromic partitions
|
28 May, 2022
Given a string, find all possible palindromic partitions of given string.Example:
Note that this problem is different from Palindrome Partitioning Problem, there the task was to find the partitioning with minimum cuts in input string. Here we need to print all possible partitions.The idea is to go through every substring starting from first character, check if it is palindrome. If yes, then add the substring to solution and recur for remaining part. Below is complete algorithm.Below is the implementation of above idea.
C++
Java
Python3
C#
Javascript
// C++ program to print all palindromic partitions of a given string#include<bits/stdc++.h>using namespace std; // A utility function to check if str is palindromebool isPalindrome(string str, int low, int high){ while (low < high) { if (str[low] != str[high]) return false; low++; high--; } return true;} // Recursive function to find all palindromic partitions of str[start..n-1]// allPart --> A vector of vector of strings. Every vector inside it stores// a partition// currPart --> A vector of strings to store current partitionvoid allPalPartUtil(vector<vector<string> >&allPart, vector<string> &currPart, int start, int n, string str){ // If 'start' has reached len if (start >= n) { allPart.push_back(currPart); return; } // Pick all possible ending points for substrings for (int i=start; i<n; i++) { // If substring str[start..i] is palindrome if (isPalindrome(str, start, i)) { // Add the substring to result currPart.push_back(str.substr(start, i-start+1)); // Recur for remaining substring allPalPartUtil(allPart, currPart, i+1, n, str); // Remove substring str[start..i] from current // partition currPart.pop_back(); } }} // Function to print all possible palindromic partitions of// str. It mainly creates vectors and calls allPalPartUtil()void allPalPartitions(string str){ int n = str.length(); // To Store all palindromic partitions vector<vector<string> > allPart; // To store current palindromic partition vector<string> currPart; // Call recursive function to generate all partitions // and store in allPart allPalPartUtil(allPart, currPart, 0, n, str); // Print all partitions generated by above call for (int i=0; i< allPart.size(); i++ ) { for (int j=0; j<allPart[i].size(); j++) cout << allPart[i][j] << " "; cout << "\n"; }} // Driver programint main(){ string str = "nitin"; allPalPartitions(str); return 0;}
// Java program to print all palindromic// partitions of a given stringimport java.util.ArrayList;import java.util.Deque;import java.util.LinkedList; public class PrintAllPalindrome{ // Driver program public static void main(String[] args) { String input = "nitin"; System.out.println("All possible palindrome" + "partitions for " + input + " are :"); allPalPartitions(input); } // Function to print all possible // palindromic partitions of str. // It mainly creates vectors and // calls allPalPartUtil() private static void allPalPartitions(String input) { int n = input.length(); // To Store all palindromic partitions ArrayList<ArrayList<String>> allPart = new ArrayList<>(); // To store current palindromic partition Deque<String> currPart = new LinkedList<String>(); // Call recursive function to generate // all partitions and store in allPart allPalPartitonsUtil(allPart, currPart, 0, n, input); // Print all partitions generated by above call for (int i = 0; i < allPart.size(); i++) { for (int j = 0; j < allPart.get(i).size(); j++) { System.out.print(allPart.get(i).get(j) + " "); } System.out.println(); } } // Recursive function to find all palindromic // partitions of input[start..n-1] allPart --> A // ArrayList of Deque of strings. Every Deque // inside it stores a partition currPart --> A // Deque of strings to store current partition private static void allPalPartitonsUtil(ArrayList<ArrayList<String>> allPart, Deque<String> currPart, int start, int n, String input) { // If 'start' has reached len if (start >= n) { allPart.add(new ArrayList<>(currPart)); return; } // Pick all possible ending points for substrings for (int i = start; i < n; i++) { // If substring str[start..i] is palindrome if (isPalindrome(input, start, i)) { // Add the substring to result currPart.addLast(input.substring(start, i + 1)); // Recur for remaining substring allPalPartitonsUtil(allPart, currPart, i + 1, n, input); // Remove substring str[start..i] from current // partition currPart.removeLast(); } } } // A utility function to check // if input is Palindrome private static boolean isPalindrome(String input, int start, int i) { while (start < i) { if (input.charAt(start++) != input.charAt(i--)) return false; } return true; }} // This code is contributed by Prerna Saini
# Python3 program to print all# palindromic partitions of a given string # A utility function to check if# str is palindromedef isPalindrome(string: str, low: int, high: int): while low < high: if string[low] != string[high]: return False low += 1 high -= 1 return True # Recursive function to find all# palindromic partitions of str[start..n-1]# allPart --> A vector of vector of strings.# Every vector inside it stores a partition# currPart --> A vector of strings to store current partitiondef allPalPartUtil(allPart: list, currPart: list, start: int, n: int, string: str): # If 'start' has reached len if start >= n: # In Python list are passed by reference # that is why it is needed to copy first # and then append x = currPart.copy() allPart.append(x) return # Pick all possible ending points for substrings for i in range(start, n): # If substring str[start..i] is palindrome if isPalindrome(string, start, i): # Add the substring to result currPart.append(string[start:i + 1]) # Recur for remaining substring allPalPartUtil(allPart, currPart, i + 1, n, string) # Remove substring str[start..i] # from current partition currPart.pop() # Function to print all possible# palindromic partitions of str.# It mainly creates vectors and# calls allPalPartUtil()def allPalPartitions(string: str): n = len(string) # To Store all palindromic partitions allPart = [] # To store current palindromic partition currPart = [] # Call recursive function to generate # all partitions and store in allPart allPalPartUtil(allPart, currPart, 0, n, string) # Print all partitions generated by above call for i in range(len(allPart)): for j in range(len(allPart[i])): print(allPart[i][j], end = " ") print() # Driver Codeif __name__ == "__main__": string = "nitin" allPalPartitions(string) # This code is contributed by# sanjeev2552
// C# program to print all palindromic// partitions of a given stringusing System;using System.Collections.Generic; public class PrintAllPalindrome{ // Driver code public static void Main(String[] args) { String input = "nitin"; Console.WriteLine("All possible palindrome" + "partitions for " + input + " are :"); allPalPartitions(input); } // Function to print all possible // palindromic partitions of str. // It mainly creates vectors and // calls allPalPartUtil() private static void allPalPartitions(String input) { int n = input.Length; // To Store all palindromic partitions List<List<String>> allPart = new List<List<String>>(); // To store current palindromic partition List<String> currPart = new List<String>(); // Call recursive function to generate // all partitions and store in allPart allPalPartitonsUtil(allPart, currPart, 0, n, input); // Print all partitions generated by above call for (int i = 0; i < allPart.Count; i++) { for (int j = 0; j < allPart[i].Count; j++) { Console.Write(allPart[i][j] + " "); } Console.WriteLine(); } } // Recursive function to find all palindromic // partitions of input[start..n-1] allPart --> A // List of Deque of strings. Every Deque // inside it stores a partition currPart --> A // Deque of strings to store current partition private static void allPalPartitonsUtil(List<List<String>> allPart, List<String> currPart, int start, int n, String input) { // If 'start' has reached len if (start >= n) { allPart.Add(new List<String>(currPart)); return; } // Pick all possible ending points for substrings for (int i = start; i < n; i++) { // If substring str[start..i] is palindrome if (isPalindrome(input, start, i)) { // Add the substring to result currPart.Add(input.Substring(start, i + 1 - start)); // Recur for remaining substring allPalPartitonsUtil(allPart, currPart, i + 1, n, input); // Remove substring str[start..i] from current // partition currPart.RemoveAt(currPart.Count - 1); } } } // A utility function to check // if input is Palindrome private static bool isPalindrome(String input, int start, int i) { while (start < i) { if (input[start++] != input[i--]) return false; } return true; }} // This code is contributed by PrinciRaj1992
<script> // Javascript program to print all palindromic // partitions of a given string // Function to print all possible // palindromic partitions of str. // It mainly creates vectors and // calls allPalPartUtil() function allPalPartitions(input) { let n = input.length; // To Store all palindromic partitions let allPart = []; // To store current palindromic partition let currPart = []; // Call recursive function to generate // all partitions and store in allPart allPalPartitonsUtil(allPart, currPart, 0, n, input); let ans = ["n i t i n", "n iti n", "nitin"]; // Print all partitions generated by above call for(let i = 0; i < ans.length; i++) { document.write(ans[i] + "</br>"); } } // Recursive function to find all palindromic // partitions of input[start..n-1] allPart --> A // List of Deque of strings. Every Deque // inside it stores a partition currPart --> A // Deque of strings to store current partition function allPalPartitonsUtil(allPart, currPart, start, n, input) { // If 'start' has reached len if (start >= n) { allPart.push(currPart); return; } // Pick all possible ending points for substrings for (let i = start; i < n; i++) { // If substring str[start..i] is palindrome if (isPalindrome(input, start, i)) { // Add the substring to result currPart.push(input.substring(start, i + 1 - start)); // Recur for remaining substring allPalPartitonsUtil(allPart, currPart, i + 1, n, input); // Remove substring str[start..i] from current // partition currPart.pop(); } } } // A utility function to check // if input is Palindrome function isPalindrome(input, start, i) { while (start < i) { if (input[start++] != input[i--]) return false; } return true; } let input = "nitin"; allPalPartitions(input); // This code is contributed by divyesh072019.</script>
n i t i n
n iti n
nitin
Time complexity: O(n*2n)
Auxiliary Space: O(n2)
Approach 2: Expand around every palindrome
The idea is to split the string into all palindromes of length 1 that is convert the string to a list of its characters (but as string data type) and then expand the smaller palindromes to bigger palindromes by checking if its left and right (reversed) are equal or not if they are equal then merge them and solve for new list recursively. Also if two adjacent strings of this list are equal (when one of them is reversed), merging them would also give a palindrome so merge them and solve recursively.
Python3
class GFG: def solve(self, arr): self.res.add(tuple(arr)) # add current partitioning to result if len(arr)<=1: # Base case when there is nothing to merge return for i in range(1,len(arr)): if arr[i-1]==arr[i][::-1]: # When two adjacent such that one is reverse of another brr = arr[:i-1] + [arr[i-1]+arr[i]] + arr[i+1:] self.solve(brr) if i+1<len(arr) and arr[i-1]==arr[i+1][::-1]: # All are individually palindrome, # when one left and one right of i are reverse of each other then we can merge # the three of them to form a new partitioning way brr = arr[:i-1] + [arr[i-1]+arr[i]+arr[i+1]] + arr[i+2:] self.solve(brr) def getGray(self, S): self.res = set() # result is a set of tuples to avoid same partition multiple times self.solve(list(S)) # Call recursive function to solve for S return sorted(list(self.res))# Driver Codeif __name__ == '__main__': ob = GFG() allPart = ob.getGray("geeks") for i in range(len(allPart)): for j in range(len(allPart[i])): print(allPart[i][j], end = " ") print()# This code is contributed by Gautam Wadhwani
g e e k s
g ee k s
Time complexity: O(n*2n)
Auxiliary Space: O(n2)
This article is contributed by Ekta Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ShashwatSingh
sanjeev2552
princiraj1992
gautamsw5
simranarora5sos
divyesh072019
prasanna1995
simmytarika5
surbhikumaridav
palindrome
Recursion
Strings
Strings
Recursion
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 May, 2022"
},
{
"code": null,
"e": 136,
"s": 52,
"text": "Given a string, find all possible palindromic partitions of given string.Example: "
},
{
"code": null,
"e": 582,
"s": 138,
"text": "Note that this problem is different from Palindrome Partitioning Problem, there the task was to find the partitioning with minimum cuts in input string. Here we need to print all possible partitions.The idea is to go through every substring starting from first character, check if it is palindrome. If yes, then add the substring to solution and recur for remaining part. Below is complete algorithm.Below is the implementation of above idea. "
},
{
"code": null,
"e": 586,
"s": 582,
"text": "C++"
},
{
"code": null,
"e": 591,
"s": 586,
"text": "Java"
},
{
"code": null,
"e": 599,
"s": 591,
"text": "Python3"
},
{
"code": null,
"e": 602,
"s": 599,
"text": "C#"
},
{
"code": null,
"e": 613,
"s": 602,
"text": "Javascript"
},
{
"code": "// C++ program to print all palindromic partitions of a given string#include<bits/stdc++.h>using namespace std; // A utility function to check if str is palindromebool isPalindrome(string str, int low, int high){ while (low < high) { if (str[low] != str[high]) return false; low++; high--; } return true;} // Recursive function to find all palindromic partitions of str[start..n-1]// allPart --> A vector of vector of strings. Every vector inside it stores// a partition// currPart --> A vector of strings to store current partitionvoid allPalPartUtil(vector<vector<string> >&allPart, vector<string> &currPart, int start, int n, string str){ // If 'start' has reached len if (start >= n) { allPart.push_back(currPart); return; } // Pick all possible ending points for substrings for (int i=start; i<n; i++) { // If substring str[start..i] is palindrome if (isPalindrome(str, start, i)) { // Add the substring to result currPart.push_back(str.substr(start, i-start+1)); // Recur for remaining substring allPalPartUtil(allPart, currPart, i+1, n, str); // Remove substring str[start..i] from current // partition currPart.pop_back(); } }} // Function to print all possible palindromic partitions of// str. It mainly creates vectors and calls allPalPartUtil()void allPalPartitions(string str){ int n = str.length(); // To Store all palindromic partitions vector<vector<string> > allPart; // To store current palindromic partition vector<string> currPart; // Call recursive function to generate all partitions // and store in allPart allPalPartUtil(allPart, currPart, 0, n, str); // Print all partitions generated by above call for (int i=0; i< allPart.size(); i++ ) { for (int j=0; j<allPart[i].size(); j++) cout << allPart[i][j] << \" \"; cout << \"\\n\"; }} // Driver programint main(){ string str = \"nitin\"; allPalPartitions(str); return 0;}",
"e": 2755,
"s": 613,
"text": null
},
{
"code": "// Java program to print all palindromic// partitions of a given stringimport java.util.ArrayList;import java.util.Deque;import java.util.LinkedList; public class PrintAllPalindrome{ // Driver program public static void main(String[] args) { String input = \"nitin\"; System.out.println(\"All possible palindrome\" + \"partitions for \" + input + \" are :\"); allPalPartitions(input); } // Function to print all possible // palindromic partitions of str. // It mainly creates vectors and // calls allPalPartUtil() private static void allPalPartitions(String input) { int n = input.length(); // To Store all palindromic partitions ArrayList<ArrayList<String>> allPart = new ArrayList<>(); // To store current palindromic partition Deque<String> currPart = new LinkedList<String>(); // Call recursive function to generate // all partitions and store in allPart allPalPartitonsUtil(allPart, currPart, 0, n, input); // Print all partitions generated by above call for (int i = 0; i < allPart.size(); i++) { for (int j = 0; j < allPart.get(i).size(); j++) { System.out.print(allPart.get(i).get(j) + \" \"); } System.out.println(); } } // Recursive function to find all palindromic // partitions of input[start..n-1] allPart --> A // ArrayList of Deque of strings. Every Deque // inside it stores a partition currPart --> A // Deque of strings to store current partition private static void allPalPartitonsUtil(ArrayList<ArrayList<String>> allPart, Deque<String> currPart, int start, int n, String input) { // If 'start' has reached len if (start >= n) { allPart.add(new ArrayList<>(currPart)); return; } // Pick all possible ending points for substrings for (int i = start; i < n; i++) { // If substring str[start..i] is palindrome if (isPalindrome(input, start, i)) { // Add the substring to result currPart.addLast(input.substring(start, i + 1)); // Recur for remaining substring allPalPartitonsUtil(allPart, currPart, i + 1, n, input); // Remove substring str[start..i] from current // partition currPart.removeLast(); } } } // A utility function to check // if input is Palindrome private static boolean isPalindrome(String input, int start, int i) { while (start < i) { if (input.charAt(start++) != input.charAt(i--)) return false; } return true; }} // This code is contributed by Prerna Saini",
"e": 5699,
"s": 2755,
"text": null
},
{
"code": "# Python3 program to print all# palindromic partitions of a given string # A utility function to check if# str is palindromedef isPalindrome(string: str, low: int, high: int): while low < high: if string[low] != string[high]: return False low += 1 high -= 1 return True # Recursive function to find all# palindromic partitions of str[start..n-1]# allPart --> A vector of vector of strings.# Every vector inside it stores a partition# currPart --> A vector of strings to store current partitiondef allPalPartUtil(allPart: list, currPart: list, start: int, n: int, string: str): # If 'start' has reached len if start >= n: # In Python list are passed by reference # that is why it is needed to copy first # and then append x = currPart.copy() allPart.append(x) return # Pick all possible ending points for substrings for i in range(start, n): # If substring str[start..i] is palindrome if isPalindrome(string, start, i): # Add the substring to result currPart.append(string[start:i + 1]) # Recur for remaining substring allPalPartUtil(allPart, currPart, i + 1, n, string) # Remove substring str[start..i] # from current partition currPart.pop() # Function to print all possible# palindromic partitions of str.# It mainly creates vectors and# calls allPalPartUtil()def allPalPartitions(string: str): n = len(string) # To Store all palindromic partitions allPart = [] # To store current palindromic partition currPart = [] # Call recursive function to generate # all partitions and store in allPart allPalPartUtil(allPart, currPart, 0, n, string) # Print all partitions generated by above call for i in range(len(allPart)): for j in range(len(allPart[i])): print(allPart[i][j], end = \" \") print() # Driver Codeif __name__ == \"__main__\": string = \"nitin\" allPalPartitions(string) # This code is contributed by# sanjeev2552",
"e": 7855,
"s": 5699,
"text": null
},
{
"code": "// C# program to print all palindromic// partitions of a given stringusing System;using System.Collections.Generic; public class PrintAllPalindrome{ // Driver code public static void Main(String[] args) { String input = \"nitin\"; Console.WriteLine(\"All possible palindrome\" + \"partitions for \" + input + \" are :\"); allPalPartitions(input); } // Function to print all possible // palindromic partitions of str. // It mainly creates vectors and // calls allPalPartUtil() private static void allPalPartitions(String input) { int n = input.Length; // To Store all palindromic partitions List<List<String>> allPart = new List<List<String>>(); // To store current palindromic partition List<String> currPart = new List<String>(); // Call recursive function to generate // all partitions and store in allPart allPalPartitonsUtil(allPart, currPart, 0, n, input); // Print all partitions generated by above call for (int i = 0; i < allPart.Count; i++) { for (int j = 0; j < allPart[i].Count; j++) { Console.Write(allPart[i][j] + \" \"); } Console.WriteLine(); } } // Recursive function to find all palindromic // partitions of input[start..n-1] allPart --> A // List of Deque of strings. Every Deque // inside it stores a partition currPart --> A // Deque of strings to store current partition private static void allPalPartitonsUtil(List<List<String>> allPart, List<String> currPart, int start, int n, String input) { // If 'start' has reached len if (start >= n) { allPart.Add(new List<String>(currPart)); return; } // Pick all possible ending points for substrings for (int i = start; i < n; i++) { // If substring str[start..i] is palindrome if (isPalindrome(input, start, i)) { // Add the substring to result currPart.Add(input.Substring(start, i + 1 - start)); // Recur for remaining substring allPalPartitonsUtil(allPart, currPart, i + 1, n, input); // Remove substring str[start..i] from current // partition currPart.RemoveAt(currPart.Count - 1); } } } // A utility function to check // if input is Palindrome private static bool isPalindrome(String input, int start, int i) { while (start < i) { if (input[start++] != input[i--]) return false; } return true; }} // This code is contributed by PrinciRaj1992",
"e": 10720,
"s": 7855,
"text": null
},
{
"code": "<script> // Javascript program to print all palindromic // partitions of a given string // Function to print all possible // palindromic partitions of str. // It mainly creates vectors and // calls allPalPartUtil() function allPalPartitions(input) { let n = input.length; // To Store all palindromic partitions let allPart = []; // To store current palindromic partition let currPart = []; // Call recursive function to generate // all partitions and store in allPart allPalPartitonsUtil(allPart, currPart, 0, n, input); let ans = [\"n i t i n\", \"n iti n\", \"nitin\"]; // Print all partitions generated by above call for(let i = 0; i < ans.length; i++) { document.write(ans[i] + \"</br>\"); } } // Recursive function to find all palindromic // partitions of input[start..n-1] allPart --> A // List of Deque of strings. Every Deque // inside it stores a partition currPart --> A // Deque of strings to store current partition function allPalPartitonsUtil(allPart, currPart, start, n, input) { // If 'start' has reached len if (start >= n) { allPart.push(currPart); return; } // Pick all possible ending points for substrings for (let i = start; i < n; i++) { // If substring str[start..i] is palindrome if (isPalindrome(input, start, i)) { // Add the substring to result currPart.push(input.substring(start, i + 1 - start)); // Recur for remaining substring allPalPartitonsUtil(allPart, currPart, i + 1, n, input); // Remove substring str[start..i] from current // partition currPart.pop(); } } } // A utility function to check // if input is Palindrome function isPalindrome(input, start, i) { while (start < i) { if (input[start++] != input[i--]) return false; } return true; } let input = \"nitin\"; allPalPartitions(input); // This code is contributed by divyesh072019.</script>",
"e": 13021,
"s": 10720,
"text": null
},
{
"code": null,
"e": 13048,
"s": 13021,
"text": "n i t i n \nn iti n \nnitin "
},
{
"code": null,
"e": 13073,
"s": 13048,
"text": "Time complexity: O(n*2n)"
},
{
"code": null,
"e": 13096,
"s": 13073,
"text": "Auxiliary Space: O(n2)"
},
{
"code": null,
"e": 13139,
"s": 13096,
"text": "Approach 2: Expand around every palindrome"
},
{
"code": null,
"e": 13642,
"s": 13139,
"text": "The idea is to split the string into all palindromes of length 1 that is convert the string to a list of its characters (but as string data type) and then expand the smaller palindromes to bigger palindromes by checking if its left and right (reversed) are equal or not if they are equal then merge them and solve for new list recursively. Also if two adjacent strings of this list are equal (when one of them is reversed), merging them would also give a palindrome so merge them and solve recursively."
},
{
"code": null,
"e": 13650,
"s": 13642,
"text": "Python3"
},
{
"code": "class GFG: def solve(self, arr): self.res.add(tuple(arr)) # add current partitioning to result if len(arr)<=1: # Base case when there is nothing to merge return for i in range(1,len(arr)): if arr[i-1]==arr[i][::-1]: # When two adjacent such that one is reverse of another brr = arr[:i-1] + [arr[i-1]+arr[i]] + arr[i+1:] self.solve(brr) if i+1<len(arr) and arr[i-1]==arr[i+1][::-1]: # All are individually palindrome, # when one left and one right of i are reverse of each other then we can merge # the three of them to form a new partitioning way brr = arr[:i-1] + [arr[i-1]+arr[i]+arr[i+1]] + arr[i+2:] self.solve(brr) def getGray(self, S): self.res = set() # result is a set of tuples to avoid same partition multiple times self.solve(list(S)) # Call recursive function to solve for S return sorted(list(self.res))# Driver Codeif __name__ == '__main__': ob = GFG() allPart = ob.getGray(\"geeks\") for i in range(len(allPart)): for j in range(len(allPart[i])): print(allPart[i][j], end = \" \") print()# This code is contributed by Gautam Wadhwani",
"e": 14899,
"s": 13650,
"text": null
},
{
"code": null,
"e": 14920,
"s": 14899,
"text": "g e e k s \ng ee k s "
},
{
"code": null,
"e": 14945,
"s": 14920,
"text": "Time complexity: O(n*2n)"
},
{
"code": null,
"e": 14968,
"s": 14945,
"text": "Auxiliary Space: O(n2)"
},
{
"code": null,
"e": 15135,
"s": 14968,
"text": "This article is contributed by Ekta Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 15151,
"s": 15137,
"text": "ShashwatSingh"
},
{
"code": null,
"e": 15163,
"s": 15151,
"text": "sanjeev2552"
},
{
"code": null,
"e": 15177,
"s": 15163,
"text": "princiraj1992"
},
{
"code": null,
"e": 15187,
"s": 15177,
"text": "gautamsw5"
},
{
"code": null,
"e": 15203,
"s": 15187,
"text": "simranarora5sos"
},
{
"code": null,
"e": 15217,
"s": 15203,
"text": "divyesh072019"
},
{
"code": null,
"e": 15230,
"s": 15217,
"text": "prasanna1995"
},
{
"code": null,
"e": 15243,
"s": 15230,
"text": "simmytarika5"
},
{
"code": null,
"e": 15259,
"s": 15243,
"text": "surbhikumaridav"
},
{
"code": null,
"e": 15270,
"s": 15259,
"text": "palindrome"
},
{
"code": null,
"e": 15280,
"s": 15270,
"text": "Recursion"
},
{
"code": null,
"e": 15288,
"s": 15280,
"text": "Strings"
},
{
"code": null,
"e": 15296,
"s": 15288,
"text": "Strings"
},
{
"code": null,
"e": 15306,
"s": 15296,
"text": "Recursion"
},
{
"code": null,
"e": 15317,
"s": 15306,
"text": "palindrome"
}
] |
JasperReports - Exporting Reports
|
We have seen in the previous chapter, how to print and view a JasperReport generated document. Here, we shall see how to transform or export these reports into other formats such as PDF, HTML, and XLS. Facade class net.sf.jasperreports.engine.JasperExportManager is provided to achieve this functionality. Exporting means transforming the JasperPrint object (.jrprint file) into different format.
The following code (JasperReportExport.java) demonstrates the exporting process of the JasperReport document. The JasperExportManager provides methods to export a report into PDF, HTML, and XML only. To export to the XLS format, we have used the class net.sf.jasperreports.engine.export.JRXlsExporter. This code generates following three files −
sample_report.pdf
sample_report.html
sample_report.xls
Let's write a report template. The contents of the JRXML file (C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml) are as below −
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
name = "jasper_report_template" language = "groovy" pageWidth = "595"
pageHeight = "842" columnWidth = "555" leftMargin = "20" rightMargin = "20"
topMargin = "20" bottomMargin = "20">
<queryString>
<![CDATA[]]>
</queryString>
<field name = "country" class = "java.lang.String">
<fieldDescription><![CDATA[country]]></fieldDescription>
</field>
<field name = "name" class = "java.lang.String">
<fieldDescription><![CDATA[name]]></fieldDescription>
</field>
<columnHeader>
<band height = "23">
<staticText>
<reportElement mode = "Opaque" x = "0" y = "3"
width = "535" height = "15" backcolor = "#70A9A9" />
<box>
<bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
</box>
<textElement />
<text><![CDATA[]]> </text>
</staticText>
<staticText>
<reportElement x = "414" y = "3" width = "121" height = "15" />
<textElement textAlignment = "Center" verticalAlignment = "Middle">
<font isBold = "true" />
</textElement>
<text><![CDATA[Country]]></text>
</staticText>
<staticText>
<reportElement x = "0" y = "3" width = "136" height = "15" />
<textElement textAlignment = "Center" verticalAlignment = "Middle">
<font isBold = "true" />
</textElement>
<text><![CDATA[Name]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height = "16">
<staticText>
<reportElement mode = "Opaque" x = "0" y = "0"
width = "535" height = "14" backcolor = "#E5ECF9" />
<box>
<bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
</box>
<textElement />
<text><![CDATA[]]> </text>
</staticText>
<textField>
<reportElement x = "414" y = "0" width = "121" height = "15" />
<textElement textAlignment = "Center" verticalAlignment = "Middle">
<font size = "9" />
</textElement>
<textFieldExpression class = "java.lang.String">
<![CDATA[$F{country}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x = "0" y = "0" width = "136" height = "15" />
<textElement textAlignment = "Center" verticalAlignment = "Middle" />
<textFieldExpression class = "java.lang.String">
<![CDATA[$F{name}]]>
</textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>
Next, contents of the POJO file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java are as given below −
package com.tutorialspoint;
public class DataBean {
private String name;
private String country;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java are as given below −
package com.tutorialspoint;
import java.util.ArrayList;
public class DataBeanList {
public ArrayList<DataBean> getDataBeanList() {
ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();
dataBeanList.add(produce("Manisha", "India"));
dataBeanList.add(produce("Dennis Ritchie", "USA"));
dataBeanList.add(produce("V.Anand", "India"));
dataBeanList.add(produce("Shrinath", "California"));
return dataBeanList;
}
/**
* This method returns a DataBean object,
* with name and country set in it.
*/
private DataBean produce(String name, String country) {
DataBean dataBean = new DataBean();
dataBean.setName(name);
dataBean.setCountry(country);
return dataBean;
}
}
Write a main class file JasperReportFill.java, which gets the java bean collection from the class (DataBeanList) and passes it to the JasperReports engine, to fill the report template. Save it to the directory C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint.
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRXlsExporter;
public class JasperReportFill {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
String sourceFileName = "c://tools/jasperreports-5.0.1/"
+ "test/jasper_report_template.jasper";
String printFileName = null;
DataBeanList DataBeanList = new DataBeanList();
ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();
JRBeanCollectionDataSource beanColDataSource =
new JRBeanCollectionDataSource(dataList);
Map parameters = new HashMap();
try {
printFileName = JasperFillManager.fillReportToFile(sourceFileName,
parameters, beanColDataSource);
if (printFileName != null) {
/**
* 1- export to PDF
*/
JasperExportManager.exportReportToPdfFile(printFileName,
"C://sample_report.pdf");
/**
* 2- export to HTML
*/
JasperExportManager.exportReportToHtmlFile(printFileName,
"C://sample_report.html");
/**
* 3- export to Excel sheet
*/
JRXlsExporter exporter = new JRXlsExporter();
exporter.setParameter(JRExporterParameter.INPUT_FILE_NAME,
printFileName);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,
"C://sample_report.xls");
exporter.exportReport();
}
} catch (JRException e) {
e.printStackTrace();
}
}
}
Here, we have included the logic to export the jasper print file to pdf, html and xls format.
Let's compile and execute above files using our regular ANT build process. The build.xml file is as given below −
<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "executereport" basedir = ".">
<import file = "baseBuild.xml"/>
<target name = "executereport" depends = "compile,compilereportdesing,run">
<echo message = "Im here"/>
</target>
<target name = "compilereportdesing" description = "Compiles the JXML file and
produces the .jasper file.">
<taskdef name = "jrc"
classname = "net.sf.jasperreports.ant.JRAntCompileTask">
<classpath refid = "classpath" />
</taskdef>
<jrc destdir = ".">
<src>
<fileset dir = ".">
<include name = "*.jrxml" />
</fileset>
</src>
<classpath refid = "classpath" />
</jrc>
</target>
</project>
Go to the command prompt and then go to the directory C:\tools\jasperreports-5.0.1\test, where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill. The output is as follows −
C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml
clean-sample:
[delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
[delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
[delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint
compile:
[mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
[javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28:
warning: 'includeantruntime' was not set, defaulting t
[javac] Compiling 4 source files to C:\tools\jasperreports-5.0.1\test\classes
compilereportdesing:
[jrc] Compiling 1 report design files.
[jrc] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
[jrc] log4j:WARN Please initialize the log4j system properly.
[jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
[jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.
run:
[echo] Runnin class : com.tutorialspoint.JasperReportFill
[java] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.extensions.ExtensionsEnvironment).
[java] log4j:WARN Please initialize the log4j system properly.
executereport:
[echo] Im here
BUILD SUCCESSFUL
Total time: 32 seconds
As the result of above execution, you will find three files sample_report.pdf, sample_report.html, sample_report.xls generated in the C:\ directory.
|
[
{
"code": null,
"e": 2785,
"s": 2388,
"text": "We have seen in the previous chapter, how to print and view a JasperReport generated document. Here, we shall see how to transform or export these reports into other formats such as PDF, HTML, and XLS. Facade class net.sf.jasperreports.engine.JasperExportManager is provided to achieve this functionality. Exporting means transforming the JasperPrint object (.jrprint file) into different format."
},
{
"code": null,
"e": 3131,
"s": 2785,
"text": "The following code (JasperReportExport.java) demonstrates the exporting process of the JasperReport document. The JasperExportManager provides methods to export a report into PDF, HTML, and XML only. To export to the XLS format, we have used the class net.sf.jasperreports.engine.export.JRXlsExporter. This code generates following three files −"
},
{
"code": null,
"e": 3149,
"s": 3131,
"text": "sample_report.pdf"
},
{
"code": null,
"e": 3168,
"s": 3149,
"text": "sample_report.html"
},
{
"code": null,
"e": 3186,
"s": 3168,
"text": "sample_report.xls"
},
{
"code": null,
"e": 3328,
"s": 3186,
"text": "Let's write a report template. The contents of the JRXML file (C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrxml) are as below −"
},
{
"code": null,
"e": 6718,
"s": 3328,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE jasperReport PUBLIC \"//JasperReports//DTD Report Design//EN\"\n \"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd\">\n\n<jasperReport xmlns = \"http://jasperreports.sourceforge.net/jasperreports\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://jasperreports.sourceforge.net/jasperreports\n http://jasperreports.sourceforge.net/xsd/jasperreport.xsd\"\n name = \"jasper_report_template\" language = \"groovy\" pageWidth = \"595\"\n pageHeight = \"842\" columnWidth = \"555\" leftMargin = \"20\" rightMargin = \"20\"\n topMargin = \"20\" bottomMargin = \"20\">\n\n <queryString>\n <![CDATA[]]>\n </queryString>\n \n <field name = \"country\" class = \"java.lang.String\">\n <fieldDescription><![CDATA[country]]></fieldDescription>\n </field>\n \n <field name = \"name\" class = \"java.lang.String\">\n <fieldDescription><![CDATA[name]]></fieldDescription>\n </field>\n \n <columnHeader>\n <band height = \"23\">\n \n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"3\" \n width = \"535\" height = \"15\" backcolor = \"#70A9A9\" />\n \n <box>\n <bottomPen lineWidth = \"1.0\" lineColor = \"#CCCCCC\" />\n </box>\n \n <textElement />\n <text><![CDATA[]]> </text>\n </staticText>\n \n <staticText>\n <reportElement x = \"414\" y = \"3\" width = \"121\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font isBold = \"true\" />\n </textElement>\n \n <text><![CDATA[Country]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"0\" y = \"3\" width = \"136\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font isBold = \"true\" />\n </textElement>\n \n <text><![CDATA[Name]]></text>\n </staticText>\n \n </band>\n </columnHeader>\n\n <detail>\n <band height = \"16\">\n \n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"0\" \n width = \"535\" height = \"14\" backcolor = \"#E5ECF9\" />\n \n <box>\n <bottomPen lineWidth = \"0.25\" lineColor = \"#CCCCCC\" />\n </box>\n \n <textElement />\n <text><![CDATA[]]> </text>\n </staticText>\n \n <textField>\n <reportElement x = \"414\" y = \"0\" width = \"121\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font size = \"9\" />\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{country}]]>\n </textFieldExpression>\n </textField>\n \n <textField>\n <reportElement x = \"0\" y = \"0\" width = \"136\" height = \"15\" />\n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\" />\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{name}]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </detail>\n\t\n</jasperReport>"
},
{
"code": null,
"e": 6842,
"s": 6718,
"text": "Next, contents of the POJO file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\DataBean.java are as given below −"
},
{
"code": null,
"e": 7210,
"s": 6842,
"text": "package com.tutorialspoint;\n\npublic class DataBean {\n private String name;\n private String country;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCountry() {\n return country;\n }\n\n public void setCountry(String country) {\n this.country = country;\n }\n}"
},
{
"code": null,
"e": 7332,
"s": 7210,
"text": "The contents of the file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\DataBeanList.java are as given below −"
},
{
"code": null,
"e": 8096,
"s": 7332,
"text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\n\npublic class DataBeanList {\n public ArrayList<DataBean> getDataBeanList() {\n ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();\n\n dataBeanList.add(produce(\"Manisha\", \"India\"));\n dataBeanList.add(produce(\"Dennis Ritchie\", \"USA\"));\n dataBeanList.add(produce(\"V.Anand\", \"India\"));\n dataBeanList.add(produce(\"Shrinath\", \"California\"));\n\n return dataBeanList;\n }\n\n /**\n * This method returns a DataBean object,\n * with name and country set in it.\n */\n private DataBean produce(String name, String country) {\n DataBean dataBean = new DataBean();\n dataBean.setName(name);\n dataBean.setCountry(country);\n \n return dataBean;\n }\n}"
},
{
"code": null,
"e": 8365,
"s": 8096,
"text": "Write a main class file JasperReportFill.java, which gets the java bean collection from the class (DataBeanList) and passes it to the JasperReports engine, to fill the report template. Save it to the directory C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint. "
},
{
"code": null,
"e": 10329,
"s": 8365,
"text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport net.sf.jasperreports.engine.JRException;\nimport net.sf.jasperreports.engine.JRExporterParameter;\nimport net.sf.jasperreports.engine.JasperExportManager;\nimport net.sf.jasperreports.engine.JasperFillManager;\nimport net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;\nimport net.sf.jasperreports.engine.export.JRXlsExporter;\n\npublic class JasperReportFill {\n @SuppressWarnings(\"unchecked\")\n public static void main(String[] args) {\n String sourceFileName = \"c://tools/jasperreports-5.0.1/\"\n + \"test/jasper_report_template.jasper\";\n String printFileName = null;\n DataBeanList DataBeanList = new DataBeanList();\n ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();\n JRBeanCollectionDataSource beanColDataSource =\n new JRBeanCollectionDataSource(dataList);\n\n Map parameters = new HashMap();\n try {\n printFileName = JasperFillManager.fillReportToFile(sourceFileName,\n parameters, beanColDataSource);\n if (printFileName != null) {\n /**\n * 1- export to PDF\n */\n JasperExportManager.exportReportToPdfFile(printFileName,\n \"C://sample_report.pdf\");\n\n /**\n * 2- export to HTML\n */\n JasperExportManager.exportReportToHtmlFile(printFileName,\n \"C://sample_report.html\");\n\n /**\n * 3- export to Excel sheet\n */\n JRXlsExporter exporter = new JRXlsExporter();\n\n exporter.setParameter(JRExporterParameter.INPUT_FILE_NAME,\n printFileName);\n exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,\n \"C://sample_report.xls\");\n\n exporter.exportReport();\n }\n } catch (JRException e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 10423,
"s": 10329,
"text": "Here, we have included the logic to export the jasper print file to pdf, html and xls format."
},
{
"code": null,
"e": 10537,
"s": 10423,
"text": "Let's compile and execute above files using our regular ANT build process. The build.xml file is as given below −"
},
{
"code": null,
"e": 11350,
"s": 10537,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project name = \"JasperReportTest\" default = \"executereport\" basedir = \".\">\n <import file = \"baseBuild.xml\"/>\n\n <target name = \"executereport\" depends = \"compile,compilereportdesing,run\">\n <echo message = \"Im here\"/>\n </target>\n \n <target name = \"compilereportdesing\" description = \"Compiles the JXML file and\n produces the .jasper file.\">\n \n <taskdef name = \"jrc\"\n classname = \"net.sf.jasperreports.ant.JRAntCompileTask\">\n <classpath refid = \"classpath\" />\n </taskdef>\n \n <jrc destdir = \".\">\n <src>\n <fileset dir = \".\">\n <include name = \"*.jrxml\" />\n </fileset>\n </src>\n <classpath refid = \"classpath\" />\n </jrc>\n \n </target>\n\t\n</project>"
},
{
"code": null,
"e": 11577,
"s": 11350,
"text": "Go to the command prompt and then go to the directory C:\\tools\\jasperreports-5.0.1\\test, where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill. The output is as follows −"
},
{
"code": null,
"e": 13014,
"s": 11577,
"text": "C:\\tools\\jasperreports-5.0.1\\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill\nBuildfile: C:\\tools\\jasperreports-5.0.1\\test\\build.xml\n\nclean-sample:\n [delete] Deleting directory C:\\tools\\jasperreports-5.0.1\\test\\classes\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jasper\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrprint\n\ncompile:\n [mkdir] Created dir: C:\\tools\\jasperreports-5.0.1\\test\\classes\n [javac] C:\\tools\\jasperreports-5.0.1\\test\\baseBuild.xml:28:\n warning: 'includeantruntime' was not set, defaulting t\n [javac] Compiling 4 source files to C:\\tools\\jasperreports-5.0.1\\test\\classes\n\ncompilereportdesing:\n [jrc] Compiling 1 report design files.\n [jrc] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).\n [jrc] log4j:WARN Please initialize the log4j system properly.\n [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.\n [jrc] File : C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrxml ... OK.\n\nrun:\n [echo] Runnin class : com.tutorialspoint.JasperReportFill\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n\nexecutereport:\n [echo] Im here\n\nBUILD SUCCESSFUL\nTotal time: 32 seconds\n"
}
] |
MATLAB | Converting a Grayscale Image to Binary Image using Thresholding
|
28 Oct, 2021
Thresholding is the simplest method of image segmentation and the most common way to convert a grayscale image to a binary image.In thresholding, we select a threshold value and then all the gray level value which is below the selected threshold value is classified as 0(black i.e background ) and all the gray level which is equal to or greater than the threshold value are classified as 1(white i.e foreground).
Here g(x, y) represents threshold image pixel at (x, y) and f(x, y) represents grayscale image pixel at (x, y).Algorithm:
Read target image into MATLAB environment.Convert it to a grayscale Image if read image is an RGB Image.Calculate a threshold value, TCreate a new Image Array (say ‘binary’) with the same number of rows and columns as original image array, containing all elements as 0 (zero).Assign 1 to binary(i, j), if gray level pixel at (i, j) is greater than or equal to the threshold value, T ; else assign 0 to binary(i, j). Do the same for all gray level pixels.
Read target image into MATLAB environment.
Convert it to a grayscale Image if read image is an RGB Image.
Calculate a threshold value, T
Create a new Image Array (say ‘binary’) with the same number of rows and columns as original image array, containing all elements as 0 (zero).
Assign 1 to binary(i, j), if gray level pixel at (i, j) is greater than or equal to the threshold value, T ; else assign 0 to binary(i, j). Do the same for all gray level pixels.
Below is the implementation of above algorithm :
MATLAB
% Following MATLAB function will take a grayscale% or an RGB image as input and will return a% binary image as output function [binary] = convert2binary(img) [x, y, z]=size(img); % if Read Image is an RGB Image then convert % it to a Gray Scale Image For an RGB image % the value of z will be 3 and for a Grayscale % Image the value of z will be 1 if z==3 img=rgb2gray(img); end % change the class of image % array from 'unit8' to 'double' img=double(img); % Calculate sum of all the gray level % pixel's value of the GrayScale Image sum=0; for i=1:x for j=1:y sum=sum+img(i, j); end end % Calculate Threshold value by dividing the % calculated sum by total number of pixels % total number of pixels = rows*columns (i.e x*y) threshold=sum/(x*y); % Create a image array having same number % of rows and column as Original image % with all elements as 0 (Zero). binary=zeros(x, y); % iterate over all the pixels of Grayscale % Image and Assign 1 to binary(i, j), if gray % level value is >= threshold value % else assign 0 to binary(i, j) . for i=1:x for j=1:y if img(i, j) >= threshold binary(i, j) = 1; else binary(i, j)=0; end end endend % driver function % Read the target Imageimg=imread('apple.png'); % Call convert2binary() function to convert% Image to binary using thresholdingbinary_image=convert2binary(img); % Display resultimshow(binary_image);
Input:
Output:
Advantages of thresholding:
This method is easy to understand and simple to implement.
It Converts a grayscale image to binary image.
Resultant binary image is easy to analyze.
Disadvantages of thresholding:
We only consider the intensity of the image for thresholding process, but not consider any relationship between the pixels. So, the pixels identified by thresholding process might not be continuous.
While thresholding process we can easily include the extraneous pixels that aren’t part of the desired region and can easily miss the pixels that are part of desired region.
It is also very sensitive to noise in the image. The result of thresholding process gets worse as noise gets worse.
ruhelaa48
saurabh1990aror
Image-Processing
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
ML | Linear Regression
Reinforcement learning
Docker - COPY Instruction
Supervised and Unsupervised learning
Decision Tree Introduction with example
Getting started with Machine Learning
How to Run a Python Script using Docker?
ML | Underfitting and Overfitting
ML | Monte Carlo Tree Search (MCTS)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Oct, 2021"
},
{
"code": null,
"e": 467,
"s": 52,
"text": "Thresholding is the simplest method of image segmentation and the most common way to convert a grayscale image to a binary image.In thresholding, we select a threshold value and then all the gray level value which is below the selected threshold value is classified as 0(black i.e background ) and all the gray level which is equal to or greater than the threshold value are classified as 1(white i.e foreground). "
},
{
"code": null,
"e": 591,
"s": 467,
"text": "Here g(x, y) represents threshold image pixel at (x, y) and f(x, y) represents grayscale image pixel at (x, y).Algorithm: "
},
{
"code": null,
"e": 1048,
"s": 591,
"text": "Read target image into MATLAB environment.Convert it to a grayscale Image if read image is an RGB Image.Calculate a threshold value, TCreate a new Image Array (say ‘binary’) with the same number of rows and columns as original image array, containing all elements as 0 (zero).Assign 1 to binary(i, j), if gray level pixel at (i, j) is greater than or equal to the threshold value, T ; else assign 0 to binary(i, j). Do the same for all gray level pixels. "
},
{
"code": null,
"e": 1091,
"s": 1048,
"text": "Read target image into MATLAB environment."
},
{
"code": null,
"e": 1154,
"s": 1091,
"text": "Convert it to a grayscale Image if read image is an RGB Image."
},
{
"code": null,
"e": 1185,
"s": 1154,
"text": "Calculate a threshold value, T"
},
{
"code": null,
"e": 1328,
"s": 1185,
"text": "Create a new Image Array (say ‘binary’) with the same number of rows and columns as original image array, containing all elements as 0 (zero)."
},
{
"code": null,
"e": 1509,
"s": 1328,
"text": "Assign 1 to binary(i, j), if gray level pixel at (i, j) is greater than or equal to the threshold value, T ; else assign 0 to binary(i, j). Do the same for all gray level pixels. "
},
{
"code": null,
"e": 1560,
"s": 1509,
"text": "Below is the implementation of above algorithm : "
},
{
"code": null,
"e": 1567,
"s": 1560,
"text": "MATLAB"
},
{
"code": "% Following MATLAB function will take a grayscale% or an RGB image as input and will return a% binary image as output function [binary] = convert2binary(img) [x, y, z]=size(img); % if Read Image is an RGB Image then convert % it to a Gray Scale Image For an RGB image % the value of z will be 3 and for a Grayscale % Image the value of z will be 1 if z==3 img=rgb2gray(img); end % change the class of image % array from 'unit8' to 'double' img=double(img); % Calculate sum of all the gray level % pixel's value of the GrayScale Image sum=0; for i=1:x for j=1:y sum=sum+img(i, j); end end % Calculate Threshold value by dividing the % calculated sum by total number of pixels % total number of pixels = rows*columns (i.e x*y) threshold=sum/(x*y); % Create a image array having same number % of rows and column as Original image % with all elements as 0 (Zero). binary=zeros(x, y); % iterate over all the pixels of Grayscale % Image and Assign 1 to binary(i, j), if gray % level value is >= threshold value % else assign 0 to binary(i, j) . for i=1:x for j=1:y if img(i, j) >= threshold binary(i, j) = 1; else binary(i, j)=0; end end endend % driver function % Read the target Imageimg=imread('apple.png'); % Call convert2binary() function to convert% Image to binary using thresholdingbinary_image=convert2binary(img); % Display resultimshow(binary_image);",
"e": 3129,
"s": 1567,
"text": null
},
{
"code": null,
"e": 3138,
"s": 3129,
"text": "Input: "
},
{
"code": null,
"e": 3148,
"s": 3138,
"text": "Output: "
},
{
"code": null,
"e": 3178,
"s": 3148,
"text": "Advantages of thresholding: "
},
{
"code": null,
"e": 3237,
"s": 3178,
"text": "This method is easy to understand and simple to implement."
},
{
"code": null,
"e": 3284,
"s": 3237,
"text": "It Converts a grayscale image to binary image."
},
{
"code": null,
"e": 3327,
"s": 3284,
"text": "Resultant binary image is easy to analyze."
},
{
"code": null,
"e": 3360,
"s": 3327,
"text": "Disadvantages of thresholding: "
},
{
"code": null,
"e": 3559,
"s": 3360,
"text": "We only consider the intensity of the image for thresholding process, but not consider any relationship between the pixels. So, the pixels identified by thresholding process might not be continuous."
},
{
"code": null,
"e": 3733,
"s": 3559,
"text": "While thresholding process we can easily include the extraneous pixels that aren’t part of the desired region and can easily miss the pixels that are part of desired region."
},
{
"code": null,
"e": 3849,
"s": 3733,
"text": "It is also very sensitive to noise in the image. The result of thresholding process gets worse as noise gets worse."
},
{
"code": null,
"e": 3861,
"s": 3851,
"text": "ruhelaa48"
},
{
"code": null,
"e": 3877,
"s": 3861,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 3894,
"s": 3877,
"text": "Image-Processing"
},
{
"code": null,
"e": 3901,
"s": 3894,
"text": "MATLAB"
},
{
"code": null,
"e": 3927,
"s": 3901,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 4025,
"s": 3927,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4048,
"s": 4025,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 4071,
"s": 4048,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 4094,
"s": 4071,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 4120,
"s": 4094,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 4157,
"s": 4120,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 4197,
"s": 4157,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 4235,
"s": 4197,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 4276,
"s": 4235,
"text": "How to Run a Python Script using Docker?"
},
{
"code": null,
"e": 4310,
"s": 4276,
"text": "ML | Underfitting and Overfitting"
}
] |
How to make calculator using kivy | Python
|
19 Oct, 2021
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.
???????? Kivy Tutorial – Learn Kivy with Examples.
In this article, we will learn how to make a simple calculator using Kivy.
Prerequisites:1) Basic knowledge of Mathematics 2) Python 3) Kivy 4) Widgets and code understanding of kivy
Basic approach to make A calculator:
1) import kivy
2) import kivyApp
3) import Gridlayout
4) import config(to configure/adjust the window size)
5) Set minimum version(optional)
6) Create Layout class :
define Calculator function in it
: In this i am using try-catch because if any arithmetic
exception occur it will through the error
7) create App class
8) create .kv file (name same as the app class):
1) create buttons
2) Add the style to the buttons
3) Add functionalities of the button
9) return Layout/widget/Class(according to requirement)
10) Run an instance of the class
Implementation of the Approach: main.py
Python3
# Program to create a calculator # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # for making multiple bttons to arranging# them we are using thisfrom kivy.uix.gridlayout import GridLayout # for the size of windowfrom kivy.config import Config # Setting size to resizableConfig.set('graphics', 'resizable', 1)## Config.set('graphics', 'width', '400')## Config.set('graphics', 'height', '400') # Creating Layout classclass CalcGridLayout(GridLayout): # Function called when equals is pressed def calculate(self, calculation): if calculation: try: # Solve formula and display it in entry # which is pointed at by display self.display.text = str(eval(calculation)) except Exception: self.display.text = "Error" # Creating App classclass CalculatorApp(App): def build(self): return CalcGridLayout() # creating object and running itcalcApp = CalculatorApp()calcApp.run()
calculator.kv
Python3
# Custom button<CustButton@Button>: font_size: 32 # Define id so I can refer to the CalcGridLayout# class functions# Display points to the entry widget<CalcGridLayout>: id: calculator display: entry rows: 6 padding: 10 spacing: 10 # Where input is displayed BoxLayout: TextInput: id: entry font_size: 32 multiline: False # When buttons are pressed update the entry BoxLayout: spacing: 10 CustButton: text: "7" on_press: entry.text += self.text CustButton: text: "8" on_press: entry.text += self.text CustButton: text: "9" on_press: entry.text += self.text CustButton: text: "+" on_press: entry.text += self.text BoxLayout: spacing: 10 CustButton: text: "4" on_press: entry.text += self.text CustButton: text: "5" on_press: entry.text += self.text CustButton: text: "6" on_press: entry.text += self.text CustButton: text: "-" on_press: entry.text += self.text BoxLayout: spacing: 10 CustButton: text: "1" on_press: entry.text += self.text CustButton: text: "2" on_press: entry.text += self.text CustButton: text: "3" on_press: entry.text += self.text CustButton: text: "*" on_press: entry.text += self.text # When equals is pressed pass text in the entry # to the calculate function BoxLayout: spacing: 10 CustButton: text: "AC" on_press: entry.text = "" CustButton: text: "0" on_press: entry.text += self.text CustButton: text: "=" on_press: calculator.calculate(entry.text) CustButton: text: "/" on_press: entry.text += self.text BoxLayout: CustButton: font_size: 20 text: "Scientific calculator" on_press: entry.text = ""
Output:
saurabh1990aror
gabaa406
Python-gui
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 291,
"s": 54,
"text": "Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. "
},
{
"code": null,
"e": 342,
"s": 291,
"text": "???????? Kivy Tutorial – Learn Kivy with Examples."
},
{
"code": null,
"e": 418,
"s": 342,
"text": "In this article, we will learn how to make a simple calculator using Kivy. "
},
{
"code": null,
"e": 526,
"s": 418,
"text": "Prerequisites:1) Basic knowledge of Mathematics 2) Python 3) Kivy 4) Widgets and code understanding of kivy"
},
{
"code": null,
"e": 1165,
"s": 528,
"text": "Basic approach to make A calculator:\n\n1) import kivy\n2) import kivyApp\n3) import Gridlayout\n4) import config(to configure/adjust the window size)\n5) Set minimum version(optional)\n6) Create Layout class :\n define Calculator function in it\n : In this i am using try-catch because if any arithmetic \n exception occur it will through the error \n\n7) create App class\n8) create .kv file (name same as the app class):\n 1) create buttons\n 2) Add the style to the buttons\n 3) Add functionalities of the button \n9) return Layout/widget/Class(according to requirement)\n10) Run an instance of the class"
},
{
"code": null,
"e": 1206,
"s": 1165,
"text": "Implementation of the Approach: main.py "
},
{
"code": null,
"e": 1214,
"s": 1206,
"text": "Python3"
},
{
"code": "# Program to create a calculator # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # for making multiple bttons to arranging# them we are using thisfrom kivy.uix.gridlayout import GridLayout # for the size of windowfrom kivy.config import Config # Setting size to resizableConfig.set('graphics', 'resizable', 1)## Config.set('graphics', 'width', '400')## Config.set('graphics', 'height', '400') # Creating Layout classclass CalcGridLayout(GridLayout): # Function called when equals is pressed def calculate(self, calculation): if calculation: try: # Solve formula and display it in entry # which is pointed at by display self.display.text = str(eval(calculation)) except Exception: self.display.text = \"Error\" # Creating App classclass CalculatorApp(App): def build(self): return CalcGridLayout() # creating object and running itcalcApp = CalculatorApp()calcApp.run()",
"e": 2491,
"s": 1214,
"text": null
},
{
"code": null,
"e": 2508,
"s": 2491,
"text": " calculator.kv "
},
{
"code": null,
"e": 2516,
"s": 2508,
"text": "Python3"
},
{
"code": "# Custom button<CustButton@Button>: font_size: 32 # Define id so I can refer to the CalcGridLayout# class functions# Display points to the entry widget<CalcGridLayout>: id: calculator display: entry rows: 6 padding: 10 spacing: 10 # Where input is displayed BoxLayout: TextInput: id: entry font_size: 32 multiline: False # When buttons are pressed update the entry BoxLayout: spacing: 10 CustButton: text: \"7\" on_press: entry.text += self.text CustButton: text: \"8\" on_press: entry.text += self.text CustButton: text: \"9\" on_press: entry.text += self.text CustButton: text: \"+\" on_press: entry.text += self.text BoxLayout: spacing: 10 CustButton: text: \"4\" on_press: entry.text += self.text CustButton: text: \"5\" on_press: entry.text += self.text CustButton: text: \"6\" on_press: entry.text += self.text CustButton: text: \"-\" on_press: entry.text += self.text BoxLayout: spacing: 10 CustButton: text: \"1\" on_press: entry.text += self.text CustButton: text: \"2\" on_press: entry.text += self.text CustButton: text: \"3\" on_press: entry.text += self.text CustButton: text: \"*\" on_press: entry.text += self.text # When equals is pressed pass text in the entry # to the calculate function BoxLayout: spacing: 10 CustButton: text: \"AC\" on_press: entry.text = \"\" CustButton: text: \"0\" on_press: entry.text += self.text CustButton: text: \"=\" on_press: calculator.calculate(entry.text) CustButton: text: \"/\" on_press: entry.text += self.text BoxLayout: CustButton: font_size: 20 text: \"Scientific calculator\" on_press: entry.text = \"\" ",
"e": 4684,
"s": 2516,
"text": null
},
{
"code": null,
"e": 4694,
"s": 4684,
"text": "Output: "
},
{
"code": null,
"e": 4712,
"s": 4696,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 4721,
"s": 4712,
"text": "gabaa406"
},
{
"code": null,
"e": 4732,
"s": 4721,
"text": "Python-gui"
},
{
"code": null,
"e": 4744,
"s": 4732,
"text": "Python-kivy"
},
{
"code": null,
"e": 4751,
"s": 4744,
"text": "Python"
},
{
"code": null,
"e": 4849,
"s": 4751,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4867,
"s": 4849,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4909,
"s": 4867,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4931,
"s": 4909,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4957,
"s": 4931,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4989,
"s": 4957,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5018,
"s": 4989,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 5045,
"s": 5018,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5081,
"s": 5045,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 5112,
"s": 5081,
"text": "Python | os.path.join() method"
}
] |
POSIX Threads in OS
|
16 Jul, 2021
POSIX Threads in OS :The POSIX thread libraries are a C/C++ thread API based on standards. It enables the creation of a new concurrent process flow. It works well on multi-processor or multi-core systems, where the process flow may be scheduled to execute on another processor, increasing speed through parallel or distributed processing. Because the system does not create a new system, virtual memory space and environment for the process, threads needless overhead than “forking” or creating a new process. While multiprocessor systems are the most effective, benefits can also be obtained on uniprocessor systems that leverage delay in I/O and other system processes that may impede process execution.
To utilise the PThread interfaces, we must include the header pthread.h at the start of the CPP script.
#include <pthread.h>
PThreads is a highly concrete multithreading system that is the UNIX system’s default standard. PThreads is an abbreviation for POSIX threads, and POSIX is an abbreviation for Portable Operating System Interface, which is a type of interface that the operating system must implement. PThreads in POSIX outline the threading APIs that the operating system must provide.
Why is Pthreads used?
The fundamental purpose for adopting Pthreads is to improve programme performance.
When compared to the expense of starting and administering a process, a thread requires far less operating system overhead. Thread management takes fewer system resources than process management.
A process’s threads all share the same address space. Inter-thread communication is more efficient and, in many circumstances, more user-friendly than inter-process communication.
Threaded applications provide possible performance increases and practical advantages over non-threaded programmes in a variety of ways.
Multi-threaded programmes will run on a single-processor system but will automatically make use of a multiprocessor machine without the need for recompilation.
The most significant reason for employing Pthreads in a multiprocessor system is to take advantage of possible parallelism. This will be the major emphasis of the rest of this lesson.
In order for a programme to use Pthreads, it must be divided into discrete, independent tasks that may run concurrently.
The new thread is made runnable, and it will begin performing the start routine using the arg argument as the argument. The arg parameter is a void pointer that can point to any type of data. Casting this pointer into a scalar data type (such as int) is not advised since the casts may not be portable.
Let’s have a look at a C example of a better implementation approach :
C
#include <stdio.h>#include <stdlib.h>#include <pGeeksforGeeks.h> void *print_message_function( void *ptr ); main(){ pGeeksforGeeks_t GeeksforGeeks1, GeeksforGeeks2; char *message1 = "GeeksforGeeks 1"; char *message2 = "GeeksforGeeks 2"; int geeky1, geeky2; geeky1 = pGeeksforGeeks_create( &GeeksforGeeks1, NULL, print_message_function, (void*) message1); geeky2 = pGeeksforGeeks_create( &GeeksforGeeks2, NULL, print_message_function, (void*) message2); pGeeksforGeeks_join( GeeksforGeeks1, NULL); pGeeksforGeeks_join( GeeksforGeeks2, NULL); printf("GeeksforGeeks 1 returns: %d\n",geeky1); printf("GeeksforGeeks 2 returns: %d\n",geeky2); exit(0);} void *print_message_function( void *ptr ){ char *message; message = (char *) ptr; printf("%s \n", message);}
This programme spawns five threads, each of which runs the perform work function, which publishes the thread’s unique number to standard output. If a programmer wanted the threads to interact with each other, he or she would have to create a global variable that was defined outside of the scope of any of the functions. The following command may be used to compile this programme with the gcc compiler.
gcc pthreads_demo.c -lpthread -o pthreads_demo
Because the pthreads standard is not supported natively on Windows, the Pthreads-w32 project aims to create a portable and open-source wrapper implementation. It may also be used to transfer Unix applications (that utilizes pthreads) to Windows with little to no changes to the platform. The latest version 2.8.0 is compatible with 64-bit Windows computers after some extra updates.
Winpthreads, a wrapper implementation of pthreads in the mingw-w64 project, seeks to use more native system calls than the Pthreads-w32 project.
saurabh1990aror
Picked
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Jul, 2021"
},
{
"code": null,
"e": 760,
"s": 54,
"text": "POSIX Threads in OS :The POSIX thread libraries are a C/C++ thread API based on standards. It enables the creation of a new concurrent process flow. It works well on multi-processor or multi-core systems, where the process flow may be scheduled to execute on another processor, increasing speed through parallel or distributed processing. Because the system does not create a new system, virtual memory space and environment for the process, threads needless overhead than “forking” or creating a new process. While multiprocessor systems are the most effective, benefits can also be obtained on uniprocessor systems that leverage delay in I/O and other system processes that may impede process execution."
},
{
"code": null,
"e": 864,
"s": 760,
"text": "To utilise the PThread interfaces, we must include the header pthread.h at the start of the CPP script."
},
{
"code": null,
"e": 885,
"s": 864,
"text": "#include <pthread.h>"
},
{
"code": null,
"e": 1254,
"s": 885,
"text": "PThreads is a highly concrete multithreading system that is the UNIX system’s default standard. PThreads is an abbreviation for POSIX threads, and POSIX is an abbreviation for Portable Operating System Interface, which is a type of interface that the operating system must implement. PThreads in POSIX outline the threading APIs that the operating system must provide."
},
{
"code": null,
"e": 1276,
"s": 1254,
"text": "Why is Pthreads used?"
},
{
"code": null,
"e": 1359,
"s": 1276,
"text": "The fundamental purpose for adopting Pthreads is to improve programme performance."
},
{
"code": null,
"e": 1555,
"s": 1359,
"text": "When compared to the expense of starting and administering a process, a thread requires far less operating system overhead. Thread management takes fewer system resources than process management."
},
{
"code": null,
"e": 1735,
"s": 1555,
"text": "A process’s threads all share the same address space. Inter-thread communication is more efficient and, in many circumstances, more user-friendly than inter-process communication."
},
{
"code": null,
"e": 1872,
"s": 1735,
"text": "Threaded applications provide possible performance increases and practical advantages over non-threaded programmes in a variety of ways."
},
{
"code": null,
"e": 2032,
"s": 1872,
"text": "Multi-threaded programmes will run on a single-processor system but will automatically make use of a multiprocessor machine without the need for recompilation."
},
{
"code": null,
"e": 2216,
"s": 2032,
"text": "The most significant reason for employing Pthreads in a multiprocessor system is to take advantage of possible parallelism. This will be the major emphasis of the rest of this lesson."
},
{
"code": null,
"e": 2337,
"s": 2216,
"text": "In order for a programme to use Pthreads, it must be divided into discrete, independent tasks that may run concurrently."
},
{
"code": null,
"e": 2640,
"s": 2337,
"text": "The new thread is made runnable, and it will begin performing the start routine using the arg argument as the argument. The arg parameter is a void pointer that can point to any type of data. Casting this pointer into a scalar data type (such as int) is not advised since the casts may not be portable."
},
{
"code": null,
"e": 2711,
"s": 2640,
"text": "Let’s have a look at a C example of a better implementation approach :"
},
{
"code": null,
"e": 2713,
"s": 2711,
"text": "C"
},
{
"code": "#include <stdio.h>#include <stdlib.h>#include <pGeeksforGeeks.h> void *print_message_function( void *ptr ); main(){ pGeeksforGeeks_t GeeksforGeeks1, GeeksforGeeks2; char *message1 = \"GeeksforGeeks 1\"; char *message2 = \"GeeksforGeeks 2\"; int geeky1, geeky2; geeky1 = pGeeksforGeeks_create( &GeeksforGeeks1, NULL, print_message_function, (void*) message1); geeky2 = pGeeksforGeeks_create( &GeeksforGeeks2, NULL, print_message_function, (void*) message2); pGeeksforGeeks_join( GeeksforGeeks1, NULL); pGeeksforGeeks_join( GeeksforGeeks2, NULL); printf(\"GeeksforGeeks 1 returns: %d\\n\",geeky1); printf(\"GeeksforGeeks 2 returns: %d\\n\",geeky2); exit(0);} void *print_message_function( void *ptr ){ char *message; message = (char *) ptr; printf(\"%s \\n\", message);}",
"e": 3529,
"s": 2713,
"text": null
},
{
"code": null,
"e": 3933,
"s": 3529,
"text": "This programme spawns five threads, each of which runs the perform work function, which publishes the thread’s unique number to standard output. If a programmer wanted the threads to interact with each other, he or she would have to create a global variable that was defined outside of the scope of any of the functions. The following command may be used to compile this programme with the gcc compiler."
},
{
"code": null,
"e": 3980,
"s": 3933,
"text": "gcc pthreads_demo.c -lpthread -o pthreads_demo"
},
{
"code": null,
"e": 4363,
"s": 3980,
"text": "Because the pthreads standard is not supported natively on Windows, the Pthreads-w32 project aims to create a portable and open-source wrapper implementation. It may also be used to transfer Unix applications (that utilizes pthreads) to Windows with little to no changes to the platform. The latest version 2.8.0 is compatible with 64-bit Windows computers after some extra updates."
},
{
"code": null,
"e": 4508,
"s": 4363,
"text": "Winpthreads, a wrapper implementation of pthreads in the mingw-w64 project, seeks to use more native system calls than the Pthreads-w32 project."
},
{
"code": null,
"e": 4524,
"s": 4508,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 4531,
"s": 4524,
"text": "Picked"
},
{
"code": null,
"e": 4549,
"s": 4531,
"text": "Operating Systems"
},
{
"code": null,
"e": 4567,
"s": 4549,
"text": "Operating Systems"
}
] |
Time Complexity Analysis | Tower Of Hanoi (Recursion)
|
27 Jan, 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: 1) Only one disk can be moved at a time. 2) 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. 3) No disk may be placed on top of a smaller disk.
Pseudo Code
TOH(n, x, y, z)
{
if (n >= 1)
{
// put (n-1) disk to z by using y
TOH((n-1), x, z, y)
// move larger disk to right place
move:x-->y
// put (n-1) disk to right place
TOH((n-1), z, y, x)
}
}
Analysis of Recursion
Recursive Equation : ——-equation-1
Solving it by Backsubstitution : ———–equation-2 ———–equation-3
Put the value of T(n-2) in the equation–2 with help of equation-3 ——equation-4
Put the value of T(n-1) in equation-1 with help of equation-4
After Generalization :
Base condition T(1) =1 n – k = 1 k = n-1put, k = n-1
It is a GP series, and the sum is
, or you can say which is exponential
for 5 disks i.e. n=5 It will take 2^5-1=31 moves.
vedantmehta
aswini123p
Analysis
Recursion
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Difference between Deterministic and Non-deterministic Algorithms
What is algorithm and why analysis of it is important?
Time-Space Trade-Off in Algorithms
Complexity analysis of various operations of Binary Min Heap
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 512,
"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: 1) Only one disk can be moved at a time. 2) 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. 3) No disk may be placed on top of a smaller disk. "
},
{
"code": null,
"e": 526,
"s": 512,
"text": "Pseudo Code "
},
{
"code": null,
"e": 773,
"s": 526,
"text": "TOH(n, x, y, z)\n{\n if (n >= 1)\n {\n // put (n-1) disk to z by using y\n TOH((n-1), x, z, y)\n \n // move larger disk to right place\n move:x-->y\n \n // put (n-1) disk to right place \n TOH((n-1), z, y, x)\n }\n}"
},
{
"code": null,
"e": 796,
"s": 773,
"text": "Analysis of Recursion "
},
{
"code": null,
"e": 832,
"s": 796,
"text": "Recursive Equation : ——-equation-1 "
},
{
"code": null,
"e": 896,
"s": 832,
"text": "Solving it by Backsubstitution : ———–equation-2 ———–equation-3 "
},
{
"code": null,
"e": 976,
"s": 896,
"text": "Put the value of T(n-2) in the equation–2 with help of equation-3 ——equation-4 "
},
{
"code": null,
"e": 1039,
"s": 976,
"text": "Put the value of T(n-1) in equation-1 with help of equation-4 "
},
{
"code": null,
"e": 1063,
"s": 1039,
"text": "After Generalization : "
},
{
"code": null,
"e": 1116,
"s": 1063,
"text": "Base condition T(1) =1 n – k = 1 k = n-1put, k = n-1"
},
{
"code": null,
"e": 1151,
"s": 1116,
"text": "It is a GP series, and the sum is "
},
{
"code": null,
"e": 1189,
"s": 1151,
"text": ", or you can say which is exponential"
},
{
"code": null,
"e": 1239,
"s": 1189,
"text": "for 5 disks i.e. n=5 It will take 2^5-1=31 moves."
},
{
"code": null,
"e": 1251,
"s": 1239,
"text": "vedantmehta"
},
{
"code": null,
"e": 1262,
"s": 1251,
"text": "aswini123p"
},
{
"code": null,
"e": 1271,
"s": 1262,
"text": "Analysis"
},
{
"code": null,
"e": 1281,
"s": 1271,
"text": "Recursion"
},
{
"code": null,
"e": 1291,
"s": 1281,
"text": "Recursion"
},
{
"code": null,
"e": 1389,
"s": 1291,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1456,
"s": 1389,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 1522,
"s": 1456,
"text": "Difference between Deterministic and Non-deterministic Algorithms"
},
{
"code": null,
"e": 1577,
"s": 1522,
"text": "What is algorithm and why analysis of it is important?"
},
{
"code": null,
"e": 1612,
"s": 1577,
"text": "Time-Space Trade-Off in Algorithms"
},
{
"code": null,
"e": 1673,
"s": 1612,
"text": "Complexity analysis of various operations of Binary Min Heap"
},
{
"code": null,
"e": 1733,
"s": 1673,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 1818,
"s": 1733,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 1828,
"s": 1818,
"text": "Recursion"
},
{
"code": null,
"e": 1855,
"s": 1828,
"text": "Program for Tower of Hanoi"
}
] |
Record-Based Data Model
|
24 Aug, 2020
Data Model is the model that organizes elements of the data and tell how they relate to one-another and with the properties of real-world entities. The basic purpose of the data model is to make sure that the data stored in the data model is understood fully.
Further, it has three types-
1. Physical Data Model,
2. Record-Based Data Model,
3. Object-Oriented Data Model
Physical Data Model is not used much nowadays. In this, we will study about the Record-Based Data Model in detail.
Record-Based Data Model :When the database is organized in some fixed format of records of several than the model is known as Record-Based Data Model. It has a fixed number of fields or attributes in each record type and each field is usually of a fixed length.
Further, it is classified into three types-
Hierarchical Data Model :In hierarchical type, the model data are represented by collection of records. In this, relationships among the data are represented by links. In this model, tree data structure is used.It was developed in 1960s by IBM, to manage large amount of data for complex manufacturing projects. The basic logic structure of hierarchical data model is upside-down “tree”.Advantages –Simplicity, Data Integrity, Data security, Efficiency, Easy availability of expertise.Disadvantages –Complexity, Inflexibility, Lack of Data Independence, Lack of querying facility, Data Manipulation Language, Lack Of standards.Network Data Model :In network type, the model data are represented by collection of records. In this, relationships among the data are represented by links. Graph data structures are used in this model. It permits a record to have more than one parent.For Example- Social Media sites like Facebook, Instagram etc.Advantages –Simplicity, Data Integrity, Data Independence, Database standards.Disadvantages –System Complexity, Lack of structural Independence.Relational Data Model :Relational Data Model uses tables to represent the data and the relationship among these data. Each table has multiple columns and each column is identified by a unique name. It is a low-level model.Advantages –Structural Independence, Simplicity, Ease of designing, Implementation, Ad-Hoc query capability.Disadvantages –Hardware Overheads, Ease of design can result in bad design.
Hierarchical Data Model :In hierarchical type, the model data are represented by collection of records. In this, relationships among the data are represented by links. In this model, tree data structure is used.It was developed in 1960s by IBM, to manage large amount of data for complex manufacturing projects. The basic logic structure of hierarchical data model is upside-down “tree”.Advantages –Simplicity, Data Integrity, Data security, Efficiency, Easy availability of expertise.Disadvantages –Complexity, Inflexibility, Lack of Data Independence, Lack of querying facility, Data Manipulation Language, Lack Of standards.
It was developed in 1960s by IBM, to manage large amount of data for complex manufacturing projects. The basic logic structure of hierarchical data model is upside-down “tree”.
Advantages –Simplicity, Data Integrity, Data security, Efficiency, Easy availability of expertise.
Disadvantages –Complexity, Inflexibility, Lack of Data Independence, Lack of querying facility, Data Manipulation Language, Lack Of standards.
Network Data Model :In network type, the model data are represented by collection of records. In this, relationships among the data are represented by links. Graph data structures are used in this model. It permits a record to have more than one parent.For Example- Social Media sites like Facebook, Instagram etc.Advantages –Simplicity, Data Integrity, Data Independence, Database standards.Disadvantages –System Complexity, Lack of structural Independence.
For Example- Social Media sites like Facebook, Instagram etc.
Advantages –Simplicity, Data Integrity, Data Independence, Database standards.
Disadvantages –System Complexity, Lack of structural Independence.
Relational Data Model :Relational Data Model uses tables to represent the data and the relationship among these data. Each table has multiple columns and each column is identified by a unique name. It is a low-level model.Advantages –Structural Independence, Simplicity, Ease of designing, Implementation, Ad-Hoc query capability.Disadvantages –Hardware Overheads, Ease of design can result in bad design.
Advantages –Structural Independence, Simplicity, Ease of designing, Implementation, Ad-Hoc query capability.
Disadvantages –Hardware Overheads, Ease of design can result in bad design.
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Aug, 2020"
},
{
"code": null,
"e": 313,
"s": 53,
"text": "Data Model is the model that organizes elements of the data and tell how they relate to one-another and with the properties of real-world entities. The basic purpose of the data model is to make sure that the data stored in the data model is understood fully."
},
{
"code": null,
"e": 342,
"s": 313,
"text": "Further, it has three types-"
},
{
"code": null,
"e": 426,
"s": 342,
"text": "1. Physical Data Model, \n2. Record-Based Data Model,\n3. Object-Oriented Data Model "
},
{
"code": null,
"e": 541,
"s": 426,
"text": "Physical Data Model is not used much nowadays. In this, we will study about the Record-Based Data Model in detail."
},
{
"code": null,
"e": 803,
"s": 541,
"text": "Record-Based Data Model :When the database is organized in some fixed format of records of several than the model is known as Record-Based Data Model. It has a fixed number of fields or attributes in each record type and each field is usually of a fixed length."
},
{
"code": null,
"e": 847,
"s": 803,
"text": "Further, it is classified into three types-"
},
{
"code": null,
"e": 2338,
"s": 847,
"text": "Hierarchical Data Model :In hierarchical type, the model data are represented by collection of records. In this, relationships among the data are represented by links. In this model, tree data structure is used.It was developed in 1960s by IBM, to manage large amount of data for complex manufacturing projects. The basic logic structure of hierarchical data model is upside-down “tree”.Advantages –Simplicity, Data Integrity, Data security, Efficiency, Easy availability of expertise.Disadvantages –Complexity, Inflexibility, Lack of Data Independence, Lack of querying facility, Data Manipulation Language, Lack Of standards.Network Data Model :In network type, the model data are represented by collection of records. In this, relationships among the data are represented by links. Graph data structures are used in this model. It permits a record to have more than one parent.For Example- Social Media sites like Facebook, Instagram etc.Advantages –Simplicity, Data Integrity, Data Independence, Database standards.Disadvantages –System Complexity, Lack of structural Independence.Relational Data Model :Relational Data Model uses tables to represent the data and the relationship among these data. Each table has multiple columns and each column is identified by a unique name. It is a low-level model.Advantages –Structural Independence, Simplicity, Ease of designing, Implementation, Ad-Hoc query capability.Disadvantages –Hardware Overheads, Ease of design can result in bad design."
},
{
"code": null,
"e": 2966,
"s": 2338,
"text": "Hierarchical Data Model :In hierarchical type, the model data are represented by collection of records. In this, relationships among the data are represented by links. In this model, tree data structure is used.It was developed in 1960s by IBM, to manage large amount of data for complex manufacturing projects. The basic logic structure of hierarchical data model is upside-down “tree”.Advantages –Simplicity, Data Integrity, Data security, Efficiency, Easy availability of expertise.Disadvantages –Complexity, Inflexibility, Lack of Data Independence, Lack of querying facility, Data Manipulation Language, Lack Of standards."
},
{
"code": null,
"e": 3143,
"s": 2966,
"text": "It was developed in 1960s by IBM, to manage large amount of data for complex manufacturing projects. The basic logic structure of hierarchical data model is upside-down “tree”."
},
{
"code": null,
"e": 3242,
"s": 3143,
"text": "Advantages –Simplicity, Data Integrity, Data security, Efficiency, Easy availability of expertise."
},
{
"code": null,
"e": 3385,
"s": 3242,
"text": "Disadvantages –Complexity, Inflexibility, Lack of Data Independence, Lack of querying facility, Data Manipulation Language, Lack Of standards."
},
{
"code": null,
"e": 3844,
"s": 3385,
"text": "Network Data Model :In network type, the model data are represented by collection of records. In this, relationships among the data are represented by links. Graph data structures are used in this model. It permits a record to have more than one parent.For Example- Social Media sites like Facebook, Instagram etc.Advantages –Simplicity, Data Integrity, Data Independence, Database standards.Disadvantages –System Complexity, Lack of structural Independence."
},
{
"code": null,
"e": 3906,
"s": 3844,
"text": "For Example- Social Media sites like Facebook, Instagram etc."
},
{
"code": null,
"e": 3985,
"s": 3906,
"text": "Advantages –Simplicity, Data Integrity, Data Independence, Database standards."
},
{
"code": null,
"e": 4052,
"s": 3985,
"text": "Disadvantages –System Complexity, Lack of structural Independence."
},
{
"code": null,
"e": 4458,
"s": 4052,
"text": "Relational Data Model :Relational Data Model uses tables to represent the data and the relationship among these data. Each table has multiple columns and each column is identified by a unique name. It is a low-level model.Advantages –Structural Independence, Simplicity, Ease of designing, Implementation, Ad-Hoc query capability.Disadvantages –Hardware Overheads, Ease of design can result in bad design."
},
{
"code": null,
"e": 4567,
"s": 4458,
"text": "Advantages –Structural Independence, Simplicity, Ease of designing, Implementation, Ad-Hoc query capability."
},
{
"code": null,
"e": 4643,
"s": 4567,
"text": "Disadvantages –Hardware Overheads, Ease of design can result in bad design."
},
{
"code": null,
"e": 4648,
"s": 4643,
"text": "DBMS"
},
{
"code": null,
"e": 4653,
"s": 4648,
"text": "DBMS"
}
] |
C | Macro & Preprocessor | Question 1 - GeeksforGeeks
|
12 Jan, 2013
#include <stdio.h>#define PRINT(i, limit) do \ { \ if (i++ < limit) \ { \ printf("GeeksQuiz\n"); \ continue; \ } \ }while(1) int main(){ PRINT(0, 3); return 0;}
How many times GeeksQuiz is printed in the above program?(A) 1(B) 3(C) 4(D) Compile-time errorAnswer: (D)Explanation: The PRINT macro gets expanded at the pre-processor time i.e. before the compilation time. After the macro expansion, the if expression becomes: if (0++ < 3). Since 0 is a constant figure and represents only r-value, applying increment operator gives compile-time error: lvalue required. lvalue means a memory location with some address.
C-Macro & Preprocessor
Macro & Preprocessor
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
Output of C programs | Set 64 (Pointers)
C | Structure & Union | Question 10
C | File Handling | Question 1
|
[
{
"code": null,
"e": 24232,
"s": 24204,
"text": "\n12 Jan, 2013"
},
{
"code": "#include <stdio.h>#define PRINT(i, limit) do \\ { \\ if (i++ < limit) \\ { \\ printf(\"GeeksQuiz\\n\"); \\ continue; \\ } \\ }while(1) int main(){ PRINT(0, 3); return 0;}",
"e": 24589,
"s": 24232,
"text": null
},
{
"code": null,
"e": 25044,
"s": 24589,
"text": "How many times GeeksQuiz is printed in the above program?(A) 1(B) 3(C) 4(D) Compile-time errorAnswer: (D)Explanation: The PRINT macro gets expanded at the pre-processor time i.e. before the compilation time. After the macro expansion, the if expression becomes: if (0++ < 3). Since 0 is a constant figure and represents only r-value, applying increment operator gives compile-time error: lvalue required. lvalue means a memory location with some address."
},
{
"code": null,
"e": 25067,
"s": 25044,
"text": "C-Macro & Preprocessor"
},
{
"code": null,
"e": 25088,
"s": 25067,
"text": "Macro & Preprocessor"
},
{
"code": null,
"e": 25099,
"s": 25088,
"text": "C Language"
},
{
"code": null,
"e": 25106,
"s": 25099,
"text": "C Quiz"
},
{
"code": null,
"e": 25204,
"s": 25106,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25242,
"s": 25204,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 25262,
"s": 25242,
"text": "Multithreading in C"
},
{
"code": null,
"e": 25288,
"s": 25262,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 25310,
"s": 25288,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 25351,
"s": 25310,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 25393,
"s": 25351,
"text": "Compiling a C program:- Behind the Scenes"
},
{
"code": null,
"e": 25436,
"s": 25393,
"text": "Operator Precedence and Associativity in C"
},
{
"code": null,
"e": 25477,
"s": 25436,
"text": "Output of C programs | Set 64 (Pointers)"
},
{
"code": null,
"e": 25513,
"s": 25477,
"text": "C | Structure & Union | Question 10"
}
] |
Do you Really Need A GPU For Deep Learning? | by Bharath K | Towards Data Science
|
I have always been a huge fan of gaming and a bit of a gaming nerd.
Since childhood, the only requirement I saw for graphics cards was for the purpose of gaming.
Luckily for me, after I started getting into artificial intelligence and data science, especially deep learning, I realized the true potential of graphics cards.
This was almost like a dream come true. It was like striking two bullseyes with one arrow because I could utilize the same single graphics card for gaming as well as study and research purposes.
Note: GPUs and graphics cards pretty much mean the same thing and will be used interchangeably throughout this article.
GPUs are optimized for training artificial intelligence and deep learning models as they can process multiple computations simultaneously. They have a large number of cores, which allows for the better computation of multiple parallel processes.
In this article, we will understand what exactly a GPU and CUDA is, then explore the benefits of graphics processing units as well as when you should consider buying it if you are on a budget constraint. Finally, we will discuss the alternatives.
Without further ado, let us get started with understanding these concepts.
A Graphics Processing Unit is a specialized, electronic circuit designed to rapidly manipulate and alter memory to accelerate the creation of images in a frame buffer intended for output to a display device.
GPUs are a key part of modern computing. GPU computing and high-performance networking are transforming computational science and AI. The advancements in GPUs contribute a tremendous factor to the growth of deep learning today.
NVIDIA provides something called the Compute Unified Device Architecture (CUDA), which is crucial for supporting the various deep learning applications.
CUDA is a parallel computing platform and application programming interface model created by Nvidia. It allows software developers and software engineers to use a CUDA-enabled graphics processing unit (GPU) for general-purpose processing — an approach termed GPGPU.
These CUDA cores are highly beneficial and evolutionary in the field of artificial intelligence. We will discuss this topic further in the next section.
As discussed earlier, the NVIDIA GPUs offer the support of CUDA cores.
The number of CUDA cores differs for each type of graphics card, but it is safe to assume that most usually have over at least 1000 of them.
When you are using a deep learning framework such as TensorFlow or Pytorch, you can utilize these CUDA cores for computing your deep learning algorithms significantly faster in comparison to the same performance with a CPU.
While CPUs can do only a handful of operations at once, GPUs can perform thousands of these operations at once. Just to mention a hypothetical example, a task requiring 2–3 hours to train on a CPU could potentially be completed in about 10 minutes with the help of a decent quality GPU.
GPUs are a dynamic resource for computer vision and supercomputing with deep learning and neural networks to perform complicated tasks, sometimes even beyond human imagination.
Also, there are lots of other applications for GPUs as well. GPUs find their uses in embedded systems, mobile phones, personal computers, workstations, and game consoles.
You could make the best possible use of these graphics cards for other tasks like gaming and playing AAA games (triple-A games are basically an informal classification used for video games produced and distributed by a mid-sized or major publisher, typically having higher development and marketing budgets.) or for other graphical software purposes that need the requirement of a GPU as well like animation and designs.
GPUs also have an enormous scope in the field of robotics enabling high-tech robots to perceive the environment with the integration of artificial intelligence into them.
They are also in high demand in the automotive industry for the applications of deep learning-based self-driving cars. Large investments are being made in the development of these cars to change the future.
Last but not least, these GPUs also find a variety of applications in the medical fields of healthcare and life sciences by utilizing the data for ideal image segmentation tasks and other medical applications.
Graphics cards are pretty expensive!
Especially when you are on a budget constraint, you probably will have a tough time deciding if you want to buy a graphics card or not. So, how can you come to a sensible conclusion regarding this question?
A personal suggestion that I would like to offer is to make sure you dig yourself deeper into the field of data science. Understand the concepts of machine learning and have a basic conceptual understanding of deep learning.
If you absolutely feel certain and confident that deep learning is something you are interested in and want to pursue this intriguing topic further, then feel free to go ahead and purchase one for yourself.
In case you are wondering if there are any alternative choices or free tools to test the subject before straight away diving in, then you are in luck because there are lots of these resources available.
Let us look into these alternatives and other options available.
If you want to test out deep learning or you have concluded that you have no use for a graphics card, then what are the possible alternatives that you could choose for deep learning?
For starters, if you want to work on your own personal computer, and you have a moderate CPU capable of average computations, then you can choose to install the CPU version for TensorFlow. This simple installation can be done by a simple pip command as follows:
pip install tensorflow
For simple deep learning computations like working with the MNIST dataset, it does not make a big difference if you want to utilize the CPU or GPU versions. The CPU version should work just fine for beginner-level deep learning projects.
However, if you want hands-on experience and the feel of using a GPU, then you can do so completely for free on the Google Colaboratory or Google Colab in short. It is a product from Google Research. Colab allows anybody to write and execute arbitrary python code through the browser and is especially well suited to machine learning, data analysis, and education.
I will be writing two articles shortly on the complete guides to Jupyter Notebooks as well as Google Colab shortly in the coming week. Stay tuned for those if want to understand a detailed guide on using them.
The other alternatives include creating an AWS cloud instance or using the IBM Watson Studio, and a few more approaches where you can pay a small amount for using a GPU on the cloud.
These are some of the alternative methods from my experience. If you have better alternative suggestions, then please let me know in the comments section.
But with these alternatives, you should easily be able to explore deep learning for yourself and gain a basic understanding of the subject.
In this article, we have covered the topics of what exactly a GPU is and what are its numerous benefits. I also suggested when would be the best time to consider owning a GPU for yourself. We also checked out the various alternatives that can help you thrive in learning deep learning basics even without a GPU.
So, to answer the question “Do you Really Need A GPU For Deep Learning?” in simple terms —
If you are a beginner and you are just getting started, then absolutely not. However, if you are more serious, gained a sharper understanding and knowledge, and want to move further with deep learning, then it is highly recommended.
Check out some of my other articles that you might enjoy reading!
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Thank you all for sticking on till the end. I hope all of you enjoyed reading the article. Wish you all a wonderful day!
|
[
{
"code": null,
"e": 240,
"s": 172,
"text": "I have always been a huge fan of gaming and a bit of a gaming nerd."
},
{
"code": null,
"e": 334,
"s": 240,
"text": "Since childhood, the only requirement I saw for graphics cards was for the purpose of gaming."
},
{
"code": null,
"e": 496,
"s": 334,
"text": "Luckily for me, after I started getting into artificial intelligence and data science, especially deep learning, I realized the true potential of graphics cards."
},
{
"code": null,
"e": 691,
"s": 496,
"text": "This was almost like a dream come true. It was like striking two bullseyes with one arrow because I could utilize the same single graphics card for gaming as well as study and research purposes."
},
{
"code": null,
"e": 811,
"s": 691,
"text": "Note: GPUs and graphics cards pretty much mean the same thing and will be used interchangeably throughout this article."
},
{
"code": null,
"e": 1057,
"s": 811,
"text": "GPUs are optimized for training artificial intelligence and deep learning models as they can process multiple computations simultaneously. They have a large number of cores, which allows for the better computation of multiple parallel processes."
},
{
"code": null,
"e": 1304,
"s": 1057,
"text": "In this article, we will understand what exactly a GPU and CUDA is, then explore the benefits of graphics processing units as well as when you should consider buying it if you are on a budget constraint. Finally, we will discuss the alternatives."
},
{
"code": null,
"e": 1379,
"s": 1304,
"text": "Without further ado, let us get started with understanding these concepts."
},
{
"code": null,
"e": 1587,
"s": 1379,
"text": "A Graphics Processing Unit is a specialized, electronic circuit designed to rapidly manipulate and alter memory to accelerate the creation of images in a frame buffer intended for output to a display device."
},
{
"code": null,
"e": 1815,
"s": 1587,
"text": "GPUs are a key part of modern computing. GPU computing and high-performance networking are transforming computational science and AI. The advancements in GPUs contribute a tremendous factor to the growth of deep learning today."
},
{
"code": null,
"e": 1968,
"s": 1815,
"text": "NVIDIA provides something called the Compute Unified Device Architecture (CUDA), which is crucial for supporting the various deep learning applications."
},
{
"code": null,
"e": 2234,
"s": 1968,
"text": "CUDA is a parallel computing platform and application programming interface model created by Nvidia. It allows software developers and software engineers to use a CUDA-enabled graphics processing unit (GPU) for general-purpose processing — an approach termed GPGPU."
},
{
"code": null,
"e": 2387,
"s": 2234,
"text": "These CUDA cores are highly beneficial and evolutionary in the field of artificial intelligence. We will discuss this topic further in the next section."
},
{
"code": null,
"e": 2458,
"s": 2387,
"text": "As discussed earlier, the NVIDIA GPUs offer the support of CUDA cores."
},
{
"code": null,
"e": 2599,
"s": 2458,
"text": "The number of CUDA cores differs for each type of graphics card, but it is safe to assume that most usually have over at least 1000 of them."
},
{
"code": null,
"e": 2823,
"s": 2599,
"text": "When you are using a deep learning framework such as TensorFlow or Pytorch, you can utilize these CUDA cores for computing your deep learning algorithms significantly faster in comparison to the same performance with a CPU."
},
{
"code": null,
"e": 3110,
"s": 2823,
"text": "While CPUs can do only a handful of operations at once, GPUs can perform thousands of these operations at once. Just to mention a hypothetical example, a task requiring 2–3 hours to train on a CPU could potentially be completed in about 10 minutes with the help of a decent quality GPU."
},
{
"code": null,
"e": 3287,
"s": 3110,
"text": "GPUs are a dynamic resource for computer vision and supercomputing with deep learning and neural networks to perform complicated tasks, sometimes even beyond human imagination."
},
{
"code": null,
"e": 3458,
"s": 3287,
"text": "Also, there are lots of other applications for GPUs as well. GPUs find their uses in embedded systems, mobile phones, personal computers, workstations, and game consoles."
},
{
"code": null,
"e": 3879,
"s": 3458,
"text": "You could make the best possible use of these graphics cards for other tasks like gaming and playing AAA games (triple-A games are basically an informal classification used for video games produced and distributed by a mid-sized or major publisher, typically having higher development and marketing budgets.) or for other graphical software purposes that need the requirement of a GPU as well like animation and designs."
},
{
"code": null,
"e": 4050,
"s": 3879,
"text": "GPUs also have an enormous scope in the field of robotics enabling high-tech robots to perceive the environment with the integration of artificial intelligence into them."
},
{
"code": null,
"e": 4257,
"s": 4050,
"text": "They are also in high demand in the automotive industry for the applications of deep learning-based self-driving cars. Large investments are being made in the development of these cars to change the future."
},
{
"code": null,
"e": 4467,
"s": 4257,
"text": "Last but not least, these GPUs also find a variety of applications in the medical fields of healthcare and life sciences by utilizing the data for ideal image segmentation tasks and other medical applications."
},
{
"code": null,
"e": 4504,
"s": 4467,
"text": "Graphics cards are pretty expensive!"
},
{
"code": null,
"e": 4711,
"s": 4504,
"text": "Especially when you are on a budget constraint, you probably will have a tough time deciding if you want to buy a graphics card or not. So, how can you come to a sensible conclusion regarding this question?"
},
{
"code": null,
"e": 4936,
"s": 4711,
"text": "A personal suggestion that I would like to offer is to make sure you dig yourself deeper into the field of data science. Understand the concepts of machine learning and have a basic conceptual understanding of deep learning."
},
{
"code": null,
"e": 5143,
"s": 4936,
"text": "If you absolutely feel certain and confident that deep learning is something you are interested in and want to pursue this intriguing topic further, then feel free to go ahead and purchase one for yourself."
},
{
"code": null,
"e": 5346,
"s": 5143,
"text": "In case you are wondering if there are any alternative choices or free tools to test the subject before straight away diving in, then you are in luck because there are lots of these resources available."
},
{
"code": null,
"e": 5411,
"s": 5346,
"text": "Let us look into these alternatives and other options available."
},
{
"code": null,
"e": 5594,
"s": 5411,
"text": "If you want to test out deep learning or you have concluded that you have no use for a graphics card, then what are the possible alternatives that you could choose for deep learning?"
},
{
"code": null,
"e": 5856,
"s": 5594,
"text": "For starters, if you want to work on your own personal computer, and you have a moderate CPU capable of average computations, then you can choose to install the CPU version for TensorFlow. This simple installation can be done by a simple pip command as follows:"
},
{
"code": null,
"e": 5879,
"s": 5856,
"text": "pip install tensorflow"
},
{
"code": null,
"e": 6117,
"s": 5879,
"text": "For simple deep learning computations like working with the MNIST dataset, it does not make a big difference if you want to utilize the CPU or GPU versions. The CPU version should work just fine for beginner-level deep learning projects."
},
{
"code": null,
"e": 6482,
"s": 6117,
"text": "However, if you want hands-on experience and the feel of using a GPU, then you can do so completely for free on the Google Colaboratory or Google Colab in short. It is a product from Google Research. Colab allows anybody to write and execute arbitrary python code through the browser and is especially well suited to machine learning, data analysis, and education."
},
{
"code": null,
"e": 6692,
"s": 6482,
"text": "I will be writing two articles shortly on the complete guides to Jupyter Notebooks as well as Google Colab shortly in the coming week. Stay tuned for those if want to understand a detailed guide on using them."
},
{
"code": null,
"e": 6875,
"s": 6692,
"text": "The other alternatives include creating an AWS cloud instance or using the IBM Watson Studio, and a few more approaches where you can pay a small amount for using a GPU on the cloud."
},
{
"code": null,
"e": 7030,
"s": 6875,
"text": "These are some of the alternative methods from my experience. If you have better alternative suggestions, then please let me know in the comments section."
},
{
"code": null,
"e": 7170,
"s": 7030,
"text": "But with these alternatives, you should easily be able to explore deep learning for yourself and gain a basic understanding of the subject."
},
{
"code": null,
"e": 7482,
"s": 7170,
"text": "In this article, we have covered the topics of what exactly a GPU is and what are its numerous benefits. I also suggested when would be the best time to consider owning a GPU for yourself. We also checked out the various alternatives that can help you thrive in learning deep learning basics even without a GPU."
},
{
"code": null,
"e": 7573,
"s": 7482,
"text": "So, to answer the question “Do you Really Need A GPU For Deep Learning?” in simple terms —"
},
{
"code": null,
"e": 7806,
"s": 7573,
"text": "If you are a beginner and you are just getting started, then absolutely not. However, if you are more serious, gained a sharper understanding and knowledge, and want to move further with deep learning, then it is highly recommended."
},
{
"code": null,
"e": 7872,
"s": 7806,
"text": "Check out some of my other articles that you might enjoy reading!"
},
{
"code": null,
"e": 7895,
"s": 7872,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7918,
"s": 7895,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7941,
"s": 7918,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7964,
"s": 7941,
"text": "towardsdatascience.com"
}
] |
Count composite fibonacci numbers from given array - GeeksforGeeks
|
09 Jun, 2021
Given an array arr[] of size N, the task is to find the composite Fibonacci numbers present in the given array.
Examples:
Input: arr[] = {13, 55, 7, 3, 5, 21, 233, 144, 6}Output: 55 21 144Explanation: Composite array elements are {55, 21, 144, 6}. Fibonacci array elements are {55, 21, 144}. Therefore, array elements which are both composite as well as Fibonacci are {55, 21, 144}.
Input: arr[] = {34, 13, 11, 8, 3, 55, 233}Output: 3Explanation: Composite array elements are {34, 8, 55} Fibonacci array elements are {34, 8, 55} Therefore, array elements which are both composite as well as Fibonacci are {34, 8, 55}.
Approach: Follow the steps below to solve the problem:
Initialize a variable, say Max to store the largest element of the array.
Create a Set to store all Fibonacci numbers up to Max.
Initialize an array, say sieve[], to store all the prime numbers using Sieve Of Eratosthenes.
Finally, traverse the array and check if the current array element is both composite and Fibonacci number or not. If found to be true, then print the current element.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find all Fibonacci// numbers up to Maxset<int> createhashmap(int Max){ // Store all Fibonacci numbers // upto Max set<int> hashmap; // Stores previous element // of Fibonacci sequence int curr = 1; // Stores previous element // of Fibonacci sequence int prev = 0; // Insert prev into hashmap hashmap.insert(prev); // Insert all the Fibonacci // numbers up to Max while (curr <= Max) { // Insert curr into hashmap hashmap.insert(curr); // Stores curr into temp int temp = curr; // Update curr curr = curr + prev; // Update prev prev = temp; } return hashmap;} // Function to find all Composite// numbers up to Maxvector<bool> SieveOfEratosthenes( int Max){ // isPrime[i]: Stores if i is // a prime number or not vector<bool> isPrime(Max, true); isPrime[0] = false; isPrime[1] = false; // Calculate all prime numbers up to // Max using Sieve of Eratosthenes for (int p = 2; p * p <= Max; p++) { // If P is a prime number if (isPrime[p]) { // Set all multiple of P // as non-prime for (int i = p * p; i <= Max; i += p) { // Update isPrime isPrime[i] = false; } } } return isPrime;} // Function to find the numbers which is// both a composite and Fibonacci numberint cntFibonacciPrime(int arr[], int N){ // Stores the largest element // of the array int Max = arr[0]; // Traverse the array arr[] for (int i = 1; i < N; i++) { // Update Max Max = max(Max, arr[i]); } // isPrim[i] check i is // a prime number or not vector<bool> isPrime = SieveOfEratosthenes(Max); // Stores all the Fibonacci numbers set<int> hashmap = createhashmap(Max); // Traverse the array arr[] for (int i = 0; i < N; i++) { // current element is not // a composite number if (arr[i] == 1) continue; // If current element is a Fibonacci // and composite number if ((hashmap.count(arr[i])) && !isPrime[arr[i]]) { // Print current element cout << arr[i] << " "; } }} // Driver Codeint main(){ int arr[] = { 13, 55, 7, 3, 5, 21, 233, 144, 89 }; int N = sizeof(arr) / sizeof(arr[0]); cntFibonacciPrime(arr, N); return 0;}
// Java program to implement// the above approachimport java.util.*;class GFG{ static boolean[] isPrime; // Function to find all// Fibonacci numbers up// to Maxstatic HashSet<Integer> createhashmap(int Max){ // Store all Fibonacci numbers // upto Max HashSet<Integer> hashmap = new HashSet<>(); // Stores previous element // of Fibonacci sequence int curr = 1; // Stores previous element // of Fibonacci sequence int prev = 0; // Insert prev into hashmap hashmap.add(prev); // Insert all the Fibonacci // numbers up to Max while (curr < Max) { // Insert curr into // hashmap hashmap.add(curr); // Stores curr into // temp int temp = curr; // Update curr curr = curr + prev; // Update prev prev = temp; } return hashmap;} // Function to find all// Composite numbers up// to Maxstatic void SieveOfEratosthenes(int Max){ // isPrime[i]: Stores if i is // a prime number or not isPrime = new boolean[Max]; Arrays.fill(isPrime, true); isPrime[0] = false; isPrime[1] = false; // Calculate all prime numbers // up to Max using Sieve of // Eratosthenes for (int p = 2; p * p <= Max; p++) { // If P is a prime number if (isPrime[p]) { // Set all multiple of P // as non-prime for (int i = p * p; i <= Max; i += p) { // Update isPrime isPrime[i] = false; } } }} // Function to find the numbers which is// both a composite and Fibonacci numberstatic void cntFibonacciPrime(int arr[], int N){ // Stores the largest element // of the array int Max = arr[0]; // Traverse the array arr[] for (int i = 1; i < N; i++) { // Update Max Max = Math.max(Max, arr[i]); } // isPrim[i] check i is // a prime number or not SieveOfEratosthenes(Max); // Stores all the Fibonacci // numbers HashSet<Integer> hashmap = createhashmap(Max); // Traverse the array arr[] for (int i = 0; i < N; i++) { // current element is not // a composite number if (arr[i] == 1) continue; // If current element is a // Fibonacci and composite // number if ((hashmap.contains(arr[i])) && !isPrime[arr[i]]) { // Print current element System.out.print(arr[i] + " "); } }} // Driver Codepublic static void main(String[] args){ int arr[] = {13, 55, 7, 3, 5, 21, 233, 144, 89}; int N = arr.length; cntFibonacciPrime(arr, N);}} // This code is contributed by Princi Singh
# Python3 program to implement# the above approachimport math # Function to find all Fibonacci# numbers up to Maxdef createhashmap(Max): # Store all Fibonacci numbers # upto Max hashmap = {""} # Stores previous element # of Fibonacci sequence curr = 1 # Stores previous element # of Fibonacci sequence prev = 0 # Insert prev into hashmap hashmap.add(prev) # Insert all the Fibonacci # numbers up to Max while (curr <= Max): # Insert curr into hashmap hashmap.add(curr) # Stores curr into temp temp = curr # Update curr curr = curr + prev # Update prev prev = temp return hashmap # Function to find all Composite# numbers up to Maxdef SieveOfEratosthenes(Max): # isPrime[i]: Stores if i is # a prime number or not isPrime = [1 for x in range(Max + 1)] isPrime[0] = 0 isPrime[1] = 0 # Calculate all prime numbers up to # Max using Sieve of Eratosthenes for p in range(0, int(math.sqrt(Max))): # If P is a prime number if (isPrime[p]): # Set all multiple of P # as non-prime for i in range(2 * p, Max, p): isPrime[i] = 0 return isPrime # Function to find the numbers which is# both a composite and Fibonacci numberdef cntFibonacciPrime(arr, N): # Stores the largest element # of the array Max = arr[0] # Traverse the array arr[] for i in range(0, N): # Update Max Max = max(Max, arr[i]) # isPrim[i] check i is # a prime number or not isPrime = SieveOfEratosthenes(Max) # Stores all the Fibonacci numbers hashmap = createhashmap(Max) # Traverse the array arr[] for i in range(0, N): # Current element is not # a composite number if arr[i] == 1: continue # If current element is a Fibonacci # and composite number if ((arr[i] in hashmap) and (not(isPrime[arr[i]]))): # Print current element print(arr[i], end = " ") # Driver Codearr = [ 13, 55, 7, 3, 5, 21, 233, 144, 89 ]N = len(arr) cntFibonacciPrime(arr, N) # This code is contributed by Stream_Cipher
// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ static bool[] isPrime; // Function to find all// Fibonacci numbers up// to Maxstatic HashSet<int> createhashmap(int Max){ // Store all Fibonacci numbers // upto Max HashSet<int> hashmap = new HashSet<int>(); // Stores previous element // of Fibonacci sequence int curr = 1; // Stores previous element // of Fibonacci sequence int prev = 0; // Insert prev into hashmap hashmap.Add(prev); // Insert all the Fibonacci // numbers up to Max while (curr < Max) { // Insert curr into // hashmap hashmap.Add(curr); // Stores curr into // temp int temp = curr; // Update curr curr = curr + prev; // Update prev prev = temp; } return hashmap;} // Function to find all// Composite numbers up// to Maxstatic void SieveOfEratosthenes(int Max){ // isPrime[i]: Stores if i is // a prime number or not isPrime = new bool[Max]; for(int i = 0;i<Max;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; // Calculate all prime numbers // up to Max using Sieve of // Eratosthenes for(int p = 2; p * p <= Max; p++) { // If P is a prime number if (isPrime[p]) { // Set all multiple of P // as non-prime for(int i = p * p; i <= Max; i += p) { // Update isPrime isPrime[i] = false; } } }} // Function to find the numbers which is// both a composite and Fibonacci numberstatic void cntFibonacciPrime(int []arr, int N){ // Stores the largest element // of the array int Max = arr[0]; // Traverse the array []arr for(int i = 1; i < N; i++) { // Update Max Max = Math.Max(Max, arr[i]); } // isPrim[i] check i is // a prime number or not SieveOfEratosthenes(Max); // Stores all the Fibonacci // numbers HashSet<int> hashmap = createhashmap(Max); // Traverse the array []arr for(int i = 0; i < N; i++) { // current element is not // a composite number if (arr[i] == 1) continue; // If current element is a // Fibonacci and composite // number if ((hashmap.Contains(arr[i])) && !isPrime[arr[i]]) { // Print current element Console.Write(arr[i] + " "); } }} // Driver Codepublic static void Main(String[] args){ int []arr = { 13, 55, 7, 3, 5, 21, 233, 144, 89 }; int N = arr.Length; cntFibonacciPrime(arr, N);}} // This code is contributed by Rajput-Ji
<script> // Javascript program to implement// the above approach // Function to find all Fibonacci// numbers up to Maxfunction createhashmap(Max){ // Store all Fibonacci numbers // upto Max var hashmap = new Set(); // Stores previous element // of Fibonacci sequence var curr = 1; // Stores previous element // of Fibonacci sequence var prev = 0; // Insert prev into hashmap hashmap.add(prev); // Insert all the Fibonacci // numbers up to Max while (curr <= Max) { // Insert curr into hashmap hashmap.add(curr); // Stores curr into temp var temp = curr; // Update curr curr = curr + prev; // Update prev prev = temp; } return hashmap;} // Function to find all Composite// numbers up to Maxfunction SieveOfEratosthenes(Max){ // isPrime[i]: Stores if i is // a prime number or not var isPrime = Array(Max + 1).fill(true); isPrime[0] = false; isPrime[1] = false; // Calculate all prime numbers up to // Max using Sieve of Eratosthenes for(var p = 2; p * p <= Max; p++) { // If P is a prime number if (isPrime[p]) { // Set all multiple of P // as non-prime for(var i = p * p; i <= Max; i += p) { // Update isPrime isPrime[i] = false; } } } return isPrime;} // Function to find the numbers which is// both a composite and Fibonacci numberfunction cntFibonacciPrime(arr, N){ // Stores the largest element // of the array var Max = arr[0]; // Traverse the array arr[] for(var i = 1; i < N; i++) { // Update Max Max = Math.max(Max, arr[i]); } // isPrim[i] check i is // a prime number or not var isPrime = SieveOfEratosthenes(Max); // Stores all the Fibonacci numbers var hashmap = createhashmap(Max); // Traverse the array arr[] for(var i = 0; i < N; i++) { // current element is not // a composite number if (arr[i] == 1) continue; // If current element is a Fibonacci // and composite number if (hashmap.has(arr[i]) && !isPrime[arr[i]]) { // Print current element document.write( arr[i] + " "); } }} // Driver Codevar arr = [ 13, 55, 7, 3, 5, 21, 233, 144, 89 ];var N = arr.length; cntFibonacciPrime(arr, N); // This code is contributed by itsok </script>
55 21 144
Time Complexity: O(N + Max * log(log(Max))), where Max is the largest element in the arrayAuxiliary Space: O(N)
princi singh
Rajput-Ji
Stream_Cipher
itsok
cpp-set
Fibonacci
Maths
Prime Number
sieve
Arrays
Hash
Mathematical
Searching
Arrays
Searching
Hash
Mathematical
Prime Number
Fibonacci
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Python | Using 2D arrays/lists the right way
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum
|
[
{
"code": null,
"e": 25400,
"s": 25372,
"text": "\n09 Jun, 2021"
},
{
"code": null,
"e": 25512,
"s": 25400,
"text": "Given an array arr[] of size N, the task is to find the composite Fibonacci numbers present in the given array."
},
{
"code": null,
"e": 25522,
"s": 25512,
"text": "Examples:"
},
{
"code": null,
"e": 25783,
"s": 25522,
"text": "Input: arr[] = {13, 55, 7, 3, 5, 21, 233, 144, 6}Output: 55 21 144Explanation: Composite array elements are {55, 21, 144, 6}. Fibonacci array elements are {55, 21, 144}. Therefore, array elements which are both composite as well as Fibonacci are {55, 21, 144}."
},
{
"code": null,
"e": 26018,
"s": 25783,
"text": "Input: arr[] = {34, 13, 11, 8, 3, 55, 233}Output: 3Explanation: Composite array elements are {34, 8, 55} Fibonacci array elements are {34, 8, 55} Therefore, array elements which are both composite as well as Fibonacci are {34, 8, 55}."
},
{
"code": null,
"e": 26073,
"s": 26018,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26147,
"s": 26073,
"text": "Initialize a variable, say Max to store the largest element of the array."
},
{
"code": null,
"e": 26202,
"s": 26147,
"text": "Create a Set to store all Fibonacci numbers up to Max."
},
{
"code": null,
"e": 26296,
"s": 26202,
"text": "Initialize an array, say sieve[], to store all the prime numbers using Sieve Of Eratosthenes."
},
{
"code": null,
"e": 26463,
"s": 26296,
"text": "Finally, traverse the array and check if the current array element is both composite and Fibonacci number or not. If found to be true, then print the current element."
},
{
"code": null,
"e": 26514,
"s": 26463,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26518,
"s": 26514,
"text": "C++"
},
{
"code": null,
"e": 26523,
"s": 26518,
"text": "Java"
},
{
"code": null,
"e": 26531,
"s": 26523,
"text": "Python3"
},
{
"code": null,
"e": 26534,
"s": 26531,
"text": "C#"
},
{
"code": null,
"e": 26545,
"s": 26534,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find all Fibonacci// numbers up to Maxset<int> createhashmap(int Max){ // Store all Fibonacci numbers // upto Max set<int> hashmap; // Stores previous element // of Fibonacci sequence int curr = 1; // Stores previous element // of Fibonacci sequence int prev = 0; // Insert prev into hashmap hashmap.insert(prev); // Insert all the Fibonacci // numbers up to Max while (curr <= Max) { // Insert curr into hashmap hashmap.insert(curr); // Stores curr into temp int temp = curr; // Update curr curr = curr + prev; // Update prev prev = temp; } return hashmap;} // Function to find all Composite// numbers up to Maxvector<bool> SieveOfEratosthenes( int Max){ // isPrime[i]: Stores if i is // a prime number or not vector<bool> isPrime(Max, true); isPrime[0] = false; isPrime[1] = false; // Calculate all prime numbers up to // Max using Sieve of Eratosthenes for (int p = 2; p * p <= Max; p++) { // If P is a prime number if (isPrime[p]) { // Set all multiple of P // as non-prime for (int i = p * p; i <= Max; i += p) { // Update isPrime isPrime[i] = false; } } } return isPrime;} // Function to find the numbers which is// both a composite and Fibonacci numberint cntFibonacciPrime(int arr[], int N){ // Stores the largest element // of the array int Max = arr[0]; // Traverse the array arr[] for (int i = 1; i < N; i++) { // Update Max Max = max(Max, arr[i]); } // isPrim[i] check i is // a prime number or not vector<bool> isPrime = SieveOfEratosthenes(Max); // Stores all the Fibonacci numbers set<int> hashmap = createhashmap(Max); // Traverse the array arr[] for (int i = 0; i < N; i++) { // current element is not // a composite number if (arr[i] == 1) continue; // If current element is a Fibonacci // and composite number if ((hashmap.count(arr[i])) && !isPrime[arr[i]]) { // Print current element cout << arr[i] << \" \"; } }} // Driver Codeint main(){ int arr[] = { 13, 55, 7, 3, 5, 21, 233, 144, 89 }; int N = sizeof(arr) / sizeof(arr[0]); cntFibonacciPrime(arr, N); return 0;}",
"e": 29105,
"s": 26545,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*;class GFG{ static boolean[] isPrime; // Function to find all// Fibonacci numbers up// to Maxstatic HashSet<Integer> createhashmap(int Max){ // Store all Fibonacci numbers // upto Max HashSet<Integer> hashmap = new HashSet<>(); // Stores previous element // of Fibonacci sequence int curr = 1; // Stores previous element // of Fibonacci sequence int prev = 0; // Insert prev into hashmap hashmap.add(prev); // Insert all the Fibonacci // numbers up to Max while (curr < Max) { // Insert curr into // hashmap hashmap.add(curr); // Stores curr into // temp int temp = curr; // Update curr curr = curr + prev; // Update prev prev = temp; } return hashmap;} // Function to find all// Composite numbers up// to Maxstatic void SieveOfEratosthenes(int Max){ // isPrime[i]: Stores if i is // a prime number or not isPrime = new boolean[Max]; Arrays.fill(isPrime, true); isPrime[0] = false; isPrime[1] = false; // Calculate all prime numbers // up to Max using Sieve of // Eratosthenes for (int p = 2; p * p <= Max; p++) { // If P is a prime number if (isPrime[p]) { // Set all multiple of P // as non-prime for (int i = p * p; i <= Max; i += p) { // Update isPrime isPrime[i] = false; } } }} // Function to find the numbers which is// both a composite and Fibonacci numberstatic void cntFibonacciPrime(int arr[], int N){ // Stores the largest element // of the array int Max = arr[0]; // Traverse the array arr[] for (int i = 1; i < N; i++) { // Update Max Max = Math.max(Max, arr[i]); } // isPrim[i] check i is // a prime number or not SieveOfEratosthenes(Max); // Stores all the Fibonacci // numbers HashSet<Integer> hashmap = createhashmap(Max); // Traverse the array arr[] for (int i = 0; i < N; i++) { // current element is not // a composite number if (arr[i] == 1) continue; // If current element is a // Fibonacci and composite // number if ((hashmap.contains(arr[i])) && !isPrime[arr[i]]) { // Print current element System.out.print(arr[i] + \" \"); } }} // Driver Codepublic static void main(String[] args){ int arr[] = {13, 55, 7, 3, 5, 21, 233, 144, 89}; int N = arr.length; cntFibonacciPrime(arr, N);}} // This code is contributed by Princi Singh",
"e": 31621,
"s": 29105,
"text": null
},
{
"code": "# Python3 program to implement# the above approachimport math # Function to find all Fibonacci# numbers up to Maxdef createhashmap(Max): # Store all Fibonacci numbers # upto Max hashmap = {\"\"} # Stores previous element # of Fibonacci sequence curr = 1 # Stores previous element # of Fibonacci sequence prev = 0 # Insert prev into hashmap hashmap.add(prev) # Insert all the Fibonacci # numbers up to Max while (curr <= Max): # Insert curr into hashmap hashmap.add(curr) # Stores curr into temp temp = curr # Update curr curr = curr + prev # Update prev prev = temp return hashmap # Function to find all Composite# numbers up to Maxdef SieveOfEratosthenes(Max): # isPrime[i]: Stores if i is # a prime number or not isPrime = [1 for x in range(Max + 1)] isPrime[0] = 0 isPrime[1] = 0 # Calculate all prime numbers up to # Max using Sieve of Eratosthenes for p in range(0, int(math.sqrt(Max))): # If P is a prime number if (isPrime[p]): # Set all multiple of P # as non-prime for i in range(2 * p, Max, p): isPrime[i] = 0 return isPrime # Function to find the numbers which is# both a composite and Fibonacci numberdef cntFibonacciPrime(arr, N): # Stores the largest element # of the array Max = arr[0] # Traverse the array arr[] for i in range(0, N): # Update Max Max = max(Max, arr[i]) # isPrim[i] check i is # a prime number or not isPrime = SieveOfEratosthenes(Max) # Stores all the Fibonacci numbers hashmap = createhashmap(Max) # Traverse the array arr[] for i in range(0, N): # Current element is not # a composite number if arr[i] == 1: continue # If current element is a Fibonacci # and composite number if ((arr[i] in hashmap) and (not(isPrime[arr[i]]))): # Print current element print(arr[i], end = \" \") # Driver Codearr = [ 13, 55, 7, 3, 5, 21, 233, 144, 89 ]N = len(arr) cntFibonacciPrime(arr, N) # This code is contributed by Stream_Cipher",
"e": 33996,
"s": 31621,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ static bool[] isPrime; // Function to find all// Fibonacci numbers up// to Maxstatic HashSet<int> createhashmap(int Max){ // Store all Fibonacci numbers // upto Max HashSet<int> hashmap = new HashSet<int>(); // Stores previous element // of Fibonacci sequence int curr = 1; // Stores previous element // of Fibonacci sequence int prev = 0; // Insert prev into hashmap hashmap.Add(prev); // Insert all the Fibonacci // numbers up to Max while (curr < Max) { // Insert curr into // hashmap hashmap.Add(curr); // Stores curr into // temp int temp = curr; // Update curr curr = curr + prev; // Update prev prev = temp; } return hashmap;} // Function to find all// Composite numbers up// to Maxstatic void SieveOfEratosthenes(int Max){ // isPrime[i]: Stores if i is // a prime number or not isPrime = new bool[Max]; for(int i = 0;i<Max;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; // Calculate all prime numbers // up to Max using Sieve of // Eratosthenes for(int p = 2; p * p <= Max; p++) { // If P is a prime number if (isPrime[p]) { // Set all multiple of P // as non-prime for(int i = p * p; i <= Max; i += p) { // Update isPrime isPrime[i] = false; } } }} // Function to find the numbers which is// both a composite and Fibonacci numberstatic void cntFibonacciPrime(int []arr, int N){ // Stores the largest element // of the array int Max = arr[0]; // Traverse the array []arr for(int i = 1; i < N; i++) { // Update Max Max = Math.Max(Max, arr[i]); } // isPrim[i] check i is // a prime number or not SieveOfEratosthenes(Max); // Stores all the Fibonacci // numbers HashSet<int> hashmap = createhashmap(Max); // Traverse the array []arr for(int i = 0; i < N; i++) { // current element is not // a composite number if (arr[i] == 1) continue; // If current element is a // Fibonacci and composite // number if ((hashmap.Contains(arr[i])) && !isPrime[arr[i]]) { // Print current element Console.Write(arr[i] + \" \"); } }} // Driver Codepublic static void Main(String[] args){ int []arr = { 13, 55, 7, 3, 5, 21, 233, 144, 89 }; int N = arr.Length; cntFibonacciPrime(arr, N);}} // This code is contributed by Rajput-Ji",
"e": 36553,
"s": 33996,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach // Function to find all Fibonacci// numbers up to Maxfunction createhashmap(Max){ // Store all Fibonacci numbers // upto Max var hashmap = new Set(); // Stores previous element // of Fibonacci sequence var curr = 1; // Stores previous element // of Fibonacci sequence var prev = 0; // Insert prev into hashmap hashmap.add(prev); // Insert all the Fibonacci // numbers up to Max while (curr <= Max) { // Insert curr into hashmap hashmap.add(curr); // Stores curr into temp var temp = curr; // Update curr curr = curr + prev; // Update prev prev = temp; } return hashmap;} // Function to find all Composite// numbers up to Maxfunction SieveOfEratosthenes(Max){ // isPrime[i]: Stores if i is // a prime number or not var isPrime = Array(Max + 1).fill(true); isPrime[0] = false; isPrime[1] = false; // Calculate all prime numbers up to // Max using Sieve of Eratosthenes for(var p = 2; p * p <= Max; p++) { // If P is a prime number if (isPrime[p]) { // Set all multiple of P // as non-prime for(var i = p * p; i <= Max; i += p) { // Update isPrime isPrime[i] = false; } } } return isPrime;} // Function to find the numbers which is// both a composite and Fibonacci numberfunction cntFibonacciPrime(arr, N){ // Stores the largest element // of the array var Max = arr[0]; // Traverse the array arr[] for(var i = 1; i < N; i++) { // Update Max Max = Math.max(Max, arr[i]); } // isPrim[i] check i is // a prime number or not var isPrime = SieveOfEratosthenes(Max); // Stores all the Fibonacci numbers var hashmap = createhashmap(Max); // Traverse the array arr[] for(var i = 0; i < N; i++) { // current element is not // a composite number if (arr[i] == 1) continue; // If current element is a Fibonacci // and composite number if (hashmap.has(arr[i]) && !isPrime[arr[i]]) { // Print current element document.write( arr[i] + \" \"); } }} // Driver Codevar arr = [ 13, 55, 7, 3, 5, 21, 233, 144, 89 ];var N = arr.length; cntFibonacciPrime(arr, N); // This code is contributed by itsok </script>",
"e": 39160,
"s": 36553,
"text": null
},
{
"code": null,
"e": 39170,
"s": 39160,
"text": "55 21 144"
},
{
"code": null,
"e": 39284,
"s": 39172,
"text": "Time Complexity: O(N + Max * log(log(Max))), where Max is the largest element in the arrayAuxiliary Space: O(N)"
},
{
"code": null,
"e": 39297,
"s": 39284,
"text": "princi singh"
},
{
"code": null,
"e": 39307,
"s": 39297,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 39321,
"s": 39307,
"text": "Stream_Cipher"
},
{
"code": null,
"e": 39327,
"s": 39321,
"text": "itsok"
},
{
"code": null,
"e": 39335,
"s": 39327,
"text": "cpp-set"
},
{
"code": null,
"e": 39345,
"s": 39335,
"text": "Fibonacci"
},
{
"code": null,
"e": 39351,
"s": 39345,
"text": "Maths"
},
{
"code": null,
"e": 39364,
"s": 39351,
"text": "Prime Number"
},
{
"code": null,
"e": 39370,
"s": 39364,
"text": "sieve"
},
{
"code": null,
"e": 39377,
"s": 39370,
"text": "Arrays"
},
{
"code": null,
"e": 39382,
"s": 39377,
"text": "Hash"
},
{
"code": null,
"e": 39395,
"s": 39382,
"text": "Mathematical"
},
{
"code": null,
"e": 39405,
"s": 39395,
"text": "Searching"
},
{
"code": null,
"e": 39412,
"s": 39405,
"text": "Arrays"
},
{
"code": null,
"e": 39422,
"s": 39412,
"text": "Searching"
},
{
"code": null,
"e": 39427,
"s": 39422,
"text": "Hash"
},
{
"code": null,
"e": 39440,
"s": 39427,
"text": "Mathematical"
},
{
"code": null,
"e": 39453,
"s": 39440,
"text": "Prime Number"
},
{
"code": null,
"e": 39463,
"s": 39453,
"text": "Fibonacci"
},
{
"code": null,
"e": 39469,
"s": 39463,
"text": "sieve"
},
{
"code": null,
"e": 39567,
"s": 39469,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39635,
"s": 39567,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 39667,
"s": 39635,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 39690,
"s": 39667,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 39704,
"s": 39690,
"text": "Linear Search"
},
{
"code": null,
"e": 39749,
"s": 39704,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 39834,
"s": 39749,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 39870,
"s": 39834,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 39901,
"s": 39870,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 39935,
"s": 39901,
"text": "Hashing | Set 3 (Open Addressing)"
}
] |
Inplace vs Standard Operators in Python - GeeksforGeeks
|
10 Aug, 2021
Inplace Operators – Set 1, Set 2Normal operators do the simple assigning job. On other hand, Inplace operators behave similarly to normal operators except that they act in a different manner in case of mutable and Immutable targets.
The _add_ method, does simple addition, takes two arguments, returns the sum, and stores it in another variable without modifying any of the arguments.
On the other hand, _iadd_ method also takes two arguments, but it makes an in-place change in 1st argument passed by storing the sum in it. As object mutation is needed in this process, immutable targets such as numbers, strings, and tuples, shouldn’t have _iadd_ method.
Normal operator’s “add()” method, implements “a+b” and stores the result in the mentioned variable.
Inplace operator’s “iadd()” method, implements “a+=b” if it exists (i.e in case of immutable targets, it doesn’t exist) and changes the value of the passed argument. But if not, “a+b” is implemented.
Case 1: Immutable Targets. In Immutable targets, such as numbers, strings, and tuples. Inplace operators behave the same as normal operators, i.e only assignment takes place, no modification is taken place in the passed arguments.
Python
# Python code to demonstrate difference between # Inplace and Normal operators in Immutable Targets # importing operator to handle operator operationsimport operator # Initializing valuesx = 5y = 6a = 5b = 6 # using add() to add the arguments passed z = operator.add(a,b) # using iadd() to add the arguments passed p = operator.iadd(x,y) # printing the modified valueprint ("Value after adding using normal operator : ",end="")print (z) # printing the modified valueprint ("Value after adding using Inplace operator : ",end="")print (p) # printing value of first argument# value is unchangedprint ("Value of first argument using normal operator : ",end="")print (a) # printing value of first argument# value is unchangedprint ("Value of first argument using Inplace operator : ",end="")print (x)
Output:
Value after adding using normal operator : 11
Value after adding using Inplace operator : 11
Value of first argument using normal operator : 5
Value of first argument using Inplace operator : 5
Case 2: Mutable Targets The behavior of Inplace operators in mutable targets, such as lists and dictionaries, is different from normal operators. The updation and assignment both are carried out in case of mutable targets.
Python
# Python code to demonstrate difference between # Inplace and Normal operators in mutable Targets # importing operator to handle operator operationsimport operator # Initializing lista = [1, 2, 4, 5] # using add() to add the arguments passed z = operator.add(a,[1, 2, 3]) # printing the modified valueprint ("Value after adding using normal operator : ",end="")print (z) # printing value of first argument# value is unchangedprint ("Value of first argument using normal operator : ",end="")print (a) # using iadd() to add the arguments passed # performs a+=[1, 2, 3]p = operator.iadd(a,[1, 2, 3]) # printing the modified valueprint ("Value after adding using Inplace operator : ",end="")print (p) # printing value of first argument# value is changedprint ("Value of first argument using Inplace operator : ",end="")print (a)
Output:
Value after adding using normal operator : [1, 2, 4, 5, 1, 2, 3]
Value of first argument using normal operator : [1, 2, 4, 5]
Value after adding using Inplace operator : [1, 2, 4, 5, 1, 2, 3]
Value of first argument using Inplace operator : [1, 2, 4, 5, 1, 2, 3]
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
punamsingh628700
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Python | Get dictionary keys as a list
Bar Plot in Matplotlib
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
loops in python
Python - Call function from another file
Ways to filter Pandas DataFrame by column values
Python | Convert set into a list
Python program to find number of days between two given dates
|
[
{
"code": null,
"e": 23925,
"s": 23897,
"text": "\n10 Aug, 2021"
},
{
"code": null,
"e": 24160,
"s": 23925,
"text": "Inplace Operators – Set 1, Set 2Normal operators do the simple assigning job. On other hand, Inplace operators behave similarly to normal operators except that they act in a different manner in case of mutable and Immutable targets. "
},
{
"code": null,
"e": 24312,
"s": 24160,
"text": "The _add_ method, does simple addition, takes two arguments, returns the sum, and stores it in another variable without modifying any of the arguments."
},
{
"code": null,
"e": 24584,
"s": 24312,
"text": "On the other hand, _iadd_ method also takes two arguments, but it makes an in-place change in 1st argument passed by storing the sum in it. As object mutation is needed in this process, immutable targets such as numbers, strings, and tuples, shouldn’t have _iadd_ method."
},
{
"code": null,
"e": 24684,
"s": 24584,
"text": "Normal operator’s “add()” method, implements “a+b” and stores the result in the mentioned variable."
},
{
"code": null,
"e": 24884,
"s": 24684,
"text": "Inplace operator’s “iadd()” method, implements “a+=b” if it exists (i.e in case of immutable targets, it doesn’t exist) and changes the value of the passed argument. But if not, “a+b” is implemented."
},
{
"code": null,
"e": 25116,
"s": 24884,
"text": "Case 1: Immutable Targets. In Immutable targets, such as numbers, strings, and tuples. Inplace operators behave the same as normal operators, i.e only assignment takes place, no modification is taken place in the passed arguments. "
},
{
"code": null,
"e": 25123,
"s": 25116,
"text": "Python"
},
{
"code": "# Python code to demonstrate difference between # Inplace and Normal operators in Immutable Targets # importing operator to handle operator operationsimport operator # Initializing valuesx = 5y = 6a = 5b = 6 # using add() to add the arguments passed z = operator.add(a,b) # using iadd() to add the arguments passed p = operator.iadd(x,y) # printing the modified valueprint (\"Value after adding using normal operator : \",end=\"\")print (z) # printing the modified valueprint (\"Value after adding using Inplace operator : \",end=\"\")print (p) # printing value of first argument# value is unchangedprint (\"Value of first argument using normal operator : \",end=\"\")print (a) # printing value of first argument# value is unchangedprint (\"Value of first argument using Inplace operator : \",end=\"\")print (x)",
"e": 25927,
"s": 25123,
"text": null
},
{
"code": null,
"e": 25935,
"s": 25927,
"text": "Output:"
},
{
"code": null,
"e": 26129,
"s": 25935,
"text": "Value after adding using normal operator : 11\nValue after adding using Inplace operator : 11\nValue of first argument using normal operator : 5\nValue of first argument using Inplace operator : 5"
},
{
"code": null,
"e": 26353,
"s": 26129,
"text": "Case 2: Mutable Targets The behavior of Inplace operators in mutable targets, such as lists and dictionaries, is different from normal operators. The updation and assignment both are carried out in case of mutable targets. "
},
{
"code": null,
"e": 26360,
"s": 26353,
"text": "Python"
},
{
"code": "# Python code to demonstrate difference between # Inplace and Normal operators in mutable Targets # importing operator to handle operator operationsimport operator # Initializing lista = [1, 2, 4, 5] # using add() to add the arguments passed z = operator.add(a,[1, 2, 3]) # printing the modified valueprint (\"Value after adding using normal operator : \",end=\"\")print (z) # printing value of first argument# value is unchangedprint (\"Value of first argument using normal operator : \",end=\"\")print (a) # using iadd() to add the arguments passed # performs a+=[1, 2, 3]p = operator.iadd(a,[1, 2, 3]) # printing the modified valueprint (\"Value after adding using Inplace operator : \",end=\"\")print (p) # printing value of first argument# value is changedprint (\"Value of first argument using Inplace operator : \",end=\"\")print (a)",
"e": 27193,
"s": 26360,
"text": null
},
{
"code": null,
"e": 27203,
"s": 27193,
"text": "Output: "
},
{
"code": null,
"e": 27466,
"s": 27203,
"text": "Value after adding using normal operator : [1, 2, 4, 5, 1, 2, 3]\nValue of first argument using normal operator : [1, 2, 4, 5]\nValue after adding using Inplace operator : [1, 2, 4, 5, 1, 2, 3]\nValue of first argument using Inplace operator : [1, 2, 4, 5, 1, 2, 3]"
},
{
"code": null,
"e": 27888,
"s": 27466,
"text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 27905,
"s": 27888,
"text": "punamsingh628700"
},
{
"code": null,
"e": 27912,
"s": 27905,
"text": "Python"
},
{
"code": null,
"e": 28010,
"s": 27912,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28019,
"s": 28010,
"text": "Comments"
},
{
"code": null,
"e": 28032,
"s": 28019,
"text": "Old Comments"
},
{
"code": null,
"e": 28068,
"s": 28032,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 28107,
"s": 28068,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28130,
"s": 28107,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 28181,
"s": 28130,
"text": "Multithreading in Python | Set 2 (Synchronization)"
},
{
"code": null,
"e": 28213,
"s": 28181,
"text": "Python Dictionary keys() method"
},
{
"code": null,
"e": 28229,
"s": 28213,
"text": "loops in python"
},
{
"code": null,
"e": 28270,
"s": 28229,
"text": "Python - Call function from another file"
},
{
"code": null,
"e": 28319,
"s": 28270,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 28352,
"s": 28319,
"text": "Python | Convert set into a list"
}
] |
Find the Majority Element | Set 3 (Bit Magic) - GeeksforGeeks
|
12 Feb, 2022
Pre-requisite: Majority Element, Majority Element | Set-2 (Hashing)Given an array of size N, find the majority element. The majority element is the element that appears more than n/2 times in the given array.
Examples:
Input: {3, 3, 4, 2, 4, 4, 2, 4, 4}
Output: 4
Input: {3, 3, 6, 2, 4, 4, 2, 4}
Output: No Majority Element
Approach:In this post, we solve the problem with the help of binary representation of the numbers present in the array.The task is to find the element that appears more than n/2 times. So, it appears more than all other numbers combined.So, we starting from LSB (least significant bit) of every number of the array, we count in how many numbers of the array it is set. If any bit is set in more than n/2 numbers, then that bit is set in our majority element.
The above approach works because for all other numbers combined the set bit count can’t be more than n/2, as the majority element is present more than n/2 times.
Lets see with the help of example
Input : {3, 3, 4, 2, 4, 4, 2, 4, 4}
Binary representation of the same are:
3 - 0 1 1
3 - 0 1 1
4 - 1 0 0
2 - 0 1 0
4 - 1 0 0
4 - 1 0 0
2 - 0 1 0
4 - 1 0 0
4 - 1 0 0
----------
- 5 4 0
Here n is 9, so n/2 = 4 and an only 3rd bit from right satisfy count>4 and hence set in majority element and all other bits are not set.
So, our majority element is 1 0 0, which is 4 But there more to it, This approach works when the majority element is present in the array. What if it is not present?
Let’s see with the help of this example:
Input : {3, 3, 6, 2, 4, 4, 2, 4}
Binary representation of the same are:
3 - 0 1 1
3 - 0 1 1
6 - 1 1 0
2 - 0 1 0
4 - 1 0 0
4 - 1 0 0
2 - 0 1 0
4 - 1 0 0
----------
- 4 5 0
Here n is 8, so n/2 = 4 and an only 2nd bit from right satisfy count>4 and hence set it should be set in majority element and all other bits not set.
So, our majority element according to this is 0 1 0, which is 2 But actually majority element is not present in the array. So, we do one more pass of the array, to make sure this element is present more than n/2 times.
Here is the implementation of the above idea
C++
Java
Python3
C#
Javascript
#include <iostream>using namespace std; void findMajority(int arr[], int n){ // Number of bits in the integer int len = sizeof(int) * 8; // Variable to calculate majority element int number = 0; // Loop to iterate through all the bits of number for (int i = 0; i < len; i++) { int count = 0; // Loop to iterate through all elements in array // to count the total set bit // at position i from right for (int j = 0; j < n; j++) { if (arr[j] & (1 << i)) count++; } // If the total set bits exceeds n/2, // this bit should be present in majority Element. if (count > (n / 2)) number += (1 << i); } int count = 0; // iterate through array get // the count of candidate majority element for (int i = 0; i < n; i++) if (arr[i] == number) count++; // Verify if the count exceeds n/2 if (count > (n / 2)) cout << number; else cout << "Majority Element Not Present";} // Driver Programint main(){ int arr[] = { 3, 3, 4, 2, 4, 4, 2, 4, 4 }; int n = sizeof(arr) / sizeof(arr[0]); findMajority(arr, n); return 0;}
class GFG{ static void findMajority(int arr[], int n) { // Number of bits in the integer int len = 32; // Variable to calculate majority element int number = 0; // Loop to iterate through all the bits of number for (int i = 0; i < len; i++) { int count = 0; // Loop to iterate through all elements in array // to count the total set bit // at position i from right for (int j = 0; j < n; j++) { if ((arr[j] & (1 << i)) != 0) count++; } // If the total set bits exceeds n/2, // this bit should be present in majority Element. if (count > (n / 2)) number += (1 << i); } int count = 0; // iterate through array get // the count of candidate majority element for (int i = 0; i < n; i++) if (arr[i] == number) count++; // Verify if the count exceeds n/2 if (count > (n / 2)) System.out.println(number); else System.out.println("Majority Element Not Present"); } // Driver Code public static void main (String[] args) { int arr[] = { 3, 3, 4, 2, 4, 4, 2, 4, 4 }; int n = arr.length; findMajority(arr, n); }} // This code is contributed by AnkitRai01
def findMajority(arr, n): # Number of bits in the integer Len = 32 # Variable to calculate majority element number = 0 # Loop to iterate through # all the bits of number for i in range(Len): count = 0 # Loop to iterate through all elements # in array to count the total set bit # at position i from right for j in range(n): if (arr[j] & (1 << i)): count += 1 # If the total set bits exceeds n/2, # this bit should be present in # majority Element. if (count > (n // 2)): number += (1 << i) count = 0 # iterate through array get # the count of candidate majority element for i in range(n): if (arr[i] == number): count += 1 # Verify if the count exceeds n/2 if (count > (n // 2)): print(number) else: print("Majority Element Not Present") # Driver Codearr = [3, 3, 4, 2, 4, 4, 2, 4, 4]n = len(arr)findMajority(arr, n) # This code is contributed by Mohit Kumar
using System; class GFG{ static void findMajority(int []arr, int n) { // Number of bits in the integer int len = 32; // Variable to calculate majority element int number = 0; // Loop to iterate through all the bits of number for (int i = 0; i < len; i++) { int count = 0; // Loop to iterate through all elements // in array to count the total set bit // at position i from right for (int j = 0; j < n; j++) { if ((arr[j] & (1 << i)) != 0) count++; } // If the total set bits exceeds n/2, // this bit should be present in majority Element. if (countt > (n / 2)) number += (1 << i); } int count = 0; // iterate through array get // the count of candidate majority element for (int i = 0; i < n; i++) if (arr[i] == number) count++; // Verify if the count exceeds n/2 if (count > (n / 2)) Console.Write(number); else Console.Write("Majority Element Not Present"); } // Driver Code static public void Main () { int []arr = { 3, 3, 4, 2, 4, 4, 2, 4, 4 }; int n = arr.Length; findMajority(arr, n); }} // This code is contributed by @Tushi..
<script> function findMajority(arr, n){ // Number of bits in the integer let len = 32; // Variable to calculate majority element let number = 0; // Loop to iterate through all // the bits of number for(let i = 0; i < len; i++) { let countt = 0; // Loop to iterate through all elements // in array to count the total set bit // at position i from right for(let j = 0; j < n; j++) { if ((arr[j] & (1 << i)) != 0) countt++; } // If the total set bits exceeds n/2, // this bit should be present in // majority Element. if (countt > parseInt(n / 2, 10)) number += (1 << i); } let count = 0; // Iterate through array get // the count of candidate // majority element for(let i = 0; i < n; i++) if (arr[i] == number) count++; // Verify if the count exceeds n/2 if (count > parseInt(n / 2, 10)) document.write(number); else document.write("Majority Element Not Present");} // Driver Codelet arr = [ 3, 3, 4, 2, 4, 4, 2, 4, 4 ];let n = arr.length; findMajority(arr, n); // This code is contributed by decode2207 </script>
4
Time complexity : O(N) Space Complexity: O(1)
mohit kumar 29
ankthon
jit_t
akd27
decode2207
sagar0719kumar
setBitCount
Arrays
Bit Magic
Arrays
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Program to find sum of elements in a given array
Building Heap from Array
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
Cyclic Redundancy Check and Modulo-2 Division
|
[
{
"code": null,
"e": 24822,
"s": 24794,
"text": "\n12 Feb, 2022"
},
{
"code": null,
"e": 25031,
"s": 24822,
"text": "Pre-requisite: Majority Element, Majority Element | Set-2 (Hashing)Given an array of size N, find the majority element. The majority element is the element that appears more than n/2 times in the given array."
},
{
"code": null,
"e": 25043,
"s": 25031,
"text": "Examples: "
},
{
"code": null,
"e": 25151,
"s": 25043,
"text": "Input: {3, 3, 4, 2, 4, 4, 2, 4, 4}\nOutput: 4\n\nInput: {3, 3, 6, 2, 4, 4, 2, 4}\nOutput: No Majority Element\n "
},
{
"code": null,
"e": 25610,
"s": 25151,
"text": "Approach:In this post, we solve the problem with the help of binary representation of the numbers present in the array.The task is to find the element that appears more than n/2 times. So, it appears more than all other numbers combined.So, we starting from LSB (least significant bit) of every number of the array, we count in how many numbers of the array it is set. If any bit is set in more than n/2 numbers, then that bit is set in our majority element."
},
{
"code": null,
"e": 25772,
"s": 25610,
"text": "The above approach works because for all other numbers combined the set bit count can’t be more than n/2, as the majority element is present more than n/2 times."
},
{
"code": null,
"e": 25808,
"s": 25772,
"text": "Lets see with the help of example "
},
{
"code": null,
"e": 25996,
"s": 25808,
"text": "Input : {3, 3, 4, 2, 4, 4, 2, 4, 4}\nBinary representation of the same are:\n\n3 - 0 1 1\n3 - 0 1 1\n4 - 1 0 0\n2 - 0 1 0\n4 - 1 0 0\n4 - 1 0 0\n2 - 0 1 0\n4 - 1 0 0\n4 - 1 0 0\n----------\n - 5 4 0 "
},
{
"code": null,
"e": 26133,
"s": 25996,
"text": "Here n is 9, so n/2 = 4 and an only 3rd bit from right satisfy count>4 and hence set in majority element and all other bits are not set."
},
{
"code": null,
"e": 26300,
"s": 26133,
"text": "So, our majority element is 1 0 0, which is 4 But there more to it, This approach works when the majority element is present in the array. What if it is not present? "
},
{
"code": null,
"e": 26341,
"s": 26300,
"text": "Let’s see with the help of this example:"
},
{
"code": null,
"e": 26516,
"s": 26341,
"text": "Input : {3, 3, 6, 2, 4, 4, 2, 4}\nBinary representation of the same are:\n\n3 - 0 1 1\n3 - 0 1 1\n6 - 1 1 0\n2 - 0 1 0\n4 - 1 0 0\n4 - 1 0 0\n2 - 0 1 0\n4 - 1 0 0\n----------\n - 4 5 0 "
},
{
"code": null,
"e": 26666,
"s": 26516,
"text": "Here n is 8, so n/2 = 4 and an only 2nd bit from right satisfy count>4 and hence set it should be set in majority element and all other bits not set."
},
{
"code": null,
"e": 26886,
"s": 26666,
"text": "So, our majority element according to this is 0 1 0, which is 2 But actually majority element is not present in the array. So, we do one more pass of the array, to make sure this element is present more than n/2 times. "
},
{
"code": null,
"e": 26932,
"s": 26886,
"text": "Here is the implementation of the above idea "
},
{
"code": null,
"e": 26936,
"s": 26932,
"text": "C++"
},
{
"code": null,
"e": 26941,
"s": 26936,
"text": "Java"
},
{
"code": null,
"e": 26949,
"s": 26941,
"text": "Python3"
},
{
"code": null,
"e": 26952,
"s": 26949,
"text": "C#"
},
{
"code": null,
"e": 26963,
"s": 26952,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; void findMajority(int arr[], int n){ // Number of bits in the integer int len = sizeof(int) * 8; // Variable to calculate majority element int number = 0; // Loop to iterate through all the bits of number for (int i = 0; i < len; i++) { int count = 0; // Loop to iterate through all elements in array // to count the total set bit // at position i from right for (int j = 0; j < n; j++) { if (arr[j] & (1 << i)) count++; } // If the total set bits exceeds n/2, // this bit should be present in majority Element. if (count > (n / 2)) number += (1 << i); } int count = 0; // iterate through array get // the count of candidate majority element for (int i = 0; i < n; i++) if (arr[i] == number) count++; // Verify if the count exceeds n/2 if (count > (n / 2)) cout << number; else cout << \"Majority Element Not Present\";} // Driver Programint main(){ int arr[] = { 3, 3, 4, 2, 4, 4, 2, 4, 4 }; int n = sizeof(arr) / sizeof(arr[0]); findMajority(arr, n); return 0;}",
"e": 28157,
"s": 26963,
"text": null
},
{
"code": "class GFG{ static void findMajority(int arr[], int n) { // Number of bits in the integer int len = 32; // Variable to calculate majority element int number = 0; // Loop to iterate through all the bits of number for (int i = 0; i < len; i++) { int count = 0; // Loop to iterate through all elements in array // to count the total set bit // at position i from right for (int j = 0; j < n; j++) { if ((arr[j] & (1 << i)) != 0) count++; } // If the total set bits exceeds n/2, // this bit should be present in majority Element. if (count > (n / 2)) number += (1 << i); } int count = 0; // iterate through array get // the count of candidate majority element for (int i = 0; i < n; i++) if (arr[i] == number) count++; // Verify if the count exceeds n/2 if (count > (n / 2)) System.out.println(number); else System.out.println(\"Majority Element Not Present\"); } // Driver Code public static void main (String[] args) { int arr[] = { 3, 3, 4, 2, 4, 4, 2, 4, 4 }; int n = arr.length; findMajority(arr, n); }} // This code is contributed by AnkitRai01",
"e": 29598,
"s": 28157,
"text": null
},
{
"code": "def findMajority(arr, n): # Number of bits in the integer Len = 32 # Variable to calculate majority element number = 0 # Loop to iterate through # all the bits of number for i in range(Len): count = 0 # Loop to iterate through all elements # in array to count the total set bit # at position i from right for j in range(n): if (arr[j] & (1 << i)): count += 1 # If the total set bits exceeds n/2, # this bit should be present in # majority Element. if (count > (n // 2)): number += (1 << i) count = 0 # iterate through array get # the count of candidate majority element for i in range(n): if (arr[i] == number): count += 1 # Verify if the count exceeds n/2 if (count > (n // 2)): print(number) else: print(\"Majority Element Not Present\") # Driver Codearr = [3, 3, 4, 2, 4, 4, 2, 4, 4]n = len(arr)findMajority(arr, n) # This code is contributed by Mohit Kumar",
"e": 30667,
"s": 29598,
"text": null
},
{
"code": "using System; class GFG{ static void findMajority(int []arr, int n) { // Number of bits in the integer int len = 32; // Variable to calculate majority element int number = 0; // Loop to iterate through all the bits of number for (int i = 0; i < len; i++) { int count = 0; // Loop to iterate through all elements // in array to count the total set bit // at position i from right for (int j = 0; j < n; j++) { if ((arr[j] & (1 << i)) != 0) count++; } // If the total set bits exceeds n/2, // this bit should be present in majority Element. if (countt > (n / 2)) number += (1 << i); } int count = 0; // iterate through array get // the count of candidate majority element for (int i = 0; i < n; i++) if (arr[i] == number) count++; // Verify if the count exceeds n/2 if (count > (n / 2)) Console.Write(number); else Console.Write(\"Majority Element Not Present\"); } // Driver Code static public void Main () { int []arr = { 3, 3, 4, 2, 4, 4, 2, 4, 4 }; int n = arr.Length; findMajority(arr, n); }} // This code is contributed by @Tushi..",
"e": 32111,
"s": 30667,
"text": null
},
{
"code": "<script> function findMajority(arr, n){ // Number of bits in the integer let len = 32; // Variable to calculate majority element let number = 0; // Loop to iterate through all // the bits of number for(let i = 0; i < len; i++) { let countt = 0; // Loop to iterate through all elements // in array to count the total set bit // at position i from right for(let j = 0; j < n; j++) { if ((arr[j] & (1 << i)) != 0) countt++; } // If the total set bits exceeds n/2, // this bit should be present in // majority Element. if (countt > parseInt(n / 2, 10)) number += (1 << i); } let count = 0; // Iterate through array get // the count of candidate // majority element for(let i = 0; i < n; i++) if (arr[i] == number) count++; // Verify if the count exceeds n/2 if (count > parseInt(n / 2, 10)) document.write(number); else document.write(\"Majority Element Not Present\");} // Driver Codelet arr = [ 3, 3, 4, 2, 4, 4, 2, 4, 4 ];let n = arr.length; findMajority(arr, n); // This code is contributed by decode2207 </script>",
"e": 33363,
"s": 32111,
"text": null
},
{
"code": null,
"e": 33365,
"s": 33363,
"text": "4"
},
{
"code": null,
"e": 33414,
"s": 33367,
"text": "Time complexity : O(N) Space Complexity: O(1) "
},
{
"code": null,
"e": 33429,
"s": 33414,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 33437,
"s": 33429,
"text": "ankthon"
},
{
"code": null,
"e": 33443,
"s": 33437,
"text": "jit_t"
},
{
"code": null,
"e": 33449,
"s": 33443,
"text": "akd27"
},
{
"code": null,
"e": 33460,
"s": 33449,
"text": "decode2207"
},
{
"code": null,
"e": 33475,
"s": 33460,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 33487,
"s": 33475,
"text": "setBitCount"
},
{
"code": null,
"e": 33494,
"s": 33487,
"text": "Arrays"
},
{
"code": null,
"e": 33504,
"s": 33494,
"text": "Bit Magic"
},
{
"code": null,
"e": 33511,
"s": 33504,
"text": "Arrays"
},
{
"code": null,
"e": 33521,
"s": 33511,
"text": "Bit Magic"
},
{
"code": null,
"e": 33619,
"s": 33521,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33644,
"s": 33619,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 33664,
"s": 33644,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 33702,
"s": 33664,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 33751,
"s": 33702,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33776,
"s": 33751,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 33803,
"s": 33776,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 33849,
"s": 33803,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 33917,
"s": 33849,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 33946,
"s": 33917,
"text": "Count set bits in an integer"
}
] |
Displaying bar graphs using Matplotlib
|
In this program, we will plot a bar graph using the matplotlib library. The most important Step in solving matplotlib related problems using the matplotlib library is importing the matplotlib library. The syntax is −
import matplotlib.pyplot as plt
Pyplot is a collection of command style functions that make Matplotlib work like MATLAB
Step 1: Define a list of values.
Step 2: Use the bar() function in the matplotlib.pyplot library and define different parameters like height, width, etc.
Step 3: Label the axes using xlabel() and ylabel().
Step 3: Plot the graph using show().
import matplotlib.pyplot as plt
data_x = ['Mumbai', 'Delhi', 'Ahmedabad', 'Banglore']
data_y = [40, 35, 29, 32]
plt.xlabel("CITY")
plt.ylabel("POPULATION")
plt.title("BAR PLOT")
plt.bar(data_x, data_y, color='red')
plt.show()
|
[
{
"code": null,
"e": 1279,
"s": 1062,
"text": "In this program, we will plot a bar graph using the matplotlib library. The most important Step in solving matplotlib related problems using the matplotlib library is importing the matplotlib library. The syntax is −"
},
{
"code": null,
"e": 1311,
"s": 1279,
"text": "import matplotlib.pyplot as plt"
},
{
"code": null,
"e": 1399,
"s": 1311,
"text": "Pyplot is a collection of command style functions that make Matplotlib work like MATLAB"
},
{
"code": null,
"e": 1642,
"s": 1399,
"text": "Step 1: Define a list of values.\nStep 2: Use the bar() function in the matplotlib.pyplot library and define different parameters like height, width, etc.\nStep 3: Label the axes using xlabel() and ylabel().\nStep 3: Plot the graph using show()."
},
{
"code": null,
"e": 1871,
"s": 1642,
"text": "import matplotlib.pyplot as plt\n\ndata_x = ['Mumbai', 'Delhi', 'Ahmedabad', 'Banglore']\ndata_y = [40, 35, 29, 32]\n\nplt.xlabel(\"CITY\")\nplt.ylabel(\"POPULATION\")\nplt.title(\"BAR PLOT\")\n\nplt.bar(data_x, data_y, color='red')\nplt.show()"
}
] |
How to read and write Excel file in Node.js ? - GeeksforGeeks
|
10 Jan, 2022
Node.js is an open-source and cross-platform JavaScript runtime environment that can also be used to read from a file and write to a file which can be in txt, ods, xlsx, docx, etc format.
The following example covers how an excel file(.xlsx) file is read from an excel file and then converted into JSON and also to write to it. It can be achieved using a package called xlsx to achieve our goal.
Module Installation: You can install xlsx module using the following command:
npm install xlsx
Note: For the following example, text.xlsx is a dummy data file that has been used.
Filename: test.xlsx
Sheet 1:
Sheet 2:
So the excel file test.xlsx has 2 sheets, one having Student details and another having lecturer details.
Read Operation Filename: read.js
Javascript
// Requiring the moduleconst reader = require('xlsx') // Reading our test fileconst file = reader.readFile('./test.xlsx') let data = [] const sheets = file.SheetNames for(let i = 0; i < sheets.length; i++){ const temp = reader.utils.sheet_to_json( file.Sheets[file.SheetNames[i]]) temp.forEach((res) => { data.push(res) })} // Printing dataconsole.log(data)
Explanation: First, the npm module is included in the read.js file and then the excel file is read into a workbook i.e constant file in the above program.
The number of files in that particular excel file is available in the SheetNames property of the workbook. It can be accessed as follows:
const sheets = file.SheetNames // Here the value of the sheets will be 2
A for loop is run until the end of the excel file starting from the first page. One of the most important functions used in the code above is the sheet_to_json() function present in the utils module of the xlsx package. It accepts a worksheet object as a parameter and returns an array of JSON objects.
There is a forEach loop which iterates through every JSON object present in the array temp and pushes it into a variable data which would contain all the data in JSON format.
Finally, the data is printed or any other modification can be performed on the array of JSON objects.
Step to run the application:
Run the read.js file using the following command:
node read.js
Output:
Write Operation In the following example, we will convert an array of JSON objects into an excel sheet and append it to the file.
Filename: write.js
Javascript
// Requiring moduleconst reader = require('xlsx') // Reading our test fileconst file = reader.readFile('./test.xlsx') // Sample data setlet student_data = [{ Student:'Nikhil', Age:22, Branch:'ISE', Marks: 70},{ Student:'Amitha', Age:21, Branch:'EC', Marks:80}] const ws = reader.utils.json_to_sheet(student_data) reader.utils.book_append_sheet(file,ws,"Sheet3") // Writing to our filereader.writeFile(file,'./test.xlsx')
Explanation: Here we have an array of JSON objects called student_data. We use two main functions in this program i.e json_to_sheet() which accepts an array of objects and converts them into a worksheet and another function is the book_append_sheet() to append the worksheet into the workbook.
Finally, all the changes are written to the test.xlsx file using writeFile() function which takes a workbook and a excel file as input parameter.
Step to run the application:
Run the read.js file using the following command:
node write.js
Output: The final test.xlsx file would look something like this:
Sheet 1:
Sheet 2:
Sheet 3: We can see sheet 3 is appended into the test.xlsx as shown below:
marvelousprince012233
jaroslavloumaml
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Express.js res.render() Function
Roadmap to Become a Web Developer in 2022
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?
Top 10 Angular Libraries For Web Developers
|
[
{
"code": null,
"e": 24534,
"s": 24506,
"text": "\n10 Jan, 2022"
},
{
"code": null,
"e": 24722,
"s": 24534,
"text": "Node.js is an open-source and cross-platform JavaScript runtime environment that can also be used to read from a file and write to a file which can be in txt, ods, xlsx, docx, etc format."
},
{
"code": null,
"e": 24930,
"s": 24722,
"text": "The following example covers how an excel file(.xlsx) file is read from an excel file and then converted into JSON and also to write to it. It can be achieved using a package called xlsx to achieve our goal."
},
{
"code": null,
"e": 25008,
"s": 24930,
"text": "Module Installation: You can install xlsx module using the following command:"
},
{
"code": null,
"e": 25025,
"s": 25008,
"text": "npm install xlsx"
},
{
"code": null,
"e": 25109,
"s": 25025,
"text": "Note: For the following example, text.xlsx is a dummy data file that has been used."
},
{
"code": null,
"e": 25130,
"s": 25109,
"text": "Filename: test.xlsx "
},
{
"code": null,
"e": 25139,
"s": 25130,
"text": "Sheet 1:"
},
{
"code": null,
"e": 25148,
"s": 25139,
"text": "Sheet 2:"
},
{
"code": null,
"e": 25254,
"s": 25148,
"text": "So the excel file test.xlsx has 2 sheets, one having Student details and another having lecturer details."
},
{
"code": null,
"e": 25288,
"s": 25254,
"text": "Read Operation Filename: read.js "
},
{
"code": null,
"e": 25299,
"s": 25288,
"text": "Javascript"
},
{
"code": "// Requiring the moduleconst reader = require('xlsx') // Reading our test fileconst file = reader.readFile('./test.xlsx') let data = [] const sheets = file.SheetNames for(let i = 0; i < sheets.length; i++){ const temp = reader.utils.sheet_to_json( file.Sheets[file.SheetNames[i]]) temp.forEach((res) => { data.push(res) })} // Printing dataconsole.log(data)",
"e": 25680,
"s": 25299,
"text": null
},
{
"code": null,
"e": 25835,
"s": 25680,
"text": "Explanation: First, the npm module is included in the read.js file and then the excel file is read into a workbook i.e constant file in the above program."
},
{
"code": null,
"e": 25973,
"s": 25835,
"text": "The number of files in that particular excel file is available in the SheetNames property of the workbook. It can be accessed as follows:"
},
{
"code": null,
"e": 26047,
"s": 25973,
"text": "const sheets = file.SheetNames // Here the value of the sheets will be 2"
},
{
"code": null,
"e": 26350,
"s": 26047,
"text": "A for loop is run until the end of the excel file starting from the first page. One of the most important functions used in the code above is the sheet_to_json() function present in the utils module of the xlsx package. It accepts a worksheet object as a parameter and returns an array of JSON objects."
},
{
"code": null,
"e": 26525,
"s": 26350,
"text": "There is a forEach loop which iterates through every JSON object present in the array temp and pushes it into a variable data which would contain all the data in JSON format."
},
{
"code": null,
"e": 26627,
"s": 26525,
"text": "Finally, the data is printed or any other modification can be performed on the array of JSON objects."
},
{
"code": null,
"e": 26656,
"s": 26627,
"text": "Step to run the application:"
},
{
"code": null,
"e": 26706,
"s": 26656,
"text": "Run the read.js file using the following command:"
},
{
"code": null,
"e": 26719,
"s": 26706,
"text": "node read.js"
},
{
"code": null,
"e": 26727,
"s": 26719,
"text": "Output:"
},
{
"code": null,
"e": 26857,
"s": 26727,
"text": "Write Operation In the following example, we will convert an array of JSON objects into an excel sheet and append it to the file."
},
{
"code": null,
"e": 26876,
"s": 26857,
"text": "Filename: write.js"
},
{
"code": null,
"e": 26887,
"s": 26876,
"text": "Javascript"
},
{
"code": "// Requiring moduleconst reader = require('xlsx') // Reading our test fileconst file = reader.readFile('./test.xlsx') // Sample data setlet student_data = [{ Student:'Nikhil', Age:22, Branch:'ISE', Marks: 70},{ Student:'Amitha', Age:21, Branch:'EC', Marks:80}] const ws = reader.utils.json_to_sheet(student_data) reader.utils.book_append_sheet(file,ws,\"Sheet3\") // Writing to our filereader.writeFile(file,'./test.xlsx')",
"e": 27337,
"s": 26887,
"text": null
},
{
"code": null,
"e": 27631,
"s": 27337,
"text": "Explanation: Here we have an array of JSON objects called student_data. We use two main functions in this program i.e json_to_sheet() which accepts an array of objects and converts them into a worksheet and another function is the book_append_sheet() to append the worksheet into the workbook."
},
{
"code": null,
"e": 27777,
"s": 27631,
"text": "Finally, all the changes are written to the test.xlsx file using writeFile() function which takes a workbook and a excel file as input parameter."
},
{
"code": null,
"e": 27806,
"s": 27777,
"text": "Step to run the application:"
},
{
"code": null,
"e": 27856,
"s": 27806,
"text": "Run the read.js file using the following command:"
},
{
"code": null,
"e": 27870,
"s": 27856,
"text": "node write.js"
},
{
"code": null,
"e": 27936,
"s": 27870,
"text": "Output: The final test.xlsx file would look something like this: "
},
{
"code": null,
"e": 27945,
"s": 27936,
"text": "Sheet 1:"
},
{
"code": null,
"e": 27954,
"s": 27945,
"text": "Sheet 2:"
},
{
"code": null,
"e": 28029,
"s": 27954,
"text": "Sheet 3: We can see sheet 3 is appended into the test.xlsx as shown below:"
},
{
"code": null,
"e": 28051,
"s": 28029,
"text": "marvelousprince012233"
},
{
"code": null,
"e": 28067,
"s": 28051,
"text": "jaroslavloumaml"
},
{
"code": null,
"e": 28080,
"s": 28067,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 28088,
"s": 28080,
"text": "Node.js"
},
{
"code": null,
"e": 28105,
"s": 28088,
"text": "Web Technologies"
},
{
"code": null,
"e": 28203,
"s": 28105,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28212,
"s": 28203,
"text": "Comments"
},
{
"code": null,
"e": 28225,
"s": 28212,
"text": "Old Comments"
},
{
"code": null,
"e": 28262,
"s": 28225,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 28319,
"s": 28262,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 28373,
"s": 28319,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 28410,
"s": 28373,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 28443,
"s": 28410,
"text": "Express.js res.render() Function"
},
{
"code": null,
"e": 28485,
"s": 28443,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28547,
"s": 28485,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28590,
"s": 28547,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28640,
"s": 28590,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Best Python libraries for Machine Learning - GeeksforGeeks
|
24 Jan, 2022
Machine Learning, as the name suggests, is the science of programming a computer by which they are able to learn from different kinds of data. A more general definition given by Arthur Samuel is – “Machine Learning is the field of study that gives computers the ability to learn without being explicitly programmed.” They are typically used to solve various types of life problems. In the older days, people used to perform Machine Learning tasks by manually coding all the algorithms and mathematical and statistical formula. This made the process time consuming, tedious and inefficient. But in the modern days, it is become very much easy and efficient compared to the olden days by various python libraries, frameworks, and modules. Today, Python is one of the most popular programming languages for this task and it has replaced many languages in the industry, one of the reason is its vast collection of libraries. Python libraries that used in Machine Learning are:
Numpy
Scipy
Scikit-learn
Theano
TensorFlow
Keras
PyTorch
Pandas
Matplotlib
NumPy is a very popular python library for large multi-dimensional array and matrix processing, with the help of a large collection of high-level mathematical functions. It is very useful for fundamental scientific computations in Machine Learning. It is particularly useful for linear algebra, Fourier transform, and random number capabilities. High-end libraries like TensorFlow uses NumPy internally for manipulation of Tensors.
Python3
# Python program using NumPy# for some basic mathematical# operations import numpy as np # Creating two arrays of rank 2x = np.array([[1, 2], [3, 4]])y = np.array([[5, 6], [7, 8]]) # Creating two arrays of rank 1v = np.array([9, 10])w = np.array([11, 12]) # Inner product of vectorsprint(np.dot(v, w), "\n") # Matrix and Vector productprint(np.dot(x, v), "\n") # Matrix and matrix productprint(np.dot(x, y))
Output:
219
[29 67]
[[19 22]
[43 50]]
For more details refer to Numpy.
SciPy is a very popular library among Machine Learning enthusiasts as it contains different modules for optimization, linear algebra, integration and statistics. There is a difference between the SciPy library and the SciPy stack. The SciPy is one of the core packages that make up the SciPy stack. SciPy is also very useful for image manipulation.
Python3
# Python script using Scipy# for image manipulation from scipy.misc import imread, imsave, imresize # Read a JPEG image into a numpy arrayimg = imread('D:/Programs / cat.jpg') # path of the imageprint(img.dtype, img.shape) # Tinting the imageimg_tint = img * [1, 0.45, 0.3] # Saving the tinted imageimsave('D:/Programs / cat_tinted.jpg', img_tint) # Resizing the tinted image to be 300 x 300 pixelsimg_tint_resize = imresize(img_tint, (300, 300)) # Saving the resized tinted imageimsave('D:/Programs / cat_tinted_resized.jpg', img_tint_resize)
Original image:
Tinted image:
Resized tinted image:
For more details refer to documentation.
Scikit-learn is one of the most popular ML libraries for classical ML algorithms. It is built on top of two basic Python libraries, viz., NumPy and SciPy. Scikit-learn supports most of the supervised and unsupervised learning algorithms. Scikit-learn can also be used for data-mining and data-analysis, which makes it a great tool who is starting out with ML.
Python3
# Python script using Scikit-learn# for Decision Tree Classifier # Sample Decision Tree Classifierfrom sklearn import datasetsfrom sklearn import metricsfrom sklearn.tree import DecisionTreeClassifier # load the iris datasetsdataset = datasets.load_iris() # fit a CART model to the datamodel = DecisionTreeClassifier()model.fit(dataset.data, dataset.target)print(model) # make predictionsexpected = dataset.targetpredicted = model.predict(dataset.data) # summarize the fit of the modelprint(metrics.classification_report(expected, predicted))print(metrics.confusion_matrix(expected, predicted))
Output:
DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=None,
max_features=None, max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, presort=False, random_state=None,
splitter='best')
precision recall f1-score support
0 1.00 1.00 1.00 50
1 1.00 1.00 1.00 50
2 1.00 1.00 1.00 50
micro avg 1.00 1.00 1.00 150
macro avg 1.00 1.00 1.00 150
weighted avg 1.00 1.00 1.00 150
[[50 0 0]
[ 0 50 0]
[ 0 0 50]]
For more details refer to documentation.
We all know that Machine Learning is basically mathematics and statistics. Theano is a popular python library that is used to define, evaluate and optimize mathematical expressions involving multi-dimensional arrays in an efficient manner. It is achieved by optimizing the utilization of CPU and GPU. It is extensively used for unit-testing and self-verification to detect and diagnose different types of errors. Theano is a very powerful library that has been used in large-scale computationally intensive scientific projects for a long time but is simple and approachable enough to be used by individuals for their own projects.
Python3
# Python program using Theano# for computing a Logistic# Function import theanoimport theano.tensor as Tx = T.dmatrix('x')s = 1 / (1 + T.exp(-x))logistic = theano.function([x], s)logistic([[0, 1], [-1, -2]])
Output:
array([[0.5, 0.73105858],
[0.26894142, 0.11920292]])
For more details refer to documentation.
TensorFlow is a very popular open-source library for high performance numerical computation developed by the Google Brain team in Google. As the name suggests, Tensorflow is a framework that involves defining and running computations involving tensors. It can train and run deep neural networks that can be used to develop several AI applications. TensorFlow is widely used in the field of deep learning research and application.
Python3
# Python program using TensorFlow# for multiplying two arrays # import `tensorflow`import tensorflow as tf # Initialize two constantsx1 = tf.constant([1, 2, 3, 4])x2 = tf.constant([5, 6, 7, 8]) # Multiplyresult = tf.multiply(x1, x2) # Initialize the Sessionsess = tf.Session() # Print the resultprint(sess.run(result)) # Close the sessionsess.close()
Output:
[ 5 12 21 32]
For more details refer to documentation.
Keras is a very popular Machine Learning library for Python. It is a high-level neural networks API capable of running on top of TensorFlow, CNTK, or Theano. It can run seamlessly on both CPU and GPU. Keras makes it really for ML beginners to build and design a Neural Network. One of the best thing about Keras is that it allows for easy and fast prototyping.For more details refer to documentation.
PyTorch is a popular open-source Machine Learning library for Python based on Torch, which is an open-source Machine Learning library which is implemented in C with a wrapper in Lua. It has an extensive choice of tools and libraries that supports on Computer Vision, Natural Language Processing(NLP) and many more ML programs. It allows developers to perform computations on Tensors with GPU acceleration and also helps in creating computational graphs.
Python3
# Python program using PyTorch# for defining tensors fit a# two-layer network to random# data and calculating the loss import torch dtype = torch.floatdevice = torch.device("cpu")# device = torch.device("cuda:0") Uncomment this to run on GPU # N is batch size; D_in is input dimension;# H is hidden dimension; D_out is output dimension.N, D_in, H, D_out = 64, 1000, 100, 10 # Create random input and output datax = torch.random(N, D_in, device = device, dtype = dtype)y = torch.random(N, D_out, device = device, dtype = dtype) # Randomly initialize weightsw1 = torch.random(D_in, H, device = device, dtype = dtype)w2 = torch.random(H, D_out, device = device, dtype = dtype) learning_rate = 1e-6for t in range(500): # Forward pass: compute predicted y h = x.mm(w1) h_relu = h.clamp(min = 0) y_pred = h_relu.mm(w2) # Compute and print loss loss = (y_pred - y).pow(2).sum().item() print(t, loss) # Backprop to compute gradients of w1 and w2 with respect to loss grad_y_pred = 2.0 * (y_pred - y) grad_w2 = h_relu.t().mm(grad_y_pred) grad_h_relu = grad_y_pred.mm(w2.t()) grad_h = grad_h_relu.clone() grad_h[h < 0] = 0 grad_w1 = x.t().mm(grad_h) # Update weights using gradient descent w1 -= learning_rate * grad_w1 w2 -= learning_rate * grad_w2
Output:
0 47168344.0
1 46385584.0
2 43153576.0
...
...
...
497 3.987660602433607e-05
498 3.945609932998195e-05
499 3.897604619851336e-05
For more details refer to documentation.
Pandas is a popular Python library for data analysis. It is not directly related to Machine Learning. As we know that the dataset must be prepared before training. In this case, Pandas comes handy as it was developed specifically for data extraction and preparation. It provides high-level data structures and wide variety tools for data analysis. It provides many inbuilt methods for groping, combining and filtering data.
Python3
# Python program using Pandas for# arranging a given set of data# into a table # importing pandas as pdimport pandas as pd data = {"country": ["Brazil", "Russia", "India", "China", "South Africa"], "capital": ["Brasilia", "Moscow", "New Delhi", "Beijing", "Pretoria"], "area": [8.516, 17.10, 3.286, 9.597, 1.221], "population": [200.4, 143.5, 1252, 1357, 52.98] } data_table = pd.DataFrame(data)print(data_table)
Output:
For more details refer to Pandas.
Matplotlib is a very popular Python library for data visualization. Like Pandas, it is not directly related to Machine Learning. It particularly comes in handy when a programmer wants to visualize the patterns in the data. It is a 2D plotting library used for creating 2D graphs and plots. A module named pyplot makes it easy for programmers for plotting as it provides features to control line styles, font properties, formatting axes, etc. It provides various kinds of graphs and plots for data visualization, viz., histogram, error charts, bar chats, etc,
Python3
# Python program using Matplotlib# for forming a linear plot # importing the necessary packages and modulesimport matplotlib.pyplot as pltimport numpy as np # Prepare the datax = np.linspace(0, 10, 100) # Plot the dataplt.plot(x, x, label ='linear') # Add a legendplt.legend() # Show the plotplt.show()
Output:
For more details refer to documentation.
Akanksha_Rai
adnanirshad158
rs1686740
sagar0719kumar
rkbhola5
Python-Library
Technical Scripter 2018
Advanced Computer Subject
Machine Learning
Python
Technical Scripter
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Copying Files to and from Docker Containers
System Design Tutorial
ML | Underfitting and Overfitting
ML | Label Encoding of datasets in Python
Docker - COPY Instruction
Agents in Artificial Intelligence
Difference between Informed and Uninformed Search in AI
Search Algorithms in AI
Deploy Machine Learning Model using Flask
Elbow Method for optimal value of k in KMeans
|
[
{
"code": null,
"e": 23835,
"s": 23807,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 24810,
"s": 23835,
"text": "Machine Learning, as the name suggests, is the science of programming a computer by which they are able to learn from different kinds of data. A more general definition given by Arthur Samuel is – “Machine Learning is the field of study that gives computers the ability to learn without being explicitly programmed.” They are typically used to solve various types of life problems. In the older days, people used to perform Machine Learning tasks by manually coding all the algorithms and mathematical and statistical formula. This made the process time consuming, tedious and inefficient. But in the modern days, it is become very much easy and efficient compared to the olden days by various python libraries, frameworks, and modules. Today, Python is one of the most popular programming languages for this task and it has replaced many languages in the industry, one of the reason is its vast collection of libraries. Python libraries that used in Machine Learning are: "
},
{
"code": null,
"e": 24816,
"s": 24810,
"text": "Numpy"
},
{
"code": null,
"e": 24822,
"s": 24816,
"text": "Scipy"
},
{
"code": null,
"e": 24835,
"s": 24822,
"text": "Scikit-learn"
},
{
"code": null,
"e": 24842,
"s": 24835,
"text": "Theano"
},
{
"code": null,
"e": 24853,
"s": 24842,
"text": "TensorFlow"
},
{
"code": null,
"e": 24859,
"s": 24853,
"text": "Keras"
},
{
"code": null,
"e": 24867,
"s": 24859,
"text": "PyTorch"
},
{
"code": null,
"e": 24874,
"s": 24867,
"text": "Pandas"
},
{
"code": null,
"e": 24885,
"s": 24874,
"text": "Matplotlib"
},
{
"code": null,
"e": 25323,
"s": 24889,
"text": "NumPy is a very popular python library for large multi-dimensional array and matrix processing, with the help of a large collection of high-level mathematical functions. It is very useful for fundamental scientific computations in Machine Learning. It is particularly useful for linear algebra, Fourier transform, and random number capabilities. High-end libraries like TensorFlow uses NumPy internally for manipulation of Tensors. "
},
{
"code": null,
"e": 25331,
"s": 25323,
"text": "Python3"
},
{
"code": "# Python program using NumPy# for some basic mathematical# operations import numpy as np # Creating two arrays of rank 2x = np.array([[1, 2], [3, 4]])y = np.array([[5, 6], [7, 8]]) # Creating two arrays of rank 1v = np.array([9, 10])w = np.array([11, 12]) # Inner product of vectorsprint(np.dot(v, w), \"\\n\") # Matrix and Vector productprint(np.dot(x, v), \"\\n\") # Matrix and matrix productprint(np.dot(x, y))",
"e": 25739,
"s": 25331,
"text": null
},
{
"code": null,
"e": 25749,
"s": 25739,
"text": "Output: "
},
{
"code": null,
"e": 25784,
"s": 25749,
"text": "219 \n\n[29 67] \n\n[[19 22]\n [43 50]]"
},
{
"code": null,
"e": 25821,
"s": 25784,
"text": "For more details refer to Numpy. "
},
{
"code": null,
"e": 26174,
"s": 25823,
"text": "SciPy is a very popular library among Machine Learning enthusiasts as it contains different modules for optimization, linear algebra, integration and statistics. There is a difference between the SciPy library and the SciPy stack. The SciPy is one of the core packages that make up the SciPy stack. SciPy is also very useful for image manipulation. "
},
{
"code": null,
"e": 26182,
"s": 26174,
"text": "Python3"
},
{
"code": "# Python script using Scipy# for image manipulation from scipy.misc import imread, imsave, imresize # Read a JPEG image into a numpy arrayimg = imread('D:/Programs / cat.jpg') # path of the imageprint(img.dtype, img.shape) # Tinting the imageimg_tint = img * [1, 0.45, 0.3] # Saving the tinted imageimsave('D:/Programs / cat_tinted.jpg', img_tint) # Resizing the tinted image to be 300 x 300 pixelsimg_tint_resize = imresize(img_tint, (300, 300)) # Saving the resized tinted imageimsave('D:/Programs / cat_tinted_resized.jpg', img_tint_resize)",
"e": 26726,
"s": 26182,
"text": null
},
{
"code": null,
"e": 26744,
"s": 26726,
"text": "Original image: "
},
{
"code": null,
"e": 26760,
"s": 26744,
"text": "Tinted image: "
},
{
"code": null,
"e": 26784,
"s": 26760,
"text": "Resized tinted image: "
},
{
"code": null,
"e": 26829,
"s": 26784,
"text": "For more details refer to documentation. "
},
{
"code": null,
"e": 27193,
"s": 26831,
"text": "Scikit-learn is one of the most popular ML libraries for classical ML algorithms. It is built on top of two basic Python libraries, viz., NumPy and SciPy. Scikit-learn supports most of the supervised and unsupervised learning algorithms. Scikit-learn can also be used for data-mining and data-analysis, which makes it a great tool who is starting out with ML. "
},
{
"code": null,
"e": 27201,
"s": 27193,
"text": "Python3"
},
{
"code": "# Python script using Scikit-learn# for Decision Tree Classifier # Sample Decision Tree Classifierfrom sklearn import datasetsfrom sklearn import metricsfrom sklearn.tree import DecisionTreeClassifier # load the iris datasetsdataset = datasets.load_iris() # fit a CART model to the datamodel = DecisionTreeClassifier()model.fit(dataset.data, dataset.target)print(model) # make predictionsexpected = dataset.targetpredicted = model.predict(dataset.data) # summarize the fit of the modelprint(metrics.classification_report(expected, predicted))print(metrics.confusion_matrix(expected, predicted))",
"e": 27796,
"s": 27201,
"text": null
},
{
"code": null,
"e": 27806,
"s": 27796,
"text": "Output: "
},
{
"code": null,
"e": 28574,
"s": 27806,
"text": "DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=None,\n max_features=None, max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, presort=False, random_state=None,\n splitter='best')\n precision recall f1-score support\n\n 0 1.00 1.00 1.00 50\n 1 1.00 1.00 1.00 50\n 2 1.00 1.00 1.00 50\n\n micro avg 1.00 1.00 1.00 150\n macro avg 1.00 1.00 1.00 150\nweighted avg 1.00 1.00 1.00 150\n\n[[50 0 0]\n [ 0 50 0]\n [ 0 0 50]]"
},
{
"code": null,
"e": 28621,
"s": 28574,
"text": " For more details refer to documentation. "
},
{
"code": null,
"e": 29256,
"s": 28623,
"text": "We all know that Machine Learning is basically mathematics and statistics. Theano is a popular python library that is used to define, evaluate and optimize mathematical expressions involving multi-dimensional arrays in an efficient manner. It is achieved by optimizing the utilization of CPU and GPU. It is extensively used for unit-testing and self-verification to detect and diagnose different types of errors. Theano is a very powerful library that has been used in large-scale computationally intensive scientific projects for a long time but is simple and approachable enough to be used by individuals for their own projects. "
},
{
"code": null,
"e": 29264,
"s": 29256,
"text": "Python3"
},
{
"code": "# Python program using Theano# for computing a Logistic# Function import theanoimport theano.tensor as Tx = T.dmatrix('x')s = 1 / (1 + T.exp(-x))logistic = theano.function([x], s)logistic([[0, 1], [-1, -2]])",
"e": 29472,
"s": 29264,
"text": null
},
{
"code": null,
"e": 29482,
"s": 29472,
"text": "Output: "
},
{
"code": null,
"e": 29542,
"s": 29482,
"text": "array([[0.5, 0.73105858],\n [0.26894142, 0.11920292]])"
},
{
"code": null,
"e": 29587,
"s": 29542,
"text": "For more details refer to documentation. "
},
{
"code": null,
"e": 30021,
"s": 29589,
"text": "TensorFlow is a very popular open-source library for high performance numerical computation developed by the Google Brain team in Google. As the name suggests, Tensorflow is a framework that involves defining and running computations involving tensors. It can train and run deep neural networks that can be used to develop several AI applications. TensorFlow is widely used in the field of deep learning research and application. "
},
{
"code": null,
"e": 30029,
"s": 30021,
"text": "Python3"
},
{
"code": "# Python program using TensorFlow# for multiplying two arrays # import `tensorflow`import tensorflow as tf # Initialize two constantsx1 = tf.constant([1, 2, 3, 4])x2 = tf.constant([5, 6, 7, 8]) # Multiplyresult = tf.multiply(x1, x2) # Initialize the Sessionsess = tf.Session() # Print the resultprint(sess.run(result)) # Close the sessionsess.close()",
"e": 30382,
"s": 30029,
"text": null
},
{
"code": null,
"e": 30392,
"s": 30382,
"text": "Output: "
},
{
"code": null,
"e": 30406,
"s": 30392,
"text": "[ 5 12 21 32]"
},
{
"code": null,
"e": 30451,
"s": 30406,
"text": "For more details refer to documentation. "
},
{
"code": null,
"e": 30858,
"s": 30453,
"text": "Keras is a very popular Machine Learning library for Python. It is a high-level neural networks API capable of running on top of TensorFlow, CNTK, or Theano. It can run seamlessly on both CPU and GPU. Keras makes it really for ML beginners to build and design a Neural Network. One of the best thing about Keras is that it allows for easy and fast prototyping.For more details refer to documentation. "
},
{
"code": null,
"e": 31316,
"s": 30860,
"text": "PyTorch is a popular open-source Machine Learning library for Python based on Torch, which is an open-source Machine Learning library which is implemented in C with a wrapper in Lua. It has an extensive choice of tools and libraries that supports on Computer Vision, Natural Language Processing(NLP) and many more ML programs. It allows developers to perform computations on Tensors with GPU acceleration and also helps in creating computational graphs. "
},
{
"code": null,
"e": 31324,
"s": 31316,
"text": "Python3"
},
{
"code": "# Python program using PyTorch# for defining tensors fit a# two-layer network to random# data and calculating the loss import torch dtype = torch.floatdevice = torch.device(\"cpu\")# device = torch.device(\"cuda:0\") Uncomment this to run on GPU # N is batch size; D_in is input dimension;# H is hidden dimension; D_out is output dimension.N, D_in, H, D_out = 64, 1000, 100, 10 # Create random input and output datax = torch.random(N, D_in, device = device, dtype = dtype)y = torch.random(N, D_out, device = device, dtype = dtype) # Randomly initialize weightsw1 = torch.random(D_in, H, device = device, dtype = dtype)w2 = torch.random(H, D_out, device = device, dtype = dtype) learning_rate = 1e-6for t in range(500): # Forward pass: compute predicted y h = x.mm(w1) h_relu = h.clamp(min = 0) y_pred = h_relu.mm(w2) # Compute and print loss loss = (y_pred - y).pow(2).sum().item() print(t, loss) # Backprop to compute gradients of w1 and w2 with respect to loss grad_y_pred = 2.0 * (y_pred - y) grad_w2 = h_relu.t().mm(grad_y_pred) grad_h_relu = grad_y_pred.mm(w2.t()) grad_h = grad_h_relu.clone() grad_h[h < 0] = 0 grad_w1 = x.t().mm(grad_h) # Update weights using gradient descent w1 -= learning_rate * grad_w1 w2 -= learning_rate * grad_w2",
"e": 32619,
"s": 31324,
"text": null
},
{
"code": null,
"e": 32629,
"s": 32619,
"text": "Output: "
},
{
"code": null,
"e": 32758,
"s": 32629,
"text": "0 47168344.0\n1 46385584.0\n2 43153576.0\n...\n...\n...\n497 3.987660602433607e-05\n498 3.945609932998195e-05\n499 3.897604619851336e-05"
},
{
"code": null,
"e": 32803,
"s": 32758,
"text": "For more details refer to documentation. "
},
{
"code": null,
"e": 33231,
"s": 32805,
"text": "Pandas is a popular Python library for data analysis. It is not directly related to Machine Learning. As we know that the dataset must be prepared before training. In this case, Pandas comes handy as it was developed specifically for data extraction and preparation. It provides high-level data structures and wide variety tools for data analysis. It provides many inbuilt methods for groping, combining and filtering data. "
},
{
"code": null,
"e": 33239,
"s": 33231,
"text": "Python3"
},
{
"code": "# Python program using Pandas for# arranging a given set of data# into a table # importing pandas as pdimport pandas as pd data = {\"country\": [\"Brazil\", \"Russia\", \"India\", \"China\", \"South Africa\"], \"capital\": [\"Brasilia\", \"Moscow\", \"New Delhi\", \"Beijing\", \"Pretoria\"], \"area\": [8.516, 17.10, 3.286, 9.597, 1.221], \"population\": [200.4, 143.5, 1252, 1357, 52.98] } data_table = pd.DataFrame(data)print(data_table)",
"e": 33671,
"s": 33239,
"text": null
},
{
"code": null,
"e": 33681,
"s": 33671,
"text": "Output: "
},
{
"code": null,
"e": 33719,
"s": 33681,
"text": "For more details refer to Pandas. "
},
{
"code": null,
"e": 34282,
"s": 33721,
"text": "Matplotlib is a very popular Python library for data visualization. Like Pandas, it is not directly related to Machine Learning. It particularly comes in handy when a programmer wants to visualize the patterns in the data. It is a 2D plotting library used for creating 2D graphs and plots. A module named pyplot makes it easy for programmers for plotting as it provides features to control line styles, font properties, formatting axes, etc. It provides various kinds of graphs and plots for data visualization, viz., histogram, error charts, bar chats, etc, "
},
{
"code": null,
"e": 34290,
"s": 34282,
"text": "Python3"
},
{
"code": "# Python program using Matplotlib# for forming a linear plot # importing the necessary packages and modulesimport matplotlib.pyplot as pltimport numpy as np # Prepare the datax = np.linspace(0, 10, 100) # Plot the dataplt.plot(x, x, label ='linear') # Add a legendplt.legend() # Show the plotplt.show()",
"e": 34594,
"s": 34290,
"text": null
},
{
"code": null,
"e": 34604,
"s": 34594,
"text": "Output: "
},
{
"code": null,
"e": 34646,
"s": 34604,
"text": "For more details refer to documentation. "
},
{
"code": null,
"e": 34659,
"s": 34646,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 34674,
"s": 34659,
"text": "adnanirshad158"
},
{
"code": null,
"e": 34684,
"s": 34674,
"text": "rs1686740"
},
{
"code": null,
"e": 34699,
"s": 34684,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 34708,
"s": 34699,
"text": "rkbhola5"
},
{
"code": null,
"e": 34723,
"s": 34708,
"text": "Python-Library"
},
{
"code": null,
"e": 34747,
"s": 34723,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 34773,
"s": 34747,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 34790,
"s": 34773,
"text": "Machine Learning"
},
{
"code": null,
"e": 34797,
"s": 34790,
"text": "Python"
},
{
"code": null,
"e": 34816,
"s": 34797,
"text": "Technical Scripter"
},
{
"code": null,
"e": 34833,
"s": 34816,
"text": "Machine Learning"
},
{
"code": null,
"e": 34931,
"s": 34833,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34940,
"s": 34931,
"text": "Comments"
},
{
"code": null,
"e": 34953,
"s": 34940,
"text": "Old Comments"
},
{
"code": null,
"e": 34997,
"s": 34953,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 35020,
"s": 34997,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 35054,
"s": 35020,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 35096,
"s": 35054,
"text": "ML | Label Encoding of datasets in Python"
},
{
"code": null,
"e": 35122,
"s": 35096,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 35156,
"s": 35122,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 35212,
"s": 35156,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 35236,
"s": 35212,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 35278,
"s": 35236,
"text": "Deploy Machine Learning Model using Flask"
}
] |
How does JavaScript focus() method works?
|
Javascript focus() methods helps to highlight a HTML form element. It sets the element as an active element in the current document. In current documentation, focus can be applied to only one single element. The focus can be applied either to a text, a button, etc.
element.focus(options);
In the following example, initially, the text "Tutorialspoint" is in an anchor tag 'a', which as an id called 'focus'. Later on, a function is declared in which the id is called using a DOM method and focus() method is applied on it to change the color of text "Tutorialspoint" to red. Here a button is used for the click event.
Live Demo
<html>
<head>
<style>
a:focus, a:active {
color: red;
}
</style>
</head>
<body>
<a href="http://www.tutorialspoint.com/" id="focus">Tutorialspoint</a>
<input type="button" value="getfocus" onclick="getfo()">
<script>
function getfo() {
document.getElementById("focus").focus();
}
</script>
</body>
</html>
After executing the above code we will get the following image displayed on the screen.
Once we click on the get focus button we will get the following output.
|
[
{
"code": null,
"e": 1330,
"s": 1062,
"text": "Javascript focus() methods helps to highlight a HTML form element. It sets the element as an active element in the current document. In current documentation, focus can be applied to only one single element. The focus can be applied either to a text, a button, etc. "
},
{
"code": null,
"e": 1354,
"s": 1330,
"text": "element.focus(options);"
},
{
"code": null,
"e": 1683,
"s": 1354,
"text": "In the following example, initially, the text \"Tutorialspoint\" is in an anchor tag 'a', which as an id called 'focus'. Later on, a function is declared in which the id is called using a DOM method and focus() method is applied on it to change the color of text \"Tutorialspoint\" to red. Here a button is used for the click event."
},
{
"code": null,
"e": 1693,
"s": 1683,
"text": "Live Demo"
},
{
"code": null,
"e": 2023,
"s": 1693,
"text": "<html>\n<head>\n<style>\n a:focus, a:active {\n color: red;\n }\n</style>\n</head>\n<body>\n<a href=\"http://www.tutorialspoint.com/\" id=\"focus\">Tutorialspoint</a>\n<input type=\"button\" value=\"getfocus\" onclick=\"getfo()\">\n<script>\n function getfo() {\n document.getElementById(\"focus\").focus();\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2111,
"s": 2023,
"text": "After executing the above code we will get the following image displayed on the screen."
},
{
"code": null,
"e": 2183,
"s": 2111,
"text": "Once we click on the get focus button we will get the following output."
}
] |
NLP | Using dateutil to parse dates. - GeeksforGeeks
|
18 Jun, 2019
The parser module can parse datetime strings in many more formats. There can be no better library than dateutil to parse dates and times in Python. To lookup the timezones, the tz module provides everything. When these modules are combined, they make it very easy to parse strings into timezone-aware datetime objects.
Installation :dateutil can be installed using pip or easy_install, that is, sudo pip install dateutil==2.0 or sudo easy_install dateutil==2.0. 2.0 version for Python 3 compatibility is required. The complete documentation can be found at http://labix.org/python-dateutil.
Code: Parsing Examples
# importing libraryfrom dateutil import parser print (parser.parse('Thu Sep 25 10:36:28 2010')) print (parser.parse('Thursday, 25. September 2010 10:36AM')) print (parser.parse('9 / 25 / 2010 10:36:28')) print (parser.parse('9 / 25 / 2010')) print (parser.parse('2010-09-25T10:36:28Z'))
Output :
datetime.datetime(2010, 9, 25, 10, 36, 28)
datetime.datetime(2010, 9, 25, 10, 36)
datetime.datetime(2010, 9, 25, 10, 36, 28)
datetime.datetime(2010, 9, 25, 0, 0)
datetime.datetime(2010, 9, 25, 10, 36, 28, tzinfo=tzutc())
All it takes is importing the parser module and calling the parse() function with a datetime string. The parser can return a sensible datetime object, but it cannot parse the string, it will raise a ValueError.How it works :
The parser instead of looking for recognizable tokens, guess what those tokens refer to. It doesn’t use regular expressions.
The order of these tokens matters as it uses a date format that looks like Month/Day/Year (the default order), while others use a Day/Month/Year format.
The parse() function takes an optional keyword argument, dayfirst, which defaults to False to deal with this problem.
It can correctly parse dates in the latter format if it is set to True.
parser.parse('16 / 6/2019', dayfirst = True)
Output :
datetime.datetime(2016, 6, 16, 0, 0)
Another ordering issue can occur with two-digit years. but ’11-6-19′ is an ambiguous date format. Since dateutil defaults to the Month-Day-Year format, ’11-6-19′ is parsed to the year 2019. But if yearfirst = True is passed into parse(), it can be parsed to the year 2011.
print (parser.parse('11-6-19'))print (parser.parse('10-6-25', yearfirst = True))
Output :
datetime.datetime(2019, 11, 6, 0, 0)
datetime.datetime(2011, 6, 19, 0, 0)
dateutil parser can also do fuzzy parsing and allows to ignore extraneous characters in a datetime string. parse() will raise a ValueError with the default value of False, when it encounters unknown tokens. A datetime object can usually be returned, if fuzzy = True.
Python-nltk
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Intuition of Adam Optimizer
CNN | Introduction to Pooling Layer
Convolutional Neural Network (CNN) in Machine Learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 25589,
"s": 25561,
"text": "\n18 Jun, 2019"
},
{
"code": null,
"e": 25908,
"s": 25589,
"text": "The parser module can parse datetime strings in many more formats. There can be no better library than dateutil to parse dates and times in Python. To lookup the timezones, the tz module provides everything. When these modules are combined, they make it very easy to parse strings into timezone-aware datetime objects."
},
{
"code": null,
"e": 26180,
"s": 25908,
"text": "Installation :dateutil can be installed using pip or easy_install, that is, sudo pip install dateutil==2.0 or sudo easy_install dateutil==2.0. 2.0 version for Python 3 compatibility is required. The complete documentation can be found at http://labix.org/python-dateutil."
},
{
"code": null,
"e": 26203,
"s": 26180,
"text": "Code: Parsing Examples"
},
{
"code": "# importing libraryfrom dateutil import parser print (parser.parse('Thu Sep 25 10:36:28 2010')) print (parser.parse('Thursday, 25. September 2010 10:36AM')) print (parser.parse('9 / 25 / 2010 10:36:28')) print (parser.parse('9 / 25 / 2010')) print (parser.parse('2010-09-25T10:36:28Z'))",
"e": 26495,
"s": 26203,
"text": null
},
{
"code": null,
"e": 26504,
"s": 26495,
"text": "Output :"
},
{
"code": null,
"e": 26725,
"s": 26504,
"text": "datetime.datetime(2010, 9, 25, 10, 36, 28)\ndatetime.datetime(2010, 9, 25, 10, 36)\ndatetime.datetime(2010, 9, 25, 10, 36, 28)\ndatetime.datetime(2010, 9, 25, 0, 0)\ndatetime.datetime(2010, 9, 25, 10, 36, 28, tzinfo=tzutc())"
},
{
"code": null,
"e": 26950,
"s": 26725,
"text": "All it takes is importing the parser module and calling the parse() function with a datetime string. The parser can return a sensible datetime object, but it cannot parse the string, it will raise a ValueError.How it works :"
},
{
"code": null,
"e": 27075,
"s": 26950,
"text": "The parser instead of looking for recognizable tokens, guess what those tokens refer to. It doesn’t use regular expressions."
},
{
"code": null,
"e": 27228,
"s": 27075,
"text": "The order of these tokens matters as it uses a date format that looks like Month/Day/Year (the default order), while others use a Day/Month/Year format."
},
{
"code": null,
"e": 27346,
"s": 27228,
"text": "The parse() function takes an optional keyword argument, dayfirst, which defaults to False to deal with this problem."
},
{
"code": null,
"e": 27418,
"s": 27346,
"text": "It can correctly parse dates in the latter format if it is set to True."
},
{
"code": "parser.parse('16 / 6/2019', dayfirst = True)",
"e": 27463,
"s": 27418,
"text": null
},
{
"code": null,
"e": 27472,
"s": 27463,
"text": "Output :"
},
{
"code": null,
"e": 27509,
"s": 27472,
"text": "datetime.datetime(2016, 6, 16, 0, 0)"
},
{
"code": null,
"e": 27782,
"s": 27509,
"text": "Another ordering issue can occur with two-digit years. but ’11-6-19′ is an ambiguous date format. Since dateutil defaults to the Month-Day-Year format, ’11-6-19′ is parsed to the year 2019. But if yearfirst = True is passed into parse(), it can be parsed to the year 2011."
},
{
"code": "print (parser.parse('11-6-19'))print (parser.parse('10-6-25', yearfirst = True))",
"e": 27863,
"s": 27782,
"text": null
},
{
"code": null,
"e": 27872,
"s": 27863,
"text": "Output :"
},
{
"code": null,
"e": 27946,
"s": 27872,
"text": "datetime.datetime(2019, 11, 6, 0, 0)\ndatetime.datetime(2011, 6, 19, 0, 0)"
},
{
"code": null,
"e": 28213,
"s": 27946,
"text": "dateutil parser can also do fuzzy parsing and allows to ignore extraneous characters in a datetime string. parse() will raise a ValueError with the default value of False, when it encounters unknown tokens. A datetime object can usually be returned, if fuzzy = True."
},
{
"code": null,
"e": 28225,
"s": 28213,
"text": "Python-nltk"
},
{
"code": null,
"e": 28242,
"s": 28225,
"text": "Machine Learning"
},
{
"code": null,
"e": 28249,
"s": 28242,
"text": "Python"
},
{
"code": null,
"e": 28266,
"s": 28249,
"text": "Machine Learning"
},
{
"code": null,
"e": 28364,
"s": 28266,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28405,
"s": 28364,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 28438,
"s": 28405,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 28466,
"s": 28438,
"text": "Intuition of Adam Optimizer"
},
{
"code": null,
"e": 28502,
"s": 28466,
"text": "CNN | Introduction to Pooling Layer"
},
{
"code": null,
"e": 28557,
"s": 28502,
"text": "Convolutional Neural Network (CNN) in Machine Learning"
},
{
"code": null,
"e": 28585,
"s": 28557,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 28635,
"s": 28585,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 28657,
"s": 28635,
"text": "Python map() function"
}
] |
Java Program For Hexadecimal to Decimal Conversion - GeeksforGeeks
|
09 Mar, 2021
Given a Hexadecimal number N, convert N into an equivalent decimal number i.e convert the number with base value 16 to base value 10. The decimal number system uses 10 digits 0-9 and the Hexadecimal number system uses 0-9, A-F to represent any numeric value.
Illustration:
Input : 1AB
Output: 427
Input : 1A
Output: 26
Approach:
The idea is to extract the digits of a given hexadecimal number starting from the rightmost digit.Keep a variable ‘dec_value’. At the time of extracting digits from the hexadecimal number, multiply the digit with the proper base (Power of 16) and add it to the above variable taken that is ‘dec_value’. In the end, the variable ‘dec_value’ will store the required decimal number.
The idea is to extract the digits of a given hexadecimal number starting from the rightmost digit.
Keep a variable ‘dec_value’.
At the time of extracting digits from the hexadecimal number, multiply the digit with the proper base (Power of 16) and add it to the above variable taken that is ‘dec_value’.
In the end, the variable ‘dec_value’ will store the required decimal number.
convert hexadecimal number ( 1AB ) to equivalent decimal value
Implementation:
Example
Java
// Java program to convert Hexadecimal to Decimal Number // Importing input output classesimport java.io.*; // Main classclass GFG { // Method // To convert hexadecimal to decimal static int hexadecimalToDecimal(String hexVal) { // Storing the length of the int len = hexVal.length(); // Initializing base value to 1, i.e 16^0 int base = 1; // Initially declaring and initializing // decimal value to zero int dec_val = 0; // Extracting characters as // digits from last character for (int i = len - 1; i >= 0; i--) { // Condition check // Case 1 // If character lies in '0'-'9', converting // it to integral 0-9 by subtracting 48 from // ASCII value if (hexVal.charAt(i) >= '0' && hexVal.charAt(i) <= '9') { dec_val += (hexVal.charAt(i) - 48) * base; // Incrementing base by power base = base * 16; } // Case 2 // if case 1 is bypassed // Now, if character lies in 'A'-'F' , // converting it to integral 10 - 15 by // subtracting 55 from ASCII value else if (hexVal.charAt(i) >= 'A' && hexVal.charAt(i) <= 'F') { dec_val += (hexVal.charAt(i) - 55) * base; // Incrementing base by power base = base * 16; } } // Returning the decimal value return dec_val; } // Method 2 // Main driver method public static void main(String[] args) { // Custom input hexadecimal number to be // converted into decimal number String hexNum = "1A"; // Calling the above method to convert and // alongside printing the hexadecimal number System.out.println(hexadecimalToDecimal(hexNum)); }}
26
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n09 Mar, 2021"
},
{
"code": null,
"e": 25484,
"s": 25225,
"text": "Given a Hexadecimal number N, convert N into an equivalent decimal number i.e convert the number with base value 16 to base value 10. The decimal number system uses 10 digits 0-9 and the Hexadecimal number system uses 0-9, A-F to represent any numeric value."
},
{
"code": null,
"e": 25499,
"s": 25484,
"text": "Illustration: "
},
{
"code": null,
"e": 25546,
"s": 25499,
"text": "Input : 1AB\nOutput: 427\n\nInput : 1A\nOutput: 26"
},
{
"code": null,
"e": 25556,
"s": 25546,
"text": "Approach:"
},
{
"code": null,
"e": 25937,
"s": 25556,
"text": "The idea is to extract the digits of a given hexadecimal number starting from the rightmost digit.Keep a variable ‘dec_value’. At the time of extracting digits from the hexadecimal number, multiply the digit with the proper base (Power of 16) and add it to the above variable taken that is ‘dec_value’. In the end, the variable ‘dec_value’ will store the required decimal number. "
},
{
"code": null,
"e": 26036,
"s": 25937,
"text": "The idea is to extract the digits of a given hexadecimal number starting from the rightmost digit."
},
{
"code": null,
"e": 26066,
"s": 26036,
"text": "Keep a variable ‘dec_value’. "
},
{
"code": null,
"e": 26243,
"s": 26066,
"text": "At the time of extracting digits from the hexadecimal number, multiply the digit with the proper base (Power of 16) and add it to the above variable taken that is ‘dec_value’. "
},
{
"code": null,
"e": 26321,
"s": 26243,
"text": "In the end, the variable ‘dec_value’ will store the required decimal number. "
},
{
"code": null,
"e": 26384,
"s": 26321,
"text": "convert hexadecimal number ( 1AB ) to equivalent decimal value"
},
{
"code": null,
"e": 26400,
"s": 26384,
"text": "Implementation:"
},
{
"code": null,
"e": 26409,
"s": 26400,
"text": "Example "
},
{
"code": null,
"e": 26414,
"s": 26409,
"text": "Java"
},
{
"code": "// Java program to convert Hexadecimal to Decimal Number // Importing input output classesimport java.io.*; // Main classclass GFG { // Method // To convert hexadecimal to decimal static int hexadecimalToDecimal(String hexVal) { // Storing the length of the int len = hexVal.length(); // Initializing base value to 1, i.e 16^0 int base = 1; // Initially declaring and initializing // decimal value to zero int dec_val = 0; // Extracting characters as // digits from last character for (int i = len - 1; i >= 0; i--) { // Condition check // Case 1 // If character lies in '0'-'9', converting // it to integral 0-9 by subtracting 48 from // ASCII value if (hexVal.charAt(i) >= '0' && hexVal.charAt(i) <= '9') { dec_val += (hexVal.charAt(i) - 48) * base; // Incrementing base by power base = base * 16; } // Case 2 // if case 1 is bypassed // Now, if character lies in 'A'-'F' , // converting it to integral 10 - 15 by // subtracting 55 from ASCII value else if (hexVal.charAt(i) >= 'A' && hexVal.charAt(i) <= 'F') { dec_val += (hexVal.charAt(i) - 55) * base; // Incrementing base by power base = base * 16; } } // Returning the decimal value return dec_val; } // Method 2 // Main driver method public static void main(String[] args) { // Custom input hexadecimal number to be // converted into decimal number String hexNum = \"1A\"; // Calling the above method to convert and // alongside printing the hexadecimal number System.out.println(hexadecimalToDecimal(hexNum)); }}",
"e": 28354,
"s": 26414,
"text": null
},
{
"code": null,
"e": 28357,
"s": 28354,
"text": "26"
},
{
"code": null,
"e": 28362,
"s": 28357,
"text": "Java"
},
{
"code": null,
"e": 28376,
"s": 28362,
"text": "Java Programs"
},
{
"code": null,
"e": 28381,
"s": 28376,
"text": "Java"
},
{
"code": null,
"e": 28479,
"s": 28381,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28494,
"s": 28479,
"text": "Stream In Java"
},
{
"code": null,
"e": 28515,
"s": 28494,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28534,
"s": 28515,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28564,
"s": 28534,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28610,
"s": 28564,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28636,
"s": 28610,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28670,
"s": 28636,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 28717,
"s": 28670,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 28749,
"s": 28717,
"text": "How to Iterate HashMap in Java?"
}
] |
Dart - Standard Input Output - GeeksforGeeks
|
30 Jun, 2021
In Dart programming language, you can take standard input from the user through the console via the use of .readLineSync() function. To take input from the console you need to import a library, named dart:io from libraries of Dart.
About Stdin Class:
This class allows the user to read data from standard input in both synchronous and asynchronous ways. The method readLineSync() is one of the methods used to take input from the user. Refer to the official doc for other methods, from here.
Taking a string input from user:
Dart
// importing dart:io fileimport 'dart:io'; void main(){ print("Enter your name?"); // Reading name of the Geek String? name = stdin.readLineSync(); // Printing the name print("Hello, $name! \nWelcome to GeeksforGeeks!!");}
Input:
Geek
Output:
Enter your name?
Hello, Geek!
Welcome to GeeksforGeeks!!
Taking integer value as input:
Dart
// Importing dart:io fileimport 'dart:io'; void main(){ // Asking for favourite number print("Enter your favourite number:"); // Scanning number int? n = int.parse(stdin.readLineSync()!); // Here ? and ! are for null safety // Printing that number print("Your favourite number is $n");}
Input:
01
Output:
Enter your favourite number:
Your favourite number is 1
In dart, there are two ways to display output in the console:
Using print statement.Using stdout.write() statement.
Using print statement.
Using stdout.write() statement.
Printing Output in two different ways:
Dart
import 'dart:io'; void main(){ // Printing in first way print("Welcome to GeeksforGeeks! // printing from print statement"); // Printing in second way stdout.write("Welcome to GeeksforGeeks! // printing from stdout.write()");}
Output:
Welcome to GeeksforGeeks! // printing from print statement
Welcome to GeeksforGeeks! // printing from stdout.write()
Note: The print() statement brings the cursor to next line while stdout.write() don’t bring the cursor to the next line, it remains in the same line.If the print statements are switched in the above program then:
Output:
Welcome to GeeksforGeeks! // printing from stdout.write()Welcome to GeeksforGeeks! // printing from print statement
Making a simple addition program:
Dart
import 'dart:io'; void main(){ print("-----------GeeksForGeeks-----------"); print("Enter first number"); int? n1 = int.parse(stdin.readLineSync()!); print("Enter second number"); int? n2 = int.parse(stdin.readLineSync()!); // Adding them and printing them int sum = n1 + n2; print("Sum is $sum");}
Input:
11
12
Output:
-----------GeeksForGeeks-----------
Enter first number
Enter second number
Sum is 23
almostsagar
rajatrrpalankar
Dart-IO
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Checkbox Widget
Flutter - Flexible Widget
Flutter - BoxShadow Widget
Dart Tutorial
Container class in Flutter
Flutter - Stack Widget
Operators in Dart
|
[
{
"code": null,
"e": 25302,
"s": 25274,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 25535,
"s": 25302,
"text": "In Dart programming language, you can take standard input from the user through the console via the use of .readLineSync() function. To take input from the console you need to import a library, named dart:io from libraries of Dart. "
},
{
"code": null,
"e": 25555,
"s": 25535,
"text": "About Stdin Class: "
},
{
"code": null,
"e": 25797,
"s": 25555,
"text": "This class allows the user to read data from standard input in both synchronous and asynchronous ways. The method readLineSync() is one of the methods used to take input from the user. Refer to the official doc for other methods, from here. "
},
{
"code": null,
"e": 25830,
"s": 25797,
"text": "Taking a string input from user:"
},
{
"code": null,
"e": 25835,
"s": 25830,
"text": "Dart"
},
{
"code": "// importing dart:io fileimport 'dart:io'; void main(){ print(\"Enter your name?\"); // Reading name of the Geek String? name = stdin.readLineSync(); // Printing the name print(\"Hello, $name! \\nWelcome to GeeksforGeeks!!\");}",
"e": 26074,
"s": 25835,
"text": null
},
{
"code": null,
"e": 26082,
"s": 26074,
"text": "Input: "
},
{
"code": null,
"e": 26087,
"s": 26082,
"text": "Geek"
},
{
"code": null,
"e": 26096,
"s": 26087,
"text": "Output: "
},
{
"code": null,
"e": 26154,
"s": 26096,
"text": "Enter your name?\nHello, Geek! \nWelcome to GeeksforGeeks!!"
},
{
"code": null,
"e": 26186,
"s": 26154,
"text": "Taking integer value as input: "
},
{
"code": null,
"e": 26191,
"s": 26186,
"text": "Dart"
},
{
"code": "// Importing dart:io fileimport 'dart:io'; void main(){ // Asking for favourite number print(\"Enter your favourite number:\"); // Scanning number int? n = int.parse(stdin.readLineSync()!); // Here ? and ! are for null safety // Printing that number print(\"Your favourite number is $n\");}",
"e": 26499,
"s": 26191,
"text": null
},
{
"code": null,
"e": 26507,
"s": 26499,
"text": "Input: "
},
{
"code": null,
"e": 26510,
"s": 26507,
"text": "01"
},
{
"code": null,
"e": 26519,
"s": 26510,
"text": "Output: "
},
{
"code": null,
"e": 26575,
"s": 26519,
"text": "Enter your favourite number:\nYour favourite number is 1"
},
{
"code": null,
"e": 26640,
"s": 26577,
"text": "In dart, there are two ways to display output in the console: "
},
{
"code": null,
"e": 26694,
"s": 26640,
"text": "Using print statement.Using stdout.write() statement."
},
{
"code": null,
"e": 26717,
"s": 26694,
"text": "Using print statement."
},
{
"code": null,
"e": 26749,
"s": 26717,
"text": "Using stdout.write() statement."
},
{
"code": null,
"e": 26788,
"s": 26749,
"text": "Printing Output in two different ways:"
},
{
"code": null,
"e": 26793,
"s": 26788,
"text": "Dart"
},
{
"code": "import 'dart:io'; void main(){ // Printing in first way print(\"Welcome to GeeksforGeeks! // printing from print statement\"); // Printing in second way stdout.write(\"Welcome to GeeksforGeeks! // printing from stdout.write()\");}",
"e": 27033,
"s": 26793,
"text": null
},
{
"code": null,
"e": 27043,
"s": 27033,
"text": "Output: "
},
{
"code": null,
"e": 27160,
"s": 27043,
"text": "Welcome to GeeksforGeeks! // printing from print statement\nWelcome to GeeksforGeeks! // printing from stdout.write()"
},
{
"code": null,
"e": 27375,
"s": 27160,
"text": "Note: The print() statement brings the cursor to next line while stdout.write() don’t bring the cursor to the next line, it remains in the same line.If the print statements are switched in the above program then: "
},
{
"code": null,
"e": 27384,
"s": 27375,
"text": "Output: "
},
{
"code": null,
"e": 27500,
"s": 27384,
"text": "Welcome to GeeksforGeeks! // printing from stdout.write()Welcome to GeeksforGeeks! // printing from print statement"
},
{
"code": null,
"e": 27534,
"s": 27500,
"text": "Making a simple addition program:"
},
{
"code": null,
"e": 27539,
"s": 27534,
"text": "Dart"
},
{
"code": "import 'dart:io'; void main(){ print(\"-----------GeeksForGeeks-----------\"); print(\"Enter first number\"); int? n1 = int.parse(stdin.readLineSync()!); print(\"Enter second number\"); int? n2 = int.parse(stdin.readLineSync()!); // Adding them and printing them int sum = n1 + n2; print(\"Sum is $sum\");}",
"e": 27864,
"s": 27539,
"text": null
},
{
"code": null,
"e": 27872,
"s": 27864,
"text": "Input: "
},
{
"code": null,
"e": 27878,
"s": 27872,
"text": "11\n12"
},
{
"code": null,
"e": 27887,
"s": 27878,
"text": "Output: "
},
{
"code": null,
"e": 27972,
"s": 27887,
"text": "-----------GeeksForGeeks-----------\nEnter first number\nEnter second number\nSum is 23"
},
{
"code": null,
"e": 27984,
"s": 27972,
"text": "almostsagar"
},
{
"code": null,
"e": 28000,
"s": 27984,
"text": "rajatrrpalankar"
},
{
"code": null,
"e": 28008,
"s": 28000,
"text": "Dart-IO"
},
{
"code": null,
"e": 28013,
"s": 28008,
"text": "Dart"
},
{
"code": null,
"e": 28111,
"s": 28013,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28143,
"s": 28111,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 28182,
"s": 28143,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 28208,
"s": 28182,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 28234,
"s": 28208,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 28260,
"s": 28234,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 28287,
"s": 28260,
"text": "Flutter - BoxShadow Widget"
},
{
"code": null,
"e": 28301,
"s": 28287,
"text": "Dart Tutorial"
},
{
"code": null,
"e": 28328,
"s": 28301,
"text": "Container class in Flutter"
},
{
"code": null,
"e": 28351,
"s": 28328,
"text": "Flutter - Stack Widget"
}
] |
How to change the size of figures drawn with matplotlib? - GeeksforGeeks
|
26 May, 2021
The main purpose of matplotlib is to create a figure representing data. The use of visualizing data is to tell stories by curating data into a form easier to understand, highlighting the trends and outliers. We can populate the figure with all different types of data, including axes, a graph plot, a geometric shape, etc. “When” we plot graphs we may want to set the size of a figure to a certain size. You may want to make the figure wider in size, taller in height, etc.
This can be achieved by an attribute of matplotlib known as figsize. The figsize attribute allows us to specify the width and height of a figure in unit inches.
Syntax:
import matplotlib.pyplot as plt
figure_name = plt.figure(figsize=(width, height))
The figsize attribute is a parameter of the function figure(). It is an optional attribute, by default the figure has the dimensions as (6.4, 4.8). This is a standard plot where the attribute is not mentioned in the function.
Normally each unit inch is of 80 x 80 pixels. The number of pixels per unit inch can be changed by the parameter dpi, which can also be specified in the same function.
Approach:
We create a variable plt_1, and set it equal to, plt.figure(figsize=(6,3)).
This creates a figure object, which has a width of 6 inches and 3 inches in height.
The values of the figsize attribute are a tuple of 2 values.
Example 1:
Python3
# We start by importing matplotlibimport matplotlib.pyplot as plt # Plotting a figure of width 6 and height 3plt_1 = plt.figure(figsize=(6, 3)) # Let's plot the equation y=2*xx = [1, 2, 3, 4, 5] # y = [2,4,6,8,10]y = [x*2 for x in x] # plt.plot() specifies the arguments for x-axis# and y-axis to be plottedplt.plot(x, y) # To show this figure object, we use the line,# fig.show()plt.show()
Output:
This works if you’re using a python IDE other than jupyter notebooks. If you are using
jupyter notebooks, then you would not use, plt.show(). Instead, you would specify in the
Code right after importing matplotlib, %matplotlib inline.
Example 2:
To see the dynamic nature of figure sizing in matplotlib, now we to create a figure with the dimensions inverted. The height will now be double the size of the width.
Python3
# We start by importing matplotlibimport matplotlib.pyplot as plt # Plotting a figure of width 3 and height 6plt_1 = plt.figure(figsize=(3, 6)) # Let's plot the equation y=2*xx = [1, 2, 3, 4, 5] # y = [2,4,6,8,10]y = [x*2 for x in x] # plt.plot() specifies the arguments for# x-axis and y-axis to be plottedplt.plot(x, y) # To show this figure object, we use the line,# fig.show()plt.show()
Output:
simranarora5sos
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
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": 26261,
"s": 26233,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 26735,
"s": 26261,
"text": "The main purpose of matplotlib is to create a figure representing data. The use of visualizing data is to tell stories by curating data into a form easier to understand, highlighting the trends and outliers. We can populate the figure with all different types of data, including axes, a graph plot, a geometric shape, etc. “When” we plot graphs we may want to set the size of a figure to a certain size. You may want to make the figure wider in size, taller in height, etc."
},
{
"code": null,
"e": 26896,
"s": 26735,
"text": "This can be achieved by an attribute of matplotlib known as figsize. The figsize attribute allows us to specify the width and height of a figure in unit inches."
},
{
"code": null,
"e": 26905,
"s": 26896,
"text": " Syntax:"
},
{
"code": null,
"e": 26937,
"s": 26905,
"text": "import matplotlib.pyplot as plt"
},
{
"code": null,
"e": 26987,
"s": 26937,
"text": "figure_name = plt.figure(figsize=(width, height))"
},
{
"code": null,
"e": 27214,
"s": 26987,
"text": "The figsize attribute is a parameter of the function figure(). It is an optional attribute, by default the figure has the dimensions as (6.4, 4.8). This is a standard plot where the attribute is not mentioned in the function. "
},
{
"code": null,
"e": 27382,
"s": 27214,
"text": "Normally each unit inch is of 80 x 80 pixels. The number of pixels per unit inch can be changed by the parameter dpi, which can also be specified in the same function."
},
{
"code": null,
"e": 27392,
"s": 27382,
"text": "Approach:"
},
{
"code": null,
"e": 27468,
"s": 27392,
"text": "We create a variable plt_1, and set it equal to, plt.figure(figsize=(6,3))."
},
{
"code": null,
"e": 27552,
"s": 27468,
"text": "This creates a figure object, which has a width of 6 inches and 3 inches in height."
},
{
"code": null,
"e": 27613,
"s": 27552,
"text": "The values of the figsize attribute are a tuple of 2 values."
},
{
"code": null,
"e": 27624,
"s": 27613,
"text": "Example 1:"
},
{
"code": null,
"e": 27632,
"s": 27624,
"text": "Python3"
},
{
"code": "# We start by importing matplotlibimport matplotlib.pyplot as plt # Plotting a figure of width 6 and height 3plt_1 = plt.figure(figsize=(6, 3)) # Let's plot the equation y=2*xx = [1, 2, 3, 4, 5] # y = [2,4,6,8,10]y = [x*2 for x in x] # plt.plot() specifies the arguments for x-axis# and y-axis to be plottedplt.plot(x, y) # To show this figure object, we use the line,# fig.show()plt.show()",
"e": 28023,
"s": 27632,
"text": null
},
{
"code": null,
"e": 28031,
"s": 28023,
"text": "Output:"
},
{
"code": null,
"e": 28120,
"s": 28031,
"text": "This works if you’re using a python IDE other than jupyter notebooks. If you are using "
},
{
"code": null,
"e": 28211,
"s": 28120,
"text": "jupyter notebooks, then you would not use, plt.show(). Instead, you would specify in the "
},
{
"code": null,
"e": 28270,
"s": 28211,
"text": "Code right after importing matplotlib, %matplotlib inline."
},
{
"code": null,
"e": 28281,
"s": 28270,
"text": "Example 2:"
},
{
"code": null,
"e": 28448,
"s": 28281,
"text": "To see the dynamic nature of figure sizing in matplotlib, now we to create a figure with the dimensions inverted. The height will now be double the size of the width."
},
{
"code": null,
"e": 28456,
"s": 28448,
"text": "Python3"
},
{
"code": "# We start by importing matplotlibimport matplotlib.pyplot as plt # Plotting a figure of width 3 and height 6plt_1 = plt.figure(figsize=(3, 6)) # Let's plot the equation y=2*xx = [1, 2, 3, 4, 5] # y = [2,4,6,8,10]y = [x*2 for x in x] # plt.plot() specifies the arguments for# x-axis and y-axis to be plottedplt.plot(x, y) # To show this figure object, we use the line,# fig.show()plt.show()",
"e": 28847,
"s": 28456,
"text": null
},
{
"code": null,
"e": 28855,
"s": 28847,
"text": "Output:"
},
{
"code": null,
"e": 28871,
"s": 28855,
"text": "simranarora5sos"
},
{
"code": null,
"e": 28889,
"s": 28871,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 28913,
"s": 28889,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28920,
"s": 28913,
"text": "Python"
},
{
"code": null,
"e": 28939,
"s": 28920,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29037,
"s": 28939,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29055,
"s": 29037,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29090,
"s": 29055,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29122,
"s": 29090,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29144,
"s": 29122,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29186,
"s": 29144,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29216,
"s": 29186,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29242,
"s": 29216,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29271,
"s": 29242,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29315,
"s": 29271,
"text": "Reading and Writing to text files in Python"
}
] |
“static const” vs “#define” vs “enum” - GeeksforGeeks
|
25 Oct, 2018
In this article, we will be analyzing “static const”, “#define” and “enum”. These three are often confusing and choosing which one to use can sometimes be a difficult task.
static const
static const : “static const” is basically a combination of static(a storage specifier) and const(a type qualifier).
Static : determines the lifetime and visibility/accessibility of the variable. This means if a variable is declared as a static variable, it will remain in the memory the whole time when the program is running, while the normal or auto variables are destroyed when the function (where the variable was defined) is over.Const : is a type qualifier. A type qualifier is used to express additional info about a value through type system. When a variable is initialized using the const type qualifier, it will not accept further change in its value.So combining static and const, we can say that when a variable is initialized using static const, it will retain its value till the execution of the program and also, it will not accept any change in its value.
Syntax:
static const data_type name_of_variable = initial_value;
// C++ program to demonstrate the use of// static const #include <bits/stdc++.h> using namespace std;// function to add constant value to inputint addConst(int input){ // value = 5 will be stored in // memory even after the // execution of the // function is finished static const int value = 5; // constant_not_static will // not accept change in value // but it will get destroyed // after the execution of // function is complete const int constant_not_static = 13; input += value; // value++; ==> this statement will produce error return input;} int main(){ int input = 10; cout << addConst(input) << endl; return 0;}
15
“What is #define“?
It is often misinterpreted as a programming statement. But it is actually sets up a macro. A macro causes a text to replace before compilation takes place. To know more about macros refer to macros_vs_function article.
Syntax:
#define token [value]
NOTE: token should not have any spaces, value can have spaces.Example:
#define ll long long int
// C++ program to demonstrate// the use of #define #include <bits/stdc++.h> // defining long long int as => ll#define ll long long int // defining for loop#define f(i, a, b, c) for (ll i = a; i < b; i += c)using namespace std; // function to count to a given numbervoid count(ll input){ // loop implemented using macros // for(long long int j=1; j<input+1;j+=1) f(j, 1, input + 1, 1) { cout << j << " "; } cout << endl;} int main(){ // ll will get replaced by // long long int ll num = 10; count(num); return 0;}
1 2 3 4 5 6 7 8 9 10
What is enum?
Enumeration is a user-defined data type. It is used to assign names to integral constants to improve code readability. To use enumeration “enum” keyword is used in C/C++.
Syntax:
enum flag{constant1= 2, constant2=3, constant3=4....};
What makes “enum” different from “#define” is that it automatically assigns values to the variables. In the previous example if the values were not assigned=>
enum{constant1, constant2, constantd3...}
The variables will be assigned the values automatically(constant1= 0, constant2= 1, constant3= 2...). There are various advantages of using enum instead of macros. One of them is automatic assignment of values.
// C++ program to demonstrate// the use of enum #include <bits/stdc++.h> using namespace std; int main(){ // declaring weekdays data type enum weekdays { mon, tues, wed, thurs, fri, sat, sun }; // a variable named day1 holds the value of wed enum weekdays day1 = wed; // mon holds 0, tue holds 1 and so on cout << "The value stored in wed is :" << day1 << endl; // looping through the values of // defined integral constants for (int i = mon; i <= sun; i++) cout << i << " "; cout << endl; return 0;}
The value stored in wed is :2
0 1 2 3 4 5 6
For more on enumeration refer to the Enumeration(or enum) in C article.
C-Struct-Union-Enum
Picked
Technical Scripter 2018
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
|
[
{
"code": null,
"e": 25478,
"s": 25450,
"text": "\n25 Oct, 2018"
},
{
"code": null,
"e": 25651,
"s": 25478,
"text": "In this article, we will be analyzing “static const”, “#define” and “enum”. These three are often confusing and choosing which one to use can sometimes be a difficult task."
},
{
"code": null,
"e": 25664,
"s": 25651,
"text": "static const"
},
{
"code": null,
"e": 25781,
"s": 25664,
"text": "static const : “static const” is basically a combination of static(a storage specifier) and const(a type qualifier)."
},
{
"code": null,
"e": 26537,
"s": 25781,
"text": "Static : determines the lifetime and visibility/accessibility of the variable. This means if a variable is declared as a static variable, it will remain in the memory the whole time when the program is running, while the normal or auto variables are destroyed when the function (where the variable was defined) is over.Const : is a type qualifier. A type qualifier is used to express additional info about a value through type system. When a variable is initialized using the const type qualifier, it will not accept further change in its value.So combining static and const, we can say that when a variable is initialized using static const, it will retain its value till the execution of the program and also, it will not accept any change in its value."
},
{
"code": null,
"e": 26545,
"s": 26537,
"text": "Syntax:"
},
{
"code": null,
"e": 26603,
"s": 26545,
"text": "static const data_type name_of_variable = initial_value;\n"
},
{
"code": "// C++ program to demonstrate the use of// static const #include <bits/stdc++.h> using namespace std;// function to add constant value to inputint addConst(int input){ // value = 5 will be stored in // memory even after the // execution of the // function is finished static const int value = 5; // constant_not_static will // not accept change in value // but it will get destroyed // after the execution of // function is complete const int constant_not_static = 13; input += value; // value++; ==> this statement will produce error return input;} int main(){ int input = 10; cout << addConst(input) << endl; return 0;}",
"e": 27285,
"s": 26603,
"text": null
},
{
"code": null,
"e": 27289,
"s": 27285,
"text": "15\n"
},
{
"code": null,
"e": 27308,
"s": 27289,
"text": "“What is #define“?"
},
{
"code": null,
"e": 27527,
"s": 27308,
"text": "It is often misinterpreted as a programming statement. But it is actually sets up a macro. A macro causes a text to replace before compilation takes place. To know more about macros refer to macros_vs_function article."
},
{
"code": null,
"e": 27535,
"s": 27527,
"text": "Syntax:"
},
{
"code": null,
"e": 27558,
"s": 27535,
"text": "#define token [value]\n"
},
{
"code": null,
"e": 27629,
"s": 27558,
"text": "NOTE: token should not have any spaces, value can have spaces.Example:"
},
{
"code": null,
"e": 27655,
"s": 27629,
"text": " #define ll long long int"
},
{
"code": "// C++ program to demonstrate// the use of #define #include <bits/stdc++.h> // defining long long int as => ll#define ll long long int // defining for loop#define f(i, a, b, c) for (ll i = a; i < b; i += c)using namespace std; // function to count to a given numbervoid count(ll input){ // loop implemented using macros // for(long long int j=1; j<input+1;j+=1) f(j, 1, input + 1, 1) { cout << j << \" \"; } cout << endl;} int main(){ // ll will get replaced by // long long int ll num = 10; count(num); return 0;}",
"e": 28215,
"s": 27655,
"text": null
},
{
"code": null,
"e": 28237,
"s": 28215,
"text": "1 2 3 4 5 6 7 8 9 10\n"
},
{
"code": null,
"e": 28251,
"s": 28237,
"text": "What is enum?"
},
{
"code": null,
"e": 28422,
"s": 28251,
"text": "Enumeration is a user-defined data type. It is used to assign names to integral constants to improve code readability. To use enumeration “enum” keyword is used in C/C++."
},
{
"code": null,
"e": 28430,
"s": 28422,
"text": "Syntax:"
},
{
"code": null,
"e": 28486,
"s": 28430,
"text": "enum flag{constant1= 2, constant2=3, constant3=4....};\n"
},
{
"code": null,
"e": 28645,
"s": 28486,
"text": "What makes “enum” different from “#define” is that it automatically assigns values to the variables. In the previous example if the values were not assigned=>"
},
{
"code": null,
"e": 28688,
"s": 28645,
"text": "enum{constant1, constant2, constantd3...}\n"
},
{
"code": null,
"e": 28899,
"s": 28688,
"text": "The variables will be assigned the values automatically(constant1= 0, constant2= 1, constant3= 2...). There are various advantages of using enum instead of macros. One of them is automatic assignment of values."
},
{
"code": "// C++ program to demonstrate// the use of enum #include <bits/stdc++.h> using namespace std; int main(){ // declaring weekdays data type enum weekdays { mon, tues, wed, thurs, fri, sat, sun }; // a variable named day1 holds the value of wed enum weekdays day1 = wed; // mon holds 0, tue holds 1 and so on cout << \"The value stored in wed is :\" << day1 << endl; // looping through the values of // defined integral constants for (int i = mon; i <= sun; i++) cout << i << \" \"; cout << endl; return 0;}",
"e": 29563,
"s": 28899,
"text": null
},
{
"code": null,
"e": 29608,
"s": 29563,
"text": "The value stored in wed is :2\n0 1 2 3 4 5 6\n"
},
{
"code": null,
"e": 29680,
"s": 29608,
"text": "For more on enumeration refer to the Enumeration(or enum) in C article."
},
{
"code": null,
"e": 29700,
"s": 29680,
"text": "C-Struct-Union-Enum"
},
{
"code": null,
"e": 29707,
"s": 29700,
"text": "Picked"
},
{
"code": null,
"e": 29731,
"s": 29707,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 29742,
"s": 29731,
"text": "C Language"
},
{
"code": null,
"e": 29746,
"s": 29742,
"text": "C++"
},
{
"code": null,
"e": 29750,
"s": 29746,
"text": "CPP"
},
{
"code": null,
"e": 29848,
"s": 29750,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29886,
"s": 29848,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 29912,
"s": 29886,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 29932,
"s": 29912,
"text": "Multithreading in C"
},
{
"code": null,
"e": 29954,
"s": 29932,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 29995,
"s": 29954,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 30013,
"s": 29995,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 30059,
"s": 30013,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 30078,
"s": 30059,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 30121,
"s": 30078,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
PostgreSQL - Change Column Type - GeeksforGeeks
|
28 Aug, 2020
In this article, we will discuss the step by step process of changing the data type of a column using the ALTER TABLE statement in PostgreSQL.
Syntax:
ALTER TABLE table_name
ALTER COLUMN column_name [SET DATA] TYPE new_data_type;
Let’s analyze the above syntax:
First, specify the name of the table to which the column you want to change belongs in the ALTER TABLE clause.
Second, give the name of column whose data type will be changed in the ALTER COLUMN clause.
Third, provide the new data type for the column after the TYPE keyword. It is possible to use either SET DATA TYPE or TYPE.
Example:Let’s create a table (say, assets) and insert a few rows into it for the demonstration using the below statement:
CREATE TABLE assets (
id serial PRIMARY KEY,
name TEXT NOT NULL,
asset_no VARCHAR NOT NULL,
description TEXT,
LOCATION TEXT,
acquired_date DATE NOT NULL
);
INSERT INTO assets (
NAME,
asset_no,
location,
acquired_date
)
VALUES
(
'Server',
'10001',
'Server room',
'2020-01-01'
),
(
'UPS',
'10002',
'Server room',
'2020-05-16'
);
Now we will change the data type of the name column to VARCHAR, using the below statement:
ALTER TABLE assets ALTER COLUMN name TYPE VARCHAR;
Now we change the data type of description and location columns from TEXT to VARCHAR using the below statement:
ALTER TABLE assets
ALTER COLUMN location TYPE VARCHAR,
ALTER COLUMN description TYPE VARCHAR;
Now we check the table for the changes made using the below statement:
SELECT * FROM assets;
Output:
postgreSQL-dataTypes
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - CREATE PROCEDURE
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - TIME Data Type
PostgreSQL - REPLACE Function
PostgreSQL - Copy Table
PostgreSQL - CREATE SCHEMA
PostgreSQL - Identity Column
PostgreSQL - SELECT
PostgreSQL - ROW_NUMBER Function
|
[
{
"code": null,
"e": 25355,
"s": 25327,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 25498,
"s": 25355,
"text": "In this article, we will discuss the step by step process of changing the data type of a column using the ALTER TABLE statement in PostgreSQL."
},
{
"code": null,
"e": 25585,
"s": 25498,
"text": "Syntax:\nALTER TABLE table_name\nALTER COLUMN column_name [SET DATA] TYPE new_data_type;"
},
{
"code": null,
"e": 25617,
"s": 25585,
"text": "Let’s analyze the above syntax:"
},
{
"code": null,
"e": 25728,
"s": 25617,
"text": "First, specify the name of the table to which the column you want to change belongs in the ALTER TABLE clause."
},
{
"code": null,
"e": 25820,
"s": 25728,
"text": "Second, give the name of column whose data type will be changed in the ALTER COLUMN clause."
},
{
"code": null,
"e": 25944,
"s": 25820,
"text": "Third, provide the new data type for the column after the TYPE keyword. It is possible to use either SET DATA TYPE or TYPE."
},
{
"code": null,
"e": 26066,
"s": 25944,
"text": "Example:Let’s create a table (say, assets) and insert a few rows into it for the demonstration using the below statement:"
},
{
"code": null,
"e": 26510,
"s": 26066,
"text": "CREATE TABLE assets (\n id serial PRIMARY KEY,\n name TEXT NOT NULL,\n asset_no VARCHAR NOT NULL,\n description TEXT,\n LOCATION TEXT,\n acquired_date DATE NOT NULL\n);\n\nINSERT INTO assets (\n NAME,\n asset_no,\n location,\n acquired_date\n)\nVALUES\n (\n 'Server',\n '10001',\n 'Server room',\n '2020-01-01'\n ),\n (\n 'UPS',\n '10002',\n 'Server room',\n '2020-05-16'\n);"
},
{
"code": null,
"e": 26601,
"s": 26510,
"text": "Now we will change the data type of the name column to VARCHAR, using the below statement:"
},
{
"code": null,
"e": 26652,
"s": 26601,
"text": "ALTER TABLE assets ALTER COLUMN name TYPE VARCHAR;"
},
{
"code": null,
"e": 26764,
"s": 26652,
"text": "Now we change the data type of description and location columns from TEXT to VARCHAR using the below statement:"
},
{
"code": null,
"e": 26867,
"s": 26764,
"text": "ALTER TABLE assets \n ALTER COLUMN location TYPE VARCHAR,\n ALTER COLUMN description TYPE VARCHAR;"
},
{
"code": null,
"e": 26938,
"s": 26867,
"text": "Now we check the table for the changes made using the below statement:"
},
{
"code": null,
"e": 26960,
"s": 26938,
"text": "SELECT * FROM assets;"
},
{
"code": null,
"e": 26968,
"s": 26960,
"text": "Output:"
},
{
"code": null,
"e": 26989,
"s": 26968,
"text": "postgreSQL-dataTypes"
},
{
"code": null,
"e": 27015,
"s": 26989,
"text": "postgreSQL-managing-table"
},
{
"code": null,
"e": 27026,
"s": 27015,
"text": "PostgreSQL"
},
{
"code": null,
"e": 27124,
"s": 27026,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27154,
"s": 27124,
"text": "PostgreSQL - CREATE PROCEDURE"
},
{
"code": null,
"e": 27183,
"s": 27154,
"text": "PostgreSQL - GROUP BY clause"
},
{
"code": null,
"e": 27207,
"s": 27183,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 27235,
"s": 27207,
"text": "PostgreSQL - TIME Data Type"
},
{
"code": null,
"e": 27265,
"s": 27235,
"text": "PostgreSQL - REPLACE Function"
},
{
"code": null,
"e": 27289,
"s": 27265,
"text": "PostgreSQL - Copy Table"
},
{
"code": null,
"e": 27316,
"s": 27289,
"text": "PostgreSQL - CREATE SCHEMA"
},
{
"code": null,
"e": 27345,
"s": 27316,
"text": "PostgreSQL - Identity Column"
},
{
"code": null,
"e": 27365,
"s": 27345,
"text": "PostgreSQL - SELECT"
}
] |
ZoneId systemDefault() method in Java with Examples - GeeksforGeeks
|
19 Aug, 2019
The systemDefault() method of the ZoneId class in Java is used to return the system default time-zone.
Syntax:
public String systemDefault()
Parameters: This method does not accepts any parameters.
Return Value: This method returns the zone ID.
Exceptions: This method throws following exception:
DateTimeException – It throws this exception if the converted zone ID has an invalid format.
ZoneRulesException – It throws this exception if the converted zone region ID cannot be found.
Below programs illustrate the systemDefault() method:Program 1:
// Java program to demonstrate// ZoneId.systemDefault() method import java.time.*; public class GFG { public static void main(String[] args) { // create ZoneId object ZoneId zoneId = ZoneId.systemDefault(); // printresult System.out.println("ZoneId: " + zoneId); }}
ZoneId: Etc/UTC
Program 2:
// Java program to demonstrate// ZoneId.systemDefault() method import java.time.*; public class GFG { public static void main(String[] args) { // create ZoneId object ZoneId zoneId = ZoneId.systemDefault(); if (zoneId.getId().equals("Etc/UTC")) System.out.println("This zone is Etc/UTC"); else System.out.println("This zone is not Etc/UTC"); }}
This zone is Etc/UTC
References:https://docs.oracle.com/javase/10/docs/api/java/time/ZoneId.html#systemDefault()
Akanksha_Rai
Java-Functions
Java-time package
Java-ZoneId
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
|
[
{
"code": null,
"e": 25303,
"s": 25275,
"text": "\n19 Aug, 2019"
},
{
"code": null,
"e": 25406,
"s": 25303,
"text": "The systemDefault() method of the ZoneId class in Java is used to return the system default time-zone."
},
{
"code": null,
"e": 25414,
"s": 25406,
"text": "Syntax:"
},
{
"code": null,
"e": 25445,
"s": 25414,
"text": "public String systemDefault()\n"
},
{
"code": null,
"e": 25502,
"s": 25445,
"text": "Parameters: This method does not accepts any parameters."
},
{
"code": null,
"e": 25549,
"s": 25502,
"text": "Return Value: This method returns the zone ID."
},
{
"code": null,
"e": 25601,
"s": 25549,
"text": "Exceptions: This method throws following exception:"
},
{
"code": null,
"e": 25694,
"s": 25601,
"text": "DateTimeException – It throws this exception if the converted zone ID has an invalid format."
},
{
"code": null,
"e": 25789,
"s": 25694,
"text": "ZoneRulesException – It throws this exception if the converted zone region ID cannot be found."
},
{
"code": null,
"e": 25853,
"s": 25789,
"text": "Below programs illustrate the systemDefault() method:Program 1:"
},
{
"code": "// Java program to demonstrate// ZoneId.systemDefault() method import java.time.*; public class GFG { public static void main(String[] args) { // create ZoneId object ZoneId zoneId = ZoneId.systemDefault(); // printresult System.out.println(\"ZoneId: \" + zoneId); }}",
"e": 26199,
"s": 25853,
"text": null
},
{
"code": null,
"e": 26216,
"s": 26199,
"text": "ZoneId: Etc/UTC\n"
},
{
"code": null,
"e": 26227,
"s": 26216,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// ZoneId.systemDefault() method import java.time.*; public class GFG { public static void main(String[] args) { // create ZoneId object ZoneId zoneId = ZoneId.systemDefault(); if (zoneId.getId().equals(\"Etc/UTC\")) System.out.println(\"This zone is Etc/UTC\"); else System.out.println(\"This zone is not Etc/UTC\"); }}",
"e": 26648,
"s": 26227,
"text": null
},
{
"code": null,
"e": 26670,
"s": 26648,
"text": "This zone is Etc/UTC\n"
},
{
"code": null,
"e": 26762,
"s": 26670,
"text": "References:https://docs.oracle.com/javase/10/docs/api/java/time/ZoneId.html#systemDefault()"
},
{
"code": null,
"e": 26775,
"s": 26762,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 26790,
"s": 26775,
"text": "Java-Functions"
},
{
"code": null,
"e": 26808,
"s": 26790,
"text": "Java-time package"
},
{
"code": null,
"e": 26820,
"s": 26808,
"text": "Java-ZoneId"
},
{
"code": null,
"e": 26825,
"s": 26820,
"text": "Java"
},
{
"code": null,
"e": 26830,
"s": 26825,
"text": "Java"
},
{
"code": null,
"e": 26928,
"s": 26830,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26979,
"s": 26928,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27009,
"s": 26979,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27028,
"s": 27009,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27043,
"s": 27028,
"text": "Stream In Java"
},
{
"code": null,
"e": 27074,
"s": 27043,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27092,
"s": 27074,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27124,
"s": 27092,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27144,
"s": 27124,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27176,
"s": 27144,
"text": "Multidimensional Arrays in Java"
}
] |
Functions in Go Language - GeeksforGeeks
|
16 Oct, 2020
Functions are generally the block of codes or statements in a program that gives the user the ability to reuse the same code which ultimately saves the excessive use of memory, acts as a time saver and more importantly, provides better readability of the code. So basically, a function is a collection of statements that perform some specific task and return the result to the caller. A function can also perform some specific task without returning anything.
Function declaration means a way to construct a function.Syntax:
func function_name(Parameter-list)(Return_type){
// function body.....
}
The declaration of the function contains:
func: It is a keyword in Go language, which is used to create a function.
function_name: It is the name of the function.
Parameter-list: It contains the name and the type of the function parameters.
Return_type: It is optional and it contain the types of the values that function returns. If you are using return_type in your function, then it is necessary to use a return statement in your function.
Function Invocation or Function Calling is done when the user wants to execute the function. The function needs to be called for using its functionality. As shown in the below example, we have a function named as area() with two parameters. Now we call this function in the main function by using its name, i.e, area(12, 10) with two parameters. Example:
C
// Go program to illustrate the// use of functionpackage mainimport "fmt" // area() is used to find the// area of the rectangle// area() function two parameters,// i.e, length and widthfunc area(length, width int)int{ Ar := length* width return Ar} // Main functionfunc main() { // Display the area of the rectangle // with method calling fmt.Printf("Area of rectangle is : %d", area(12, 10))}
Output:
Area of rectangle is : 120
In Go language, the parameters passed to a function are called actual parameters, whereas the parameters received by a function are called formal parameters.Note: By default Go language use call by value method to pass arguments in function.Go language supports two ways to pass arguments to your function:
Call by value: : In this parameter passing method, values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of the caller.Example:
C
// Go program to illustrate the// concept of the call by valuepackage main import "fmt" // function which swap valuesfunc swap(a, b int)int{ var o int o= a a=b b=o return o} // Main functionfunc main() { var p int = 10 var q int = 20 fmt.Printf("p = %d and q = %d", p, q) // call by values swap(p, q) fmt.Printf("\np = %d and q = %d",p, q)}
Output:
p = 10 and q = 20
p = 10 and q = 20
Call by reference: Both the actual and formal parameters refer to the same locations, so any changes made inside the function are actually reflected in actual parameters of the caller.Example:
C
// Go program to illustrate the// concept of the call by referencepackage main import "fmt" // function which swap valuesfunc swap(a, b *int)int{ var o int o = *a *a = *b *b = o return o} // Main functionfunc main() { var p int = 10 var q int = 20 fmt.Printf("p = %d and q = %d", p, q) // call by reference swap(&p, &q) fmt.Printf("\np = %d and q = %d",p, q)}
Output:
p = 10 and q = 20
p = 20 and q = 10
kentwest
Go-Functions
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to concatenate two strings in Golang
time.Sleep() Function in Golang With Examples
6 Best Books to Learn Go Programming Language
strings.Contains Function in Golang with Examples
Time Formatting in Golang
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Golang Maps
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
|
[
{
"code": null,
"e": 26176,
"s": 26148,
"text": "\n16 Oct, 2020"
},
{
"code": null,
"e": 26637,
"s": 26176,
"text": "Functions are generally the block of codes or statements in a program that gives the user the ability to reuse the same code which ultimately saves the excessive use of memory, acts as a time saver and more importantly, provides better readability of the code. So basically, a function is a collection of statements that perform some specific task and return the result to the caller. A function can also perform some specific task without returning anything. "
},
{
"code": null,
"e": 26704,
"s": 26637,
"text": "Function declaration means a way to construct a function.Syntax: "
},
{
"code": null,
"e": 26783,
"s": 26704,
"text": "func function_name(Parameter-list)(Return_type){\n // function body.....\n}\n\n"
},
{
"code": null,
"e": 26826,
"s": 26783,
"text": "The declaration of the function contains: "
},
{
"code": null,
"e": 26900,
"s": 26826,
"text": "func: It is a keyword in Go language, which is used to create a function."
},
{
"code": null,
"e": 26947,
"s": 26900,
"text": "function_name: It is the name of the function."
},
{
"code": null,
"e": 27025,
"s": 26947,
"text": "Parameter-list: It contains the name and the type of the function parameters."
},
{
"code": null,
"e": 27227,
"s": 27025,
"text": "Return_type: It is optional and it contain the types of the values that function returns. If you are using return_type in your function, then it is necessary to use a return statement in your function."
},
{
"code": null,
"e": 27587,
"s": 27231,
"text": "Function Invocation or Function Calling is done when the user wants to execute the function. The function needs to be called for using its functionality. As shown in the below example, we have a function named as area() with two parameters. Now we call this function in the main function by using its name, i.e, area(12, 10) with two parameters. Example: "
},
{
"code": null,
"e": 27589,
"s": 27587,
"text": "C"
},
{
"code": "// Go program to illustrate the// use of functionpackage mainimport \"fmt\" // area() is used to find the// area of the rectangle// area() function two parameters,// i.e, length and widthfunc area(length, width int)int{ Ar := length* width return Ar} // Main functionfunc main() { // Display the area of the rectangle // with method calling fmt.Printf(\"Area of rectangle is : %d\", area(12, 10))}",
"e": 28003,
"s": 27589,
"text": null
},
{
"code": null,
"e": 28012,
"s": 28003,
"text": "Output: "
},
{
"code": null,
"e": 28040,
"s": 28012,
"text": "Area of rectangle is : 120\n"
},
{
"code": null,
"e": 28350,
"s": 28042,
"text": "In Go language, the parameters passed to a function are called actual parameters, whereas the parameters received by a function are called formal parameters.Note: By default Go language use call by value method to pass arguments in function.Go language supports two ways to pass arguments to your function: "
},
{
"code": null,
"e": 28646,
"s": 28350,
"text": "Call by value: : In this parameter passing method, values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of the caller.Example: "
},
{
"code": null,
"e": 28648,
"s": 28646,
"text": "C"
},
{
"code": "// Go program to illustrate the// concept of the call by valuepackage main import \"fmt\" // function which swap valuesfunc swap(a, b int)int{ var o int o= a a=b b=o return o} // Main functionfunc main() { var p int = 10 var q int = 20 fmt.Printf(\"p = %d and q = %d\", p, q) // call by values swap(p, q) fmt.Printf(\"\\np = %d and q = %d\",p, q)}",
"e": 29016,
"s": 28648,
"text": null
},
{
"code": null,
"e": 29025,
"s": 29016,
"text": "Output: "
},
{
"code": null,
"e": 29063,
"s": 29025,
"text": "p = 10 and q = 20\np = 10 and q = 20\n\n"
},
{
"code": null,
"e": 29258,
"s": 29063,
"text": " Call by reference: Both the actual and formal parameters refer to the same locations, so any changes made inside the function are actually reflected in actual parameters of the caller.Example: "
},
{
"code": null,
"e": 29260,
"s": 29258,
"text": "C"
},
{
"code": "// Go program to illustrate the// concept of the call by referencepackage main import \"fmt\" // function which swap valuesfunc swap(a, b *int)int{ var o int o = *a *a = *b *b = o return o} // Main functionfunc main() { var p int = 10 var q int = 20 fmt.Printf(\"p = %d and q = %d\", p, q) // call by reference swap(&p, &q) fmt.Printf(\"\\np = %d and q = %d\",p, q)}",
"e": 29647,
"s": 29260,
"text": null
},
{
"code": null,
"e": 29656,
"s": 29647,
"text": "Output: "
},
{
"code": null,
"e": 29694,
"s": 29656,
"text": "p = 10 and q = 20\np = 20 and q = 10\n\n"
},
{
"code": null,
"e": 29707,
"s": 29698,
"text": "kentwest"
},
{
"code": null,
"e": 29720,
"s": 29707,
"text": "Go-Functions"
},
{
"code": null,
"e": 29727,
"s": 29720,
"text": "Golang"
},
{
"code": null,
"e": 29739,
"s": 29727,
"text": "Go Language"
},
{
"code": null,
"e": 29837,
"s": 29739,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29889,
"s": 29837,
"text": "Different ways to concatenate two strings in Golang"
},
{
"code": null,
"e": 29935,
"s": 29889,
"text": "time.Sleep() Function in Golang With Examples"
},
{
"code": null,
"e": 29981,
"s": 29935,
"text": "6 Best Books to Learn Go Programming Language"
},
{
"code": null,
"e": 30031,
"s": 29981,
"text": "strings.Contains Function in Golang with Examples"
},
{
"code": null,
"e": 30057,
"s": 30031,
"text": "Time Formatting in Golang"
},
{
"code": null,
"e": 30108,
"s": 30057,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 30155,
"s": 30108,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 30167,
"s": 30155,
"text": "Golang Maps"
},
{
"code": null,
"e": 30189,
"s": 30167,
"text": "Inheritance in GoLang"
}
] |
How to use an ES6 import in Node.js? - GeeksforGeeks
|
08 Feb, 2021
Introduction to ES6 import:
The import statement is used to import modules that are exported by some other module. A module is a file that contains a piece of reusable code. The import modules are in strict mode whether it is declared or not.
Syntax of import:
import name from 'module-name'
Importing can be done in various ways:
Importing an entire module: import * as name from 'module-name'Import default export from a module:import name from 'module-name'Importing a single export from a module:import { name } from 'module-name'Importing multiple exports from a module:import { nameOne , nameTwo } from 'module-name'Importing a module for side effects onlyimport './module-name'Node js doesn’t support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error. For example, if we try to import express module by writing import express from ‘express’ node js will throw an error as follows:Node has experimental support for ES modules. To enable them we need to make some changes to the package.json file. Before following the steps make sure that Node is installed. Below are the steps to achieve the same.In the package.json file add “type” : “module”. Adding this enables ES6 modules.The package.json file should look like this:package.jsonpackage.json//package.json{ "name": "index", "version": "1.0.0", "description": "", "main": "index.js", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC"}Create a file index.js and write the program using ES6 import. For example, let’s try to import express in index.js fileindex.js fileindex.js file//index.js import express from 'express'; const app = express(); app.get('/',(req,res) => { res.send('GeeksforGeeks');}) const PORT = 5000; app.listen(PORT,() => { console.log(`Running on PORT ${PORT}`);})Now run the index.js file by typing node –experimental-modules index.js in the terminal. Using the esm module:Another way to do this is by creating a file with .mjs extension. If we are using the file with .mjs extension then we don’t have to add “type”: “module” in the package.json file. We can directly write the program and can execute it by typing node –experimental-modules index.mjs in the terminal.Now, when using a file with .mjs extension the package.json file will look like this:JavascriptJavascript// package.json when using .mjs file{ "name": "index", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC"}Create a file index.mjs and write the program using ES6 import.JavascriptJavascript//index.mjs import express from 'express'; const app = express(); app.get('/',(req,res) => { res.send('GeeksforGeeks');}) const PORT = 5000; app.listen(PORT,() => { console.log(`Running on PORT ${PORT}`);})Now in the terminal type node –experimental-modules index.mjs . This will execute the file and the application now will be running on PORT 5000.Using the esm moduleInstallationnpm install esmNow try executing the program written in the index.js file earlier by typing node -r esm index.js in the terminal. Another way to use the esm module is by creating another file say server.js that loads esm before the actual application. In the server.js file write the below code//server.js
require = require("esm")(module);
module.exports = require("./index.js");Note: In the file server.js, we are importing the index.js file which holds the actual program which needs to be executed. Now in the terminal type node server.js to execute the programThe output of the index.js and index.mjs file in the above method is:localhost:5000Advantages of using import in place of require in nodejs:Import helps in selectively loading the pieces of code which are required that helps in saving memory.In case of require loading is synchronous whereas import can be asynchronous so it performs better than required.My Personal Notes
arrow_drop_upSave
Importing an entire module: import * as name from 'module-name'
Importing an entire module:
import * as name from 'module-name'
Import default export from a module:import name from 'module-name'
Import default export from a module:
import name from 'module-name'
Importing a single export from a module:import { name } from 'module-name'
Importing a single export from a module:
import { name } from 'module-name'
Importing multiple exports from a module:import { nameOne , nameTwo } from 'module-name'
Importing multiple exports from a module:
import { nameOne , nameTwo } from 'module-name'
Importing a module for side effects onlyimport './module-name'Node js doesn’t support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error. For example, if we try to import express module by writing import express from ‘express’ node js will throw an error as follows:Node has experimental support for ES modules. To enable them we need to make some changes to the package.json file. Before following the steps make sure that Node is installed. Below are the steps to achieve the same.In the package.json file add “type” : “module”. Adding this enables ES6 modules.The package.json file should look like this:package.jsonpackage.json//package.json{ "name": "index", "version": "1.0.0", "description": "", "main": "index.js", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC"}Create a file index.js and write the program using ES6 import. For example, let’s try to import express in index.js fileindex.js fileindex.js file//index.js import express from 'express'; const app = express(); app.get('/',(req,res) => { res.send('GeeksforGeeks');}) const PORT = 5000; app.listen(PORT,() => { console.log(`Running on PORT ${PORT}`);})Now run the index.js file by typing node –experimental-modules index.js in the terminal. Using the esm module:Another way to do this is by creating a file with .mjs extension. If we are using the file with .mjs extension then we don’t have to add “type”: “module” in the package.json file. We can directly write the program and can execute it by typing node –experimental-modules index.mjs in the terminal.Now, when using a file with .mjs extension the package.json file will look like this:JavascriptJavascript// package.json when using .mjs file{ "name": "index", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC"}Create a file index.mjs and write the program using ES6 import.JavascriptJavascript//index.mjs import express from 'express'; const app = express(); app.get('/',(req,res) => { res.send('GeeksforGeeks');}) const PORT = 5000; app.listen(PORT,() => { console.log(`Running on PORT ${PORT}`);})Now in the terminal type node –experimental-modules index.mjs . This will execute the file and the application now will be running on PORT 5000.Using the esm moduleInstallationnpm install esmNow try executing the program written in the index.js file earlier by typing node -r esm index.js in the terminal. Another way to use the esm module is by creating another file say server.js that loads esm before the actual application. In the server.js file write the below code//server.js
require = require("esm")(module);
module.exports = require("./index.js");Note: In the file server.js, we are importing the index.js file which holds the actual program which needs to be executed. Now in the terminal type node server.js to execute the programThe output of the index.js and index.mjs file in the above method is:localhost:5000Advantages of using import in place of require in nodejs:Import helps in selectively loading the pieces of code which are required that helps in saving memory.In case of require loading is synchronous whereas import can be asynchronous so it performs better than required.My Personal Notes
arrow_drop_upSave
Importing a module for side effects only
import './module-name'
Node js doesn’t support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error. For example, if we try to import express module by writing import express from ‘express’ node js will throw an error as follows:
Node has experimental support for ES modules. To enable them we need to make some changes to the package.json file. Before following the steps make sure that Node is installed. Below are the steps to achieve the same.
In the package.json file add “type” : “module”. Adding this enables ES6 modules.The package.json file should look like this:package.jsonpackage.json//package.json{ "name": "index", "version": "1.0.0", "description": "", "main": "index.js", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC"}Create a file index.js and write the program using ES6 import. For example, let’s try to import express in index.js fileindex.js fileindex.js file//index.js import express from 'express'; const app = express(); app.get('/',(req,res) => { res.send('GeeksforGeeks');}) const PORT = 5000; app.listen(PORT,() => { console.log(`Running on PORT ${PORT}`);})
In the package.json file add “type” : “module”. Adding this enables ES6 modules.The package.json file should look like this:package.jsonpackage.json//package.json{ "name": "index", "version": "1.0.0", "description": "", "main": "index.js", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC"}
The package.json file should look like this:
package.json
//package.json{ "name": "index", "version": "1.0.0", "description": "", "main": "index.js", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC"}
Create a file index.js and write the program using ES6 import. For example, let’s try to import express in index.js fileindex.js fileindex.js file//index.js import express from 'express'; const app = express(); app.get('/',(req,res) => { res.send('GeeksforGeeks');}) const PORT = 5000; app.listen(PORT,() => { console.log(`Running on PORT ${PORT}`);})
Create a file index.js and write the program using ES6 import. For example, let’s try to import express in index.js file
index.js file
//index.js import express from 'express'; const app = express(); app.get('/',(req,res) => { res.send('GeeksforGeeks');}) const PORT = 5000; app.listen(PORT,() => { console.log(`Running on PORT ${PORT}`);})
Now run the index.js file by typing node –experimental-modules index.js in the terminal.
Using the esm module:
Another way to do this is by creating a file with .mjs extension. If we are using the file with .mjs extension then we don’t have to add “type”: “module” in the package.json file. We can directly write the program and can execute it by typing node –experimental-modules index.mjs in the terminal.
Now, when using a file with .mjs extension the package.json file will look like this:
Javascript
// package.json when using .mjs file{ "name": "index", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC"}
Create a file index.mjs and write the program using ES6 import.
Javascript
//index.mjs import express from 'express'; const app = express(); app.get('/',(req,res) => { res.send('GeeksforGeeks');}) const PORT = 5000; app.listen(PORT,() => { console.log(`Running on PORT ${PORT}`);})
Now in the terminal type node –experimental-modules index.mjs . This will execute the file and the application now will be running on PORT 5000.
Using the esm module
Installation
npm install esm
Now try executing the program written in the index.js file earlier by typing node -r esm index.js in the terminal.
Another way to use the esm module is by creating another file say server.js that loads esm before the actual application. In the server.js file write the below code
//server.js
require = require("esm")(module);
module.exports = require("./index.js");
Note: In the file server.js, we are importing the index.js file which holds the actual program which needs to be executed.
Now in the terminal type node server.js to execute the program
The output of the index.js and index.mjs file in the above method is:
localhost:5000
Advantages of using import in place of require in nodejs:
Import helps in selectively loading the pieces of code which are required that helps in saving memory.
In case of require loading is synchronous whereas import can be asynchronous so it performs better than required.
NodeJS-Questions
Picked
Technical Scripter 2020
Node.js
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
How to connect Node.js with React.js ?
Node.js Export Module
Mongoose Populate() Method
Mongoose find() Function
JWT Authentication with Node.js
Express.js req.params Property
How to build a basic CRUD app with Node.js and ReactJS ?
Installation of Node.js on Windows
How to Install a local module using npm?
|
[
{
"code": null,
"e": 26219,
"s": 26191,
"text": "\n08 Feb, 2021"
},
{
"code": null,
"e": 26248,
"s": 26219,
"text": "Introduction to ES6 import: "
},
{
"code": null,
"e": 26463,
"s": 26248,
"text": "The import statement is used to import modules that are exported by some other module. A module is a file that contains a piece of reusable code. The import modules are in strict mode whether it is declared or not."
},
{
"code": null,
"e": 26481,
"s": 26463,
"text": "Syntax of import:"
},
{
"code": null,
"e": 26512,
"s": 26481,
"text": "import name from 'module-name'"
},
{
"code": null,
"e": 26551,
"s": 26512,
"text": "Importing can be done in various ways:"
},
{
"code": null,
"e": 30324,
"s": 26551,
"text": "Importing an entire module: import * as name from 'module-name'Import default export from a module:import name from 'module-name'Importing a single export from a module:import { name } from 'module-name'Importing multiple exports from a module:import { nameOne , nameTwo } from 'module-name'Importing a module for side effects onlyimport './module-name'Node js doesn’t support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error. For example, if we try to import express module by writing import express from ‘express’ node js will throw an error as follows:Node has experimental support for ES modules. To enable them we need to make some changes to the package.json file. Before following the steps make sure that Node is installed. Below are the steps to achieve the same.In the package.json file add “type” : “module”. Adding this enables ES6 modules.The package.json file should look like this:package.jsonpackage.json//package.json{ \"name\": \"index\", \"version\": \"1.0.0\", \"description\": \"\", \"main\": \"index.js\", \"type\": \"module\", \"scripts\": { \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\" }, \"keywords\": [], \"author\": \"\", \"license\": \"ISC\"}Create a file index.js and write the program using ES6 import. For example, let’s try to import express in index.js fileindex.js fileindex.js file//index.js import express from 'express'; const app = express(); app.get('/',(req,res) => { res.send('GeeksforGeeks');}) const PORT = 5000; app.listen(PORT,() => { console.log(`Running on PORT ${PORT}`);})Now run the index.js file by typing node –experimental-modules index.js in the terminal. Using the esm module:Another way to do this is by creating a file with .mjs extension. If we are using the file with .mjs extension then we don’t have to add “type”: “module” in the package.json file. We can directly write the program and can execute it by typing node –experimental-modules index.mjs in the terminal.Now, when using a file with .mjs extension the package.json file will look like this:JavascriptJavascript// package.json when using .mjs file{ \"name\": \"index\", \"version\": \"1.0.0\", \"description\": \"\", \"main\": \"index.js\", \"scripts\": { \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\" }, \"keywords\": [], \"author\": \"\", \"license\": \"ISC\"}Create a file index.mjs and write the program using ES6 import.JavascriptJavascript//index.mjs import express from 'express'; const app = express(); app.get('/',(req,res) => { res.send('GeeksforGeeks');}) const PORT = 5000; app.listen(PORT,() => { console.log(`Running on PORT ${PORT}`);})Now in the terminal type node –experimental-modules index.mjs . This will execute the file and the application now will be running on PORT 5000.Using the esm moduleInstallationnpm install esmNow try executing the program written in the index.js file earlier by typing node -r esm index.js in the terminal. Another way to use the esm module is by creating another file say server.js that loads esm before the actual application. In the server.js file write the below code//server.js\nrequire = require(\"esm\")(module);\nmodule.exports = require(\"./index.js\");Note: In the file server.js, we are importing the index.js file which holds the actual program which needs to be executed. Now in the terminal type node server.js to execute the programThe output of the index.js and index.mjs file in the above method is:localhost:5000Advantages of using import in place of require in nodejs:Import helps in selectively loading the pieces of code which are required that helps in saving memory.In case of require loading is synchronous whereas import can be asynchronous so it performs better than required.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 30388,
"s": 30324,
"text": "Importing an entire module: import * as name from 'module-name'"
},
{
"code": null,
"e": 30417,
"s": 30388,
"text": "Importing an entire module: "
},
{
"code": null,
"e": 30453,
"s": 30417,
"text": "import * as name from 'module-name'"
},
{
"code": null,
"e": 30520,
"s": 30453,
"text": "Import default export from a module:import name from 'module-name'"
},
{
"code": null,
"e": 30557,
"s": 30520,
"text": "Import default export from a module:"
},
{
"code": null,
"e": 30588,
"s": 30557,
"text": "import name from 'module-name'"
},
{
"code": null,
"e": 30663,
"s": 30588,
"text": "Importing a single export from a module:import { name } from 'module-name'"
},
{
"code": null,
"e": 30704,
"s": 30663,
"text": "Importing a single export from a module:"
},
{
"code": null,
"e": 30739,
"s": 30704,
"text": "import { name } from 'module-name'"
},
{
"code": null,
"e": 30828,
"s": 30739,
"text": "Importing multiple exports from a module:import { nameOne , nameTwo } from 'module-name'"
},
{
"code": null,
"e": 30870,
"s": 30828,
"text": "Importing multiple exports from a module:"
},
{
"code": null,
"e": 30918,
"s": 30870,
"text": "import { nameOne , nameTwo } from 'module-name'"
},
{
"code": null,
"e": 34400,
"s": 30918,
"text": "Importing a module for side effects onlyimport './module-name'Node js doesn’t support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error. For example, if we try to import express module by writing import express from ‘express’ node js will throw an error as follows:Node has experimental support for ES modules. To enable them we need to make some changes to the package.json file. Before following the steps make sure that Node is installed. Below are the steps to achieve the same.In the package.json file add “type” : “module”. Adding this enables ES6 modules.The package.json file should look like this:package.jsonpackage.json//package.json{ \"name\": \"index\", \"version\": \"1.0.0\", \"description\": \"\", \"main\": \"index.js\", \"type\": \"module\", \"scripts\": { \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\" }, \"keywords\": [], \"author\": \"\", \"license\": \"ISC\"}Create a file index.js and write the program using ES6 import. For example, let’s try to import express in index.js fileindex.js fileindex.js file//index.js import express from 'express'; const app = express(); app.get('/',(req,res) => { res.send('GeeksforGeeks');}) const PORT = 5000; app.listen(PORT,() => { console.log(`Running on PORT ${PORT}`);})Now run the index.js file by typing node –experimental-modules index.js in the terminal. Using the esm module:Another way to do this is by creating a file with .mjs extension. If we are using the file with .mjs extension then we don’t have to add “type”: “module” in the package.json file. We can directly write the program and can execute it by typing node –experimental-modules index.mjs in the terminal.Now, when using a file with .mjs extension the package.json file will look like this:JavascriptJavascript// package.json when using .mjs file{ \"name\": \"index\", \"version\": \"1.0.0\", \"description\": \"\", \"main\": \"index.js\", \"scripts\": { \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\" }, \"keywords\": [], \"author\": \"\", \"license\": \"ISC\"}Create a file index.mjs and write the program using ES6 import.JavascriptJavascript//index.mjs import express from 'express'; const app = express(); app.get('/',(req,res) => { res.send('GeeksforGeeks');}) const PORT = 5000; app.listen(PORT,() => { console.log(`Running on PORT ${PORT}`);})Now in the terminal type node –experimental-modules index.mjs . This will execute the file and the application now will be running on PORT 5000.Using the esm moduleInstallationnpm install esmNow try executing the program written in the index.js file earlier by typing node -r esm index.js in the terminal. Another way to use the esm module is by creating another file say server.js that loads esm before the actual application. In the server.js file write the below code//server.js\nrequire = require(\"esm\")(module);\nmodule.exports = require(\"./index.js\");Note: In the file server.js, we are importing the index.js file which holds the actual program which needs to be executed. Now in the terminal type node server.js to execute the programThe output of the index.js and index.mjs file in the above method is:localhost:5000Advantages of using import in place of require in nodejs:Import helps in selectively loading the pieces of code which are required that helps in saving memory.In case of require loading is synchronous whereas import can be asynchronous so it performs better than required.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 34441,
"s": 34400,
"text": "Importing a module for side effects only"
},
{
"code": null,
"e": 34464,
"s": 34441,
"text": "import './module-name'"
},
{
"code": null,
"e": 34733,
"s": 34464,
"text": "Node js doesn’t support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error. For example, if we try to import express module by writing import express from ‘express’ node js will throw an error as follows:"
},
{
"code": null,
"e": 34951,
"s": 34733,
"text": "Node has experimental support for ES modules. To enable them we need to make some changes to the package.json file. Before following the steps make sure that Node is installed. Below are the steps to achieve the same."
},
{
"code": null,
"e": 35702,
"s": 34951,
"text": "In the package.json file add “type” : “module”. Adding this enables ES6 modules.The package.json file should look like this:package.jsonpackage.json//package.json{ \"name\": \"index\", \"version\": \"1.0.0\", \"description\": \"\", \"main\": \"index.js\", \"type\": \"module\", \"scripts\": { \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\" }, \"keywords\": [], \"author\": \"\", \"license\": \"ISC\"}Create a file index.js and write the program using ES6 import. For example, let’s try to import express in index.js fileindex.js fileindex.js file//index.js import express from 'express'; const app = express(); app.get('/',(req,res) => { res.send('GeeksforGeeks');}) const PORT = 5000; app.listen(PORT,() => { console.log(`Running on PORT ${PORT}`);})"
},
{
"code": null,
"e": 36091,
"s": 35702,
"text": "In the package.json file add “type” : “module”. Adding this enables ES6 modules.The package.json file should look like this:package.jsonpackage.json//package.json{ \"name\": \"index\", \"version\": \"1.0.0\", \"description\": \"\", \"main\": \"index.js\", \"type\": \"module\", \"scripts\": { \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\" }, \"keywords\": [], \"author\": \"\", \"license\": \"ISC\"}"
},
{
"code": null,
"e": 36136,
"s": 36091,
"text": "The package.json file should look like this:"
},
{
"code": null,
"e": 36149,
"s": 36136,
"text": "package.json"
},
{
"code": "//package.json{ \"name\": \"index\", \"version\": \"1.0.0\", \"description\": \"\", \"main\": \"index.js\", \"type\": \"module\", \"scripts\": { \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\" }, \"keywords\": [], \"author\": \"\", \"license\": \"ISC\"}",
"e": 36390,
"s": 36149,
"text": null
},
{
"code": null,
"e": 36753,
"s": 36390,
"text": "Create a file index.js and write the program using ES6 import. For example, let’s try to import express in index.js fileindex.js fileindex.js file//index.js import express from 'express'; const app = express(); app.get('/',(req,res) => { res.send('GeeksforGeeks');}) const PORT = 5000; app.listen(PORT,() => { console.log(`Running on PORT ${PORT}`);})"
},
{
"code": null,
"e": 36874,
"s": 36753,
"text": "Create a file index.js and write the program using ES6 import. For example, let’s try to import express in index.js file"
},
{
"code": null,
"e": 36888,
"s": 36874,
"text": "index.js file"
},
{
"code": "//index.js import express from 'express'; const app = express(); app.get('/',(req,res) => { res.send('GeeksforGeeks');}) const PORT = 5000; app.listen(PORT,() => { console.log(`Running on PORT ${PORT}`);})",
"e": 37105,
"s": 36888,
"text": null
},
{
"code": null,
"e": 37195,
"s": 37105,
"text": "Now run the index.js file by typing node –experimental-modules index.js in the terminal. "
},
{
"code": null,
"e": 37217,
"s": 37195,
"text": "Using the esm module:"
},
{
"code": null,
"e": 37514,
"s": 37217,
"text": "Another way to do this is by creating a file with .mjs extension. If we are using the file with .mjs extension then we don’t have to add “type”: “module” in the package.json file. We can directly write the program and can execute it by typing node –experimental-modules index.mjs in the terminal."
},
{
"code": null,
"e": 37600,
"s": 37514,
"text": "Now, when using a file with .mjs extension the package.json file will look like this:"
},
{
"code": null,
"e": 37611,
"s": 37600,
"text": "Javascript"
},
{
"code": "// package.json when using .mjs file{ \"name\": \"index\", \"version\": \"1.0.0\", \"description\": \"\", \"main\": \"index.js\", \"scripts\": { \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\" }, \"keywords\": [], \"author\": \"\", \"license\": \"ISC\"}",
"e": 37855,
"s": 37611,
"text": null
},
{
"code": null,
"e": 37919,
"s": 37855,
"text": "Create a file index.mjs and write the program using ES6 import."
},
{
"code": null,
"e": 37930,
"s": 37919,
"text": "Javascript"
},
{
"code": "//index.mjs import express from 'express'; const app = express(); app.get('/',(req,res) => { res.send('GeeksforGeeks');}) const PORT = 5000; app.listen(PORT,() => { console.log(`Running on PORT ${PORT}`);})",
"e": 38148,
"s": 37930,
"text": null
},
{
"code": null,
"e": 38293,
"s": 38148,
"text": "Now in the terminal type node –experimental-modules index.mjs . This will execute the file and the application now will be running on PORT 5000."
},
{
"code": null,
"e": 38314,
"s": 38293,
"text": "Using the esm module"
},
{
"code": null,
"e": 38327,
"s": 38314,
"text": "Installation"
},
{
"code": null,
"e": 38343,
"s": 38327,
"text": "npm install esm"
},
{
"code": null,
"e": 38459,
"s": 38343,
"text": "Now try executing the program written in the index.js file earlier by typing node -r esm index.js in the terminal. "
},
{
"code": null,
"e": 38624,
"s": 38459,
"text": "Another way to use the esm module is by creating another file say server.js that loads esm before the actual application. In the server.js file write the below code"
},
{
"code": null,
"e": 38710,
"s": 38624,
"text": "//server.js\nrequire = require(\"esm\")(module);\nmodule.exports = require(\"./index.js\");"
},
{
"code": null,
"e": 38834,
"s": 38710,
"text": "Note: In the file server.js, we are importing the index.js file which holds the actual program which needs to be executed. "
},
{
"code": null,
"e": 38897,
"s": 38834,
"text": "Now in the terminal type node server.js to execute the program"
},
{
"code": null,
"e": 38967,
"s": 38897,
"text": "The output of the index.js and index.mjs file in the above method is:"
},
{
"code": null,
"e": 38982,
"s": 38967,
"text": "localhost:5000"
},
{
"code": null,
"e": 39040,
"s": 38982,
"text": "Advantages of using import in place of require in nodejs:"
},
{
"code": null,
"e": 39143,
"s": 39040,
"text": "Import helps in selectively loading the pieces of code which are required that helps in saving memory."
},
{
"code": null,
"e": 39257,
"s": 39143,
"text": "In case of require loading is synchronous whereas import can be asynchronous so it performs better than required."
},
{
"code": null,
"e": 39274,
"s": 39257,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 39281,
"s": 39274,
"text": "Picked"
},
{
"code": null,
"e": 39305,
"s": 39281,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 39313,
"s": 39305,
"text": "Node.js"
},
{
"code": null,
"e": 39332,
"s": 39313,
"text": "Technical Scripter"
},
{
"code": null,
"e": 39430,
"s": 39332,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39500,
"s": 39430,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 39539,
"s": 39500,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 39561,
"s": 39539,
"text": "Node.js Export Module"
},
{
"code": null,
"e": 39588,
"s": 39561,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 39613,
"s": 39588,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 39645,
"s": 39613,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 39676,
"s": 39645,
"text": "Express.js req.params Property"
},
{
"code": null,
"e": 39733,
"s": 39676,
"text": "How to build a basic CRUD app with Node.js and ReactJS ?"
},
{
"code": null,
"e": 39768,
"s": 39733,
"text": "Installation of Node.js on Windows"
}
] |
PyQtGraph – Setting Fixed Size of Image View - GeeksforGeeks
|
28 Dec, 2021
In this article, we will see how we can set the fixed size of the image view in PyQTGraph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.). Widget used for display and analysis of image data. Implements many features like displaying 2D and 3D image data. For 3D data, a z-axis slider is displayed allowing the user to select which frame is displayed. Displays histogram of image data with movable region defining the dark/light levels, editable gradient provides a color lookup table. Fixed-size is the fixed size which can not be decreased or increased by default it is not set to the image view.We can create an image view with the help of the command given below
# creating a pyqtgraph image view object
imv = pg.ImageView()
Syntax: ImageView(parent=None, name=’ImageView’, view=None, imageItem=None, levelMode=’mono’, *args)
Parameters:
parent (QWidget): Specifies the parent widget to which this ImageView will belong. If None, then the ImageView is created with no parent.
name (str): The name used to register both the internal ViewBox and the PlotItem used to display ROI data.
view (ViewBox or PlotItem): If specified, this will be used as the display area that contains the displayed image.
imageItem (ImageItem): If specified, this object will be used to display the image. Must be an instance of ImageItem or other compatible object.
levelMode: specifies the *levelMode* argument
Returns: Object of class ImageView
In order to do this we use setFixedSize() method with the image view object
Syntax : imv.setFixedSize(w, h)Argument : It takes two integers as argumentReturn : It returns None
Below is the implementation
Python3
# importing Qt widgetsfrom PyQt5.QtWidgets import * # importing systemimport sys # importing numpy as npimport numpy as np # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import *from PyQt5.QtCore import * # Image View classclass ImageView(pg.ImageView): # constructor which inherit original # ImageView def __init__(self, *args, **kwargs): pg.ImageView.__init__(self, *args, **kwargs) class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("PyQtGraph") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon("skin.png") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a label label = QLabel("Geeksforgeeks Image View") # setting minimum width label.setMinimumWidth(130) # making label do word wrap label.setWordWrap(True) # setting configuration options pg.setConfigOptions(antialias = True) # creating image view view object imv = ImageView() # Create random 3D data set with noisy signals img = pg.gaussianFilter(np.random.normal(size=(200, 200)), (5, 5)) * 20 + 100 # setting new axis to image img = img[np.newaxis, :, :] # decay data decay = np.exp(-np.linspace(0, 0.3, 100))[:, np.newaxis, np.newaxis] # random data data = np.random.normal(size = (100, 200, 200)) data += img * decay data += 2 # adding time-varying signal sig = np.zeros(data.shape[0]) sig[30:] += np.exp(-np.linspace(1, 10, 70)) sig[40:] += np.exp(-np.linspace(1, 10, 60)) sig[70:] += np.exp(-np.linspace(1, 10, 30)) sig = sig[:, np.newaxis, np.newaxis] * 3 data[:, 50:60, 30:40] += sig # setting image to image view # Displaying the data and assign each frame a time value from 1.0 to 3.0 imv.setImage(data, xvals=np.linspace(1., 3., data.shape[0])) ## Set a custom color map colors = [ (0, 0, 0), (4, 5, 61), (84, 42, 55), (15, 87, 60), (208, 17, 141), (255, 255, 255) ] # color map cmap = pg.ColorMap(pos=np.linspace(0.0, 1.0, 6), color=colors) # setting color map to the image view imv.setColorMap(cmap) # Creating a grid layout layout = QGridLayout() # minimum width value of the label label.setFixedWidth(130) # setting this layout to the widget widget.setLayout(layout) # adding label in the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(imv, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # setting fixed size imv.setFixedSize(300, 300) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
sweetyty
simmytarika5
Python-gui
Python-PyQtGraph
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n28 Dec, 2021"
},
{
"code": null,
"e": 26405,
"s": 25537,
"text": "In this article, we will see how we can set the fixed size of the image view in PyQTGraph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.). Widget used for display and analysis of image data. Implements many features like displaying 2D and 3D image data. For 3D data, a z-axis slider is displayed allowing the user to select which frame is displayed. Displays histogram of image data with movable region defining the dark/light levels, editable gradient provides a color lookup table. Fixed-size is the fixed size which can not be decreased or increased by default it is not set to the image view.We can create an image view with the help of the command given below "
},
{
"code": null,
"e": 26467,
"s": 26405,
"text": "# creating a pyqtgraph image view object\nimv = pg.ImageView()"
},
{
"code": null,
"e": 26568,
"s": 26467,
"text": "Syntax: ImageView(parent=None, name=’ImageView’, view=None, imageItem=None, levelMode=’mono’, *args)"
},
{
"code": null,
"e": 26580,
"s": 26568,
"text": "Parameters:"
},
{
"code": null,
"e": 26718,
"s": 26580,
"text": "parent (QWidget): Specifies the parent widget to which this ImageView will belong. If None, then the ImageView is created with no parent."
},
{
"code": null,
"e": 26825,
"s": 26718,
"text": "name (str): The name used to register both the internal ViewBox and the PlotItem used to display ROI data."
},
{
"code": null,
"e": 26940,
"s": 26825,
"text": "view (ViewBox or PlotItem): If specified, this will be used as the display area that contains the displayed image."
},
{
"code": null,
"e": 27085,
"s": 26940,
"text": "imageItem (ImageItem): If specified, this object will be used to display the image. Must be an instance of ImageItem or other compatible object."
},
{
"code": null,
"e": 27131,
"s": 27085,
"text": "levelMode: specifies the *levelMode* argument"
},
{
"code": null,
"e": 27166,
"s": 27131,
"text": "Returns: Object of class ImageView"
},
{
"code": null,
"e": 27243,
"s": 27166,
"text": "In order to do this we use setFixedSize() method with the image view object "
},
{
"code": null,
"e": 27345,
"s": 27243,
"text": "Syntax : imv.setFixedSize(w, h)Argument : It takes two integers as argumentReturn : It returns None "
},
{
"code": null,
"e": 27375,
"s": 27345,
"text": "Below is the implementation "
},
{
"code": null,
"e": 27383,
"s": 27375,
"text": "Python3"
},
{
"code": "# importing Qt widgetsfrom PyQt5.QtWidgets import * # importing systemimport sys # importing numpy as npimport numpy as np # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import *from PyQt5.QtCore import * # Image View classclass ImageView(pg.ImageView): # constructor which inherit original # ImageView def __init__(self, *args, **kwargs): pg.ImageView.__init__(self, *args, **kwargs) class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"PyQtGraph\") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon(\"skin.png\") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a label label = QLabel(\"Geeksforgeeks Image View\") # setting minimum width label.setMinimumWidth(130) # making label do word wrap label.setWordWrap(True) # setting configuration options pg.setConfigOptions(antialias = True) # creating image view view object imv = ImageView() # Create random 3D data set with noisy signals img = pg.gaussianFilter(np.random.normal(size=(200, 200)), (5, 5)) * 20 + 100 # setting new axis to image img = img[np.newaxis, :, :] # decay data decay = np.exp(-np.linspace(0, 0.3, 100))[:, np.newaxis, np.newaxis] # random data data = np.random.normal(size = (100, 200, 200)) data += img * decay data += 2 # adding time-varying signal sig = np.zeros(data.shape[0]) sig[30:] += np.exp(-np.linspace(1, 10, 70)) sig[40:] += np.exp(-np.linspace(1, 10, 60)) sig[70:] += np.exp(-np.linspace(1, 10, 30)) sig = sig[:, np.newaxis, np.newaxis] * 3 data[:, 50:60, 30:40] += sig # setting image to image view # Displaying the data and assign each frame a time value from 1.0 to 3.0 imv.setImage(data, xvals=np.linspace(1., 3., data.shape[0])) ## Set a custom color map colors = [ (0, 0, 0), (4, 5, 61), (84, 42, 55), (15, 87, 60), (208, 17, 141), (255, 255, 255) ] # color map cmap = pg.ColorMap(pos=np.linspace(0.0, 1.0, 6), color=colors) # setting color map to the image view imv.setColorMap(cmap) # Creating a grid layout layout = QGridLayout() # minimum width value of the label label.setFixedWidth(130) # setting this layout to the widget widget.setLayout(layout) # adding label in the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(imv, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # setting fixed size imv.setFixedSize(300, 300) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 30740,
"s": 27383,
"text": null
},
{
"code": null,
"e": 30753,
"s": 30740,
"text": " Output : "
},
{
"code": null,
"e": 30762,
"s": 30753,
"text": "sweetyty"
},
{
"code": null,
"e": 30775,
"s": 30762,
"text": "simmytarika5"
},
{
"code": null,
"e": 30786,
"s": 30775,
"text": "Python-gui"
},
{
"code": null,
"e": 30803,
"s": 30786,
"text": "Python-PyQtGraph"
},
{
"code": null,
"e": 30810,
"s": 30803,
"text": "Python"
},
{
"code": null,
"e": 30908,
"s": 30810,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30940,
"s": 30908,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30982,
"s": 30940,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 31024,
"s": 30982,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 31051,
"s": 31024,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 31107,
"s": 31051,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 31129,
"s": 31107,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 31168,
"s": 31129,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 31199,
"s": 31168,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 31228,
"s": 31199,
"text": "Create a directory in Python"
}
] |
For Loop- primeCheck - Java | Practice | GeeksforGeeks
|
What do you do when you need to execute certain statements more than once? You put them in a loop. Loops are very powerful. Majority of coding questions need loops to work. You can't even input testcases without loops!
Here, we will use for loop and check if the given number n is prime or not.
Note: A number is prime if it's divisible by itself and 1. Also, 1 is not prime.
Example 1:
Input:
1
Output:
No
Example 2:
Input:
2
Output:
Yes
User Task:
Your task is to complete the provided function.
Constraints:
1 <= a <= 1000
0
gyaninfo1281 month ago
class Geeks {
static void isPrime(int n){
if(n==1){
System.out.println("No");
return ;
}
for(int i=2;i≤Math.sqrt(n);i++){
if(n%i==0){
System.out.println("No");
return ;
}}
System.out.println("Yes");
}}
+1
badgujarsachin831 month ago
static void isPrime(int n) {
int cheak=1;
for (int i = 2; i <= Math.sqrt(n); i++) {
// Your code here
if(n%i==0 && n!=2){
cheak=0;
}
}
if(n==1){
cheak=0;
}
if(cheak==1){
System.out.println("Yes");
}
else{
System.out.println("No");
}
}
0
sachinmishraravi2 months ago
//java
class Geeks {
static void isPrime(int n) {
boolean flag = true;
if(n == 1 || n==0) {
System.out.println("No");
return;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if(n%i == 0 ){
flag = false;
break;
}
}
if(flag)
System.out.println("Yes");
else
System.out.println("No");
}
}
+1
piyushchpkumar3 months ago
Simple Java Solution
static void isPrime(int n) { int t = 1; for (int i = 2; i <= Math.sqrt(n)+1; i++) { if(n%i==0 && n!=2 ) { t = 0; break; } } if(n==1) t =0; if(t==0)System.out.println("No"); if(t==1)System.out.println("Yes"); }
-1
ramprasana4 months ago
When I try Compile & Run I am able to get the response properly, but when I submit I am getting results for each test case run print consecutively, which is caused result failure. If I execute the same input in the compile & run I am getting results correctly. Please let me know what I am doing wrong
-1
prajjwalfire4 months ago
static void isPrime(int n) {
if(n==1)
{
System.out.println("No");
return ;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if(n%i==0)
{
System.out.println("No");
return ;
}
}
System.out.println("Yes");
}
0
swapniltayal4225 months ago
class Geeks { static void isPrime(int n) { int i = 0; for ( i = 2; i < n; i++) { if (n % i == 0){ break; } }if (i == n){ System.out.print("Yes"); }else { System.out.print("No"); }System.out.println(); }}
0
sdsapkale5 months ago
class Geeks { static void isPrime(int n) { int i=0; for (i = 2; i <= n-1; i++) { // Your code here if(n%i==0) { break; } } if(i==n){ System.out.print("Yes"); }else{ System.out.print("No"); }
System.out.println(); }
0
pradeepsgrl125 months ago
class Geeks {
static void isPrime(int n) {
boolean flag=false;
if(n<2)
{
System.out.print("No");
}
else
{
for (int i = 2; i <= Math.sqrt(n); i++) {
// Your code here
if(n%i==0)
{
flag=true;
break;
}
}
}
if(flag==true && n>1)
{
System.out.print("No");
}
else if(flag==false &&n>1)
{
System.out.print("Yes");
}
System.out.println();
}
}
0
balahari6195 months ago
class Geeks { static void isPrime(int n) { if(n<=1) System.out.println("No"); else if(n==2 || n==3) System.out.println("Yes"); else if(n%2==0 || n%3==0) System.out.println("No"); else { for (int i = 5; i <= Math.sqrt(n); i++) { // Your code here if(n%i==0) { System.out.println("No"); } } System.out.println("Yes"); } }}
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": 497,
"s": 278,
"text": "What do you do when you need to execute certain statements more than once? You put them in a loop. Loops are very powerful. Majority of coding questions need loops to work. You can't even input testcases without loops!"
},
{
"code": null,
"e": 654,
"s": 497,
"text": "Here, we will use for loop and check if the given number n is prime or not.\nNote: A number is prime if it's divisible by itself and 1. Also, 1 is not prime."
},
{
"code": null,
"e": 665,
"s": 654,
"text": "Example 1:"
},
{
"code": null,
"e": 687,
"s": 665,
"text": "Input:\n1\n\nOutput:\nNo\n"
},
{
"code": null,
"e": 698,
"s": 687,
"text": "Example 2:"
},
{
"code": null,
"e": 720,
"s": 698,
"text": "Input:\n2\n\nOutput:\nYes"
},
{
"code": null,
"e": 781,
"s": 720,
"text": "User Task: \nYour task is to complete the provided function. "
},
{
"code": null,
"e": 809,
"s": 781,
"text": "Constraints:\n1 <= a <= 1000"
},
{
"code": null,
"e": 811,
"s": 809,
"text": "0"
},
{
"code": null,
"e": 834,
"s": 811,
"text": "gyaninfo1281 month ago"
},
{
"code": null,
"e": 848,
"s": 834,
"text": "class Geeks {"
},
{
"code": null,
"e": 876,
"s": 848,
"text": "static void isPrime(int n){"
},
{
"code": null,
"e": 886,
"s": 876,
"text": "if(n==1){"
},
{
"code": null,
"e": 912,
"s": 886,
"text": "System.out.println(\"No\");"
},
{
"code": null,
"e": 921,
"s": 912,
"text": "return ;"
},
{
"code": null,
"e": 923,
"s": 921,
"text": "}"
},
{
"code": null,
"e": 956,
"s": 923,
"text": "for(int i=2;i≤Math.sqrt(n);i++){"
},
{
"code": null,
"e": 968,
"s": 956,
"text": "if(n%i==0){"
},
{
"code": null,
"e": 994,
"s": 968,
"text": "System.out.println(\"No\");"
},
{
"code": null,
"e": 1003,
"s": 994,
"text": "return ;"
},
{
"code": null,
"e": 1006,
"s": 1003,
"text": "}}"
},
{
"code": null,
"e": 1033,
"s": 1006,
"text": "System.out.println(\"Yes\");"
},
{
"code": null,
"e": 1036,
"s": 1033,
"text": "}}"
},
{
"code": null,
"e": 1041,
"s": 1038,
"text": "+1"
},
{
"code": null,
"e": 1069,
"s": 1041,
"text": "badgujarsachin831 month ago"
},
{
"code": null,
"e": 1468,
"s": 1069,
"text": " static void isPrime(int n) {\n int cheak=1;\n for (int i = 2; i <= Math.sqrt(n); i++) {\n // Your code here\n if(n%i==0 && n!=2){\n cheak=0;\n }\n }\n if(n==1){\n cheak=0;\n }\n if(cheak==1){\n System.out.println(\"Yes\");\n }\n else{\n System.out.println(\"No\");\n }\n }"
},
{
"code": null,
"e": 1470,
"s": 1468,
"text": "0"
},
{
"code": null,
"e": 1499,
"s": 1470,
"text": "sachinmishraravi2 months ago"
},
{
"code": null,
"e": 1952,
"s": 1499,
"text": "//java\n\nclass Geeks {\n static void isPrime(int n) {\n boolean flag = true;\n if(n == 1 || n==0) {\n System.out.println(\"No\");\n return;\n }\n for (int i = 2; i <= Math.sqrt(n); i++) {\n if(n%i == 0 ){ \n flag = false;\n break;\n }\n }\n \n if(flag)\n System.out.println(\"Yes\");\n else \n System.out.println(\"No\");\n }\n}"
},
{
"code": null,
"e": 1955,
"s": 1952,
"text": "+1"
},
{
"code": null,
"e": 1982,
"s": 1955,
"text": "piyushchpkumar3 months ago"
},
{
"code": null,
"e": 2005,
"s": 1982,
"text": "Simple Java Solution "
},
{
"code": null,
"e": 2325,
"s": 2007,
"text": " static void isPrime(int n) { int t = 1; for (int i = 2; i <= Math.sqrt(n)+1; i++) { if(n%i==0 && n!=2 ) { t = 0; break; } } if(n==1) t =0; if(t==0)System.out.println(\"No\"); if(t==1)System.out.println(\"Yes\"); }"
},
{
"code": null,
"e": 2328,
"s": 2325,
"text": "-1"
},
{
"code": null,
"e": 2351,
"s": 2328,
"text": "ramprasana4 months ago"
},
{
"code": null,
"e": 2655,
"s": 2351,
"text": "When I try Compile & Run I am able to get the response properly, but when I submit I am getting results for each test case run print consecutively, which is caused result failure. If I execute the same input in the compile & run I am getting results correctly. Please let me know what I am doing wrong "
},
{
"code": null,
"e": 2658,
"s": 2655,
"text": "-1"
},
{
"code": null,
"e": 2683,
"s": 2658,
"text": "prajjwalfire4 months ago"
},
{
"code": null,
"e": 3057,
"s": 2683,
"text": " static void isPrime(int n) {\n \n if(n==1)\n {\n System.out.println(\"No\");\n return ;\n }\n \n for (int i = 2; i <= Math.sqrt(n); i++) {\n\n if(n%i==0)\n {\n System.out.println(\"No\");\n return ;\n }\n }\n \n System.out.println(\"Yes\");\n\n }"
},
{
"code": null,
"e": 3059,
"s": 3057,
"text": "0"
},
{
"code": null,
"e": 3087,
"s": 3059,
"text": "swapniltayal4225 months ago"
},
{
"code": null,
"e": 3379,
"s": 3087,
"text": "class Geeks { static void isPrime(int n) { int i = 0; for ( i = 2; i < n; i++) { if (n % i == 0){ break; } }if (i == n){ System.out.print(\"Yes\"); }else { System.out.print(\"No\"); }System.out.println(); }}"
},
{
"code": null,
"e": 3381,
"s": 3379,
"text": "0"
},
{
"code": null,
"e": 3403,
"s": 3381,
"text": "sdsapkale5 months ago"
},
{
"code": null,
"e": 3706,
"s": 3403,
"text": "class Geeks { static void isPrime(int n) { int i=0; for (i = 2; i <= n-1; i++) { // Your code here if(n%i==0) { break; } } if(i==n){ System.out.print(\"Yes\"); }else{ System.out.print(\"No\"); }"
},
{
"code": null,
"e": 3739,
"s": 3706,
"text": " System.out.println(); }"
},
{
"code": null,
"e": 3741,
"s": 3739,
"text": "0"
},
{
"code": null,
"e": 3767,
"s": 3741,
"text": "pradeepsgrl125 months ago"
},
{
"code": null,
"e": 4368,
"s": 3767,
"text": "class Geeks {\n static void isPrime(int n) {\n boolean flag=false;\n if(n<2)\n {\n System.out.print(\"No\");\n \n }\n else\n {\n for (int i = 2; i <= Math.sqrt(n); i++) {\n // Your code here\n if(n%i==0)\n {\n flag=true;\n break;\n }\n }\n }\n if(flag==true && n>1)\n {\n System.out.print(\"No\");\n }\n else if(flag==false &&n>1)\n {\n System.out.print(\"Yes\");\n }\n\n System.out.println();\n }\n}"
},
{
"code": null,
"e": 4370,
"s": 4368,
"text": "0"
},
{
"code": null,
"e": 4394,
"s": 4370,
"text": "balahari6195 months ago"
},
{
"code": null,
"e": 4853,
"s": 4394,
"text": "class Geeks { static void isPrime(int n) { if(n<=1) System.out.println(\"No\"); else if(n==2 || n==3) System.out.println(\"Yes\"); else if(n%2==0 || n%3==0) System.out.println(\"No\"); else { for (int i = 5; i <= Math.sqrt(n); i++) { // Your code here if(n%i==0) { System.out.println(\"No\"); } } System.out.println(\"Yes\"); } }}"
},
{
"code": null,
"e": 4999,
"s": 4853,
"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": 5035,
"s": 4999,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5045,
"s": 5035,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5055,
"s": 5045,
"text": "\nContest\n"
},
{
"code": null,
"e": 5118,
"s": 5055,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5266,
"s": 5118,
"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": 5474,
"s": 5266,
"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": 5580,
"s": 5474,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Flutter - AppBar Widget - GeeksforGeeks
|
22 Oct, 2020
AppBar is usually the topmost component of the app (or sometimes the bottom-most), it contains the toolbar and some other common action buttons. As all the components in a flutter application is a widget or a combination of widgets. So AppBar is also a built-in class or widget in flutter which gives the functionality of the AppBar out of the box. The AppBar widget is based on Material Design and much of the information is already provided by other classes like MediaQuery, Scaffold as to where the content of the AppBar should be placed. Though the AppBar class is very flexible and can be easily customized, we can also use SilverAppBar widget which gives scrollable functionality to the app bar. Or we can create our own custom app bar from scratch.
AppBar(
{Key key,
Widget leading,
bool automaticallyImplyLeading: true,
Widget title,
List<Widget> actions,
double elevation,
Color shadowColor,
ShapeBorder shape,
Color backgroundColor,
Brightness brightness,
IconThemeData iconTheme,
IconThemeData actionsIconTheme,
TextTheme textTheme,
...}
)
actions: This property takes in a list of widgets as a parameter to be displayed after the title if the AppBar is a row.
title: This property usually takes in the main widget as a parameter to be displayed in the AppBar.
backgroundColor: This property is used to add colors to the background of the Appbar.
elevation: This property is used to set the z-coordinate at which to place this app bar relative to its parent.
shape: This property is used to give shape to the Appbar and manage its shadow.
Example 1:
Dart
import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), ), //AppBar body: const Center( child: Text( 'GeeksforGeeks', style: TextStyle(fontSize: 24), ), //Text ), // center ), //Scaffold debugShowCheckedModeBanner: false, //Removing Debug Banner )); //MaterialApp}
Output:
Explanation:
First, we have imported the material.dart file as the AppBar widget utilizes it, we will also do the same in the following two examples. Then we have our main function calling runApp. At top, we have MaterialApp widget followed by Scaffold. The MaterialApp widget provided Style to AppBar and the Scaffold widget by default places the AppBar widget at the top of the screen. This is just the bare basic out of the box AppBar provided by flutter. This AppBar is utilizing only the title property of the AppBar class, which takes in the main widget to be displayed in the AppBar. In this case, it is a Text widget.
In the body, we have a child text widget inside the center widget displaying the text ‘GeeksforGeeks‘, with a font size of 24. In the end, the debug banner has been disabled. This will be followed by the next two examples below.
Example 2:
Dart
import "package:flutter/material.dart"; void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text("GeeksforGeeks"), titleSpacing: 00.0, centerTitle: true, toolbarHeight: 60.2, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(360)), elevation: 0.00, backgroundColor: Colors.greenAccent[400], ), //AppBar body: const Center( child: Text( 'GeeksforGeeks', style: TextStyle(fontSize: 24), ), //Text ), //Center ), //Scaffold debugShowCheckedModeBanner: false, //Removing Debug Banner )); //MaterialApp}
Output:
Explanation:
Here the AppBar widget is utilizing seven properties in total. It starts with the title ‘GeeksforGeeks’. The second is the titlespacing which takes in double as a parameter and in this case, it is set to 00.0 to keep text close together. The third property is centerTitle which takes in boolean as a parameter and is set to true here. The fourth property is toolbarHeight which also takes in double as a parameter. This property provides a shadow underneath the AppBar which in turn makes it look elevated. The fifth property is shape it is utilized to give a different shape to the AppBar by modifying the border of the AppBar. The sixth property is elevation, it defines the z-coordinates at which the AppBar is to be placed with respect to its parent. It also takes in double as a parameter. And the last is the backgroundColor which controls the background color of the AppBar, in this case, we have the signature geeksforgeeks greenAccect.
Example 3:
Dart
import "package:flutter/material.dart"; void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text("GeeksforGeeks"), actions: <Widget>[ IconButton( icon: Icon(Icons.comment), tooltip: 'Comment Icon', onPressed: () {}, ), //IconButton IconButton( icon: Icon(Icons.settings), tooltip: 'Setting Icon', onPressed: () {}, ), //IconButton ], //<Widget>[] backgroundColor: Colors.greenAccent[400], elevation: 50.0, leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu Icon', onPressed: () {}, ), //IconButton brightness: Brightness.dark, ), //AppBar body: const Center( child: Text( "Geeksforgeeks", style: TextStyle(fontSize: 24), ), //Text ), //Center ), //Scaffold debugShowCheckedModeBanner: false, //Removing Debug Banner )); //MaterialApp}
Output:
Explanation:
Here we can see that in addition to the title on the app Bar we have three more icons on the AppBar, one on the left and two on the right of the title. This AppBar widget starts with the usual title property which is taking Text widget as a parameter. The title is followed by the action property which takes in a list of widgets as a parameter to be displayed after the title if the AppBar is a row. In this case, we can see the two icons namely the comment and setting. These two icons are IconsButton widgets, utilizing three properties namely icon, tooltip, and onPressed function. The onPressed function is not specified in any of the IconButton so it is null. The icon property takes in string as a parameter which is the name of the specific icon. The tooltip property also takes in a string as the parameter which is displays in a floating label, while hovering with the mouse or on the long-press. In the first IconButton we have Icons.comment & Comment Icon and in the second IconButton we have Icons.setting & Setting Icon as the parameter for the icon and tooltip respectively. Now, all this is followed but the backgroundColor and elevation are set to Colors.greenAccent[400] and 50.0 respectively. After that, we have the leading property which takes in a widget as a parameter, to be displayed before the title in the AppBar. In this case, the leading is also a IconButton, which displays a menu icon. The onPressed property is not mentioned and the tooltip property is given a parameter of string ‘Menu Icon’. And the body is similar to the first and second examples.
ankit_kumar_
android
Flutter
Flutter-widgets
Android
Articles
Dart
Flutter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android Architecture
How to Create and Add Data to SQLite Database in Android?
MVVM (Model View ViewModel) Architecture Pattern in Android
Resource Raw Folder in Android Studio
Broadcast Receiver in Android With Example
Tree Traversals (Inorder, Preorder and Postorder)
SQL | Join (Inner, Left, Right and Full Joins)
find command in Linux with examples
How to write a Pseudo Code?
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
|
[
{
"code": null,
"e": 27185,
"s": 27157,
"text": "\n22 Oct, 2020"
},
{
"code": null,
"e": 27941,
"s": 27185,
"text": "AppBar is usually the topmost component of the app (or sometimes the bottom-most), it contains the toolbar and some other common action buttons. As all the components in a flutter application is a widget or a combination of widgets. So AppBar is also a built-in class or widget in flutter which gives the functionality of the AppBar out of the box. The AppBar widget is based on Material Design and much of the information is already provided by other classes like MediaQuery, Scaffold as to where the content of the AppBar should be placed. Though the AppBar class is very flexible and can be easily customized, we can also use SilverAppBar widget which gives scrollable functionality to the app bar. Or we can create our own custom app bar from scratch."
},
{
"code": null,
"e": 28237,
"s": 27941,
"text": "AppBar(\n{Key key,\nWidget leading,\nbool automaticallyImplyLeading: true,\nWidget title,\nList<Widget> actions,\ndouble elevation,\nColor shadowColor,\nShapeBorder shape,\nColor backgroundColor,\nBrightness brightness,\nIconThemeData iconTheme,\nIconThemeData actionsIconTheme,\nTextTheme textTheme,\n...}\n)\n"
},
{
"code": null,
"e": 28358,
"s": 28237,
"text": "actions: This property takes in a list of widgets as a parameter to be displayed after the title if the AppBar is a row."
},
{
"code": null,
"e": 28458,
"s": 28358,
"text": "title: This property usually takes in the main widget as a parameter to be displayed in the AppBar."
},
{
"code": null,
"e": 28544,
"s": 28458,
"text": "backgroundColor: This property is used to add colors to the background of the Appbar."
},
{
"code": null,
"e": 28656,
"s": 28544,
"text": "elevation: This property is used to set the z-coordinate at which to place this app bar relative to its parent."
},
{
"code": null,
"e": 28736,
"s": 28656,
"text": "shape: This property is used to give shape to the Appbar and manage its shadow."
},
{
"code": null,
"e": 28747,
"s": 28736,
"text": "Example 1:"
},
{
"code": null,
"e": 28752,
"s": 28747,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), ), //AppBar body: const Center( child: Text( 'GeeksforGeeks', style: TextStyle(fontSize: 24), ), //Text ), // center ), //Scaffold debugShowCheckedModeBanner: false, //Removing Debug Banner )); //MaterialApp}",
"e": 29167,
"s": 28752,
"text": null
},
{
"code": null,
"e": 29175,
"s": 29167,
"text": "Output:"
},
{
"code": null,
"e": 29188,
"s": 29175,
"text": "Explanation:"
},
{
"code": null,
"e": 29802,
"s": 29188,
"text": "First, we have imported the material.dart file as the AppBar widget utilizes it, we will also do the same in the following two examples. Then we have our main function calling runApp. At top, we have MaterialApp widget followed by Scaffold. The MaterialApp widget provided Style to AppBar and the Scaffold widget by default places the AppBar widget at the top of the screen. This is just the bare basic out of the box AppBar provided by flutter. This AppBar is utilizing only the title property of the AppBar class, which takes in the main widget to be displayed in the AppBar. In this case, it is a Text widget. "
},
{
"code": null,
"e": 30031,
"s": 29802,
"text": "In the body, we have a child text widget inside the center widget displaying the text ‘GeeksforGeeks‘, with a font size of 24. In the end, the debug banner has been disabled. This will be followed by the next two examples below."
},
{
"code": null,
"e": 30042,
"s": 30031,
"text": "Example 2:"
},
{
"code": null,
"e": 30047,
"s": 30042,
"text": "Dart"
},
{
"code": "import \"package:flutter/material.dart\"; void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text(\"GeeksforGeeks\"), titleSpacing: 00.0, centerTitle: true, toolbarHeight: 60.2, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(360)), elevation: 0.00, backgroundColor: Colors.greenAccent[400], ), //AppBar body: const Center( child: Text( 'GeeksforGeeks', style: TextStyle(fontSize: 24), ), //Text ), //Center ), //Scaffold debugShowCheckedModeBanner: false, //Removing Debug Banner )); //MaterialApp}",
"e": 30695,
"s": 30047,
"text": null
},
{
"code": null,
"e": 30703,
"s": 30695,
"text": "Output:"
},
{
"code": null,
"e": 30716,
"s": 30703,
"text": "Explanation:"
},
{
"code": null,
"e": 31661,
"s": 30716,
"text": "Here the AppBar widget is utilizing seven properties in total. It starts with the title ‘GeeksforGeeks’. The second is the titlespacing which takes in double as a parameter and in this case, it is set to 00.0 to keep text close together. The third property is centerTitle which takes in boolean as a parameter and is set to true here. The fourth property is toolbarHeight which also takes in double as a parameter. This property provides a shadow underneath the AppBar which in turn makes it look elevated. The fifth property is shape it is utilized to give a different shape to the AppBar by modifying the border of the AppBar. The sixth property is elevation, it defines the z-coordinates at which the AppBar is to be placed with respect to its parent. It also takes in double as a parameter. And the last is the backgroundColor which controls the background color of the AppBar, in this case, we have the signature geeksforgeeks greenAccect."
},
{
"code": null,
"e": 31672,
"s": 31661,
"text": "Example 3:"
},
{
"code": null,
"e": 31677,
"s": 31672,
"text": "Dart"
},
{
"code": "import \"package:flutter/material.dart\"; void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text(\"GeeksforGeeks\"), actions: <Widget>[ IconButton( icon: Icon(Icons.comment), tooltip: 'Comment Icon', onPressed: () {}, ), //IconButton IconButton( icon: Icon(Icons.settings), tooltip: 'Setting Icon', onPressed: () {}, ), //IconButton ], //<Widget>[] backgroundColor: Colors.greenAccent[400], elevation: 50.0, leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu Icon', onPressed: () {}, ), //IconButton brightness: Brightness.dark, ), //AppBar body: const Center( child: Text( \"Geeksforgeeks\", style: TextStyle(fontSize: 24), ), //Text ), //Center ), //Scaffold debugShowCheckedModeBanner: false, //Removing Debug Banner )); //MaterialApp}",
"e": 32690,
"s": 31677,
"text": null
},
{
"code": null,
"e": 32698,
"s": 32690,
"text": "Output:"
},
{
"code": null,
"e": 32711,
"s": 32698,
"text": "Explanation:"
},
{
"code": null,
"e": 34298,
"s": 32711,
"text": "Here we can see that in addition to the title on the app Bar we have three more icons on the AppBar, one on the left and two on the right of the title. This AppBar widget starts with the usual title property which is taking Text widget as a parameter. The title is followed by the action property which takes in a list of widgets as a parameter to be displayed after the title if the AppBar is a row. In this case, we can see the two icons namely the comment and setting. These two icons are IconsButton widgets, utilizing three properties namely icon, tooltip, and onPressed function. The onPressed function is not specified in any of the IconButton so it is null. The icon property takes in string as a parameter which is the name of the specific icon. The tooltip property also takes in a string as the parameter which is displays in a floating label, while hovering with the mouse or on the long-press. In the first IconButton we have Icons.comment & Comment Icon and in the second IconButton we have Icons.setting & Setting Icon as the parameter for the icon and tooltip respectively. Now, all this is followed but the backgroundColor and elevation are set to Colors.greenAccent[400] and 50.0 respectively. After that, we have the leading property which takes in a widget as a parameter, to be displayed before the title in the AppBar. In this case, the leading is also a IconButton, which displays a menu icon. The onPressed property is not mentioned and the tooltip property is given a parameter of string ‘Menu Icon’. And the body is similar to the first and second examples."
},
{
"code": null,
"e": 34311,
"s": 34298,
"text": "ankit_kumar_"
},
{
"code": null,
"e": 34319,
"s": 34311,
"text": "android"
},
{
"code": null,
"e": 34327,
"s": 34319,
"text": "Flutter"
},
{
"code": null,
"e": 34343,
"s": 34327,
"text": "Flutter-widgets"
},
{
"code": null,
"e": 34351,
"s": 34343,
"text": "Android"
},
{
"code": null,
"e": 34360,
"s": 34351,
"text": "Articles"
},
{
"code": null,
"e": 34365,
"s": 34360,
"text": "Dart"
},
{
"code": null,
"e": 34373,
"s": 34365,
"text": "Flutter"
},
{
"code": null,
"e": 34381,
"s": 34373,
"text": "Android"
},
{
"code": null,
"e": 34479,
"s": 34381,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34500,
"s": 34479,
"text": "Android Architecture"
},
{
"code": null,
"e": 34558,
"s": 34500,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 34618,
"s": 34558,
"text": "MVVM (Model View ViewModel) Architecture Pattern in Android"
},
{
"code": null,
"e": 34656,
"s": 34618,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 34699,
"s": 34656,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 34749,
"s": 34699,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 34796,
"s": 34749,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 34832,
"s": 34796,
"text": "find command in Linux with examples"
},
{
"code": null,
"e": 34860,
"s": 34832,
"text": "How to write a Pseudo Code?"
}
] |
C++ Switch
|
Use the switch statement to select one of many code blocks to be executed.
This is how it works:
The switch expression is evaluated once
The value of the expression is compared with the values of each case
If there is a match, the associated block of code is executed
The break and default keywords are optional, and will be described later in this chapter
The example below uses the weekday number to calculate the weekday name:
When C++ reaches a break
keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside
the block.
When a match is found, and the job is done, it's time for a break. There is no need for more testing.
A break can save a lot of execution time because it "ignores" the execution
of all the rest of the code in the switch block.
The default keyword specifies some code to run if there is no
case match:
Note: The default keyword must be used as the last statement
in the switch, and it does not need a break.
Insert the missing parts to complete the following switch statement.
int day = 2;
switch () {
1:
cout << "Saturday";
break;
2:
cout << "Sunday";
;
}
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 75,
"s": 0,
"text": "Use the switch statement to select one of many code blocks to be executed."
},
{
"code": null,
"e": 97,
"s": 75,
"text": "This is how it works:"
},
{
"code": null,
"e": 137,
"s": 97,
"text": "The switch expression is evaluated once"
},
{
"code": null,
"e": 206,
"s": 137,
"text": "The value of the expression is compared with the values of each case"
},
{
"code": null,
"e": 268,
"s": 206,
"text": "If there is a match, the associated block of code is executed"
},
{
"code": null,
"e": 357,
"s": 268,
"text": "The break and default keywords are optional, and will be described later in this chapter"
},
{
"code": null,
"e": 430,
"s": 357,
"text": "The example below uses the weekday number to calculate the weekday name:"
},
{
"code": null,
"e": 500,
"s": 430,
"text": "When C++ reaches a break \nkeyword, it breaks out of the switch block."
},
{
"code": null,
"e": 578,
"s": 500,
"text": "This will stop the execution of more code and case testing inside \nthe block."
},
{
"code": null,
"e": 680,
"s": 578,
"text": "When a match is found, and the job is done, it's time for a break. There is no need for more testing."
},
{
"code": null,
"e": 806,
"s": 680,
"text": "A break can save a lot of execution time because it \"ignores\" the execution \nof all the rest of the code in the switch block."
},
{
"code": null,
"e": 881,
"s": 806,
"text": "The default keyword specifies some code to run if there is no \ncase match:"
},
{
"code": null,
"e": 988,
"s": 881,
"text": "Note: The default keyword must be used as the last statement \nin the switch, and it does not need a break."
},
{
"code": null,
"e": 1057,
"s": 988,
"text": "Insert the missing parts to complete the following switch statement."
},
{
"code": null,
"e": 1156,
"s": 1057,
"text": "int day = 2;\nswitch () {\n 1:\n cout << \"Saturday\";\n break;\n 2:\n cout << \"Sunday\";\n ;\n}\n"
},
{
"code": null,
"e": 1175,
"s": 1156,
"text": "Start the Exercise"
},
{
"code": null,
"e": 1208,
"s": 1175,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1250,
"s": 1208,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1357,
"s": 1250,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1376,
"s": 1357,
"text": "[email protected]"
}
] |
Moving X-axis in Matplotlib during real-time plot
|
To move X-axis in Matplotlib during real-time plot, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a figure and a set of subplots.
Create x and y data points using numpy.
Plot x and y data points using plot() method.
Make an animation by repeatedly calling a function *animate* that moves the X-axis during real-time plot.
To display the figure, use show() method.
import matplotlib.pylab as plt
import matplotlib.animation as animation
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
x = np.linspace(0, 15, 100)
y = np.cos(x)
ax.plot(x, y, lw=2, color='red')
def animate(frame):
ax.set_xlim(left=0, right=frame)
ani = animation.FuncAnimation(fig, animate, frames=10)
plt.show()
|
[
{
"code": null,
"e": 1148,
"s": 1062,
"text": "To move X-axis in Matplotlib during real-time plot, we can take the following steps −"
},
{
"code": null,
"e": 1224,
"s": 1148,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1263,
"s": 1224,
"text": "Create a figure and a set of subplots."
},
{
"code": null,
"e": 1303,
"s": 1263,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1349,
"s": 1303,
"text": "Plot x and y data points using plot() method."
},
{
"code": null,
"e": 1455,
"s": 1349,
"text": "Make an animation by repeatedly calling a function *animate* that moves the X-axis during real-time plot."
},
{
"code": null,
"e": 1497,
"s": 1455,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1904,
"s": 1497,
"text": "import matplotlib.pylab as plt\nimport matplotlib.animation as animation\nimport numpy as np\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfig, ax = plt.subplots()\n\nx = np.linspace(0, 15, 100)\ny = np.cos(x)\n\nax.plot(x, y, lw=2, color='red')\n\ndef animate(frame):\n ax.set_xlim(left=0, right=frame)\n\nani = animation.FuncAnimation(fig, animate, frames=10)\n\nplt.show()"
}
] |
Deploy Machine Learning Web App on Azure | by Sagnik Chattopadhyaya | Towards Data Science
|
As a Machine Learning Engineer you role isn’t limited to building a model, but it also covers to make Models Deployable. Which on later stage is handled by DevOps team. In this Story,I will show you step by step how you can deploy an ML Classification Web App on Azure. This article is a part of the MSP Developer Stories initiative by the Microsoft Student Partners (India) program.
To start with, you need to build an web app first. For that you can use Streamlit. It is a python based open sourced framework that would help you to display text, charts, maps, dataframe, build interactive interface and many more and all that in few hours. As a first step you would build only an app.py file on your local machine and make sure it looks as expected.
Launch your Streamlit app by running streamlit run app.pyin a shell from the folder where the app.py file is saved. Whenever the app.py file is saved, the local web app will update automatically.
After you have completed building it on your local machine, next task is to deploy it to the actual internet for others to view it anytime. Now you cannot use GitHub pages as Streamlit web app is an non static site. but you can surely use a GitHub Repository for deploying it to Azure.
Have a look at my code from GitHub ,you will understand how simple it is to make an Streamlit web app.
Streamlit’s Getting Started tutorial would help to learn the API, so I will jump straight to deployment of the Streamlit web app.
For this example, I will publish an Binary Classification model showing whether Mushroom are Edible or Poisonous. I will use the Mushrooms dataset , you can find the dataset also on my GitHub.
After you have your web app ready to publish, you will create an Docker Container on the Azure Container Registry. This container will have all the files required to run the web app.
I will use Azure Shell through out but you can use Azure Portal or install the Azure CLI on your local machine. using Azure Shell or Azure CLI would be exactly same, difference is one you will use from Browser and the other you will use from Terminal.
Once you open Azure Shell you will be asked to sign in to your Azure Account. But if you are using Azure CLI, then type the following command:
az login
After you sign in to your shell you can see something like this.
Next, you need a resource Group to keep your Container Registry and Web App service. To do so type the following
az group create -l eastus -n MushroomApp
If you are using Azure Portal then follow their documentation to build resource group .
Here the location is East Us and name MushroomApp .You can name it differently but make sure to make appropriate changes in upcoming steps.
Then you will build Container Registry under the resource group.
az acr create --name MushroomAppRegistry --resource-group MushroomApp --sku basic --admin-enabled true
If you are using portal make sure to select the MushroomApp resource group created in last step.
Move back to your GitHub repository and add few more files that would help in functioning of the web app. First we will make the Dockerfile. This would be the instructions for Docker to run.
For best practices of writing Dockerfile see their official documentation.
docs.docker.com
The code for the Dockerfile you can use for this project is given below.
For the configuration files you would need config.toml and credentials.toml . I recommend copying MarcSkovMadsen’s config.toml and credentials.toml file from his awesome-streamlit repository.
Next you would need requirements.txt to add the libraries that needs to be installed for running your Web App. Below is the requirements.txt that I will use in this for this story.
streamlitpandasnumpyscikit-learnmatplotlib
Make sure you have all these files in your GitHub repository before moving to next step.
Next we will build the docker image and save to Azure Container Registry.
az acr build --registry MushroomAppRegistry --resource-group MushroomApp --image mushroom-app <SOURCE_LOCATION>
Replace <SOURCE_LOCATION> in the above code with your Git clone link. For this story the link I will use is https://github.com/sagnik20/ML-WebApp-using-Streamlit.git .
If the Build is successful, you could see output similar to: Run ID: ca1 was successful after 2m26s.
If you wish to see the image in your Container Registry, then log in to your Azure portal and navigate to your resource group, click on your container registry and under the Services Blade, click on Repositories.
You need to create an App Service Plan for your Web app. This will determine the size of the Virtual machine which will run your Web App. The default value of sku is B1 just the first tier above Free. We will use that.
All the pricing tiers available are: F1(Free), D1(Shared), B1(Basic Small), B2(Basic Medium), B3(Basic Large), S1(Standard Small), P1V2(Premium V2 Small), PC2 (Premium Container Small), PC3 (Premium Container Medium), PC4 (Premium Container Large), I1 (Isolated Small), I2 (Isolated Medium), I3 (Isolated Large). Choose one that you need.
az appservice plan create -g MushroomApp -n MushroomAppServicePlan -l eastus --is-linux --sku B1
Run the above code to create your App Service Plan.
Create the Azure Web App from the docker container in the Container Registry by running the below command.
az webapp create -g MushroomApp -p MushroomAppServicePlan -n census-web-app -i mushroomappregistry.azurecr.io/mushroom-app:latest
Or you can do the same from the portal too.
You should now see 3 resources in your Resource Group.
To view your new website, go to mushroom-web-app resource and click on the URL on the top right shown in picture below.
The first time you view it, there will be a cold-start delay and will likely become unresponsive after about 5 minutes. Go back to the resource and click click on the URL again, and your web app should appear in your browser!
If you need to make any changes to your app.py file, then you can easily view your changes by redeploying your web app. For that again run the code below by replacing <SOURCE_LOCATION> again. You have already did it once above.
az acr build --registry MushroomAppRegistry --resource-group MushroomApp --image mushroom-app <SOURCE_LOCATION>
You can add functionality or make changes and simply redeploy the webapp to visualise the changes.
The final web app that I build looks something like this 👇
You can also view and interact with it from : https://mushroom-web-app.azurewebsites.net/ (Sorry temporarily the link is inactive).
We have successfully deployed our Machine Learning model as a Web Application simply using Docker and Azure. Full code can be found on my GitHub Repo.
Thank You for reading!
I’m Sagnik Chattopadhyaya, a Microsoft Student Partner. You can Visit my Website to know more about me. Twitter: @sagnik_20 . YouTube: Learn Overflow
Hope you got to learn from this story. ❤
Happy Learning! 🐱💻
|
[
{
"code": null,
"e": 556,
"s": 172,
"text": "As a Machine Learning Engineer you role isn’t limited to building a model, but it also covers to make Models Deployable. Which on later stage is handled by DevOps team. In this Story,I will show you step by step how you can deploy an ML Classification Web App on Azure. This article is a part of the MSP Developer Stories initiative by the Microsoft Student Partners (India) program."
},
{
"code": null,
"e": 924,
"s": 556,
"text": "To start with, you need to build an web app first. For that you can use Streamlit. It is a python based open sourced framework that would help you to display text, charts, maps, dataframe, build interactive interface and many more and all that in few hours. As a first step you would build only an app.py file on your local machine and make sure it looks as expected."
},
{
"code": null,
"e": 1120,
"s": 924,
"text": "Launch your Streamlit app by running streamlit run app.pyin a shell from the folder where the app.py file is saved. Whenever the app.py file is saved, the local web app will update automatically."
},
{
"code": null,
"e": 1406,
"s": 1120,
"text": "After you have completed building it on your local machine, next task is to deploy it to the actual internet for others to view it anytime. Now you cannot use GitHub pages as Streamlit web app is an non static site. but you can surely use a GitHub Repository for deploying it to Azure."
},
{
"code": null,
"e": 1509,
"s": 1406,
"text": "Have a look at my code from GitHub ,you will understand how simple it is to make an Streamlit web app."
},
{
"code": null,
"e": 1639,
"s": 1509,
"text": "Streamlit’s Getting Started tutorial would help to learn the API, so I will jump straight to deployment of the Streamlit web app."
},
{
"code": null,
"e": 1832,
"s": 1639,
"text": "For this example, I will publish an Binary Classification model showing whether Mushroom are Edible or Poisonous. I will use the Mushrooms dataset , you can find the dataset also on my GitHub."
},
{
"code": null,
"e": 2015,
"s": 1832,
"text": "After you have your web app ready to publish, you will create an Docker Container on the Azure Container Registry. This container will have all the files required to run the web app."
},
{
"code": null,
"e": 2267,
"s": 2015,
"text": "I will use Azure Shell through out but you can use Azure Portal or install the Azure CLI on your local machine. using Azure Shell or Azure CLI would be exactly same, difference is one you will use from Browser and the other you will use from Terminal."
},
{
"code": null,
"e": 2410,
"s": 2267,
"text": "Once you open Azure Shell you will be asked to sign in to your Azure Account. But if you are using Azure CLI, then type the following command:"
},
{
"code": null,
"e": 2419,
"s": 2410,
"text": "az login"
},
{
"code": null,
"e": 2484,
"s": 2419,
"text": "After you sign in to your shell you can see something like this."
},
{
"code": null,
"e": 2597,
"s": 2484,
"text": "Next, you need a resource Group to keep your Container Registry and Web App service. To do so type the following"
},
{
"code": null,
"e": 2638,
"s": 2597,
"text": "az group create -l eastus -n MushroomApp"
},
{
"code": null,
"e": 2726,
"s": 2638,
"text": "If you are using Azure Portal then follow their documentation to build resource group ."
},
{
"code": null,
"e": 2866,
"s": 2726,
"text": "Here the location is East Us and name MushroomApp .You can name it differently but make sure to make appropriate changes in upcoming steps."
},
{
"code": null,
"e": 2931,
"s": 2866,
"text": "Then you will build Container Registry under the resource group."
},
{
"code": null,
"e": 3034,
"s": 2931,
"text": "az acr create --name MushroomAppRegistry --resource-group MushroomApp --sku basic --admin-enabled true"
},
{
"code": null,
"e": 3131,
"s": 3034,
"text": "If you are using portal make sure to select the MushroomApp resource group created in last step."
},
{
"code": null,
"e": 3322,
"s": 3131,
"text": "Move back to your GitHub repository and add few more files that would help in functioning of the web app. First we will make the Dockerfile. This would be the instructions for Docker to run."
},
{
"code": null,
"e": 3397,
"s": 3322,
"text": "For best practices of writing Dockerfile see their official documentation."
},
{
"code": null,
"e": 3413,
"s": 3397,
"text": "docs.docker.com"
},
{
"code": null,
"e": 3486,
"s": 3413,
"text": "The code for the Dockerfile you can use for this project is given below."
},
{
"code": null,
"e": 3678,
"s": 3486,
"text": "For the configuration files you would need config.toml and credentials.toml . I recommend copying MarcSkovMadsen’s config.toml and credentials.toml file from his awesome-streamlit repository."
},
{
"code": null,
"e": 3859,
"s": 3678,
"text": "Next you would need requirements.txt to add the libraries that needs to be installed for running your Web App. Below is the requirements.txt that I will use in this for this story."
},
{
"code": null,
"e": 3902,
"s": 3859,
"text": "streamlitpandasnumpyscikit-learnmatplotlib"
},
{
"code": null,
"e": 3991,
"s": 3902,
"text": "Make sure you have all these files in your GitHub repository before moving to next step."
},
{
"code": null,
"e": 4065,
"s": 3991,
"text": "Next we will build the docker image and save to Azure Container Registry."
},
{
"code": null,
"e": 4177,
"s": 4065,
"text": "az acr build --registry MushroomAppRegistry --resource-group MushroomApp --image mushroom-app <SOURCE_LOCATION>"
},
{
"code": null,
"e": 4345,
"s": 4177,
"text": "Replace <SOURCE_LOCATION> in the above code with your Git clone link. For this story the link I will use is https://github.com/sagnik20/ML-WebApp-using-Streamlit.git ."
},
{
"code": null,
"e": 4446,
"s": 4345,
"text": "If the Build is successful, you could see output similar to: Run ID: ca1 was successful after 2m26s."
},
{
"code": null,
"e": 4659,
"s": 4446,
"text": "If you wish to see the image in your Container Registry, then log in to your Azure portal and navigate to your resource group, click on your container registry and under the Services Blade, click on Repositories."
},
{
"code": null,
"e": 4878,
"s": 4659,
"text": "You need to create an App Service Plan for your Web app. This will determine the size of the Virtual machine which will run your Web App. The default value of sku is B1 just the first tier above Free. We will use that."
},
{
"code": null,
"e": 5217,
"s": 4878,
"text": "All the pricing tiers available are: F1(Free), D1(Shared), B1(Basic Small), B2(Basic Medium), B3(Basic Large), S1(Standard Small), P1V2(Premium V2 Small), PC2 (Premium Container Small), PC3 (Premium Container Medium), PC4 (Premium Container Large), I1 (Isolated Small), I2 (Isolated Medium), I3 (Isolated Large). Choose one that you need."
},
{
"code": null,
"e": 5314,
"s": 5217,
"text": "az appservice plan create -g MushroomApp -n MushroomAppServicePlan -l eastus --is-linux --sku B1"
},
{
"code": null,
"e": 5366,
"s": 5314,
"text": "Run the above code to create your App Service Plan."
},
{
"code": null,
"e": 5473,
"s": 5366,
"text": "Create the Azure Web App from the docker container in the Container Registry by running the below command."
},
{
"code": null,
"e": 5603,
"s": 5473,
"text": "az webapp create -g MushroomApp -p MushroomAppServicePlan -n census-web-app -i mushroomappregistry.azurecr.io/mushroom-app:latest"
},
{
"code": null,
"e": 5647,
"s": 5603,
"text": "Or you can do the same from the portal too."
},
{
"code": null,
"e": 5702,
"s": 5647,
"text": "You should now see 3 resources in your Resource Group."
},
{
"code": null,
"e": 5822,
"s": 5702,
"text": "To view your new website, go to mushroom-web-app resource and click on the URL on the top right shown in picture below."
},
{
"code": null,
"e": 6048,
"s": 5822,
"text": "The first time you view it, there will be a cold-start delay and will likely become unresponsive after about 5 minutes. Go back to the resource and click click on the URL again, and your web app should appear in your browser!"
},
{
"code": null,
"e": 6276,
"s": 6048,
"text": "If you need to make any changes to your app.py file, then you can easily view your changes by redeploying your web app. For that again run the code below by replacing <SOURCE_LOCATION> again. You have already did it once above."
},
{
"code": null,
"e": 6388,
"s": 6276,
"text": "az acr build --registry MushroomAppRegistry --resource-group MushroomApp --image mushroom-app <SOURCE_LOCATION>"
},
{
"code": null,
"e": 6487,
"s": 6388,
"text": "You can add functionality or make changes and simply redeploy the webapp to visualise the changes."
},
{
"code": null,
"e": 6546,
"s": 6487,
"text": "The final web app that I build looks something like this 👇"
},
{
"code": null,
"e": 6678,
"s": 6546,
"text": "You can also view and interact with it from : https://mushroom-web-app.azurewebsites.net/ (Sorry temporarily the link is inactive)."
},
{
"code": null,
"e": 6829,
"s": 6678,
"text": "We have successfully deployed our Machine Learning model as a Web Application simply using Docker and Azure. Full code can be found on my GitHub Repo."
},
{
"code": null,
"e": 6852,
"s": 6829,
"text": "Thank You for reading!"
},
{
"code": null,
"e": 7002,
"s": 6852,
"text": "I’m Sagnik Chattopadhyaya, a Microsoft Student Partner. You can Visit my Website to know more about me. Twitter: @sagnik_20 . YouTube: Learn Overflow"
},
{
"code": null,
"e": 7043,
"s": 7002,
"text": "Hope you got to learn from this story. ❤"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.