title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to Build a REST API with Python | Towards Data Science | How can we set up a way to communicate from one software instance to another? It sounds simple, and — to be completely honest — it is.
All we need is an API.
An API (Application Programming Interface) is a simple interface that defines the types of requests (demands/questions, etc.) that can be made, how they are made, and how they are processed.
In our case, we will be building an API that allows us to send a range of GET/POST/PUT/PATCH/DELETE requests (more on this later), to different endpoints, and return or modify data connected to our API.
We will be using the Flask framework to create our API and Postman to test it. In short, we will cover:
> Setup - Our Toy Data - Initialize a Flask API - Endpoints - Running a Local Server> Writing Our API - GET - POST - 401 Unauthorized - PUT - DELETE - Users Class (summary)> That's It!
Our API will contain two endpoints, users and locations. The former will allow access to our registered user's details, whereas the latter will include a list of cafe locations.
The hypothetical use-case here is of a multi-million cafe bookmarking app, where users open the app and bookmark their favorite cafe’s — like Google Maps, but not useful.
For the sake of simplicity, we are going to store this data in two local CSV files. In reality, you probably want to take a look at something like MongoDB or Google Firebase.
Our CSV files look like this:
You can download users.csv here, and locations.csv here.
Now to our Python script, we need to import modules and initialize our API, like so:
from flask import Flaskfrom flask_restful import Resource, Api, reqparseimport pandas as pdimport astapp = Flask(__name__)api = Api(app)
As we already touched on, our API will have two endpoints, users and locations.
The result of this is — if our API was located at www.api.com, communication with the Users class would be provided at www.api.com/users and Locations at www.api.com/locations.
To create an endpoint, we define a Python class (with any name you want) and connect it to our desired endpoint with api.add_resource, like this:
Flask needs to know that this class is an endpoint for our API, and so we pass Resource in with the class definition.
Inside the class, we include our HTTP methods (GET, POST, DELETE, etc.).
Finally, we link our Users class with the /users endpoint using api.add_resource.
Because we want two endpoints, we replicate the logic:
Finally, when we write out our API, we need to test it!
To do this, we need to host our API, which we can do locally by adding app.run to the end of our script like this:
if __name__ == '__main__': app.run() # run our Flask app
Now, when we run our script, we should see something like this:
Once our server is setup, we can test our API as we build it using Postman, if you haven’t used it before it is the de-facto standard for API testing. And, don’t worry — it’s incredibly simple to use — download Postman from here.
Before going ahead, you can find the full script that we will be building here. If you’re not sure where a code snippet should go, check there!
Inside each of our classes, we keep our HTTP methods, GET, POST, and DELETE.
To create a GET method, we use def get(self). POST and DELETE follow the same pattern.
The GET method is the simplest. We return all data stored in users.csv wrapped inside a dictionary, like so:
We can then run the script to initialize our API, open Postman and send a GET request to our localhost address (typically http://127.0.0.1:5000)— this is our API entry point.
To send a GET request to our API in Postman we:
Select GET from the dropdownType the entry point of our API instance + /users (the endpoint)Hit SendCheck the status code returned by our API (we should see 200 OK)View our API’s response, which is users.csv in JSON (like a dictionary) format
Select GET from the dropdown
Type the entry point of our API instance + /users (the endpoint)
Hit Send
Check the status code returned by our API (we should see 200 OK)
View our API’s response, which is users.csv in JSON (like a dictionary) format
The POST method allows us to add records to our data. In this case, we will take arguments for usedId, name, and city.
These arguments are passed to our API endpoint as URL parameters, which look like this:
http://127.0.0.1:5000/users?userId=abc123&name=The Rock&city=Los Angeles
We can specify the required parameters, and then parse the values provided using reqparse — like this:
Let’s break our parser code down:
We initialize our parser with .RequestParser().
Add our arguments with .add_argument([arg_name], required) — note that required=True means that the argument is required in the request. Alternatively, we can add optional arguments with required=False.
Parse our arguments and their values into a Python dictionary using .parse_args().
We can then access the values passed to each argument like we usually would with key-value pairs in a dictionary.
Let’s put those together to add values to our CSV:
If it’s starting to look a little more confusing — all we’re doing is:
Creating a row of new data new_data from the URL parameters args
Appending it to the pre-existing data
Saving the newly merged data
And, returning data alongside a 200 OK status code.
We can now send a POST request to create a new user, easy!
Our code handles POST requests, allowing us to write new data to users.csv — but what if that user already exists?
For that, we need to add a check. If the userId already exists, we return a 401 Unauthorized code to the user.
Going back to Postman, we can test if our API is functioning by trying to add the same user twice — this time, The Rock received a 401 Unauthorized response.
What if we want to add a cafe to a user? We can’t use POST as this returns a 401 Unauthorized code — instead, we use PUT.
Similar to POST, we need to add if-else logic in the case of the provided userId not existing.
Other than a couple of small tweaks to the code, our PUT method is almost identical to POST.
Back in Postman, our required input parameters have changed. Now, we only need userId and a location to add to the users bookmarked locations.
We can also delete records with the DELETE method.
This method is pretty straightforward, we need to specify a userId to remove, and add some if-else logic in the case of a non-existent userId.
So if Jill decides our app is useless and wants to leave, we would send a DELETE request containing her userId.
We can test this in Postman, and as expected, we return our data without Jill’s record. What if we try and delete a non-existent user?
Again, we receive our 404 Not Found and a brief message explaining that the userId was not found.
That’s all of the parts that make up the Users class, accessed via our /users endpoint. You can find the full script for it here.
After that, we still need to put together the Locations class. This other class should allow us to GET, POST, PATCH (update), and DELETE locations.
Each location is given a unique ID — when a user bookmarks a location, that unique ID is added to their locations list with PUT /users.
The code for this is not that much different from what we wrote in the Users class so that we won't repeat ourselves. However, you can find it alongside the Users class here.
It’s as simple as that. Setting up an API with Flask and Python is incredibly straightforward.
We now have an easy-to-use and standardized method for communicating between different interfaces.
We’ve covered all of the most common request methods — GET, POST, PUT, and DELETE — and a few HTTP status codes too — 200, 401, and 404.
Finally, we’ve learned how to host our API locally and test it with Postman — allowing us to quickly diagnose issues and ensure our API is behaving as intended.
All-in-all, API development is a crucial skill for developers, data scientists, and almost any other tech-inclined role you can imagine.
If you want more, I post programming tutorials on YouTube here. Or, if you have any questions or ideas for improvement, let me know on Twitter or in the comments below.
I hope you enjoyed the article and thank-you for reading!
Looking at taking the next steps in API development and sharing your work with the world? Read about API deployment with Google Cloud Platform here: | [
{
"code": null,
"e": 307,
"s": 172,
"text": "How can we set up a way to communicate from one software instance to another? It sounds simple, and — to be completely honest — it is."
},
{
"code": null,
"e": 330,
"s": 307,
"text": "All we need is an API."
},
{
"code": null,
"e": 521,
"s": 330,
"text": "An API (Application Programming Interface) is a simple interface that defines the types of requests (demands/questions, etc.) that can be made, how they are made, and how they are processed."
},
{
"code": null,
"e": 724,
"s": 521,
"text": "In our case, we will be building an API that allows us to send a range of GET/POST/PUT/PATCH/DELETE requests (more on this later), to different endpoints, and return or modify data connected to our API."
},
{
"code": null,
"e": 828,
"s": 724,
"text": "We will be using the Flask framework to create our API and Postman to test it. In short, we will cover:"
},
{
"code": null,
"e": 1023,
"s": 828,
"text": "> Setup - Our Toy Data - Initialize a Flask API - Endpoints - Running a Local Server> Writing Our API - GET - POST - 401 Unauthorized - PUT - DELETE - Users Class (summary)> That's It!"
},
{
"code": null,
"e": 1201,
"s": 1023,
"text": "Our API will contain two endpoints, users and locations. The former will allow access to our registered user's details, whereas the latter will include a list of cafe locations."
},
{
"code": null,
"e": 1372,
"s": 1201,
"text": "The hypothetical use-case here is of a multi-million cafe bookmarking app, where users open the app and bookmark their favorite cafe’s — like Google Maps, but not useful."
},
{
"code": null,
"e": 1547,
"s": 1372,
"text": "For the sake of simplicity, we are going to store this data in two local CSV files. In reality, you probably want to take a look at something like MongoDB or Google Firebase."
},
{
"code": null,
"e": 1577,
"s": 1547,
"text": "Our CSV files look like this:"
},
{
"code": null,
"e": 1634,
"s": 1577,
"text": "You can download users.csv here, and locations.csv here."
},
{
"code": null,
"e": 1719,
"s": 1634,
"text": "Now to our Python script, we need to import modules and initialize our API, like so:"
},
{
"code": null,
"e": 1856,
"s": 1719,
"text": "from flask import Flaskfrom flask_restful import Resource, Api, reqparseimport pandas as pdimport astapp = Flask(__name__)api = Api(app)"
},
{
"code": null,
"e": 1936,
"s": 1856,
"text": "As we already touched on, our API will have two endpoints, users and locations."
},
{
"code": null,
"e": 2113,
"s": 1936,
"text": "The result of this is — if our API was located at www.api.com, communication with the Users class would be provided at www.api.com/users and Locations at www.api.com/locations."
},
{
"code": null,
"e": 2259,
"s": 2113,
"text": "To create an endpoint, we define a Python class (with any name you want) and connect it to our desired endpoint with api.add_resource, like this:"
},
{
"code": null,
"e": 2377,
"s": 2259,
"text": "Flask needs to know that this class is an endpoint for our API, and so we pass Resource in with the class definition."
},
{
"code": null,
"e": 2450,
"s": 2377,
"text": "Inside the class, we include our HTTP methods (GET, POST, DELETE, etc.)."
},
{
"code": null,
"e": 2532,
"s": 2450,
"text": "Finally, we link our Users class with the /users endpoint using api.add_resource."
},
{
"code": null,
"e": 2587,
"s": 2532,
"text": "Because we want two endpoints, we replicate the logic:"
},
{
"code": null,
"e": 2643,
"s": 2587,
"text": "Finally, when we write out our API, we need to test it!"
},
{
"code": null,
"e": 2758,
"s": 2643,
"text": "To do this, we need to host our API, which we can do locally by adding app.run to the end of our script like this:"
},
{
"code": null,
"e": 2819,
"s": 2758,
"text": "if __name__ == '__main__': app.run() # run our Flask app"
},
{
"code": null,
"e": 2883,
"s": 2819,
"text": "Now, when we run our script, we should see something like this:"
},
{
"code": null,
"e": 3113,
"s": 2883,
"text": "Once our server is setup, we can test our API as we build it using Postman, if you haven’t used it before it is the de-facto standard for API testing. And, don’t worry — it’s incredibly simple to use — download Postman from here."
},
{
"code": null,
"e": 3257,
"s": 3113,
"text": "Before going ahead, you can find the full script that we will be building here. If you’re not sure where a code snippet should go, check there!"
},
{
"code": null,
"e": 3334,
"s": 3257,
"text": "Inside each of our classes, we keep our HTTP methods, GET, POST, and DELETE."
},
{
"code": null,
"e": 3421,
"s": 3334,
"text": "To create a GET method, we use def get(self). POST and DELETE follow the same pattern."
},
{
"code": null,
"e": 3530,
"s": 3421,
"text": "The GET method is the simplest. We return all data stored in users.csv wrapped inside a dictionary, like so:"
},
{
"code": null,
"e": 3705,
"s": 3530,
"text": "We can then run the script to initialize our API, open Postman and send a GET request to our localhost address (typically http://127.0.0.1:5000)— this is our API entry point."
},
{
"code": null,
"e": 3753,
"s": 3705,
"text": "To send a GET request to our API in Postman we:"
},
{
"code": null,
"e": 3996,
"s": 3753,
"text": "Select GET from the dropdownType the entry point of our API instance + /users (the endpoint)Hit SendCheck the status code returned by our API (we should see 200 OK)View our API’s response, which is users.csv in JSON (like a dictionary) format"
},
{
"code": null,
"e": 4025,
"s": 3996,
"text": "Select GET from the dropdown"
},
{
"code": null,
"e": 4090,
"s": 4025,
"text": "Type the entry point of our API instance + /users (the endpoint)"
},
{
"code": null,
"e": 4099,
"s": 4090,
"text": "Hit Send"
},
{
"code": null,
"e": 4164,
"s": 4099,
"text": "Check the status code returned by our API (we should see 200 OK)"
},
{
"code": null,
"e": 4243,
"s": 4164,
"text": "View our API’s response, which is users.csv in JSON (like a dictionary) format"
},
{
"code": null,
"e": 4362,
"s": 4243,
"text": "The POST method allows us to add records to our data. In this case, we will take arguments for usedId, name, and city."
},
{
"code": null,
"e": 4450,
"s": 4362,
"text": "These arguments are passed to our API endpoint as URL parameters, which look like this:"
},
{
"code": null,
"e": 4523,
"s": 4450,
"text": "http://127.0.0.1:5000/users?userId=abc123&name=The Rock&city=Los Angeles"
},
{
"code": null,
"e": 4626,
"s": 4523,
"text": "We can specify the required parameters, and then parse the values provided using reqparse — like this:"
},
{
"code": null,
"e": 4660,
"s": 4626,
"text": "Let’s break our parser code down:"
},
{
"code": null,
"e": 4708,
"s": 4660,
"text": "We initialize our parser with .RequestParser()."
},
{
"code": null,
"e": 4911,
"s": 4708,
"text": "Add our arguments with .add_argument([arg_name], required) — note that required=True means that the argument is required in the request. Alternatively, we can add optional arguments with required=False."
},
{
"code": null,
"e": 4994,
"s": 4911,
"text": "Parse our arguments and their values into a Python dictionary using .parse_args()."
},
{
"code": null,
"e": 5108,
"s": 4994,
"text": "We can then access the values passed to each argument like we usually would with key-value pairs in a dictionary."
},
{
"code": null,
"e": 5159,
"s": 5108,
"text": "Let’s put those together to add values to our CSV:"
},
{
"code": null,
"e": 5230,
"s": 5159,
"text": "If it’s starting to look a little more confusing — all we’re doing is:"
},
{
"code": null,
"e": 5295,
"s": 5230,
"text": "Creating a row of new data new_data from the URL parameters args"
},
{
"code": null,
"e": 5333,
"s": 5295,
"text": "Appending it to the pre-existing data"
},
{
"code": null,
"e": 5362,
"s": 5333,
"text": "Saving the newly merged data"
},
{
"code": null,
"e": 5414,
"s": 5362,
"text": "And, returning data alongside a 200 OK status code."
},
{
"code": null,
"e": 5473,
"s": 5414,
"text": "We can now send a POST request to create a new user, easy!"
},
{
"code": null,
"e": 5588,
"s": 5473,
"text": "Our code handles POST requests, allowing us to write new data to users.csv — but what if that user already exists?"
},
{
"code": null,
"e": 5699,
"s": 5588,
"text": "For that, we need to add a check. If the userId already exists, we return a 401 Unauthorized code to the user."
},
{
"code": null,
"e": 5857,
"s": 5699,
"text": "Going back to Postman, we can test if our API is functioning by trying to add the same user twice — this time, The Rock received a 401 Unauthorized response."
},
{
"code": null,
"e": 5979,
"s": 5857,
"text": "What if we want to add a cafe to a user? We can’t use POST as this returns a 401 Unauthorized code — instead, we use PUT."
},
{
"code": null,
"e": 6074,
"s": 5979,
"text": "Similar to POST, we need to add if-else logic in the case of the provided userId not existing."
},
{
"code": null,
"e": 6167,
"s": 6074,
"text": "Other than a couple of small tweaks to the code, our PUT method is almost identical to POST."
},
{
"code": null,
"e": 6310,
"s": 6167,
"text": "Back in Postman, our required input parameters have changed. Now, we only need userId and a location to add to the users bookmarked locations."
},
{
"code": null,
"e": 6361,
"s": 6310,
"text": "We can also delete records with the DELETE method."
},
{
"code": null,
"e": 6504,
"s": 6361,
"text": "This method is pretty straightforward, we need to specify a userId to remove, and add some if-else logic in the case of a non-existent userId."
},
{
"code": null,
"e": 6616,
"s": 6504,
"text": "So if Jill decides our app is useless and wants to leave, we would send a DELETE request containing her userId."
},
{
"code": null,
"e": 6751,
"s": 6616,
"text": "We can test this in Postman, and as expected, we return our data without Jill’s record. What if we try and delete a non-existent user?"
},
{
"code": null,
"e": 6849,
"s": 6751,
"text": "Again, we receive our 404 Not Found and a brief message explaining that the userId was not found."
},
{
"code": null,
"e": 6979,
"s": 6849,
"text": "That’s all of the parts that make up the Users class, accessed via our /users endpoint. You can find the full script for it here."
},
{
"code": null,
"e": 7127,
"s": 6979,
"text": "After that, we still need to put together the Locations class. This other class should allow us to GET, POST, PATCH (update), and DELETE locations."
},
{
"code": null,
"e": 7263,
"s": 7127,
"text": "Each location is given a unique ID — when a user bookmarks a location, that unique ID is added to their locations list with PUT /users."
},
{
"code": null,
"e": 7438,
"s": 7263,
"text": "The code for this is not that much different from what we wrote in the Users class so that we won't repeat ourselves. However, you can find it alongside the Users class here."
},
{
"code": null,
"e": 7533,
"s": 7438,
"text": "It’s as simple as that. Setting up an API with Flask and Python is incredibly straightforward."
},
{
"code": null,
"e": 7632,
"s": 7533,
"text": "We now have an easy-to-use and standardized method for communicating between different interfaces."
},
{
"code": null,
"e": 7769,
"s": 7632,
"text": "We’ve covered all of the most common request methods — GET, POST, PUT, and DELETE — and a few HTTP status codes too — 200, 401, and 404."
},
{
"code": null,
"e": 7930,
"s": 7769,
"text": "Finally, we’ve learned how to host our API locally and test it with Postman — allowing us to quickly diagnose issues and ensure our API is behaving as intended."
},
{
"code": null,
"e": 8067,
"s": 7930,
"text": "All-in-all, API development is a crucial skill for developers, data scientists, and almost any other tech-inclined role you can imagine."
},
{
"code": null,
"e": 8236,
"s": 8067,
"text": "If you want more, I post programming tutorials on YouTube here. Or, if you have any questions or ideas for improvement, let me know on Twitter or in the comments below."
},
{
"code": null,
"e": 8294,
"s": 8236,
"text": "I hope you enjoyed the article and thank-you for reading!"
}
]
|
Bitwise NOT operator in Golang | 05 May, 2020
Bitwise NOT operator in the programming world usually takes one number and returns the inverted bits of that number as shown below:
Bitwise NOT of 1 = 0
Bitwise NOT of 0 = 1
Example:
Input : X = 010101
Output : Bitwise NOT of X = 101010
But Golang doesn’t have any specified unary Bitwise NOT(~) or you can say Bitwise Complement operator like other programming languages(C/C++, Java, Python, etc). Here, you have to use Bitwise XOR(^) operator as Bitwise NOT operator. But how?
Let’s understand how Bitwise XOR takes in any two equal length bit patterns and performs Exclusive OR operation on each pair of corresponding bits.
1 XOR 1 = 0
1 XOR 0 = 1
0 XOR 0 = 0
0 XOR 1 = 1
Here, you can see the result of XOR(M, N) = 1 only if M != N else it will be 0. So here, we will use the XOR operator as a unary operator to implement the one’s complement to a number.In Golang, suppose you have a given bit M, so ^M = 1 ^ M which will be equal to one’s complement or you can say the Bitwise NOT operator result.
Example: Suppose you have the given bits as 010101.
Input: 11111111 XOR 00001111
Output: 11110000
package main import "fmt" func main() { // taking the number in the hexadecimal // form it is 15 i.e. 00001111 in 8-bit form var bitwisenot byte = 0x0F // printing the number in 8-Bit fmt.Printf("%08b\n", bitwisenot) // using the ^M = 1 ^ M fmt.Printf("%08b\n", ^bitwisenot)}
Output:
00001111
11110000
Here, you can see, if we simply solve the Bitwise Not of 00001111 then it will be equal to 11110000.
Go-Operators
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 May, 2020"
},
{
"code": null,
"e": 160,
"s": 28,
"text": "Bitwise NOT operator in the programming world usually takes one number and returns the inverted bits of that number as shown below:"
},
{
"code": null,
"e": 203,
"s": 160,
"text": "Bitwise NOT of 1 = 0\nBitwise NOT of 0 = 1\n"
},
{
"code": null,
"e": 212,
"s": 203,
"text": "Example:"
},
{
"code": null,
"e": 267,
"s": 212,
"text": "Input : X = 010101\nOutput : Bitwise NOT of X = 101010\n"
},
{
"code": null,
"e": 509,
"s": 267,
"text": "But Golang doesn’t have any specified unary Bitwise NOT(~) or you can say Bitwise Complement operator like other programming languages(C/C++, Java, Python, etc). Here, you have to use Bitwise XOR(^) operator as Bitwise NOT operator. But how?"
},
{
"code": null,
"e": 657,
"s": 509,
"text": "Let’s understand how Bitwise XOR takes in any two equal length bit patterns and performs Exclusive OR operation on each pair of corresponding bits."
},
{
"code": null,
"e": 709,
"s": 657,
"text": "1 XOR 1 = 0 \n1 XOR 0 = 1 \n0 XOR 0 = 0\n0 XOR 1 = 1 \n"
},
{
"code": null,
"e": 1038,
"s": 709,
"text": "Here, you can see the result of XOR(M, N) = 1 only if M != N else it will be 0. So here, we will use the XOR operator as a unary operator to implement the one’s complement to a number.In Golang, suppose you have a given bit M, so ^M = 1 ^ M which will be equal to one’s complement or you can say the Bitwise NOT operator result."
},
{
"code": null,
"e": 1090,
"s": 1038,
"text": "Example: Suppose you have the given bits as 010101."
},
{
"code": null,
"e": 1137,
"s": 1090,
"text": "Input: 11111111 XOR 00001111\nOutput: 11110000\n"
},
{
"code": " package main import \"fmt\" func main() { // taking the number in the hexadecimal // form it is 15 i.e. 00001111 in 8-bit form var bitwisenot byte = 0x0F // printing the number in 8-Bit fmt.Printf(\"%08b\\n\", bitwisenot) // using the ^M = 1 ^ M fmt.Printf(\"%08b\\n\", ^bitwisenot)}",
"e": 1454,
"s": 1137,
"text": null
},
{
"code": null,
"e": 1462,
"s": 1454,
"text": "Output:"
},
{
"code": null,
"e": 1481,
"s": 1462,
"text": "00001111\n11110000\n"
},
{
"code": null,
"e": 1582,
"s": 1481,
"text": "Here, you can see, if we simply solve the Bitwise Not of 00001111 then it will be equal to 11110000."
},
{
"code": null,
"e": 1595,
"s": 1582,
"text": "Go-Operators"
},
{
"code": null,
"e": 1602,
"s": 1595,
"text": "Picked"
},
{
"code": null,
"e": 1614,
"s": 1602,
"text": "Go Language"
}
]
|
How to handle errors in node.js ? | 11 Jun, 2020
Node.js is a JavaScript extension used for server-side scripting. Error handling is a mandatory step in application development. A Node.js developer may work with both synchronous and asynchronous functions simultaneously. Handling errors in asynchronous functions is important because their behavior may vary, unlike synchronous functions. While try-catch blocks are effective for synchronous functions, asynchronous functions can be dealt with callbacks, promises, and async-await. Try-catch is synchronous means that if an asynchronous function throws an error in a synchronous try/catch block, no error throws. Errors thrown in Node.js applications can be handled in the following ways:
Using try-catch blockUsing callbacksUsing promises and promise callbacksUsing async-await
Using try-catch block
Using callbacks
Using promises and promise callbacks
Using async-await
Using try-catch block: The try-catch block can be used to handle errors thrown by a block of code.
function dosomething(){ throw new Error( 'a error is thrown from dosomething');} function init(){ try{ dosomething(); } catch(e){ console.log(e); } console.log( "After successful error handling");} init();
Output:
Error: a error is thrown from dosomething
at dosomething (/home/cg/root/6422736/main.js:4:11)
at init (/home/cg/root/6422736/main.js:9:9)
at Object. (/home/cg/root/6422736/main.js:17:1)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
After successful error handling
Explanation: The init() function is called which in turn calls dosomething() function which throws an error object. This error object is caught by the catch block of the init() method. If there is no proper handling of the error the program will terminate. The catch block prints the call stack to show the point where the error occurred.
Using callbacks: A callback is a function called at the completion of a certain task. Callbacks are widely used in Node.js as it prevents any blocking, and allows other code to be run in the meantime. The program does not wait for file reading to complete and proceeds to print “Program Ended” while continuing to read the file. If any error occurs like file does not exist in the system then the error is printed after “Program Ended”, else the content of the file is outputted.
var fs = require("fs"); fs.readFile('foo.txt', function (err, data) { if (err) { console.error(err);}else{ console.log(data.toString());}}); console.log("Program Ended");
Output:
Program Ended
[Error: ENOENT: no such file or directory,
open 'C:\Users\User\Desktop\foo.txt'] {
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'C:\\Users\\User\\Desktop\\foo.txt'
}
Explanation: In this case, the file does not exist in the system hence the error is thrown.
Using promises and promise callbacks: Promises are an enhancement to Node.js callbacks. When defining the callback, the value which is returned is called a “promise”. The key difference between a promise and a callback is the return value. There is no concept of a return value in callbacks. The return value provides more control for defining the callback function. In order to use promises, the promise module must be installed and imported in the application. The .then clause handles the output of the promise. If an error occurs in any .then clause or if any of the promises above rejects, it is passed to the immediate .catch clause. In case of a promise being rejected, and there is no error handler then the program terminates.
var Promise = require('promise');var MongoClient = require('mongodb').MongoClient;var url = 'mongodb://localhost/TestDB'; MongoClient.connect(url) .then(function(err, db) { db.collection('Test').updateOne({ "Name": "Joe" }, { $set: { "Name": "Beck" } }); }); .catch(error => alert(error.message))
Output:
// In this case we assume the url is wrong
MongoError: failed to connect to server [localhost:27017]
// error message may vary
Using async-await: Async-await is a special syntax to work with promises in a simpler way that is easy to understand. When we use async/await, .then is replaced by await which handles the waiting in the function. The error handling is done by the .catch clause. Async-await can also be wrapped in a try-catch block for error handling. In case no error handler exists the program terminates due to uncaught error.
async function f() { let response = await fetch('http://xyzurl');} // f() becomes a rejected promisef().catch(alert);
Output:
// the url is wrong //
TypeError: failed to fetch
Node.js-Misc
Picked
Node.js
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
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 ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Jun, 2020"
},
{
"code": null,
"e": 719,
"s": 28,
"text": "Node.js is a JavaScript extension used for server-side scripting. Error handling is a mandatory step in application development. A Node.js developer may work with both synchronous and asynchronous functions simultaneously. Handling errors in asynchronous functions is important because their behavior may vary, unlike synchronous functions. While try-catch blocks are effective for synchronous functions, asynchronous functions can be dealt with callbacks, promises, and async-await. Try-catch is synchronous means that if an asynchronous function throws an error in a synchronous try/catch block, no error throws. Errors thrown in Node.js applications can be handled in the following ways:"
},
{
"code": null,
"e": 809,
"s": 719,
"text": "Using try-catch blockUsing callbacksUsing promises and promise callbacksUsing async-await"
},
{
"code": null,
"e": 831,
"s": 809,
"text": "Using try-catch block"
},
{
"code": null,
"e": 847,
"s": 831,
"text": "Using callbacks"
},
{
"code": null,
"e": 884,
"s": 847,
"text": "Using promises and promise callbacks"
},
{
"code": null,
"e": 902,
"s": 884,
"text": "Using async-await"
},
{
"code": null,
"e": 1001,
"s": 902,
"text": "Using try-catch block: The try-catch block can be used to handle errors thrown by a block of code."
},
{
"code": "function dosomething(){ throw new Error( 'a error is thrown from dosomething');} function init(){ try{ dosomething(); } catch(e){ console.log(e); } console.log( \"After successful error handling\");} init();",
"e": 1244,
"s": 1001,
"text": null
},
{
"code": null,
"e": 1252,
"s": 1244,
"text": "Output:"
},
{
"code": null,
"e": 1784,
"s": 1252,
"text": "Error: a error is thrown from dosomething\n at dosomething (/home/cg/root/6422736/main.js:4:11)\n at init (/home/cg/root/6422736/main.js:9:9)\n at Object. (/home/cg/root/6422736/main.js:17:1)\n at Module._compile (module.js:570:32)\n at Object.Module._extensions..js (module.js:579:10)\n at Module.load (module.js:487:32)\n at tryModuleLoad (module.js:446:12)\n at Function.Module._load (module.js:438:3)\n at Module.runMain (module.js:604:10)\n at run (bootstrap_node.js:389:7)\nAfter successful error handling\n"
},
{
"code": null,
"e": 2123,
"s": 1784,
"text": "Explanation: The init() function is called which in turn calls dosomething() function which throws an error object. This error object is caught by the catch block of the init() method. If there is no proper handling of the error the program will terminate. The catch block prints the call stack to show the point where the error occurred."
},
{
"code": null,
"e": 2603,
"s": 2123,
"text": "Using callbacks: A callback is a function called at the completion of a certain task. Callbacks are widely used in Node.js as it prevents any blocking, and allows other code to be run in the meantime. The program does not wait for file reading to complete and proceeds to print “Program Ended” while continuing to read the file. If any error occurs like file does not exist in the system then the error is printed after “Program Ended”, else the content of the file is outputted."
},
{
"code": "var fs = require(\"fs\"); fs.readFile('foo.txt', function (err, data) { if (err) { console.error(err);}else{ console.log(data.toString());}}); console.log(\"Program Ended\");",
"e": 2786,
"s": 2603,
"text": null
},
{
"code": null,
"e": 2794,
"s": 2786,
"text": "Output:"
},
{
"code": null,
"e": 2994,
"s": 2794,
"text": "Program Ended\n[Error: ENOENT: no such file or directory, \n open 'C:\\Users\\User\\Desktop\\foo.txt'] {\n errno: -4058,\n code: 'ENOENT',\n syscall: 'open',\n path: 'C:\\\\Users\\\\User\\\\Desktop\\\\foo.txt'\n}\n"
},
{
"code": null,
"e": 3086,
"s": 2994,
"text": "Explanation: In this case, the file does not exist in the system hence the error is thrown."
},
{
"code": null,
"e": 3822,
"s": 3086,
"text": "Using promises and promise callbacks: Promises are an enhancement to Node.js callbacks. When defining the callback, the value which is returned is called a “promise”. The key difference between a promise and a callback is the return value. There is no concept of a return value in callbacks. The return value provides more control for defining the callback function. In order to use promises, the promise module must be installed and imported in the application. The .then clause handles the output of the promise. If an error occurs in any .then clause or if any of the promises above rejects, it is passed to the immediate .catch clause. In case of a promise being rejected, and there is no error handler then the program terminates."
},
{
"code": "var Promise = require('promise');var MongoClient = require('mongodb').MongoClient;var url = 'mongodb://localhost/TestDB'; MongoClient.connect(url) .then(function(err, db) { db.collection('Test').updateOne({ \"Name\": \"Joe\" }, { $set: { \"Name\": \"Beck\" } }); }); .catch(error => alert(error.message)) ",
"e": 4198,
"s": 3822,
"text": null
},
{
"code": null,
"e": 4206,
"s": 4198,
"text": "Output:"
},
{
"code": null,
"e": 4334,
"s": 4206,
"text": "// In this case we assume the url is wrong\nMongoError: failed to connect to server [localhost:27017]\n// error message may vary\n"
},
{
"code": null,
"e": 4747,
"s": 4334,
"text": "Using async-await: Async-await is a special syntax to work with promises in a simpler way that is easy to understand. When we use async/await, .then is replaced by await which handles the waiting in the function. The error handling is done by the .catch clause. Async-await can also be wrapped in a try-catch block for error handling. In case no error handler exists the program terminates due to uncaught error."
},
{
"code": "async function f() { let response = await fetch('http://xyzurl');} // f() becomes a rejected promisef().catch(alert);",
"e": 4867,
"s": 4747,
"text": null
},
{
"code": null,
"e": 4875,
"s": 4867,
"text": "Output:"
},
{
"code": null,
"e": 4927,
"s": 4875,
"text": "// the url is wrong //\nTypeError: failed to fetch \n"
},
{
"code": null,
"e": 4940,
"s": 4927,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 4947,
"s": 4940,
"text": "Picked"
},
{
"code": null,
"e": 4955,
"s": 4947,
"text": "Node.js"
},
{
"code": null,
"e": 4972,
"s": 4955,
"text": "Web Technologies"
},
{
"code": null,
"e": 4999,
"s": 4972,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 5097,
"s": 4999,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5127,
"s": 5097,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 5184,
"s": 5127,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 5238,
"s": 5184,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 5278,
"s": 5238,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 5310,
"s": 5278,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 5372,
"s": 5310,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5433,
"s": 5372,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5483,
"s": 5433,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5526,
"s": 5483,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Ways to express a number as product of two different factors | 23 Jun, 2022
Given a number n, write a program to calculate the number of ways in which numbers can be expressed as the product of two different factors.
Examples:
Input : 12
Output : 3
12 can be expressed as 1 * 12, 2 * 6 and 3*4.
Input : 36
Output : 4
36 can be expressed as 1 * 36, 2 * 18, 3 * 12 and 4 * 9.
All factors of 12 are = 1, 2, 3, 4, 6, 12
We can observe that factors always exist in
pair which is equal to number.
Here (1, 12), (2, 6) and (3, 4) are such pairs.
As a number can be expressed as the product of two factors we only need to find the number of factors of number up to the square root of the number. And we only need to find only different pairs so in the case of a perfect square we don’t include that factor.
C++
Java
Python 3
C#
PHP
Javascript
// CPP program to find number of ways// in which number expressed as// product of two different factors#include <bits/stdc++.h>using namespace std; // To count number of ways in which// number expressed as product// of two different numbersint countWays(int n){ // To store count of such pairs int count = 0; // Counting number of pairs // upto sqrt(n) - 1 for (int i = 1; i * i < n; i++) if (n % i == 0) count++; // To return count of pairs return count;} // Driver program to test countWays()int main(){ int n = 12; cout << countWays(n) << endl; return 0;}
// Java program to find number of ways// in which number expressed as// product of two different factorspublic class Main { // To count number of ways in which // number expressed as product // of two different numbers static int countWays(int n) { // To store count of such pairs int count = 0; // Counting number of pairs // upto sqrt(n) - 1 for (int i = 1; i * i < n; i++) if (n % i == 0) count++; // To return count of pairs return count; } // Driver program to test countWays() public static void main(String[] args) { int n = 12; System.out.println(countWays(n)); }}
# Python 3 program to find number of ways# in which number expressed as# product of two different factors # To count number of ways in which# number expressed as product# of two different numbersdef countWays(n): # To store count of such pairs count = 0 i = 1 # Counting number of pairs # upto sqrt(n) - 1 while ((i * i)<n) : if(n % i == 0): count += 1 i += 1 # To return count of pairs return count # Driver program to test countWays()n = 12print (countWays(n)) # This code is contributed# by Azkia Anam.
// C# program to find number of ways// in which number expressed as// product of two different factorsusing System; public class main { // To count number of ways in which // number expressed as product // of two different numbers static int countWays(int n) { // To store count of such pairs int count = 0; // Counting number of pairs // upto sqrt(n) - 1 for (int i = 1; i * i < n; i++) if (n % i == 0) count++; // To return count of pairs return count; } // Driver program to test countWays() public static void Main() { int n = 12; Console.WriteLine(countWays(n)); }} // This code is contributed by Anant Agarwal.
<?php// PHP program to find number of ways// in which number expressed as// product of two different factors // To count number of ways in which// number expressed as product// of two different numbersfunction countWays($n){ // To store count of such pairs $count = 0; // Counting number of pairs // upto sqrt(n) - 1 for ($i = 1; $i * $i < $n; $i++) if ($n % $i == 0) $count++; // To return count of pairs return $count;} // Driver Code$n = 12;echo countWays($n), "\n"; // This code is contributed by ajit?>
<script>// JavaScript program to find number of ways// in which number expressed as// product of two different factors // To count number of ways in which // number expressed as product // of two different numbers function countWays(n) { // To store count of such pairs let count = 0; // Counting number of pairs // upto sqrt(n) - 1 for (let i = 1; i * i < n; i++) if (n % i == 0) count++; // To return count of pairs return count; } // Driver Code let n = 12; document.write(countWays(n)); </script>
Output:
3
Time Complexity: O(√n) Auxiliary Space: O(1)
This article is contributed by Aarti_Rathi and nuclode. 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.
jit_t
code_hunt
codewithmini
prime-factor
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Merge two sorted arrays with O(1) extra space
Segment Tree | Set 1 (Sum of given range)
Fizz Buzz Implementation
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 194,
"s": 52,
"text": "Given a number n, write a program to calculate the number of ways in which numbers can be expressed as the product of two different factors. "
},
{
"code": null,
"e": 205,
"s": 194,
"text": "Examples: "
},
{
"code": null,
"e": 354,
"s": 205,
"text": "Input : 12\nOutput : 3\n12 can be expressed as 1 * 12, 2 * 6 and 3*4. \n\nInput : 36\nOutput : 4\n36 can be expressed as 1 * 36, 2 * 18, 3 * 12 and 4 * 9."
},
{
"code": null,
"e": 521,
"s": 354,
"text": "All factors of 12 are = 1, 2, 3, 4, 6, 12\n\nWe can observe that factors always exist in\npair which is equal to number.\n\nHere (1, 12), (2, 6) and (3, 4) are such pairs."
},
{
"code": null,
"e": 782,
"s": 521,
"text": "As a number can be expressed as the product of two factors we only need to find the number of factors of number up to the square root of the number. And we only need to find only different pairs so in the case of a perfect square we don’t include that factor. "
},
{
"code": null,
"e": 786,
"s": 782,
"text": "C++"
},
{
"code": null,
"e": 791,
"s": 786,
"text": "Java"
},
{
"code": null,
"e": 800,
"s": 791,
"text": "Python 3"
},
{
"code": null,
"e": 803,
"s": 800,
"text": "C#"
},
{
"code": null,
"e": 807,
"s": 803,
"text": "PHP"
},
{
"code": null,
"e": 818,
"s": 807,
"text": "Javascript"
},
{
"code": "// CPP program to find number of ways// in which number expressed as// product of two different factors#include <bits/stdc++.h>using namespace std; // To count number of ways in which// number expressed as product// of two different numbersint countWays(int n){ // To store count of such pairs int count = 0; // Counting number of pairs // upto sqrt(n) - 1 for (int i = 1; i * i < n; i++) if (n % i == 0) count++; // To return count of pairs return count;} // Driver program to test countWays()int main(){ int n = 12; cout << countWays(n) << endl; return 0;}",
"e": 1427,
"s": 818,
"text": null
},
{
"code": "// Java program to find number of ways// in which number expressed as// product of two different factorspublic class Main { // To count number of ways in which // number expressed as product // of two different numbers static int countWays(int n) { // To store count of such pairs int count = 0; // Counting number of pairs // upto sqrt(n) - 1 for (int i = 1; i * i < n; i++) if (n % i == 0) count++; // To return count of pairs return count; } // Driver program to test countWays() public static void main(String[] args) { int n = 12; System.out.println(countWays(n)); }}",
"e": 2123,
"s": 1427,
"text": null
},
{
"code": "# Python 3 program to find number of ways# in which number expressed as# product of two different factors # To count number of ways in which# number expressed as product# of two different numbersdef countWays(n): # To store count of such pairs count = 0 i = 1 # Counting number of pairs # upto sqrt(n) - 1 while ((i * i)<n) : if(n % i == 0): count += 1 i += 1 # To return count of pairs return count # Driver program to test countWays()n = 12print (countWays(n)) # This code is contributed# by Azkia Anam.",
"e": 2700,
"s": 2123,
"text": null
},
{
"code": "// C# program to find number of ways// in which number expressed as// product of two different factorsusing System; public class main { // To count number of ways in which // number expressed as product // of two different numbers static int countWays(int n) { // To store count of such pairs int count = 0; // Counting number of pairs // upto sqrt(n) - 1 for (int i = 1; i * i < n; i++) if (n % i == 0) count++; // To return count of pairs return count; } // Driver program to test countWays() public static void Main() { int n = 12; Console.WriteLine(countWays(n)); }} // This code is contributed by Anant Agarwal.",
"e": 3442,
"s": 2700,
"text": null
},
{
"code": "<?php// PHP program to find number of ways// in which number expressed as// product of two different factors // To count number of ways in which// number expressed as product// of two different numbersfunction countWays($n){ // To store count of such pairs $count = 0; // Counting number of pairs // upto sqrt(n) - 1 for ($i = 1; $i * $i < $n; $i++) if ($n % $i == 0) $count++; // To return count of pairs return $count;} // Driver Code$n = 12;echo countWays($n), \"\\n\"; // This code is contributed by ajit?>",
"e": 3991,
"s": 3442,
"text": null
},
{
"code": "<script>// JavaScript program to find number of ways// in which number expressed as// product of two different factors // To count number of ways in which // number expressed as product // of two different numbers function countWays(n) { // To store count of such pairs let count = 0; // Counting number of pairs // upto sqrt(n) - 1 for (let i = 1; i * i < n; i++) if (n % i == 0) count++; // To return count of pairs return count; } // Driver Code let n = 12; document.write(countWays(n)); </script>",
"e": 4604,
"s": 3991,
"text": null
},
{
"code": null,
"e": 4614,
"s": 4604,
"text": "Output: "
},
{
"code": null,
"e": 4616,
"s": 4614,
"text": "3"
},
{
"code": null,
"e": 4661,
"s": 4616,
"text": "Time Complexity: O(√n) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5093,
"s": 4661,
"text": "This article is contributed by Aarti_Rathi and nuclode. 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": 5099,
"s": 5093,
"text": "jit_t"
},
{
"code": null,
"e": 5109,
"s": 5099,
"text": "code_hunt"
},
{
"code": null,
"e": 5122,
"s": 5109,
"text": "codewithmini"
},
{
"code": null,
"e": 5135,
"s": 5122,
"text": "prime-factor"
},
{
"code": null,
"e": 5148,
"s": 5135,
"text": "Mathematical"
},
{
"code": null,
"e": 5167,
"s": 5148,
"text": "School Programming"
},
{
"code": null,
"e": 5180,
"s": 5167,
"text": "Mathematical"
},
{
"code": null,
"e": 5278,
"s": 5180,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5310,
"s": 5278,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 5354,
"s": 5310,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 5400,
"s": 5354,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 5442,
"s": 5400,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 5467,
"s": 5442,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 5485,
"s": 5467,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5510,
"s": 5485,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5526,
"s": 5510,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 5549,
"s": 5526,
"text": "Introduction To PYTHON"
}
]
|
SAS - Functions | SAS has a wide variety of in built functions which help in analysing and processing the data. These functions are used as part of the DATA statements. They take the data variables as arguments and return the result which is stored into another variable. Depending on the type of function, the number of arguments it takes can vary. Some functions accept zero arguments while some other
accept fixed number of variables. Below is a list of types of functions SAS provides.
The general syntax for using a function in SAS is as below.
FUNCTIONNAME(argument1, argument2...argumentn)
Here the argument can be a constant, variable, expression or another function.
Depending on their usage, the functions in SAS are categorised as below.
Mathematical
Date and Time
Character
Truncation
Miscellaneous
These are the functions used to apply some mathematical calculations on the variable values.
The below SAS program shows the use of some important mathematical functions.
data Math_functions;
v1=21; v2=42; v3=13; v4=10; v5=29;
/* Get Maximum value */
max_val = MAX(v1,v2,v3,v4,v5);
/* Get Minimum value */
min_val = MIN (v1,v2,v3,v4,v5);
/* Get Median value */
med_val = MEDIAN (v1,v2,v3,v4,v5);
/* Get a random number */
rand_val = RANUNI(0);
/* Get Square root of sum of the values */
SR_val= SQRT(sum(v1,v2,v3,v4,v5));
proc print data = Math_functions noobs;
run;
When the above code is run, we get the following output −
These are the functions used to process date and time values.
The below SAS program shows the use of date and time functions.
data date_functions;
INPUT @1 date1 date9. @11 date2 date9.;
format date1 date9. date2 date9.;
/* Get the interval between the dates in years*/
Years_ = INTCK('YEAR',date1,date2);
/* Get the interval between the dates in months*/
months_ = INTCK('MONTH',date1,date2);
/* Get the week day from the date*/
weekday_ = WEEKDAY(date1);
/* Get Today's date in SAS date format */
today_ = TODAY();
/* Get current time in SAS time format */
time_ = time();
DATALINES;
21OCT2000 16AUG1998
01MAR2009 11JUL2012
;
proc print data = date_functions noobs;
run;
When the above code is run, we get the following output −
These are the functions used to process character or text values.
The below SAS program shows the use of character functions.
data character_functions;
/* Convert the string into lower case */
lowcse_ = LOWCASE('HELLO');
/* Convert the string into upper case */
upcase_ = UPCASE('hello');
/* Reverse the string */
reverse_ = REVERSE('Hello');
/* Return the nth word */
nth_letter_ = SCAN('Learn SAS Now',2);
run;
proc print data = character_functions noobs;
run;
When the above code is run, we get the following output −
These are the functions used to truncate numeric values.
The below SAS program shows the use of truncation functions.
data trunc_functions;
/* Nearest greatest integer */
ceil_ = CEIL(11.85);
/* Nearest greatest integer */
floor_ = FLOOR(11.85);
/* Integer portion of a number */
int_ = INT(32.41);
/* Round off to nearest value */
round_ = ROUND(5621.78);
run;
proc print data = trunc_functions noobs;
run;
When the above code is run, we get the following output −
Let us now understand the miscellaneous functions of SAS with some examples.
The below SAS program shows the use of Miscellaneous functions.
data misc_functions;
/* Nearest greatest integer */
state2=zipstate('01040');
/* Amortization calculation */
payment = mort(50000, . , .10/12,30*12);
proc print data = misc_functions noobs;
run;
When the above code is run, we get the following output − | [
{
"code": null,
"e": 3189,
"s": 2717,
"text": "SAS has a wide variety of in built functions which help in analysing and processing the data. These functions are used as part of the DATA statements. They take the data variables as arguments and return the result which is stored into another variable. Depending on the type of function, the number of arguments it takes can vary. Some functions accept zero arguments while some other\naccept fixed number of variables. Below is a list of types of functions SAS provides."
},
{
"code": null,
"e": 3249,
"s": 3189,
"text": "The general syntax for using a function in SAS is as below."
},
{
"code": null,
"e": 3297,
"s": 3249,
"text": "FUNCTIONNAME(argument1, argument2...argumentn)\n"
},
{
"code": null,
"e": 3376,
"s": 3297,
"text": "Here the argument can be a constant, variable, expression or another function."
},
{
"code": null,
"e": 3449,
"s": 3376,
"text": "Depending on their usage, the functions in SAS are categorised as below."
},
{
"code": null,
"e": 3462,
"s": 3449,
"text": "Mathematical"
},
{
"code": null,
"e": 3476,
"s": 3462,
"text": "Date and Time"
},
{
"code": null,
"e": 3486,
"s": 3476,
"text": "Character"
},
{
"code": null,
"e": 3497,
"s": 3486,
"text": "Truncation"
},
{
"code": null,
"e": 3511,
"s": 3497,
"text": "Miscellaneous"
},
{
"code": null,
"e": 3604,
"s": 3511,
"text": "These are the functions used to apply some mathematical calculations on the variable values."
},
{
"code": null,
"e": 3682,
"s": 3604,
"text": "The below SAS program shows the use of some important mathematical functions."
},
{
"code": null,
"e": 3703,
"s": 3682,
"text": "data Math_functions;"
},
{
"code": null,
"e": 4084,
"s": 3703,
"text": "v1=21; v2=42; v3=13; v4=10; v5=29;\n\n/* Get Maximum value */\nmax_val = MAX(v1,v2,v3,v4,v5);\n\n/* Get Minimum value */\nmin_val = MIN (v1,v2,v3,v4,v5);\n\n/* Get Median value */\nmed_val = MEDIAN (v1,v2,v3,v4,v5);\n\n/* Get a random number */\nrand_val = RANUNI(0);\n\n/* Get Square root of sum of the values */\nSR_val= SQRT(sum(v1,v2,v3,v4,v5));\n\nproc print data = Math_functions noobs;\nrun;"
},
{
"code": null,
"e": 4142,
"s": 4084,
"text": "When the above code is run, we get the following output −"
},
{
"code": null,
"e": 4204,
"s": 4142,
"text": "These are the functions used to process date and time values."
},
{
"code": null,
"e": 4269,
"s": 4204,
"text": "The below SAS program shows the use of date and time functions."
},
{
"code": null,
"e": 4823,
"s": 4269,
"text": "data date_functions;\nINPUT @1 date1 date9. @11 date2 date9.;\nformat date1 date9. date2 date9.;\n\n/* Get the interval between the dates in years*/\nYears_ = INTCK('YEAR',date1,date2);\n\n/* Get the interval between the dates in months*/\nmonths_ = INTCK('MONTH',date1,date2);\n\n/* Get the week day from the date*/\nweekday_ = WEEKDAY(date1);\n\n/* Get Today's date in SAS date format */\ntoday_ = TODAY();\n\n/* Get current time in SAS time format */\ntime_ = time();\nDATALINES;\n21OCT2000 16AUG1998\n01MAR2009 11JUL2012\n;\nproc print data = date_functions noobs;\nrun;"
},
{
"code": null,
"e": 4881,
"s": 4823,
"text": "When the above code is run, we get the following output −"
},
{
"code": null,
"e": 4947,
"s": 4881,
"text": "These are the functions used to process character or text values."
},
{
"code": null,
"e": 5008,
"s": 4947,
"text": "The below SAS program shows the use of character functions."
},
{
"code": null,
"e": 5356,
"s": 5008,
"text": "data character_functions;\n\n/* Convert the string into lower case */\nlowcse_ = LOWCASE('HELLO');\n \n/* Convert the string into upper case */\nupcase_ = UPCASE('hello');\n \n/* Reverse the string */\nreverse_ = REVERSE('Hello');\n \n/* Return the nth word */\nnth_letter_ = SCAN('Learn SAS Now',2);\nrun;\n\nproc print data = character_functions noobs;\nrun;"
},
{
"code": null,
"e": 5414,
"s": 5356,
"text": "When the above code is run, we get the following output −"
},
{
"code": null,
"e": 5471,
"s": 5414,
"text": "These are the functions used to truncate numeric values."
},
{
"code": null,
"e": 5532,
"s": 5471,
"text": "The below SAS program shows the use of truncation functions."
},
{
"code": null,
"e": 5833,
"s": 5532,
"text": "data trunc_functions;\n\n/* Nearest greatest integer */\nceil_ = CEIL(11.85);\n \n/* Nearest greatest integer */\nfloor_ = FLOOR(11.85);\n \n/* Integer portion of a number */\nint_ = INT(32.41);\n \n/* Round off to nearest value */\nround_ = ROUND(5621.78);\nrun;\n\nproc print data = trunc_functions noobs;\nrun;"
},
{
"code": null,
"e": 5891,
"s": 5833,
"text": "When the above code is run, we get the following output −"
},
{
"code": null,
"e": 5968,
"s": 5891,
"text": "Let us now understand the miscellaneous functions of SAS with some examples."
},
{
"code": null,
"e": 6032,
"s": 5968,
"text": "The below SAS program shows the use of Miscellaneous functions."
},
{
"code": null,
"e": 6231,
"s": 6032,
"text": "data misc_functions;\n\n/* Nearest greatest integer */\nstate2=zipstate('01040');\n \n/* Amortization calculation */\npayment = mort(50000, . , .10/12,30*12);\n\nproc print data = misc_functions noobs;\nrun;"
}
]
|
How to Build a Simple Auto-Login Bot with Python | 19 Oct, 2021
In this article, we are going to see how to built a simple auto-login bot using python.
In this present scenario, every website uses authentication and we have to log in by entering proper credentials. But sometimes it becomes very hectic to login again and again to a particular website. So, to come out of this problem lets, built our own auto login bot using python.
We will be using Selenium (python library) for making the auto-login bot. Python Selenium library helps us to access all functionalities of Selenium WebDriver like Firefox, Chrome, Remote etc.
First of all, we have to install selenium using the below command:
pip install selenium
After successful installation of selenium, we also have to install chromedriver for accessing the chrome webdriver of selenium. You can download the same from here (Download version according to your system chrome version and according to your OS).
Make sure that you have noted the location where the chromedriver has been downloaded (as it is used in our python script). Now After downloading extract the zip file and please note the file location of the extracted file as we have needed it later in python code. (You can find the location by clicking on properties and then details).
First of all import the webdrivers from the selenium library.
Find the URL of the login page to which you want to logged in.
Provide the location executable chrome driver to selenium webdriver to access the chrome browser.
Finally, find the name or id or class or CSS selector of username and password by right-clicking inspect on username and password.
Below is the implementation:
Python3
# Used to import the webdriver from seleniumfrom selenium import webdriver import os # Get the path of chromedriver which you have install def startBot(username, password, url): path = "C:\\Users\\hp\\Downloads\\chromedriver" # giving the path of chromedriver to selenium webdriver driver = webdriver.Chrome(path) # opening the website in chrome. driver.get(url) # find the id or name or class of # username by inspecting on username input driver.find_element_by_name( "id/class/name of username").send_keys(username) # find the password by inspecting on password input driver.find_element_by_name( "id/class/name of password").send_keys(password) # click on submit driver.find_element_by_css_selector( "id/class/name/css selector of login button").click() # Driver Code# Enter below your login credentialsusername = "Enter your username"password = "Enter your password" # URL of the login page of site# which you want to automate login.url = "Enter the URL of login page of website" # Call the functionstartBot(username, password, url)
Output:
sooda367
adnanirshad158
Blogathon-2021
Picked
Python Selenium-Exercises
Python-projects
Python-selenium
Blogathon
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
SQL Query to Convert Datetime to Date
Python program to convert XML to Dictionary
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
How to toggle password visibility in forms using Bootstrap-icons ?
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": 54,
"s": 26,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 142,
"s": 54,
"text": "In this article, we are going to see how to built a simple auto-login bot using python."
},
{
"code": null,
"e": 424,
"s": 142,
"text": "In this present scenario, every website uses authentication and we have to log in by entering proper credentials. But sometimes it becomes very hectic to login again and again to a particular website. So, to come out of this problem lets, built our own auto login bot using python."
},
{
"code": null,
"e": 617,
"s": 424,
"text": "We will be using Selenium (python library) for making the auto-login bot. Python Selenium library helps us to access all functionalities of Selenium WebDriver like Firefox, Chrome, Remote etc."
},
{
"code": null,
"e": 684,
"s": 617,
"text": "First of all, we have to install selenium using the below command:"
},
{
"code": null,
"e": 705,
"s": 684,
"text": "pip install selenium"
},
{
"code": null,
"e": 954,
"s": 705,
"text": "After successful installation of selenium, we also have to install chromedriver for accessing the chrome webdriver of selenium. You can download the same from here (Download version according to your system chrome version and according to your OS)."
},
{
"code": null,
"e": 1292,
"s": 954,
"text": "Make sure that you have noted the location where the chromedriver has been downloaded (as it is used in our python script). Now After downloading extract the zip file and please note the file location of the extracted file as we have needed it later in python code. (You can find the location by clicking on properties and then details)."
},
{
"code": null,
"e": 1354,
"s": 1292,
"text": "First of all import the webdrivers from the selenium library."
},
{
"code": null,
"e": 1417,
"s": 1354,
"text": "Find the URL of the login page to which you want to logged in."
},
{
"code": null,
"e": 1515,
"s": 1417,
"text": "Provide the location executable chrome driver to selenium webdriver to access the chrome browser."
},
{
"code": null,
"e": 1646,
"s": 1515,
"text": "Finally, find the name or id or class or CSS selector of username and password by right-clicking inspect on username and password."
},
{
"code": null,
"e": 1675,
"s": 1646,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 1683,
"s": 1675,
"text": "Python3"
},
{
"code": "# Used to import the webdriver from seleniumfrom selenium import webdriver import os # Get the path of chromedriver which you have install def startBot(username, password, url): path = \"C:\\\\Users\\\\hp\\\\Downloads\\\\chromedriver\" # giving the path of chromedriver to selenium webdriver driver = webdriver.Chrome(path) # opening the website in chrome. driver.get(url) # find the id or name or class of # username by inspecting on username input driver.find_element_by_name( \"id/class/name of username\").send_keys(username) # find the password by inspecting on password input driver.find_element_by_name( \"id/class/name of password\").send_keys(password) # click on submit driver.find_element_by_css_selector( \"id/class/name/css selector of login button\").click() # Driver Code# Enter below your login credentialsusername = \"Enter your username\"password = \"Enter your password\" # URL of the login page of site# which you want to automate login.url = \"Enter the URL of login page of website\" # Call the functionstartBot(username, password, url)",
"e": 2804,
"s": 1683,
"text": null
},
{
"code": null,
"e": 2812,
"s": 2804,
"text": "Output:"
},
{
"code": null,
"e": 2821,
"s": 2812,
"text": "sooda367"
},
{
"code": null,
"e": 2836,
"s": 2821,
"text": "adnanirshad158"
},
{
"code": null,
"e": 2851,
"s": 2836,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 2858,
"s": 2851,
"text": "Picked"
},
{
"code": null,
"e": 2884,
"s": 2858,
"text": "Python Selenium-Exercises"
},
{
"code": null,
"e": 2900,
"s": 2884,
"text": "Python-projects"
},
{
"code": null,
"e": 2916,
"s": 2900,
"text": "Python-selenium"
},
{
"code": null,
"e": 2926,
"s": 2916,
"text": "Blogathon"
},
{
"code": null,
"e": 2933,
"s": 2926,
"text": "Python"
},
{
"code": null,
"e": 3031,
"s": 2933,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3072,
"s": 3031,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 3110,
"s": 3072,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 3154,
"s": 3110,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 3214,
"s": 3154,
"text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python"
},
{
"code": null,
"e": 3281,
"s": 3214,
"text": "How to toggle password visibility in forms using Bootstrap-icons ?"
},
{
"code": null,
"e": 3309,
"s": 3281,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3359,
"s": 3309,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3381,
"s": 3359,
"text": "Python map() function"
},
{
"code": null,
"e": 3399,
"s": 3381,
"text": "Python Dictionary"
}
]
|
Implementing Edit Profile Data Functionality in Social Media Android App | 17 May, 2022
This is the Part 3 of “Build a Social Media App on Android Studio” tutorial, and we are going to cover the following functionalities in this article:
We are going to edit our profile data like changing name, changing the password of the user, and changing profile pic.
Changing password is a very important feature because it may happen that sometimes someone knows our password and in that case, we need to change our password.
We change our profile pic using selecting an image from the gallery or clicking an image from the camera.
Step 1: Add dependency to build.gradle (Module: app)
Navigate to the Gradle Scripts > build. gradle(Module: app) and add the below dependency in the dependencies section.
implementation "androidx.recyclerview:recyclerview:1.1.0"
implementation 'de.hdodenhof:circleimageview:3.1.0'
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
Now sync the project from the top right corner option of Sync now.
Step 2: Add read, write and camera permission in the AndroidManifest.xml file
Navigate to the AndroidManifest.xml file and add the below permission for getting read, write and camera permission in the app.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
Step 3: Create a new empty activity and name the activity as EditProfilePage
Working with the activity_edit_profile_page.xml file. On this page will be changing the email, name, and profile picture of the user. Navigate to the app > res > layout > activity_edit_profile_page.xml and add the below code to that file. Below is the code for the activity_edit_profile_page.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:orientation="vertical" tools:context=".EditProfilePage"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:text="Edit Profile Data" android:textAlignment="center" android:textColor="@android:color/black" android:textSize="26sp" /> <de.hdodenhof.circleimageview.CircleImageView android:id="@+id/setting_profile_image" android:layout_width="130dp" android:layout_height="130dp" android:layout_marginStart="140dp" android:layout_marginTop="40dp" android:src="@drawable/ic_users" /> <TextView android:id="@+id/profilepic" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Update Profile Pic" android:textAlignment="center" android:textColor="@android:color/black" android:textSize="20sp" /> <TextView android:id="@+id/editname" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Update Name" android:textAlignment="center" android:textColor="@android:color/black" android:textSize="20sp" /> <TextView android:id="@+id/changepassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Change Password " android:textAlignment="center" android:textColor="@android:color/black" android:textSize="20sp" /> </LinearLayout>
Step 4: Create a new layout resource file
Go to the app > res > layout > New > Layout Resource File and name the file as dialog_update_password. Navigate to the app > res > layout > dialog_update_password.xml and add the below code to that file. Below is the code for the dialog_update_password.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="20dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Update Password" android:textAlignment="center" android:textColor="@color/colorBlack" android:textSize="16sp" android:textStyle="bold" /> <com.google.android.material.textfield.TextInputLayout android:id="@+id/oldpass" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" app:passwordToggleEnabled="true"> <EditText android:id="@+id/oldpasslog" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Old Password" android:inputType="textPassword" /> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout android:id="@+id/newpass" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/oldpasslog" android:layout_centerHorizontal="true" android:layout_centerVertical="true" app:passwordToggleEnabled="true"> <EditText android:id="@+id/newpasslog" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="New Password" android:inputType="textPassword" /> </com.google.android.material.textfield.TextInputLayout> <Button android:id="@+id/updatepass" style="@style/Widget.AppCompat.Button.Colored" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Update Password" /> </LinearLayout>
Step 5: Working with the EditProfilePage.java file
Go to the EditProfilePage.java file and refer to the following code. Below is the code for the EditProfilePage.java file. Comments are added inside the code to understand the code in more detail.
Java
package com.example.socialmediaapp; import android.Manifest;import android.app.Activity;import android.app.AlertDialog;import android.app.ProgressDialog;import android.content.ContentValues;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageManager;import android.net.Uri;import android.os.Bundle;import android.provider.MediaStore;import android.text.TextUtils;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.core.content.ContextCompat; import com.bumptech.glide.Glide;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.android.gms.tasks.Task;import com.google.firebase.auth.AuthCredential;import com.google.firebase.auth.EmailAuthProvider;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.Query;import com.google.firebase.database.ValueEventListener;import com.google.firebase.storage.FirebaseStorage;import com.google.firebase.storage.StorageReference;import com.google.firebase.storage.UploadTask; import java.util.HashMap; public class EditProfilePage extends AppCompatActivity { private FirebaseAuth firebaseAuth; FirebaseUser firebaseUser; FirebaseDatabase firebaseDatabase; DatabaseReference databaseReference; StorageReference storageReference; String storagepath = "Users_Profile_Cover_image/"; String uid; ImageView set; TextView profilepic, editname, editpassword; ProgressDialog pd; private static final int CAMERA_REQUEST = 100; private static final int STORAGE_REQUEST = 200; private static final int IMAGEPICK_GALLERY_REQUEST = 300; private static final int IMAGE_PICKCAMERA_REQUEST = 400; String cameraPermission[]; String storagePermission[]; Uri imageuri; String profileOrCoverPhoto; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_profile_page); profilepic = findViewById(R.id.profilepic); editname = findViewById(R.id.editname); set = findViewById(R.id.setting_profile_image); pd = new ProgressDialog(this); pd.setCanceledOnTouchOutside(false); editpassword = findViewById(R.id.changepassword); firebaseAuth = FirebaseAuth.getInstance(); firebaseUser = firebaseAuth.getCurrentUser(); firebaseDatabase = FirebaseDatabase.getInstance(); storageReference = FirebaseStorage.getInstance().getReference(); databaseReference = firebaseDatabase.getReference("Users"); cameraPermission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}; Query query = databaseReference.orderByChild("email").equalTo(firebaseUser.getEmail()); query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { String image = "" + dataSnapshot1.child("image").getValue(); try { Glide.with(EditProfilePage.this).load(image).into(set); } catch (Exception e) { } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); editpassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pd.setMessage("Changing Password"); showPasswordChangeDailog(); } }); profilepic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pd.setMessage("Updating Profile Picture"); profileOrCoverPhoto = "image"; showImagePicDialog(); } }); editname.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pd.setMessage("Updating Name"); showNamephoneupdate("name"); } }); } @Override protected void onPause() { super.onPause(); Query query = databaseReference.orderByChild("email").equalTo(firebaseUser.getEmail()); query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { String image = "" + dataSnapshot1.child("image").getValue(); try { Glide.with(EditProfilePage.this).load(image).into(set); } catch (Exception e) { } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); editpassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pd.setMessage("Changing Password"); showPasswordChangeDailog(); } }); } @Override protected void onStart() { super.onStart(); Query query = databaseReference.orderByChild("email").equalTo(firebaseUser.getEmail()); query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { String image = "" + dataSnapshot1.child("image").getValue(); try { Glide.with(EditProfilePage.this).load(image).into(set); } catch (Exception e) { } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); editpassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pd.setMessage("Changing Password"); showPasswordChangeDailog(); } }); } // checking storage permission ,if given then we can add something in our storage private Boolean checkStoragePermission() { boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result; } // requesting for storage permission private void requestStoragePermission() { requestPermissions(storagePermission, STORAGE_REQUEST); } // checking camera permission ,if given then we can click image using our camera private Boolean checkCameraPermission() { boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED); boolean result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result && result1; } // requesting for camera permission if not given private void requestCameraPermission() { requestPermissions(cameraPermission, CAMERA_REQUEST); } // We will show an alert box where we will write our old and new password private void showPasswordChangeDailog() { View view = LayoutInflater.from(this).inflate(R.layout.dialog_update_password, null); final EditText oldpass = view.findViewById(R.id.oldpasslog); final EditText newpass = view.findViewById(R.id.newpasslog); Button editpass = view.findViewById(R.id.updatepass); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(view); final AlertDialog dialog = builder.create(); dialog.show(); editpass.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String oldp = oldpass.getText().toString().trim(); String newp = newpass.getText().toString().trim(); if (TextUtils.isEmpty(oldp)) { Toast.makeText(EditProfilePage.this, "Current Password cant be empty", Toast.LENGTH_LONG).show(); return; } if (TextUtils.isEmpty(newp)) { Toast.makeText(EditProfilePage.this, "New Password cant be empty", Toast.LENGTH_LONG).show(); return; } dialog.dismiss(); updatePassword(oldp, newp); } }); } // Now we will check that if old password was authenticated // correctly then we will update the new password private void updatePassword(String oldp, final String newp) { pd.show(); final FirebaseUser user = firebaseAuth.getCurrentUser(); AuthCredential authCredential = EmailAuthProvider.getCredential(user.getEmail(), oldp); user.reauthenticate(authCredential) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { user.updatePassword(newp) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { pd.dismiss(); Toast.makeText(EditProfilePage.this, "Changed Password", Toast.LENGTH_LONG).show(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(EditProfilePage.this, "Failed", Toast.LENGTH_LONG).show(); } }); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(EditProfilePage.this, "Failed", Toast.LENGTH_LONG).show(); } }); } // Updating name private void showNamephoneupdate(final String key) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Update" + key); // creating a layout to write the new name LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); layout.setPadding(10, 10, 10, 10); final EditText editText = new EditText(this); editText.setHint("Enter" + key); layout.addView(editText); builder.setView(layout); builder.setPositiveButton("Update", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final String value = editText.getText().toString().trim(); if (!TextUtils.isEmpty(value)) { pd.show(); // Here we are updating the new name HashMap<String, Object> result = new HashMap<>(); result.put(key, value); databaseReference.child(firebaseUser.getUid()).updateChildren(result).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { pd.dismiss(); // after updated we will show updated Toast.makeText(EditProfilePage.this, " updated ", Toast.LENGTH_LONG).show(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(EditProfilePage.this, "Unable to update", Toast.LENGTH_LONG).show(); } }); if (key.equals("name")) { final DatabaseReference databaser = FirebaseDatabase.getInstance().getReference("Posts"); Query query = databaser.orderByChild("uid").equalTo(uid); query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { String child = databaser.getKey(); dataSnapshot1.getRef().child("uname").setValue(value); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } } else { Toast.makeText(EditProfilePage.this, "Unable to update", Toast.LENGTH_LONG).show(); } } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { pd.dismiss(); } }); builder.create().show(); } // Here we are showing image pic dialog where we will select // and image either from camera or gallery private void showImagePicDialog() { String options[] = {"Camera", "Gallery"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Pick Image From"); builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // if access is not given then we will request for permission if (which == 0) { if (!checkCameraPermission()) { requestCameraPermission(); } else { pickFromCamera(); } } else if (which == 1) { if (!checkStoragePermission()) { requestStoragePermission(); } else { pickFromGallery(); } } } }); builder.create().show(); } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (resultCode == Activity.RESULT_OK) { if (requestCode == IMAGEPICK_GALLERY_REQUEST) { imageuri = data.getData(); uploadProfileCoverPhoto(imageuri); } if (requestCode == IMAGE_PICKCAMERA_REQUEST) { uploadProfileCoverPhoto(imageuri); } } super.onActivityResult(requestCode, resultCode, data); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case CAMERA_REQUEST: { if (grantResults.length > 0) { boolean camera_accepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; boolean writeStorageaccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED; if (camera_accepted && writeStorageaccepted) { pickFromCamera(); } else { Toast.makeText(this, "Please Enable Camera and Storage Permissions", Toast.LENGTH_LONG).show(); } } } break; case STORAGE_REQUEST: { if (grantResults.length > 0) { boolean writeStorageaccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; if (writeStorageaccepted) { pickFromGallery(); } else { Toast.makeText(this, "Please Enable Storage Permissions", Toast.LENGTH_LONG).show(); } } } break; } } // Here we will click a photo and then go to startactivityforresult for updating data private void pickFromCamera() { ContentValues contentValues = new ContentValues(); contentValues.put(MediaStore.Images.Media.TITLE, "Temp_pic"); contentValues.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description"); imageuri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues); Intent camerIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); camerIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageuri); startActivityForResult(camerIntent, IMAGE_PICKCAMERA_REQUEST); } // We will select an image from gallery private void pickFromGallery() { Intent galleryIntent = new Intent(Intent.ACTION_PICK); galleryIntent.setType("image/*"); startActivityForResult(galleryIntent, IMAGEPICK_GALLERY_REQUEST); } // We will upload the image from here. private void uploadProfileCoverPhoto(final Uri uri) { pd.show(); // We are taking the filepath as storagepath + firebaseauth.getUid()+".png" String filepathname = storagepath + "" + profileOrCoverPhoto + "_" + firebaseUser.getUid(); StorageReference storageReference1 = storageReference.child(filepathname); storageReference1.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl(); while (!uriTask.isSuccessful()) ; // We will get the url of our image using uritask final Uri downloadUri = uriTask.getResult(); if (uriTask.isSuccessful()) { // updating our image url into the realtime database HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put(profileOrCoverPhoto, downloadUri.toString()); databaseReference.child(firebaseUser.getUid()).updateChildren(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { pd.dismiss(); Toast.makeText(EditProfilePage.this, "Updated", Toast.LENGTH_LONG).show(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(EditProfilePage.this, "Error Updating ", Toast.LENGTH_LONG).show(); } }); } else { pd.dismiss(); Toast.makeText(EditProfilePage.this, "Error", Toast.LENGTH_LONG).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(EditProfilePage.this, "Error", Toast.LENGTH_LONG).show(); } }); }}
Step 6: Create Realtime Database inside the firebase console
Go to the firebase console > Realtime Database and create your database.
Then Start in Test Mode and Enable the real-time database.
Output:
When you update the data, the data is stored like the following
For all the drawable file used in this article please refer to this link: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing
Below is the file structure after performing these operations:
happyclasher745
Firebase
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 May, 2022"
},
{
"code": null,
"e": 202,
"s": 52,
"text": "This is the Part 3 of “Build a Social Media App on Android Studio” tutorial, and we are going to cover the following functionalities in this article:"
},
{
"code": null,
"e": 321,
"s": 202,
"text": "We are going to edit our profile data like changing name, changing the password of the user, and changing profile pic."
},
{
"code": null,
"e": 481,
"s": 321,
"text": "Changing password is a very important feature because it may happen that sometimes someone knows our password and in that case, we need to change our password."
},
{
"code": null,
"e": 587,
"s": 481,
"text": "We change our profile pic using selecting an image from the gallery or clicking an image from the camera."
},
{
"code": null,
"e": 640,
"s": 587,
"text": "Step 1: Add dependency to build.gradle (Module: app)"
},
{
"code": null,
"e": 758,
"s": 640,
"text": "Navigate to the Gradle Scripts > build. gradle(Module: app) and add the below dependency in the dependencies section."
},
{
"code": null,
"e": 1052,
"s": 758,
"text": "implementation \"androidx.recyclerview:recyclerview:1.1.0\"\nimplementation 'de.hdodenhof:circleimageview:3.1.0'\nimplementation 'com.github.bumptech.glide:glide:4.11.0'\nannotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'\nannotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'"
},
{
"code": null,
"e": 1119,
"s": 1052,
"text": "Now sync the project from the top right corner option of Sync now."
},
{
"code": null,
"e": 1197,
"s": 1119,
"text": "Step 2: Add read, write and camera permission in the AndroidManifest.xml file"
},
{
"code": null,
"e": 1325,
"s": 1197,
"text": "Navigate to the AndroidManifest.xml file and add the below permission for getting read, write and camera permission in the app."
},
{
"code": null,
"e": 1539,
"s": 1325,
"text": "<uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" />\n<uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\" />\n<uses-permission android:name=\"android.permission.CAMERA\" />"
},
{
"code": null,
"e": 1616,
"s": 1539,
"text": "Step 3: Create a new empty activity and name the activity as EditProfilePage"
},
{
"code": null,
"e": 1920,
"s": 1616,
"text": "Working with the activity_edit_profile_page.xml file. On this page will be changing the email, name, and profile picture of the user. Navigate to the app > res > layout > activity_edit_profile_page.xml and add the below code to that file. Below is the code for the activity_edit_profile_page.xml file. "
},
{
"code": null,
"e": 1924,
"s": 1920,
"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:orientation=\"vertical\" tools:context=\".EditProfilePage\"> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"50dp\" android:text=\"Edit Profile Data\" android:textAlignment=\"center\" android:textColor=\"@android:color/black\" android:textSize=\"26sp\" /> <de.hdodenhof.circleimageview.CircleImageView android:id=\"@+id/setting_profile_image\" android:layout_width=\"130dp\" android:layout_height=\"130dp\" android:layout_marginStart=\"140dp\" android:layout_marginTop=\"40dp\" android:src=\"@drawable/ic_users\" /> <TextView android:id=\"@+id/profilepic\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"20dp\" android:text=\"Update Profile Pic\" android:textAlignment=\"center\" android:textColor=\"@android:color/black\" android:textSize=\"20sp\" /> <TextView android:id=\"@+id/editname\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"20dp\" android:text=\"Update Name\" android:textAlignment=\"center\" android:textColor=\"@android:color/black\" android:textSize=\"20sp\" /> <TextView android:id=\"@+id/changepassword\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"20dp\" android:text=\"Change Password \" android:textAlignment=\"center\" android:textColor=\"@android:color/black\" android:textSize=\"20sp\" /> </LinearLayout>",
"e": 3852,
"s": 1924,
"text": null
},
{
"code": null,
"e": 3894,
"s": 3852,
"text": "Step 4: Create a new layout resource file"
},
{
"code": null,
"e": 4158,
"s": 3894,
"text": "Go to the app > res > layout > New > Layout Resource File and name the file as dialog_update_password. Navigate to the app > res > layout > dialog_update_password.xml and add the below code to that file. Below is the code for the dialog_update_password.xml file. "
},
{
"code": null,
"e": 4162,
"s": 4158,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\" android:padding=\"20dp\"> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Update Password\" android:textAlignment=\"center\" android:textColor=\"@color/colorBlack\" android:textSize=\"16sp\" android:textStyle=\"bold\" /> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/oldpass\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_centerVertical=\"true\" app:passwordToggleEnabled=\"true\"> <EditText android:id=\"@+id/oldpasslog\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:hint=\"Old Password\" android:inputType=\"textPassword\" /> </com.google.android.material.textfield.TextInputLayout> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/newpass\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/oldpasslog\" android:layout_centerHorizontal=\"true\" android:layout_centerVertical=\"true\" app:passwordToggleEnabled=\"true\"> <EditText android:id=\"@+id/newpasslog\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:hint=\"New Password\" android:inputType=\"textPassword\" /> </com.google.android.material.textfield.TextInputLayout> <Button android:id=\"@+id/updatepass\" style=\"@style/Widget.AppCompat.Button.Colored\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:text=\"Update Password\" /> </LinearLayout>",
"e": 6331,
"s": 4162,
"text": null
},
{
"code": null,
"e": 6382,
"s": 6331,
"text": "Step 5: Working with the EditProfilePage.java file"
},
{
"code": null,
"e": 6578,
"s": 6382,
"text": "Go to the EditProfilePage.java file and refer to the following code. Below is the code for the EditProfilePage.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 6583,
"s": 6578,
"text": "Java"
},
{
"code": "package com.example.socialmediaapp; import android.Manifest;import android.app.Activity;import android.app.AlertDialog;import android.app.ProgressDialog;import android.content.ContentValues;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageManager;import android.net.Uri;import android.os.Bundle;import android.provider.MediaStore;import android.text.TextUtils;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.core.content.ContextCompat; import com.bumptech.glide.Glide;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.android.gms.tasks.Task;import com.google.firebase.auth.AuthCredential;import com.google.firebase.auth.EmailAuthProvider;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.Query;import com.google.firebase.database.ValueEventListener;import com.google.firebase.storage.FirebaseStorage;import com.google.firebase.storage.StorageReference;import com.google.firebase.storage.UploadTask; import java.util.HashMap; public class EditProfilePage extends AppCompatActivity { private FirebaseAuth firebaseAuth; FirebaseUser firebaseUser; FirebaseDatabase firebaseDatabase; DatabaseReference databaseReference; StorageReference storageReference; String storagepath = \"Users_Profile_Cover_image/\"; String uid; ImageView set; TextView profilepic, editname, editpassword; ProgressDialog pd; private static final int CAMERA_REQUEST = 100; private static final int STORAGE_REQUEST = 200; private static final int IMAGEPICK_GALLERY_REQUEST = 300; private static final int IMAGE_PICKCAMERA_REQUEST = 400; String cameraPermission[]; String storagePermission[]; Uri imageuri; String profileOrCoverPhoto; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_profile_page); profilepic = findViewById(R.id.profilepic); editname = findViewById(R.id.editname); set = findViewById(R.id.setting_profile_image); pd = new ProgressDialog(this); pd.setCanceledOnTouchOutside(false); editpassword = findViewById(R.id.changepassword); firebaseAuth = FirebaseAuth.getInstance(); firebaseUser = firebaseAuth.getCurrentUser(); firebaseDatabase = FirebaseDatabase.getInstance(); storageReference = FirebaseStorage.getInstance().getReference(); databaseReference = firebaseDatabase.getReference(\"Users\"); cameraPermission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}; Query query = databaseReference.orderByChild(\"email\").equalTo(firebaseUser.getEmail()); query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { String image = \"\" + dataSnapshot1.child(\"image\").getValue(); try { Glide.with(EditProfilePage.this).load(image).into(set); } catch (Exception e) { } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); editpassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pd.setMessage(\"Changing Password\"); showPasswordChangeDailog(); } }); profilepic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pd.setMessage(\"Updating Profile Picture\"); profileOrCoverPhoto = \"image\"; showImagePicDialog(); } }); editname.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pd.setMessage(\"Updating Name\"); showNamephoneupdate(\"name\"); } }); } @Override protected void onPause() { super.onPause(); Query query = databaseReference.orderByChild(\"email\").equalTo(firebaseUser.getEmail()); query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { String image = \"\" + dataSnapshot1.child(\"image\").getValue(); try { Glide.with(EditProfilePage.this).load(image).into(set); } catch (Exception e) { } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); editpassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pd.setMessage(\"Changing Password\"); showPasswordChangeDailog(); } }); } @Override protected void onStart() { super.onStart(); Query query = databaseReference.orderByChild(\"email\").equalTo(firebaseUser.getEmail()); query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { String image = \"\" + dataSnapshot1.child(\"image\").getValue(); try { Glide.with(EditProfilePage.this).load(image).into(set); } catch (Exception e) { } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); editpassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pd.setMessage(\"Changing Password\"); showPasswordChangeDailog(); } }); } // checking storage permission ,if given then we can add something in our storage private Boolean checkStoragePermission() { boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result; } // requesting for storage permission private void requestStoragePermission() { requestPermissions(storagePermission, STORAGE_REQUEST); } // checking camera permission ,if given then we can click image using our camera private Boolean checkCameraPermission() { boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED); boolean result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result && result1; } // requesting for camera permission if not given private void requestCameraPermission() { requestPermissions(cameraPermission, CAMERA_REQUEST); } // We will show an alert box where we will write our old and new password private void showPasswordChangeDailog() { View view = LayoutInflater.from(this).inflate(R.layout.dialog_update_password, null); final EditText oldpass = view.findViewById(R.id.oldpasslog); final EditText newpass = view.findViewById(R.id.newpasslog); Button editpass = view.findViewById(R.id.updatepass); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(view); final AlertDialog dialog = builder.create(); dialog.show(); editpass.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String oldp = oldpass.getText().toString().trim(); String newp = newpass.getText().toString().trim(); if (TextUtils.isEmpty(oldp)) { Toast.makeText(EditProfilePage.this, \"Current Password cant be empty\", Toast.LENGTH_LONG).show(); return; } if (TextUtils.isEmpty(newp)) { Toast.makeText(EditProfilePage.this, \"New Password cant be empty\", Toast.LENGTH_LONG).show(); return; } dialog.dismiss(); updatePassword(oldp, newp); } }); } // Now we will check that if old password was authenticated // correctly then we will update the new password private void updatePassword(String oldp, final String newp) { pd.show(); final FirebaseUser user = firebaseAuth.getCurrentUser(); AuthCredential authCredential = EmailAuthProvider.getCredential(user.getEmail(), oldp); user.reauthenticate(authCredential) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { user.updatePassword(newp) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { pd.dismiss(); Toast.makeText(EditProfilePage.this, \"Changed Password\", Toast.LENGTH_LONG).show(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(EditProfilePage.this, \"Failed\", Toast.LENGTH_LONG).show(); } }); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(EditProfilePage.this, \"Failed\", Toast.LENGTH_LONG).show(); } }); } // Updating name private void showNamephoneupdate(final String key) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(\"Update\" + key); // creating a layout to write the new name LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); layout.setPadding(10, 10, 10, 10); final EditText editText = new EditText(this); editText.setHint(\"Enter\" + key); layout.addView(editText); builder.setView(layout); builder.setPositiveButton(\"Update\", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final String value = editText.getText().toString().trim(); if (!TextUtils.isEmpty(value)) { pd.show(); // Here we are updating the new name HashMap<String, Object> result = new HashMap<>(); result.put(key, value); databaseReference.child(firebaseUser.getUid()).updateChildren(result).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { pd.dismiss(); // after updated we will show updated Toast.makeText(EditProfilePage.this, \" updated \", Toast.LENGTH_LONG).show(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(EditProfilePage.this, \"Unable to update\", Toast.LENGTH_LONG).show(); } }); if (key.equals(\"name\")) { final DatabaseReference databaser = FirebaseDatabase.getInstance().getReference(\"Posts\"); Query query = databaser.orderByChild(\"uid\").equalTo(uid); query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { String child = databaser.getKey(); dataSnapshot1.getRef().child(\"uname\").setValue(value); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } } else { Toast.makeText(EditProfilePage.this, \"Unable to update\", Toast.LENGTH_LONG).show(); } } }); builder.setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { pd.dismiss(); } }); builder.create().show(); } // Here we are showing image pic dialog where we will select // and image either from camera or gallery private void showImagePicDialog() { String options[] = {\"Camera\", \"Gallery\"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(\"Pick Image From\"); builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // if access is not given then we will request for permission if (which == 0) { if (!checkCameraPermission()) { requestCameraPermission(); } else { pickFromCamera(); } } else if (which == 1) { if (!checkStoragePermission()) { requestStoragePermission(); } else { pickFromGallery(); } } } }); builder.create().show(); } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (resultCode == Activity.RESULT_OK) { if (requestCode == IMAGEPICK_GALLERY_REQUEST) { imageuri = data.getData(); uploadProfileCoverPhoto(imageuri); } if (requestCode == IMAGE_PICKCAMERA_REQUEST) { uploadProfileCoverPhoto(imageuri); } } super.onActivityResult(requestCode, resultCode, data); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case CAMERA_REQUEST: { if (grantResults.length > 0) { boolean camera_accepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; boolean writeStorageaccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED; if (camera_accepted && writeStorageaccepted) { pickFromCamera(); } else { Toast.makeText(this, \"Please Enable Camera and Storage Permissions\", Toast.LENGTH_LONG).show(); } } } break; case STORAGE_REQUEST: { if (grantResults.length > 0) { boolean writeStorageaccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; if (writeStorageaccepted) { pickFromGallery(); } else { Toast.makeText(this, \"Please Enable Storage Permissions\", Toast.LENGTH_LONG).show(); } } } break; } } // Here we will click a photo and then go to startactivityforresult for updating data private void pickFromCamera() { ContentValues contentValues = new ContentValues(); contentValues.put(MediaStore.Images.Media.TITLE, \"Temp_pic\"); contentValues.put(MediaStore.Images.Media.DESCRIPTION, \"Temp Description\"); imageuri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues); Intent camerIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); camerIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageuri); startActivityForResult(camerIntent, IMAGE_PICKCAMERA_REQUEST); } // We will select an image from gallery private void pickFromGallery() { Intent galleryIntent = new Intent(Intent.ACTION_PICK); galleryIntent.setType(\"image/*\"); startActivityForResult(galleryIntent, IMAGEPICK_GALLERY_REQUEST); } // We will upload the image from here. private void uploadProfileCoverPhoto(final Uri uri) { pd.show(); // We are taking the filepath as storagepath + firebaseauth.getUid()+\".png\" String filepathname = storagepath + \"\" + profileOrCoverPhoto + \"_\" + firebaseUser.getUid(); StorageReference storageReference1 = storageReference.child(filepathname); storageReference1.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl(); while (!uriTask.isSuccessful()) ; // We will get the url of our image using uritask final Uri downloadUri = uriTask.getResult(); if (uriTask.isSuccessful()) { // updating our image url into the realtime database HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put(profileOrCoverPhoto, downloadUri.toString()); databaseReference.child(firebaseUser.getUid()).updateChildren(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { pd.dismiss(); Toast.makeText(EditProfilePage.this, \"Updated\", Toast.LENGTH_LONG).show(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(EditProfilePage.this, \"Error Updating \", Toast.LENGTH_LONG).show(); } }); } else { pd.dismiss(); Toast.makeText(EditProfilePage.this, \"Error\", Toast.LENGTH_LONG).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(EditProfilePage.this, \"Error\", Toast.LENGTH_LONG).show(); } }); }}",
"e": 27277,
"s": 6583,
"text": null
},
{
"code": null,
"e": 27338,
"s": 27277,
"text": "Step 6: Create Realtime Database inside the firebase console"
},
{
"code": null,
"e": 27411,
"s": 27338,
"text": "Go to the firebase console > Realtime Database and create your database."
},
{
"code": null,
"e": 27470,
"s": 27411,
"text": "Then Start in Test Mode and Enable the real-time database."
},
{
"code": null,
"e": 27478,
"s": 27470,
"text": "Output:"
},
{
"code": null,
"e": 27542,
"s": 27478,
"text": "When you update the data, the data is stored like the following"
},
{
"code": null,
"e": 27701,
"s": 27542,
"text": "For all the drawable file used in this article please refer to this link: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing"
},
{
"code": null,
"e": 27764,
"s": 27701,
"text": "Below is the file structure after performing these operations:"
},
{
"code": null,
"e": 27780,
"s": 27764,
"text": "happyclasher745"
},
{
"code": null,
"e": 27789,
"s": 27780,
"text": "Firebase"
},
{
"code": null,
"e": 27797,
"s": 27789,
"text": "Android"
},
{
"code": null,
"e": 27802,
"s": 27797,
"text": "Java"
},
{
"code": null,
"e": 27807,
"s": 27802,
"text": "Java"
},
{
"code": null,
"e": 27815,
"s": 27807,
"text": "Android"
}
]
|
SVG scale Attribute | 31 Mar, 2022
The scale attribute decides the displacement scale factor that must be used on a <feDisplacementMap> filter primitive. Only <feDisplacementMap> element is using this attribute.
Syntax:
scale = "number"
Attribute Values: The scale attribute accepts the values mentioned above and described below
number: It is either an integer or a number with a fractional component. The default value is equal to 0.
The below examples illustrate the use of the scale attribute.
Example 1:
HTML
<!DOCTYPE html><html> <body> <div style="color: green; margin-left: 50px;"> <h1>GeeksforGeeks</h1> <svg viewBox="0 0 480 100" xmlns="http://www.w3.org/2000/svg"> <filter id="geek1" x="-20%" y="-20%" width="150%" height="150%"> <feTurbulence type="turbulence" baseFrequency="0.10" numOctaves="2" result="turbulence" /> <feDisplacementMap in2="turbulence" in="SourceGraphic" scale="5" /> </filter> <polygon points="50, 9 60.5, 39.5 92.7, 40.1 67, 59.5 76.4, 90.3 50, 71.9 23.6, 90.3 32.9, 59.5 7.2, 40.1 39.4,39.5" style="filter: url(#geek1);" fill="hsl(106,80%,50%)" /> </svg> </div></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html> <body> <div style="color: green; margin-left: 50px;"> <h1>GeeksforGeeks</h1> <svg viewBox="0 0 480 100" xmlns="http://www.w3.org/2000/svg"> <filter id="geek2" x="-20%" y="-20%" width="150%" height="150%"> <feTurbulence type="turbulence" baseFrequency="0.05" numOctaves="2" result="turbulence" /> <feDisplacementMap in2="turbulence" in="SourceGraphic" scale="20" /> </filter> <polygon points="50, 9 60.5, 39.5 92.7, 40.1 67, 59.5 76.4, 90.3 50, 71.9 23.6, 90.3 32.9, 59.5 7.2, 40.1 39.4, 39.5" style="filter: url(#geek2);" fill="hsl(106,80%,50%)" /> </svg> </div></body> </html>
Output:
HTML-SVG
SVG-Attribute
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Mar, 2022"
},
{
"code": null,
"e": 205,
"s": 28,
"text": "The scale attribute decides the displacement scale factor that must be used on a <feDisplacementMap> filter primitive. Only <feDisplacementMap> element is using this attribute."
},
{
"code": null,
"e": 213,
"s": 205,
"text": "Syntax:"
},
{
"code": null,
"e": 230,
"s": 213,
"text": "scale = \"number\""
},
{
"code": null,
"e": 323,
"s": 230,
"text": "Attribute Values: The scale attribute accepts the values mentioned above and described below"
},
{
"code": null,
"e": 429,
"s": 323,
"text": "number: It is either an integer or a number with a fractional component. The default value is equal to 0."
},
{
"code": null,
"e": 491,
"s": 429,
"text": "The below examples illustrate the use of the scale attribute."
},
{
"code": null,
"e": 502,
"s": 491,
"text": "Example 1:"
},
{
"code": null,
"e": 507,
"s": 502,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <div style=\"color: green; margin-left: 50px;\"> <h1>GeeksforGeeks</h1> <svg viewBox=\"0 0 480 100\" xmlns=\"http://www.w3.org/2000/svg\"> <filter id=\"geek1\" x=\"-20%\" y=\"-20%\" width=\"150%\" height=\"150%\"> <feTurbulence type=\"turbulence\" baseFrequency=\"0.10\" numOctaves=\"2\" result=\"turbulence\" /> <feDisplacementMap in2=\"turbulence\" in=\"SourceGraphic\" scale=\"5\" /> </filter> <polygon points=\"50, 9 60.5, 39.5 92.7, 40.1 67, 59.5 76.4, 90.3 50, 71.9 23.6, 90.3 32.9, 59.5 7.2, 40.1 39.4,39.5\" style=\"filter: url(#geek1);\" fill=\"hsl(106,80%,50%)\" /> </svg> </div></body> </html>",
"e": 1420,
"s": 507,
"text": null
},
{
"code": null,
"e": 1428,
"s": 1420,
"text": "Output:"
},
{
"code": null,
"e": 1439,
"s": 1428,
"text": "Example 2:"
},
{
"code": null,
"e": 1444,
"s": 1439,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <div style=\"color: green; margin-left: 50px;\"> <h1>GeeksforGeeks</h1> <svg viewBox=\"0 0 480 100\" xmlns=\"http://www.w3.org/2000/svg\"> <filter id=\"geek2\" x=\"-20%\" y=\"-20%\" width=\"150%\" height=\"150%\"> <feTurbulence type=\"turbulence\" baseFrequency=\"0.05\" numOctaves=\"2\" result=\"turbulence\" /> <feDisplacementMap in2=\"turbulence\" in=\"SourceGraphic\" scale=\"20\" /> </filter> <polygon points=\"50, 9 60.5, 39.5 92.7, 40.1 67, 59.5 76.4, 90.3 50, 71.9 23.6, 90.3 32.9, 59.5 7.2, 40.1 39.4, 39.5\" style=\"filter: url(#geek2);\" fill=\"hsl(106,80%,50%)\" /> </svg> </div></body> </html>",
"e": 2347,
"s": 1444,
"text": null
},
{
"code": null,
"e": 2355,
"s": 2347,
"text": "Output:"
},
{
"code": null,
"e": 2364,
"s": 2355,
"text": "HTML-SVG"
},
{
"code": null,
"e": 2378,
"s": 2364,
"text": "SVG-Attribute"
},
{
"code": null,
"e": 2383,
"s": 2378,
"text": "HTML"
},
{
"code": null,
"e": 2400,
"s": 2383,
"text": "Web Technologies"
},
{
"code": null,
"e": 2405,
"s": 2400,
"text": "HTML"
},
{
"code": null,
"e": 2503,
"s": 2405,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2527,
"s": 2503,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2566,
"s": 2527,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2605,
"s": 2566,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 2642,
"s": 2605,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 2662,
"s": 2642,
"text": "Angular File Upload"
},
{
"code": null,
"e": 2695,
"s": 2662,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2756,
"s": 2695,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2799,
"s": 2756,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2871,
"s": 2799,
"text": "Differences between Functional Components and Class Components in React"
}
]
|
ulong keyword in C# | 22 Jun, 2020
Keywords are the words in a language that are used for some internal process or represent some predefined actions. ulong is a keyword that is used to declare a variable which can store an unsigned integer value from the range 0 to 18,446,744,073,709,551,615. It is an alias of System.UInt64.
ulong keyword occupies 8 bytes (64 bits) space in the memory.
Syntax:
ulong variable_name = value;
Example:
Input: num: 223
Output: num: 223
Size of a ulong variable: 8
Input: num = 0
Output: Type of num: System.UInt64
num: 0
Size of a ulong variable: 8
Note:
If we input number beyond the range, it shows error-Integral constant is too large
Integral constant is too large
If we input wrong value for eg. -34, it shows error-Constant value `-34' cannot be converted to a `ulong'
Constant value `-34' cannot be converted to a `ulong'
// C# program for ulong keyword using System; using System.Text; class Prog { static void Main(string[] args) { // variable declaration ulong num = 223; // to print value Console.WriteLine("num: " + num); // to print size Console.WriteLine("Size of a ulong variable: " + sizeof(ulong)); } }
Output:
num: 223
Size of a ulong variable: 8
Example 2:
// C# program for ulong keywordusing System;using System.Text; namespace Test { class Prog { static void Main(string[] args) { // variable declaration ulong num = 0; // to print type of variable Console.WriteLine("Type of num: " + num.GetType()); // to print value Console.WriteLine("num: " + num); // to print size Console.WriteLine("Size of a ulong variable: " + sizeof(ulong)); // to print minimum & maximum value of ulong Console.WriteLine("Min value of ulong: " + ulong.MinValue); Console.WriteLine("Max value of ulong: " + ulong.MaxValue); // hit ENTER to exit Console.ReadLine(); }}}
Output:
Type of num: System.UInt64
num: 0
Size of a ulong variable: 8
Min value of ulong: 0
Max value of ulong: 18446744073709551615
CSharp-keyword
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
C# | .NET Framework (Basic Architecture and Component Stack)
HashSet in C# with Examples
Lambda Expressions in C#
Switch Statement in C#
Partial Classes in C#
Hello World in C# | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 320,
"s": 28,
"text": "Keywords are the words in a language that are used for some internal process or represent some predefined actions. ulong is a keyword that is used to declare a variable which can store an unsigned integer value from the range 0 to 18,446,744,073,709,551,615. It is an alias of System.UInt64."
},
{
"code": null,
"e": 382,
"s": 320,
"text": "ulong keyword occupies 8 bytes (64 bits) space in the memory."
},
{
"code": null,
"e": 390,
"s": 382,
"text": "Syntax:"
},
{
"code": null,
"e": 419,
"s": 390,
"text": "ulong variable_name = value;"
},
{
"code": null,
"e": 428,
"s": 419,
"text": "Example:"
},
{
"code": null,
"e": 601,
"s": 428,
"text": "Input: num: 223\n\nOutput: num: 223\n Size of a ulong variable: 8\n\nInput: num = 0\n\nOutput: Type of num: System.UInt64\n num: 0\n Size of a ulong variable: 8"
},
{
"code": null,
"e": 607,
"s": 601,
"text": "Note:"
},
{
"code": null,
"e": 690,
"s": 607,
"text": "If we input number beyond the range, it shows error-Integral constant is too large"
},
{
"code": null,
"e": 721,
"s": 690,
"text": "Integral constant is too large"
},
{
"code": null,
"e": 827,
"s": 721,
"text": "If we input wrong value for eg. -34, it shows error-Constant value `-34' cannot be converted to a `ulong'"
},
{
"code": null,
"e": 881,
"s": 827,
"text": "Constant value `-34' cannot be converted to a `ulong'"
},
{
"code": "// C# program for ulong keyword using System; using System.Text; class Prog { static void Main(string[] args) { // variable declaration ulong num = 223; // to print value Console.WriteLine(\"num: \" + num); // to print size Console.WriteLine(\"Size of a ulong variable: \" + sizeof(ulong)); } } \n",
"e": 1242,
"s": 881,
"text": null
},
{
"code": null,
"e": 1250,
"s": 1242,
"text": "Output:"
},
{
"code": null,
"e": 1288,
"s": 1250,
"text": "num: 223\nSize of a ulong variable: 8\n"
},
{
"code": null,
"e": 1299,
"s": 1288,
"text": "Example 2:"
},
{
"code": "// C# program for ulong keywordusing System;using System.Text; namespace Test { class Prog { static void Main(string[] args) { // variable declaration ulong num = 0; // to print type of variable Console.WriteLine(\"Type of num: \" + num.GetType()); // to print value Console.WriteLine(\"num: \" + num); // to print size Console.WriteLine(\"Size of a ulong variable: \" + sizeof(ulong)); // to print minimum & maximum value of ulong Console.WriteLine(\"Min value of ulong: \" + ulong.MinValue); Console.WriteLine(\"Max value of ulong: \" + ulong.MaxValue); // hit ENTER to exit Console.ReadLine(); }}}",
"e": 2004,
"s": 1299,
"text": null
},
{
"code": null,
"e": 2012,
"s": 2004,
"text": "Output:"
},
{
"code": null,
"e": 2138,
"s": 2012,
"text": "Type of num: System.UInt64\nnum: 0\nSize of a ulong variable: 8\nMin value of ulong: 0\nMax value of ulong: 18446744073709551615\n"
},
{
"code": null,
"e": 2153,
"s": 2138,
"text": "CSharp-keyword"
},
{
"code": null,
"e": 2156,
"s": 2153,
"text": "C#"
},
{
"code": null,
"e": 2254,
"s": 2156,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2297,
"s": 2254,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 2346,
"s": 2297,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 2369,
"s": 2346,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 2385,
"s": 2369,
"text": "C# | List Class"
},
{
"code": null,
"e": 2446,
"s": 2385,
"text": "C# | .NET Framework (Basic Architecture and Component Stack)"
},
{
"code": null,
"e": 2474,
"s": 2446,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 2499,
"s": 2474,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 2522,
"s": 2499,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 2544,
"s": 2522,
"text": "Partial Classes in C#"
}
]
|
C Program for Rabin-Karp Algorithm for Pattern Searching | 11 Dec, 2018
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m.
Examples:
Input: txt[] = "THIS IS A TEST TEXT"
pat[] = "TEST"
Output: Pattern found at index 10
Input: txt[] = "AABAACAADAABAABA"
pat[] = "AABA"
Output: Pattern found at index 0
Pattern found at index 9
Pattern found at index 12
The Naive String Matching algorithm slides the pattern one by one. After each slide, it one by one checks characters at the current shift and if all characters match then prints the match.Like the Naive Algorithm, Rabin-Karp algorithm also slides the pattern one by one. But unlike the Naive algorithm, Rabin Karp algorithm matches the hash value of the pattern with the hash value of current substring of text, and if the hash values match then only it starts matching individual characters. So Rabin Karp algorithm needs to calculate hash values for following strings.
1) Pattern itself.2) All the substrings of text of length m.
C/C++
/* Following program is a C implementation of Rabin KarpAlgorithm given in the CLRS book */#include <stdio.h>#include <string.h> // d is the number of characters in the input alphabet#define d 256 /* pat -> pattern txt -> text q -> A prime number*/void search(char pat[], char txt[], int q){ int M = strlen(pat); int N = strlen(txt); int i, j; int p = 0; // hash value for pattern int t = 0; // hash value for txt int h = 1; // The value of h would be "pow(d, M-1)%q" for (i = 0; i < M - 1; i++) h = (h * d) % q; // Calculate the hash value of pattern and first // window of text for (i = 0; i < M; i++) { p = (d * p + pat[i]) % q; t = (d * t + txt[i]) % q; } // Slide the pattern over text one by one for (i = 0; i <= N - M; i++) { // Check the hash values of current window of text // and pattern. If the hash values match then only // check for characters on by one if (p == t) { /* Check for characters one by one */ for (j = 0; j < M; j++) { if (txt[i + j] != pat[j]) break; } // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) printf("Pattern found at index %d \n", i); } // Calculate hash value for next window of text: Remove // leading digit, add trailing digit if (i < N - M) { t = (d * (t - txt[i] * h) + txt[i + M]) % q; // We might get negative value of t, converting it // to positive if (t < 0) t = (t + q); } }} /* Driver program to test above function */int main(){ char txt[] = "GEEKS FOR GEEKS"; char pat[] = "GEEK"; int q = 101; // A prime number search(pat, txt, q); return 0;}
Pattern found at index 0
Pattern found at index 10
Please refer complete article on Rabin-Karp Algorithm for Pattern Searching for more details!
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 202,
"s": 28,
"text": "Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m."
},
{
"code": null,
"e": 212,
"s": 202,
"text": "Examples:"
},
{
"code": null,
"e": 470,
"s": 212,
"text": "Input: txt[] = \"THIS IS A TEST TEXT\"\n pat[] = \"TEST\"\nOutput: Pattern found at index 10\n\nInput: txt[] = \"AABAACAADAABAABA\"\n pat[] = \"AABA\"\nOutput: Pattern found at index 0\n Pattern found at index 9\n Pattern found at index 12\n\n"
},
{
"code": null,
"e": 1041,
"s": 470,
"text": "The Naive String Matching algorithm slides the pattern one by one. After each slide, it one by one checks characters at the current shift and if all characters match then prints the match.Like the Naive Algorithm, Rabin-Karp algorithm also slides the pattern one by one. But unlike the Naive algorithm, Rabin Karp algorithm matches the hash value of the pattern with the hash value of current substring of text, and if the hash values match then only it starts matching individual characters. So Rabin Karp algorithm needs to calculate hash values for following strings."
},
{
"code": null,
"e": 1102,
"s": 1041,
"text": "1) Pattern itself.2) All the substrings of text of length m."
},
{
"code": null,
"e": 1108,
"s": 1102,
"text": "C/C++"
},
{
"code": "/* Following program is a C implementation of Rabin KarpAlgorithm given in the CLRS book */#include <stdio.h>#include <string.h> // d is the number of characters in the input alphabet#define d 256 /* pat -> pattern txt -> text q -> A prime number*/void search(char pat[], char txt[], int q){ int M = strlen(pat); int N = strlen(txt); int i, j; int p = 0; // hash value for pattern int t = 0; // hash value for txt int h = 1; // The value of h would be \"pow(d, M-1)%q\" for (i = 0; i < M - 1; i++) h = (h * d) % q; // Calculate the hash value of pattern and first // window of text for (i = 0; i < M; i++) { p = (d * p + pat[i]) % q; t = (d * t + txt[i]) % q; } // Slide the pattern over text one by one for (i = 0; i <= N - M; i++) { // Check the hash values of current window of text // and pattern. If the hash values match then only // check for characters on by one if (p == t) { /* Check for characters one by one */ for (j = 0; j < M; j++) { if (txt[i + j] != pat[j]) break; } // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) printf(\"Pattern found at index %d \\n\", i); } // Calculate hash value for next window of text: Remove // leading digit, add trailing digit if (i < N - M) { t = (d * (t - txt[i] * h) + txt[i + M]) % q; // We might get negative value of t, converting it // to positive if (t < 0) t = (t + q); } }} /* Driver program to test above function */int main(){ char txt[] = \"GEEKS FOR GEEKS\"; char pat[] = \"GEEK\"; int q = 101; // A prime number search(pat, txt, q); return 0;}",
"e": 2952,
"s": 1108,
"text": null
},
{
"code": null,
"e": 3005,
"s": 2952,
"text": "Pattern found at index 0 \nPattern found at index 10\n"
},
{
"code": null,
"e": 3099,
"s": 3005,
"text": "Please refer complete article on Rabin-Karp Algorithm for Pattern Searching for more details!"
},
{
"code": null,
"e": 3110,
"s": 3099,
"text": "C Programs"
}
]
|
numpy.unravel_index() function | Python | 22 Apr, 2020
numpy.unravel_index() function converts a flat index or array of flat indices into a tuple of coordinate arrays.
Syntax : numpy.unravel_index(indices, shape, order = ‘C’)Parameters :indices : [array_like] An integer array whose elements are indices into the flattened version of an array of dimensions shape.shape : [tuple of ints] The shape of the array to use for unraveling indices.order : [{‘C’, ‘F’}, optional] Determines whether the multi-index should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order.
Return : [tuple of ndarray] Each array in the tuple has the same shape as the indices array.
Code #1 :
# Python program explaining# numpy.unravel_index() function # importing numpy as geek import numpy as geek gfg = geek.unravel_index([22, 41, 37], (7, 6)) print(gfg)
Output :
(array([3, 6, 6]), array([4, 5, 1]))
Code #2 :
# Python program explaining# numpy.unravel_index() function # importing numpy as geek import numpy as geek gfg = geek.unravel_index([22, 41, 37], (7, 6), order = 'F') print(gfg)
Output :
(array([1, 6, 2]), array([3, 5, 5]))
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 141,
"s": 28,
"text": "numpy.unravel_index() function converts a flat index or array of flat indices into a tuple of coordinate arrays."
},
{
"code": null,
"e": 570,
"s": 141,
"text": "Syntax : numpy.unravel_index(indices, shape, order = ‘C’)Parameters :indices : [array_like] An integer array whose elements are indices into the flattened version of an array of dimensions shape.shape : [tuple of ints] The shape of the array to use for unraveling indices.order : [{‘C’, ‘F’}, optional] Determines whether the multi-index should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order."
},
{
"code": null,
"e": 663,
"s": 570,
"text": "Return : [tuple of ndarray] Each array in the tuple has the same shape as the indices array."
},
{
"code": null,
"e": 673,
"s": 663,
"text": "Code #1 :"
},
{
"code": "# Python program explaining# numpy.unravel_index() function # importing numpy as geek import numpy as geek gfg = geek.unravel_index([22, 41, 37], (7, 6)) print(gfg) ",
"e": 842,
"s": 673,
"text": null
},
{
"code": null,
"e": 851,
"s": 842,
"text": "Output :"
},
{
"code": null,
"e": 889,
"s": 851,
"text": "(array([3, 6, 6]), array([4, 5, 1]))\n"
},
{
"code": null,
"e": 900,
"s": 889,
"text": " Code #2 :"
},
{
"code": "# Python program explaining# numpy.unravel_index() function # importing numpy as geek import numpy as geek gfg = geek.unravel_index([22, 41, 37], (7, 6), order = 'F') print(gfg) ",
"e": 1082,
"s": 900,
"text": null
},
{
"code": null,
"e": 1091,
"s": 1082,
"text": "Output :"
},
{
"code": null,
"e": 1129,
"s": 1091,
"text": "(array([1, 6, 2]), array([3, 5, 5]))\n"
},
{
"code": null,
"e": 1160,
"s": 1129,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 1173,
"s": 1160,
"text": "Python-numpy"
},
{
"code": null,
"e": 1180,
"s": 1173,
"text": "Python"
},
{
"code": null,
"e": 1278,
"s": 1180,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1296,
"s": 1278,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1318,
"s": 1296,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1350,
"s": 1318,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1379,
"s": 1350,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1406,
"s": 1379,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1436,
"s": 1406,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 1457,
"s": 1436,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1493,
"s": 1457,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 1516,
"s": 1493,
"text": "Introduction To PYTHON"
}
]
|
\varnothing - Tex Command | \varnothing - Used to create varnothing symbol.
{ \varnothing}
\varnothing command draws varnothing symbol.
\varnothing
∅
\varnothing
∅
\varnothing
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 8034,
"s": 7986,
"text": "\\varnothing - Used to create varnothing symbol."
},
{
"code": null,
"e": 8049,
"s": 8034,
"text": "{ \\varnothing}"
},
{
"code": null,
"e": 8094,
"s": 8049,
"text": "\\varnothing command draws varnothing symbol."
},
{
"code": null,
"e": 8113,
"s": 8094,
"text": "\n\\varnothing\n\n∅\n\n\n"
},
{
"code": null,
"e": 8130,
"s": 8113,
"text": "\\varnothing\n\n∅\n\n"
},
{
"code": null,
"e": 8142,
"s": 8130,
"text": "\\varnothing"
},
{
"code": null,
"e": 8174,
"s": 8142,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8187,
"s": 8174,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8220,
"s": 8187,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8233,
"s": 8220,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8265,
"s": 8233,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8301,
"s": 8265,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8336,
"s": 8301,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8353,
"s": 8336,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8386,
"s": 8353,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8400,
"s": 8386,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8432,
"s": 8400,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8447,
"s": 8432,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8454,
"s": 8447,
"text": " Print"
},
{
"code": null,
"e": 8465,
"s": 8454,
"text": " Add Notes"
}
]
|
Preview of the Neo4j Graph Data Science plugin with examples from the “Graph Algorithms: Practical Examples in Apache Spark and Neo4j” book | by Tomaz Bratanic | Towards Data Science | In the past couple of years, the field of data science has gained much traction. It has become an essential part of business and academic research. Combined with the increasing popularity of graphs and graph databases, folks at Neo4j decided to release the Graph Data Science (GDS) plugin. It is the successor of the Graph Algorithms plugin, that is to be deprecated. However, this is still a preview version of the GDS and the official launch will follow in the coming weeks.
Those of you who are familiar with Graph Algorithms plugin will notice that the syntax hasn’t changed much to allow for a smoother transition. To show what has changed, I have prepared the migration guides in the form of Apache Zeppelin notebooks that can be found on GitHub.
Neo4j connector for Apache Zeppelin was developed by Andrea Santurbano, who also designed the beautiful home page notebook of this project and helped with his ideas. In the migrations guides, we used the examples from the Graph Algorithms: Practical Examples in Apache Spark and Neo4j book written by Mark Needham and Amy Hodler. As the book also demonstrates the Apache Spark implementations of the graph algorithms, we decided it is only appropriate that we include them as well. When setting up the Apache Spark environment, I ran into the same issues as the co-author of this book, who was kind enough to write a blog post about it. Shout out to Mark!
Here is what you can expect from this project:
16 single graph algorithms notebooks with implementations in Apache Spark as well as the migration guides to GDS
Link prediction analysis from the book ported to GDS
Neo4j Graph Data Science and Graph Algorithms plugins are not compatible, so they do not and will not work together on a single instance of Neo4j. In this project, we used two Neo4j instances to demonstrate both the old and the new syntax.
To get a better feeling of what the notebooks have to offer, we will now go through the PageRank example notebooks. All the quotes that you shall see in this blog post are excerpts from the book mentioned above.
Each graph algorithm has a main notebook that includes a short presentation of the algorithm as well as its use-cases. The following is the introduction to the PageRank algorithm:
PageRank is named after Google cofounder Larry Page, who created it to rank websites in Google’s search results. The basic assumption is that a page with more incoming and more influential incoming links is more likely a credible source. PageRank measures the number and quality of incoming relationships to a node to determine an estimation of how important that node is. Nodes with more sway over a network are presumed to have more incoming relationships from other influential nodes.
On the bottom of the main notebook, you will find links to Neo4j and/or Apache Spark implementation of the algorithm.
In the actual notebooks, you will find both the Graph Algorithms and the Graph Data Science algorithms examples. Still, for the clarity of this blog post, I decided to show only the new GDS syntax.
The example graph is available as a CSV file on GitHub and can be easily fetched using a LOAD CSV cypher statement.
// import nodesWITH “https://raw.githubusercontent.com/neo4j-graph-analytics/book/master/data/social-nodes.csv"AS uriLOAD CSV WITH HEADERS FROM uri AS rowMERGE (:User {id: row.id});// import relationshipsWITH “https://raw.githubusercontent.com/neo4j-graph-analytics/book/master/data/social-relationships.csv"AS uriLOAD CSV WITH HEADERS FROM uri AS rowMATCH (source:User {id: row.src})MATCH (destination:User {id: row.dst})MERGE (source)-[:FOLLOWS]->(destination);
We can visualize the example graph in Zeppelin by using the following cypher statement:
MATCH p=(:User)-[:FOLLOWS]->(:User)RETURN p;
Results
The recommended way of using the GDS library is with pre-loaded named graphs. A projected graph can be stored in memory and be later retrieved by any of the graph algorithms using its name. This allows for more efficient graph analytics pipelines, where we run many graph algorithms in sequence on the same in-memory graph.
The general syntax is:
CALL gds.graph.create('nameOfGraph','NodeLabel','RelationshipType')
In this example, we will be using the following cypher statement to load the graph in memory:
CALL gds.graph.create(‘pagerank_example’, ‘User’, ‘FOLLOWS’);
The general syntax for streaming results from algorithms is:
CALL gds.<algorithm>.stream()
For the PageRank example, the cypher procedure looks like:
CALL gds.pageRank.stream(‘pagerank_example’, {maxIterations: 20, dampingFactor: 0.85}) YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).id AS name, scoreORDER BY score DESC LIMIT 10
Results
As we might expect, Doug has the highest PageRank because he is followed by allother users in his subgraph. Although Mark only has one follower, that follower isDoug, so Mark is also considered important in this graph. It’s not only the number of followers that is important, but also the importance of those followers.
Sometimes, we want to write back the results of the algorithm to the graph instead of streaming them. The general syntax for the write-back algorithms is:
CALL gds.<algorithm>.write({writeProperty:'pagerank'})
Where the writePropertyparameter is mandatory if you want to write-back the results. This is to prevent any unwanted writing to the graph.
In our PageRank example we use:
CALL gds.pageRank.write(‘pagerank_example’, {maxIterations: 20, dampingFactor: 0.85, writeProperty:’pageRank’})
After we are done with our graph analysis, we want to release the GDS graph from memory using the following cypher statement.
CALL gds.graph.drop(‘pagerank_example’);
As mentioned before, the book also offers implementations of graph algorithms in Apache Spark, so I just copied them to the notebooks.
In this example, we are using GraphFrames library to load the graph and calculate the PageRank centrality.
def create_social_graph(): nodes = spark.read.csv(“spark-warehouse/social-nodes.csv”, header=True) relationships = spark.read.csv(“spark-warehouse/social-relationships.csv”, header=True) return GraphFrame(nodes, relationships)g = create_social_graph()
Let’s see an example of the fixed iterations approach.Notice in Spark that the damping factor is more intuitively calledthe reset probability, with the inverse value. In other words, resetProbability=0.15 in this example is equivalent to dampingFactor:0.85 in Neo4j.
results = g.pageRank(resetProbability=0.15, maxIter=20)results.vertices.sort(“pagerank”, ascending=False).show()
Results
Results are similar to the Neo4j results.
PageRank implementations vary, so they can produce differentscoring even when the ordering is the same. Neo4j initializes nodesusing a value of 1 minus the dampening factor whereas Spark usesa value of 1. In this case, the relative rankings (the goal of Pag‐eRank) are identical but the underlying score values used to reachthose results are different.
And now let’s try the convergence implementation that will run PageRank until it closes in on a solution within the set tolerance:
results = g.pageRank(resetProbability=0.15, tol=0.01)results.vertices.sort(“pagerank”, ascending=False).show()
Results
The PageRank scores for each person are slightly different than with the fixed number of iterations variant, but as we would expect, their order remains the same.
We can calculate the personalized PageRank score for a given node by passing in the sourceId parameter. The following code calculates the PPR for Doug:
me = “Doug”results = g.pageRank(resetProbability=0.15, maxIter=20, sourceId=me)people_to_follow = results.vertices.sort(“pagerank”, ascending=False)already_follows = list(g.edges.filter(“src = ‘{me}’”).toPandas()[“dst”])people_to_exclude = already_follows + [me]people_to_follow[~people_to_follow.id.isin(people_to_exclude)].show()
Results
The results of this query could be used to make recommendations for people whoDoug should follow. Notice that we are also making sure that we exclude people who Doug already follows, as well as himself, from our final result.
Alice is the best suggestion for somebody that Doug should follow, but we might suggest Michael and Bridget as well.
Again, thanks to Amy and Mark for writing this excellent book, and thanks to the Neo4j graph data science team for going all the way to deliver such a fantastic tool to help us find more insights within our graph. As I mentioned in the intro of this blog posts, currently this is still a preview of the GDS plugin, and the official launch will be coming in the next couple of weeks. Try the Graph Data Science plugin yourself, and please share any comments, feedback, or suggestion.
As always, you can find the notebooks on GitHub. | [
{
"code": null,
"e": 649,
"s": 172,
"text": "In the past couple of years, the field of data science has gained much traction. It has become an essential part of business and academic research. Combined with the increasing popularity of graphs and graph databases, folks at Neo4j decided to release the Graph Data Science (GDS) plugin. It is the successor of the Graph Algorithms plugin, that is to be deprecated. However, this is still a preview version of the GDS and the official launch will follow in the coming weeks."
},
{
"code": null,
"e": 925,
"s": 649,
"text": "Those of you who are familiar with Graph Algorithms plugin will notice that the syntax hasn’t changed much to allow for a smoother transition. To show what has changed, I have prepared the migration guides in the form of Apache Zeppelin notebooks that can be found on GitHub."
},
{
"code": null,
"e": 1581,
"s": 925,
"text": "Neo4j connector for Apache Zeppelin was developed by Andrea Santurbano, who also designed the beautiful home page notebook of this project and helped with his ideas. In the migrations guides, we used the examples from the Graph Algorithms: Practical Examples in Apache Spark and Neo4j book written by Mark Needham and Amy Hodler. As the book also demonstrates the Apache Spark implementations of the graph algorithms, we decided it is only appropriate that we include them as well. When setting up the Apache Spark environment, I ran into the same issues as the co-author of this book, who was kind enough to write a blog post about it. Shout out to Mark!"
},
{
"code": null,
"e": 1628,
"s": 1581,
"text": "Here is what you can expect from this project:"
},
{
"code": null,
"e": 1741,
"s": 1628,
"text": "16 single graph algorithms notebooks with implementations in Apache Spark as well as the migration guides to GDS"
},
{
"code": null,
"e": 1794,
"s": 1741,
"text": "Link prediction analysis from the book ported to GDS"
},
{
"code": null,
"e": 2034,
"s": 1794,
"text": "Neo4j Graph Data Science and Graph Algorithms plugins are not compatible, so they do not and will not work together on a single instance of Neo4j. In this project, we used two Neo4j instances to demonstrate both the old and the new syntax."
},
{
"code": null,
"e": 2246,
"s": 2034,
"text": "To get a better feeling of what the notebooks have to offer, we will now go through the PageRank example notebooks. All the quotes that you shall see in this blog post are excerpts from the book mentioned above."
},
{
"code": null,
"e": 2426,
"s": 2246,
"text": "Each graph algorithm has a main notebook that includes a short presentation of the algorithm as well as its use-cases. The following is the introduction to the PageRank algorithm:"
},
{
"code": null,
"e": 2914,
"s": 2426,
"text": "PageRank is named after Google cofounder Larry Page, who created it to rank websites in Google’s search results. The basic assumption is that a page with more incoming and more influential incoming links is more likely a credible source. PageRank measures the number and quality of incoming relationships to a node to determine an estimation of how important that node is. Nodes with more sway over a network are presumed to have more incoming relationships from other influential nodes."
},
{
"code": null,
"e": 3032,
"s": 2914,
"text": "On the bottom of the main notebook, you will find links to Neo4j and/or Apache Spark implementation of the algorithm."
},
{
"code": null,
"e": 3230,
"s": 3032,
"text": "In the actual notebooks, you will find both the Graph Algorithms and the Graph Data Science algorithms examples. Still, for the clarity of this blog post, I decided to show only the new GDS syntax."
},
{
"code": null,
"e": 3346,
"s": 3230,
"text": "The example graph is available as a CSV file on GitHub and can be easily fetched using a LOAD CSV cypher statement."
},
{
"code": null,
"e": 3810,
"s": 3346,
"text": "// import nodesWITH “https://raw.githubusercontent.com/neo4j-graph-analytics/book/master/data/social-nodes.csv\"AS uriLOAD CSV WITH HEADERS FROM uri AS rowMERGE (:User {id: row.id});// import relationshipsWITH “https://raw.githubusercontent.com/neo4j-graph-analytics/book/master/data/social-relationships.csv\"AS uriLOAD CSV WITH HEADERS FROM uri AS rowMATCH (source:User {id: row.src})MATCH (destination:User {id: row.dst})MERGE (source)-[:FOLLOWS]->(destination);"
},
{
"code": null,
"e": 3898,
"s": 3810,
"text": "We can visualize the example graph in Zeppelin by using the following cypher statement:"
},
{
"code": null,
"e": 3943,
"s": 3898,
"text": "MATCH p=(:User)-[:FOLLOWS]->(:User)RETURN p;"
},
{
"code": null,
"e": 3951,
"s": 3943,
"text": "Results"
},
{
"code": null,
"e": 4275,
"s": 3951,
"text": "The recommended way of using the GDS library is with pre-loaded named graphs. A projected graph can be stored in memory and be later retrieved by any of the graph algorithms using its name. This allows for more efficient graph analytics pipelines, where we run many graph algorithms in sequence on the same in-memory graph."
},
{
"code": null,
"e": 4298,
"s": 4275,
"text": "The general syntax is:"
},
{
"code": null,
"e": 4366,
"s": 4298,
"text": "CALL gds.graph.create('nameOfGraph','NodeLabel','RelationshipType')"
},
{
"code": null,
"e": 4460,
"s": 4366,
"text": "In this example, we will be using the following cypher statement to load the graph in memory:"
},
{
"code": null,
"e": 4522,
"s": 4460,
"text": "CALL gds.graph.create(‘pagerank_example’, ‘User’, ‘FOLLOWS’);"
},
{
"code": null,
"e": 4583,
"s": 4522,
"text": "The general syntax for streaming results from algorithms is:"
},
{
"code": null,
"e": 4613,
"s": 4583,
"text": "CALL gds.<algorithm>.stream()"
},
{
"code": null,
"e": 4672,
"s": 4613,
"text": "For the PageRank example, the cypher procedure looks like:"
},
{
"code": null,
"e": 4858,
"s": 4672,
"text": "CALL gds.pageRank.stream(‘pagerank_example’, {maxIterations: 20, dampingFactor: 0.85}) YIELD nodeId, scoreRETURN gds.util.asNode(nodeId).id AS name, scoreORDER BY score DESC LIMIT 10"
},
{
"code": null,
"e": 4866,
"s": 4858,
"text": "Results"
},
{
"code": null,
"e": 5186,
"s": 4866,
"text": "As we might expect, Doug has the highest PageRank because he is followed by allother users in his subgraph. Although Mark only has one follower, that follower isDoug, so Mark is also considered important in this graph. It’s not only the number of followers that is important, but also the importance of those followers."
},
{
"code": null,
"e": 5341,
"s": 5186,
"text": "Sometimes, we want to write back the results of the algorithm to the graph instead of streaming them. The general syntax for the write-back algorithms is:"
},
{
"code": null,
"e": 5396,
"s": 5341,
"text": "CALL gds.<algorithm>.write({writeProperty:'pagerank'})"
},
{
"code": null,
"e": 5535,
"s": 5396,
"text": "Where the writePropertyparameter is mandatory if you want to write-back the results. This is to prevent any unwanted writing to the graph."
},
{
"code": null,
"e": 5567,
"s": 5535,
"text": "In our PageRank example we use:"
},
{
"code": null,
"e": 5691,
"s": 5567,
"text": "CALL gds.pageRank.write(‘pagerank_example’, {maxIterations: 20, dampingFactor: 0.85, writeProperty:’pageRank’})"
},
{
"code": null,
"e": 5817,
"s": 5691,
"text": "After we are done with our graph analysis, we want to release the GDS graph from memory using the following cypher statement."
},
{
"code": null,
"e": 5858,
"s": 5817,
"text": "CALL gds.graph.drop(‘pagerank_example’);"
},
{
"code": null,
"e": 5993,
"s": 5858,
"text": "As mentioned before, the book also offers implementations of graph algorithms in Apache Spark, so I just copied them to the notebooks."
},
{
"code": null,
"e": 6100,
"s": 5993,
"text": "In this example, we are using GraphFrames library to load the graph and calculate the PageRank centrality."
},
{
"code": null,
"e": 6361,
"s": 6100,
"text": "def create_social_graph(): nodes = spark.read.csv(“spark-warehouse/social-nodes.csv”, header=True) relationships = spark.read.csv(“spark-warehouse/social-relationships.csv”, header=True) return GraphFrame(nodes, relationships)g = create_social_graph()"
},
{
"code": null,
"e": 6628,
"s": 6361,
"text": "Let’s see an example of the fixed iterations approach.Notice in Spark that the damping factor is more intuitively calledthe reset probability, with the inverse value. In other words, resetProbability=0.15 in this example is equivalent to dampingFactor:0.85 in Neo4j."
},
{
"code": null,
"e": 6741,
"s": 6628,
"text": "results = g.pageRank(resetProbability=0.15, maxIter=20)results.vertices.sort(“pagerank”, ascending=False).show()"
},
{
"code": null,
"e": 6749,
"s": 6741,
"text": "Results"
},
{
"code": null,
"e": 6791,
"s": 6749,
"text": "Results are similar to the Neo4j results."
},
{
"code": null,
"e": 7144,
"s": 6791,
"text": "PageRank implementations vary, so they can produce differentscoring even when the ordering is the same. Neo4j initializes nodesusing a value of 1 minus the dampening factor whereas Spark usesa value of 1. In this case, the relative rankings (the goal of Pag‐eRank) are identical but the underlying score values used to reachthose results are different."
},
{
"code": null,
"e": 7275,
"s": 7144,
"text": "And now let’s try the convergence implementation that will run PageRank until it closes in on a solution within the set tolerance:"
},
{
"code": null,
"e": 7386,
"s": 7275,
"text": "results = g.pageRank(resetProbability=0.15, tol=0.01)results.vertices.sort(“pagerank”, ascending=False).show()"
},
{
"code": null,
"e": 7394,
"s": 7386,
"text": "Results"
},
{
"code": null,
"e": 7557,
"s": 7394,
"text": "The PageRank scores for each person are slightly different than with the fixed number of iterations variant, but as we would expect, their order remains the same."
},
{
"code": null,
"e": 7709,
"s": 7557,
"text": "We can calculate the personalized PageRank score for a given node by passing in the sourceId parameter. The following code calculates the PPR for Doug:"
},
{
"code": null,
"e": 8041,
"s": 7709,
"text": "me = “Doug”results = g.pageRank(resetProbability=0.15, maxIter=20, sourceId=me)people_to_follow = results.vertices.sort(“pagerank”, ascending=False)already_follows = list(g.edges.filter(“src = ‘{me}’”).toPandas()[“dst”])people_to_exclude = already_follows + [me]people_to_follow[~people_to_follow.id.isin(people_to_exclude)].show()"
},
{
"code": null,
"e": 8049,
"s": 8041,
"text": "Results"
},
{
"code": null,
"e": 8275,
"s": 8049,
"text": "The results of this query could be used to make recommendations for people whoDoug should follow. Notice that we are also making sure that we exclude people who Doug already follows, as well as himself, from our final result."
},
{
"code": null,
"e": 8392,
"s": 8275,
"text": "Alice is the best suggestion for somebody that Doug should follow, but we might suggest Michael and Bridget as well."
},
{
"code": null,
"e": 8875,
"s": 8392,
"text": "Again, thanks to Amy and Mark for writing this excellent book, and thanks to the Neo4j graph data science team for going all the way to deliver such a fantastic tool to help us find more insights within our graph. As I mentioned in the intro of this blog posts, currently this is still a preview of the GDS plugin, and the official launch will be coming in the next couple of weeks. Try the Graph Data Science plugin yourself, and please share any comments, feedback, or suggestion."
}
]
|
Classify strings from an array using Custom Hash Function - GeeksforGeeks | 14 May, 2021
Given an array of strings arr[] consisting of N strings, the task is to categorize the strings according to the hash value obtained by adding ASCII values % 26 of the characters in the string.
Examples:
Input: arr[][] = {“geeks”, “for”, “geeks”}Output:geeks geeksforExplanation:The hash value of string “for” is (102 + 111 + 114) % 26 = 14The hash value of string “geeks” is (103 + 101 + 101 + 107 + 115) % 26 = 7Therefore, two “geeks” are grouped together and “for” is kept in another group.
Input: arr[][] = {“adf”, “aahe”, “bce”, “bgdb”}Output: aahe bgdbbceadf Explanation: The hash value of string “adf” is (97 + 100 + 102)%26 = 13The hash value of string “aahe” is (97 + 97 + 104 + 101)%26 = 9The hash value of string “bce” is (98 + 99 + 101)%26 = 12The hash value of string “bgdb” is (98 + 103 + 100 + 98)%26 = 9Therefore, strings “aahe” and “bgdb” have same hashed value, so they are grouped together.
Approach: The idea is to use Map Data Structure for grouping together the strings with the same hash values. Follow the steps below to solve the problem:
Initialize a Map, say mp, to map hash values with respective strings in a vector.
Traverse the given array of strings and perform the following steps:Calculate the hash value of the current string according to the given function.Push the string into the vector with the calculated hash values of the string as key in the map mp.
Calculate the hash value of the current string according to the given function.
Push the string into the vector with the calculated hash values of the string as key in the map mp.
Finally, traverse the map mp and print all the strings of respective keys.
Below is the implementation of the above approach:
C++
Java
Python3
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the hash// value of the string sint stringPower(string s){ // Stores hash value of string int power = 0; int n = s.length(); // Iterate over characters of the string for (int i = 0; i < n; i++) { // Calculate hash value power = (power + (s[i])) % 26; } // Return the hash value return power;} // Function to classify the strings// according to the given conditionvoid categorisation_Of_strings( vector<string> s, int N){ // Maps strings with their strings // respective hash values map<int, vector<string> > mp; // Traverse the array of strings for (int i = 0; i < N; i++) { // Find the hash value of the // of the current string int temp = stringPower(s[i]); // Push the current string in // value vector of temp key mp[temp].push_back(s[i]); } // Traverse over the map mp for (auto power : mp) { // Print the result for (auto str : power.second) { cout << str << " "; } cout << endl; }} // Driver Codeint main(){ vector<string> arr{ "adf", "aahe", "bce", "bgdb" }; int N = arr.size(); categorisation_Of_strings(arr, N); return 0;}
// Java program for the above approachimport java.util.Arrays;import java.util.HashMap;import java.util.Map;import java.util.Vector; class GFG{ // Function to find the hash// value of the string sstatic int stringPower(String s){ // Stores hash value of string int power = 0; int n = s.length(); char C[] = s.toCharArray(); // Iterate over characters of the string for(int i = 0; i < n; i++) { // Calculate hash value power = (power + (C[i])) % 26; } // Return the hash value return power;} // Function to classify the strings// according to the given conditionstatic void categorisation_Of_strings(Vector<String> s, int N){ // Maps strings with their strings // respective hash values Map<Integer, Vector<String> > mp = new HashMap<>(); // Traverse the array of strings for(int i = 0; i < N; i++) { // Find the hash value of the // of the current string int temp = stringPower(s.get(i)); // Push the current string in // value vector of temp key if (mp.containsKey(temp)) { mp.get(temp).add(s.get(i)); } else { mp.put(temp, new Vector<String>()); mp.get(temp).add(s.get(i)); } } // Traverse over the map mp for(Map.Entry<Integer, Vector<String>> entry : mp.entrySet()) { // Print the result for(String str : entry.getValue()) { System.out.print(str + " "); } System.out.println(); }} // Driver codepublic static void main(String[] args){ String[] Sarr = { "adf", "aahe", "bce", "bgdb" }; Vector<String> arr = new Vector<String>( Arrays.asList(Sarr)); int N = arr.size(); categorisation_Of_strings(arr, N);}} // This code is contributed by abhinavjain194
# Python3 program for the above approach # Function to find the hash# value of the string sdef stringPower(s): # Stores hash value of string power = 0 n = len(s) # Iterate over characters of the string for i in range(n): # Calculate hash value power = (power + ord(s[i])) % 26 # Return the hash value return power # Function to classify the strings# according to the given conditiondef categorisation_Of_strings(s, N): # Maps strings with their strings # respective hash values mp = {} # Traverse the array of strings for i in range(N): # Find the hash value of the # of the current string temp = stringPower(s[i]) # Push the current string in # value vector of temp key if temp in mp: mp[temp].append(s[i]) else: mp[temp] = [] mp[temp].append(s[i]) # Traverse over the map mp for i in sorted (mp) : # Print the result for str in mp[i]: print(str,end = " ") print("\n",end = "") # Driver Codeif __name__ == '__main__': arr = ["adf", "aahe", "bce", "bgdb"] N = len(arr) categorisation_Of_strings(arr, N) # This code is contributed by ipg2016107.
<script> // Javascript program for the above approach // Function to find the hash// value of the string sfunction stringPower(s){ // Stores hash value of string var power = 0; var n = s.length; // Iterate over characters of the string for(var i = 0; i < n; i++) { // Calculate hash value power = (power + (s[i].charCodeAt(0))) % 26; } // Return the hash value return power;} // Function to classify the strings// according to the given conditionfunction categorisation_Of_strings(s, N){ // Maps strings with their strings // respective hash values var mp = new Map(); // Traverse the array of strings for(var i = 0; i < N; i++) { // Find the hash value of the // of the current string var temp = stringPower(s[i]); // Push the current string in // value vector of temp key if (!mp.has(temp)) { mp.set(temp, new Array()); } var tmp = mp.get(temp); tmp.push(s[i]); mp.set(temp, tmp); } var tmp = Array(); // Traverse over the map mp mp.forEach((value, key) => { tmp.push(key); }); tmp.sort((a, b) => a - b); // Traverse over the map mp tmp.forEach((value) => { // Print the result mp.get(value).forEach(element => { document.write(element + " "); }); document.write("<br>"); });} // Driver Codevar arr = [ "adf", "aahe", "bce", "bgdb" ];var N = arr.length; categorisation_Of_strings(arr, N); // This code is contributed by rutvik_56 </script>
aahe bgdb
bce
adf
Time Complexity: O(N*M), where M is the length of the longest string.Auxiliary Space: O(N*M)
ipg2016107
abhinavjain194
rutvik_56
ASCII
cpp-map
Arrays
Hash
Strings
Arrays
Hash
Strings
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": 24868,
"s": 24840,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 25061,
"s": 24868,
"text": "Given an array of strings arr[] consisting of N strings, the task is to categorize the strings according to the hash value obtained by adding ASCII values % 26 of the characters in the string."
},
{
"code": null,
"e": 25071,
"s": 25061,
"text": "Examples:"
},
{
"code": null,
"e": 25361,
"s": 25071,
"text": "Input: arr[][] = {“geeks”, “for”, “geeks”}Output:geeks geeksforExplanation:The hash value of string “for” is (102 + 111 + 114) % 26 = 14The hash value of string “geeks” is (103 + 101 + 101 + 107 + 115) % 26 = 7Therefore, two “geeks” are grouped together and “for” is kept in another group."
},
{
"code": null,
"e": 25778,
"s": 25361,
"text": "Input: arr[][] = {“adf”, “aahe”, “bce”, “bgdb”}Output: aahe bgdbbceadf Explanation: The hash value of string “adf” is (97 + 100 + 102)%26 = 13The hash value of string “aahe” is (97 + 97 + 104 + 101)%26 = 9The hash value of string “bce” is (98 + 99 + 101)%26 = 12The hash value of string “bgdb” is (98 + 103 + 100 + 98)%26 = 9Therefore, strings “aahe” and “bgdb” have same hashed value, so they are grouped together."
},
{
"code": null,
"e": 25932,
"s": 25778,
"text": "Approach: The idea is to use Map Data Structure for grouping together the strings with the same hash values. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26014,
"s": 25932,
"text": "Initialize a Map, say mp, to map hash values with respective strings in a vector."
},
{
"code": null,
"e": 26261,
"s": 26014,
"text": "Traverse the given array of strings and perform the following steps:Calculate the hash value of the current string according to the given function.Push the string into the vector with the calculated hash values of the string as key in the map mp."
},
{
"code": null,
"e": 26341,
"s": 26261,
"text": "Calculate the hash value of the current string according to the given function."
},
{
"code": null,
"e": 26441,
"s": 26341,
"text": "Push the string into the vector with the calculated hash values of the string as key in the map mp."
},
{
"code": null,
"e": 26516,
"s": 26441,
"text": "Finally, traverse the map mp and print all the strings of respective keys."
},
{
"code": null,
"e": 26567,
"s": 26516,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26571,
"s": 26567,
"text": "C++"
},
{
"code": null,
"e": 26576,
"s": 26571,
"text": "Java"
},
{
"code": null,
"e": 26584,
"s": 26576,
"text": "Python3"
},
{
"code": null,
"e": 26595,
"s": 26584,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the hash// value of the string sint stringPower(string s){ // Stores hash value of string int power = 0; int n = s.length(); // Iterate over characters of the string for (int i = 0; i < n; i++) { // Calculate hash value power = (power + (s[i])) % 26; } // Return the hash value return power;} // Function to classify the strings// according to the given conditionvoid categorisation_Of_strings( vector<string> s, int N){ // Maps strings with their strings // respective hash values map<int, vector<string> > mp; // Traverse the array of strings for (int i = 0; i < N; i++) { // Find the hash value of the // of the current string int temp = stringPower(s[i]); // Push the current string in // value vector of temp key mp[temp].push_back(s[i]); } // Traverse over the map mp for (auto power : mp) { // Print the result for (auto str : power.second) { cout << str << \" \"; } cout << endl; }} // Driver Codeint main(){ vector<string> arr{ \"adf\", \"aahe\", \"bce\", \"bgdb\" }; int N = arr.size(); categorisation_Of_strings(arr, N); return 0;}",
"e": 27925,
"s": 26595,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.Arrays;import java.util.HashMap;import java.util.Map;import java.util.Vector; class GFG{ // Function to find the hash// value of the string sstatic int stringPower(String s){ // Stores hash value of string int power = 0; int n = s.length(); char C[] = s.toCharArray(); // Iterate over characters of the string for(int i = 0; i < n; i++) { // Calculate hash value power = (power + (C[i])) % 26; } // Return the hash value return power;} // Function to classify the strings// according to the given conditionstatic void categorisation_Of_strings(Vector<String> s, int N){ // Maps strings with their strings // respective hash values Map<Integer, Vector<String> > mp = new HashMap<>(); // Traverse the array of strings for(int i = 0; i < N; i++) { // Find the hash value of the // of the current string int temp = stringPower(s.get(i)); // Push the current string in // value vector of temp key if (mp.containsKey(temp)) { mp.get(temp).add(s.get(i)); } else { mp.put(temp, new Vector<String>()); mp.get(temp).add(s.get(i)); } } // Traverse over the map mp for(Map.Entry<Integer, Vector<String>> entry : mp.entrySet()) { // Print the result for(String str : entry.getValue()) { System.out.print(str + \" \"); } System.out.println(); }} // Driver codepublic static void main(String[] args){ String[] Sarr = { \"adf\", \"aahe\", \"bce\", \"bgdb\" }; Vector<String> arr = new Vector<String>( Arrays.asList(Sarr)); int N = arr.size(); categorisation_Of_strings(arr, N);}} // This code is contributed by abhinavjain194",
"e": 29830,
"s": 27925,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the hash# value of the string sdef stringPower(s): # Stores hash value of string power = 0 n = len(s) # Iterate over characters of the string for i in range(n): # Calculate hash value power = (power + ord(s[i])) % 26 # Return the hash value return power # Function to classify the strings# according to the given conditiondef categorisation_Of_strings(s, N): # Maps strings with their strings # respective hash values mp = {} # Traverse the array of strings for i in range(N): # Find the hash value of the # of the current string temp = stringPower(s[i]) # Push the current string in # value vector of temp key if temp in mp: mp[temp].append(s[i]) else: mp[temp] = [] mp[temp].append(s[i]) # Traverse over the map mp for i in sorted (mp) : # Print the result for str in mp[i]: print(str,end = \" \") print(\"\\n\",end = \"\") # Driver Codeif __name__ == '__main__': arr = [\"adf\", \"aahe\", \"bce\", \"bgdb\"] N = len(arr) categorisation_Of_strings(arr, N) # This code is contributed by ipg2016107.",
"e": 31103,
"s": 29830,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find the hash// value of the string sfunction stringPower(s){ // Stores hash value of string var power = 0; var n = s.length; // Iterate over characters of the string for(var i = 0; i < n; i++) { // Calculate hash value power = (power + (s[i].charCodeAt(0))) % 26; } // Return the hash value return power;} // Function to classify the strings// according to the given conditionfunction categorisation_Of_strings(s, N){ // Maps strings with their strings // respective hash values var mp = new Map(); // Traverse the array of strings for(var i = 0; i < N; i++) { // Find the hash value of the // of the current string var temp = stringPower(s[i]); // Push the current string in // value vector of temp key if (!mp.has(temp)) { mp.set(temp, new Array()); } var tmp = mp.get(temp); tmp.push(s[i]); mp.set(temp, tmp); } var tmp = Array(); // Traverse over the map mp mp.forEach((value, key) => { tmp.push(key); }); tmp.sort((a, b) => a - b); // Traverse over the map mp tmp.forEach((value) => { // Print the result mp.get(value).forEach(element => { document.write(element + \" \"); }); document.write(\"<br>\"); });} // Driver Codevar arr = [ \"adf\", \"aahe\", \"bce\", \"bgdb\" ];var N = arr.length; categorisation_Of_strings(arr, N); // This code is contributed by rutvik_56 </script>",
"e": 32711,
"s": 31103,
"text": null
},
{
"code": null,
"e": 32731,
"s": 32711,
"text": "aahe bgdb \nbce \nadf"
},
{
"code": null,
"e": 32826,
"s": 32733,
"text": "Time Complexity: O(N*M), where M is the length of the longest string.Auxiliary Space: O(N*M)"
},
{
"code": null,
"e": 32837,
"s": 32826,
"text": "ipg2016107"
},
{
"code": null,
"e": 32852,
"s": 32837,
"text": "abhinavjain194"
},
{
"code": null,
"e": 32862,
"s": 32852,
"text": "rutvik_56"
},
{
"code": null,
"e": 32868,
"s": 32862,
"text": "ASCII"
},
{
"code": null,
"e": 32876,
"s": 32868,
"text": "cpp-map"
},
{
"code": null,
"e": 32883,
"s": 32876,
"text": "Arrays"
},
{
"code": null,
"e": 32888,
"s": 32883,
"text": "Hash"
},
{
"code": null,
"e": 32896,
"s": 32888,
"text": "Strings"
},
{
"code": null,
"e": 32903,
"s": 32896,
"text": "Arrays"
},
{
"code": null,
"e": 32908,
"s": 32903,
"text": "Hash"
},
{
"code": null,
"e": 32916,
"s": 32908,
"text": "Strings"
},
{
"code": null,
"e": 33014,
"s": 32916,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33082,
"s": 33014,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 33114,
"s": 33082,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 33137,
"s": 33114,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 33151,
"s": 33137,
"text": "Linear Search"
},
{
"code": null,
"e": 33196,
"s": 33151,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 33281,
"s": 33196,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 33317,
"s": 33281,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 33348,
"s": 33317,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 33382,
"s": 33348,
"text": "Hashing | Set 3 (Open Addressing)"
}
]
|
Tryit Editor v3.7 | Background Image Repeat
Tryit: Position a background image | [
{
"code": null,
"e": 49,
"s": 25,
"text": "Background Image Repeat"
}
]
|
Create an Animated GIF Using Python Matplotlib - GeeksforGeeks | 14 Sep, 2021
In this article, we will discuss how to create an animated GIF using Matplotlib in Python.
Matplotlib can be used to create mathematics-based animations only. These can include a point moving on the circumference of the circle or a sine or cosine wave which are just like sound waves. In Matplotlib we have a library named animation from which we can import a function named as FuncAnimation(). This function is used to create animations. This function is used to call an animationFunction at a particular interval with a Frame number each time and displays the output of AnimationFunction in the Figure. Hence, this function mainly takes these four as its input.
Syntax:
FuncAnimation( Figure, AnimationFunction, Frames, Interval)
Also, there are other functions and objects too, which together make animation possible. They are given below:
We will require NumPy for various mathematical functions and arrays.At last, we will require the plotting ability of matplotlib which is to be imported from its pyplot module.
We will require NumPy for various mathematical functions and arrays.
At last, we will require the plotting ability of matplotlib which is to be imported from its pyplot module.
Importing the required modules
import numpy as np
from matplotlib.animation import FuncAnimation
from IPython import display
import matplotlib.pyplot as plt
The idea is to first create a simple plot of any function (here we had taken e.g. of Cosine ) and then FuncAnimation function will go on calling AnimationFunction passed to it as a parameter after a given interval continuously.
We only have to give such an implementation that will result in a change in the position of the plot in our AnimationFunction which we had passed. And since the interval will be too small (in milliseconds) so we feel like it’s animating.
This is the basic idea for creating animations.
We are going to create a cosine wave that is displayed in a video animation format.
The various steps and ideas used are listed below.
Create a figure where the animation is to be displayed along with the x-axis and y-axis. This is done by creating a plot where we can put limits to x and y axes.
Python3
Figure = plt.figure() # creating a plotlines_plotted = plt.plot([]) # putting limits on x axis since# it is a trigonometry function# (0,2∏)line_plotted = lines_plotted[0] plt.xlim(0,2*np.pi) # putting limits on y since it is a# cosine functionplt.ylim(-1.1,1.1) # initialising x from 0 to 2∏x = np.linspace(0,2*np.pi,100) #initiallyy = 0
Now let’s create our AnimationFunction which will change the x and y coordinates of the plot continuously based on parameter frames. The reason is that FuncAnimation will call this function continuously according to frames. Since animation simply means that frames are put one after another to create a video.
Python3
# function takes frame as an inputdef AnimationFunction(frame): # setting y according to frame # number and + x. It's logic y = np.cos(x+2*np.pi*frame/100) # line is set with new values of x and y line_plotted.set_data((x, y))
Now it’s time to call our FuncAnimation function which will call the above-defined function continuously as the number of frames. We are giving an interval of 25 milliseconds.
anim_created = FuncAnimation(Figure, AnimationFunction, frames=100, interval=25)
Now it’s time to display our animation. So we have to make an HTML file out of it, through the below-given code:
Python3
video = anim_created.to_html5_video()html = display.HTML(video)display.display(html) # good practice to close the plt object.plt.close()
Hence, the complete code can be run locally (if libraries are installed) or online on Jupyter Notebooks or Colaboratory Notebooks.
Output:
Hence, we are able to create animation using Matplotlib which makes learning mathematics easy.
saurabh1990aror
singghakshay
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23927,
"s": 23899,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 24018,
"s": 23927,
"text": "In this article, we will discuss how to create an animated GIF using Matplotlib in Python."
},
{
"code": null,
"e": 24591,
"s": 24018,
"text": "Matplotlib can be used to create mathematics-based animations only. These can include a point moving on the circumference of the circle or a sine or cosine wave which are just like sound waves. In Matplotlib we have a library named animation from which we can import a function named as FuncAnimation(). This function is used to create animations. This function is used to call an animationFunction at a particular interval with a Frame number each time and displays the output of AnimationFunction in the Figure. Hence, this function mainly takes these four as its input."
},
{
"code": null,
"e": 24599,
"s": 24591,
"text": "Syntax:"
},
{
"code": null,
"e": 24660,
"s": 24599,
"text": " FuncAnimation( Figure, AnimationFunction, Frames, Interval)"
},
{
"code": null,
"e": 24771,
"s": 24660,
"text": "Also, there are other functions and objects too, which together make animation possible. They are given below:"
},
{
"code": null,
"e": 24947,
"s": 24771,
"text": "We will require NumPy for various mathematical functions and arrays.At last, we will require the plotting ability of matplotlib which is to be imported from its pyplot module."
},
{
"code": null,
"e": 25016,
"s": 24947,
"text": "We will require NumPy for various mathematical functions and arrays."
},
{
"code": null,
"e": 25124,
"s": 25016,
"text": "At last, we will require the plotting ability of matplotlib which is to be imported from its pyplot module."
},
{
"code": null,
"e": 25155,
"s": 25124,
"text": "Importing the required modules"
},
{
"code": null,
"e": 25281,
"s": 25155,
"text": "import numpy as np\nfrom matplotlib.animation import FuncAnimation\nfrom IPython import display\nimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 25509,
"s": 25281,
"text": "The idea is to first create a simple plot of any function (here we had taken e.g. of Cosine ) and then FuncAnimation function will go on calling AnimationFunction passed to it as a parameter after a given interval continuously."
},
{
"code": null,
"e": 25747,
"s": 25509,
"text": "We only have to give such an implementation that will result in a change in the position of the plot in our AnimationFunction which we had passed. And since the interval will be too small (in milliseconds) so we feel like it’s animating."
},
{
"code": null,
"e": 25796,
"s": 25747,
"text": "This is the basic idea for creating animations. "
},
{
"code": null,
"e": 25880,
"s": 25796,
"text": "We are going to create a cosine wave that is displayed in a video animation format."
},
{
"code": null,
"e": 25932,
"s": 25880,
"text": "The various steps and ideas used are listed below. "
},
{
"code": null,
"e": 26094,
"s": 25932,
"text": "Create a figure where the animation is to be displayed along with the x-axis and y-axis. This is done by creating a plot where we can put limits to x and y axes."
},
{
"code": null,
"e": 26102,
"s": 26094,
"text": "Python3"
},
{
"code": "Figure = plt.figure() # creating a plotlines_plotted = plt.plot([]) # putting limits on x axis since# it is a trigonometry function# (0,2∏)line_plotted = lines_plotted[0] plt.xlim(0,2*np.pi) # putting limits on y since it is a# cosine functionplt.ylim(-1.1,1.1) # initialising x from 0 to 2∏x = np.linspace(0,2*np.pi,100) #initiallyy = 0",
"e": 26450,
"s": 26102,
"text": null
},
{
"code": null,
"e": 26760,
"s": 26450,
"text": "Now let’s create our AnimationFunction which will change the x and y coordinates of the plot continuously based on parameter frames. The reason is that FuncAnimation will call this function continuously according to frames. Since animation simply means that frames are put one after another to create a video."
},
{
"code": null,
"e": 26768,
"s": 26760,
"text": "Python3"
},
{
"code": "# function takes frame as an inputdef AnimationFunction(frame): # setting y according to frame # number and + x. It's logic y = np.cos(x+2*np.pi*frame/100) # line is set with new values of x and y line_plotted.set_data((x, y))",
"e": 27012,
"s": 26768,
"text": null
},
{
"code": null,
"e": 27188,
"s": 27012,
"text": "Now it’s time to call our FuncAnimation function which will call the above-defined function continuously as the number of frames. We are giving an interval of 25 milliseconds."
},
{
"code": null,
"e": 27269,
"s": 27188,
"text": "anim_created = FuncAnimation(Figure, AnimationFunction, frames=100, interval=25)"
},
{
"code": null,
"e": 27382,
"s": 27269,
"text": "Now it’s time to display our animation. So we have to make an HTML file out of it, through the below-given code:"
},
{
"code": null,
"e": 27390,
"s": 27382,
"text": "Python3"
},
{
"code": "video = anim_created.to_html5_video()html = display.HTML(video)display.display(html) # good practice to close the plt object.plt.close()",
"e": 27527,
"s": 27390,
"text": null
},
{
"code": null,
"e": 27658,
"s": 27527,
"text": "Hence, the complete code can be run locally (if libraries are installed) or online on Jupyter Notebooks or Colaboratory Notebooks."
},
{
"code": null,
"e": 27666,
"s": 27658,
"text": "Output:"
},
{
"code": null,
"e": 27761,
"s": 27666,
"text": "Hence, we are able to create animation using Matplotlib which makes learning mathematics easy."
},
{
"code": null,
"e": 27777,
"s": 27761,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 27790,
"s": 27777,
"text": "singghakshay"
},
{
"code": null,
"e": 27797,
"s": 27790,
"text": "Picked"
},
{
"code": null,
"e": 27815,
"s": 27797,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 27822,
"s": 27815,
"text": "Python"
},
{
"code": null,
"e": 27920,
"s": 27822,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27929,
"s": 27920,
"text": "Comments"
},
{
"code": null,
"e": 27942,
"s": 27929,
"text": "Old Comments"
},
{
"code": null,
"e": 27974,
"s": 27942,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28030,
"s": 27974,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28072,
"s": 28030,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28114,
"s": 28072,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28150,
"s": 28114,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 28172,
"s": 28150,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28211,
"s": 28172,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28238,
"s": 28211,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28269,
"s": 28238,
"text": "Python | os.path.join() method"
}
]
|
Making the Mueller Report Searchable with OCR and Elasticsearch | by Kyle Gallatin | Towards Data Science | April 18th marked the full release of the Mueller Report — a document outlining the investigation of potential Russian interference in the 2016 presidential election. Like most government documents it is long (448 pages), and would be painfully tedious to read.
To make matters worse, the actual PDF download is basically just an image. You cannot copy/paste text, or use ctrl+f to find specific portions of text if you wanted to search the document for more targeted information.
However, we can easily make this document searchable for ourselves using two great technologies: optical character recognition (OCR) and Elasticsearch.
OCR allows us to take pictures of text, recognize, and then convert them to actual text — see this description on Wikipedia. Fortunately for us, in the modern day and age there are many open source libraries/products to perform this task.
Tesseract is one such engine. Originally developed in the 80s, it has been a Google project since 2006 and is one of most popular OCR engines. Today, we’ll be using the Python wrapper: pytesseract. I got my original PDF-OCR inspiration from this post — check it out!
Elasticsearch is a scalable search platform that uses an algorithm similar to TF-IDF, which stands for term frequency inverse document frequency.
Essentially, it’s a simple function often used within the search/similarity space that targets documents based on keywords. It also places less emphasis on words that appear frequently. For instance, because the word “the” appears in so many texts, we don’t want it to be considered an important part of our search query. TF-IDF takes this into account when comparing your query with documents. For a basic overview of it just check wikipedia.
You can download and install elastic from the website, or the respective package manager for your OS. Then you just need all the Python packages we’ll be using.
pip install elasticsearchpip install pdf2imagepip install pytesseract
First, download the Mueller Report to your host. Then, we can create a quick function to extract the text from a PDF page-by-page using pytesseract and the pdf2image libary.
Notice I set the default num_pages=10. This is because this report is really long, and on your personal computer it’ll probably take quite a long time to extract the text from every page. Additionally, it’s also a lot of data for a local Elasticsearch index if you don’t plan on deploying this to the cloud. Still, feel free to change that parameter to any value you choose.
But regardless of that, when we run this function on our PDF we now we have the text and page number for all of our PDF pages! It’s a list of dictionaries (json) which is perfect for ingestion by elastic to make it searchable.
The first thing you need to do is make sure elastic is running on the proper port. Open a terminal and start elastic (if it’s in your $PATH it should just be elasticsearch). By default, this will start the service on port 9200.
After that, we can easily use the Python client to interact with our instance. If elastic is running properly on port 9200, the following code should create the index mueller-report which has 2 fields: text and page (these correspond to our dictionary keys in the previous function).
I won’t get into the specifics, but elastic uses a language called query DSL to interact with the indices. There’s a lot you can do with it, but all we’re going to do here is create a function that will vectorize our query, and compare it with the text in our index for similarity.
The res will be a json that contains a bunch of info on our search. Realistically though, we only want our relevant results. So once we actually call the function, we can parse the json to get the most relevant text and page number.
With this, our search function looks for “department of justice” within the page texts, and returns the results. the [0] in the statement above is just to look at the first, most relevant page text and number. However, you can customize the parsing so that it returns as few/many results as you like.
Instead of viewing a poorly recorded gif of my jupyter notebook, we can actually use another elastic tool to better view our results. Kibana is an open source front end for elastic that’s great for visualization. First, install kibana from this link.
Once you have Kibana installed, start the service by running kibana in a terminal and then navigate to localhost:5601 in your favorite web broswer. This will let you interact with the application.
The only thing we have to do here before we interact with our index is create an index pattern. Go to Management > Create Index Pattern, and then type in “mueller-report” — Kibana should let you know that the pattern matches the index we created earlier in elastic.
And that’s it! If you go to the Discover tab on the left, and you can search your index in a much easier (and more aesthetic) manner than we were in elastic.
It would probably be cool to throw this up on AWS so anyone can use it (with a nicer front end), but I’m not really tryna tie my credit card to that instance at the moment. If anyone else wants to, feel free! I’ll update soon with a docker container and github link.
4/21/19 — There have been a lot of other posts/work regarding OCR and subsequent NLP on the Mueller Report. It seems that the main concern is the actual quality of the OCR text, since results can be messy due to formatting or general inaccuracy. While there’s probably no easy way to solve this for future analysis (aside from the government releasing a useful document), we can at least have elastic compensate for any misspellings in our searches by adding a fuzziness parameter to our search function.
This is a hacky, but generalizable way to account for some of the error we might find in the post OCR text. | [
{
"code": null,
"e": 434,
"s": 172,
"text": "April 18th marked the full release of the Mueller Report — a document outlining the investigation of potential Russian interference in the 2016 presidential election. Like most government documents it is long (448 pages), and would be painfully tedious to read."
},
{
"code": null,
"e": 653,
"s": 434,
"text": "To make matters worse, the actual PDF download is basically just an image. You cannot copy/paste text, or use ctrl+f to find specific portions of text if you wanted to search the document for more targeted information."
},
{
"code": null,
"e": 805,
"s": 653,
"text": "However, we can easily make this document searchable for ourselves using two great technologies: optical character recognition (OCR) and Elasticsearch."
},
{
"code": null,
"e": 1044,
"s": 805,
"text": "OCR allows us to take pictures of text, recognize, and then convert them to actual text — see this description on Wikipedia. Fortunately for us, in the modern day and age there are many open source libraries/products to perform this task."
},
{
"code": null,
"e": 1311,
"s": 1044,
"text": "Tesseract is one such engine. Originally developed in the 80s, it has been a Google project since 2006 and is one of most popular OCR engines. Today, we’ll be using the Python wrapper: pytesseract. I got my original PDF-OCR inspiration from this post — check it out!"
},
{
"code": null,
"e": 1457,
"s": 1311,
"text": "Elasticsearch is a scalable search platform that uses an algorithm similar to TF-IDF, which stands for term frequency inverse document frequency."
},
{
"code": null,
"e": 1901,
"s": 1457,
"text": "Essentially, it’s a simple function often used within the search/similarity space that targets documents based on keywords. It also places less emphasis on words that appear frequently. For instance, because the word “the” appears in so many texts, we don’t want it to be considered an important part of our search query. TF-IDF takes this into account when comparing your query with documents. For a basic overview of it just check wikipedia."
},
{
"code": null,
"e": 2062,
"s": 1901,
"text": "You can download and install elastic from the website, or the respective package manager for your OS. Then you just need all the Python packages we’ll be using."
},
{
"code": null,
"e": 2132,
"s": 2062,
"text": "pip install elasticsearchpip install pdf2imagepip install pytesseract"
},
{
"code": null,
"e": 2306,
"s": 2132,
"text": "First, download the Mueller Report to your host. Then, we can create a quick function to extract the text from a PDF page-by-page using pytesseract and the pdf2image libary."
},
{
"code": null,
"e": 2681,
"s": 2306,
"text": "Notice I set the default num_pages=10. This is because this report is really long, and on your personal computer it’ll probably take quite a long time to extract the text from every page. Additionally, it’s also a lot of data for a local Elasticsearch index if you don’t plan on deploying this to the cloud. Still, feel free to change that parameter to any value you choose."
},
{
"code": null,
"e": 2908,
"s": 2681,
"text": "But regardless of that, when we run this function on our PDF we now we have the text and page number for all of our PDF pages! It’s a list of dictionaries (json) which is perfect for ingestion by elastic to make it searchable."
},
{
"code": null,
"e": 3136,
"s": 2908,
"text": "The first thing you need to do is make sure elastic is running on the proper port. Open a terminal and start elastic (if it’s in your $PATH it should just be elasticsearch). By default, this will start the service on port 9200."
},
{
"code": null,
"e": 3420,
"s": 3136,
"text": "After that, we can easily use the Python client to interact with our instance. If elastic is running properly on port 9200, the following code should create the index mueller-report which has 2 fields: text and page (these correspond to our dictionary keys in the previous function)."
},
{
"code": null,
"e": 3702,
"s": 3420,
"text": "I won’t get into the specifics, but elastic uses a language called query DSL to interact with the indices. There’s a lot you can do with it, but all we’re going to do here is create a function that will vectorize our query, and compare it with the text in our index for similarity."
},
{
"code": null,
"e": 3935,
"s": 3702,
"text": "The res will be a json that contains a bunch of info on our search. Realistically though, we only want our relevant results. So once we actually call the function, we can parse the json to get the most relevant text and page number."
},
{
"code": null,
"e": 4236,
"s": 3935,
"text": "With this, our search function looks for “department of justice” within the page texts, and returns the results. the [0] in the statement above is just to look at the first, most relevant page text and number. However, you can customize the parsing so that it returns as few/many results as you like."
},
{
"code": null,
"e": 4487,
"s": 4236,
"text": "Instead of viewing a poorly recorded gif of my jupyter notebook, we can actually use another elastic tool to better view our results. Kibana is an open source front end for elastic that’s great for visualization. First, install kibana from this link."
},
{
"code": null,
"e": 4684,
"s": 4487,
"text": "Once you have Kibana installed, start the service by running kibana in a terminal and then navigate to localhost:5601 in your favorite web broswer. This will let you interact with the application."
},
{
"code": null,
"e": 4950,
"s": 4684,
"text": "The only thing we have to do here before we interact with our index is create an index pattern. Go to Management > Create Index Pattern, and then type in “mueller-report” — Kibana should let you know that the pattern matches the index we created earlier in elastic."
},
{
"code": null,
"e": 5108,
"s": 4950,
"text": "And that’s it! If you go to the Discover tab on the left, and you can search your index in a much easier (and more aesthetic) manner than we were in elastic."
},
{
"code": null,
"e": 5375,
"s": 5108,
"text": "It would probably be cool to throw this up on AWS so anyone can use it (with a nicer front end), but I’m not really tryna tie my credit card to that instance at the moment. If anyone else wants to, feel free! I’ll update soon with a docker container and github link."
},
{
"code": null,
"e": 5880,
"s": 5375,
"text": "4/21/19 — There have been a lot of other posts/work regarding OCR and subsequent NLP on the Mueller Report. It seems that the main concern is the actual quality of the OCR text, since results can be messy due to formatting or general inaccuracy. While there’s probably no easy way to solve this for future analysis (aside from the government releasing a useful document), we can at least have elastic compensate for any misspellings in our searches by adding a fuzziness parameter to our search function."
}
]
|
Metrics and Python II. In the previous article, we take a... | by Gabriel Naya | Towards Data Science | We make a dataset with three arrays: real values, predicted values, and likelihood values.real_values: A data set with 1000 elements between 0 and 1.pred_values: A variation of the real dataset, emulates a prediction, changing only the first 150 values.prob_values: Is the pred_values array but contains the percent of probability of being zero or one, instead of the real value 0 or 1. It will be used for ROC charts and Recall versus Precision.
real_values = []prob_values = []pred_values = []for k in range(0,1000): value = random.uniform(0, 1) real_values.append(int(round(value,0))) if k < 150: value2 = random.uniform(0, 1) prob_values.append(value2) pred_values.append(int(round(value2,0))) else: prob_values.append(value) pred_values.append(int(round(value,0)))
The Confusion Matrix is not a metric in itself but is an essential tool for classifying real data and predictions, so its components are the trigger for the first set of metrics.
from sklearn.metrics import confusion_matriximport scikitplot as skpltprint(confusion_matrix(real_values, pred_values))skplt.metrics.plot_confusion_matrix(real_values, pred_values,figsize=(8,8))
You can download complete file in https://kreilabs.com/wp-content/uploads/2019/12/Metrics_table.pdf
Here we can see pyhton implementation for table metrics in matrix_metrix routine:
import sklearn.metricsimport mathdef matrix_metrix(real_values,pred_values,beta): CM = confusion_matrix(real_values,pred_values) TN = CM[0][0] FN = CM[1][0] TP = CM[1][1] FP = CM[0][1] Population = TN+FN+TP+FP Prevalence = round( (TP+FP) / Population,2) Accuracy = round( (TP+TN) / Population,4) Precision = round( TP / (TP+FP),4 ) NPV = round( TN / (TN+FN),4 ) FDR = round( FP / (TP+FP),4 ) FOR = round( FN / (TN+FN),4 ) check_Pos = Precision + FDR check_Neg = NPV + FOR Recall = round( TP / (TP+FN),4 ) FPR = round( FP / (TN+FP),4 ) FNR = round( FN / (TP+FN),4 ) TNR = round( TN / (TN+FP),4 ) check_Pos2 = Recall + FNR check_Neg2 = FPR + TNR LRPos = round( Recall/FPR,4 ) LRNeg = round( FNR / TNR ,4 ) DOR = round( LRPos/LRNeg) F1 = round ( 2 * ((Precision*Recall)/(Precision+Recall)),4) FBeta = round ( (1+beta**2)*((Precision*Recall)/((beta**2 * Precision)+ Recall)) ,4) MCC = round ( ((TP*TN)-(FP*FN))/math.sqrt((TP+FP)*(TP+FN)*(TN+FP)*(TN+FN)) ,4) BM = Recall+TNR-1 MK = Precision+NPV-1 mat_met = pd.DataFrame({'Metric':['TP','TN','FP','FN','Prevalence','Accuracy','Precision','NPV','FDR','FOR','check_Pos','check_Neg','Recall','FPR','FNR','TNR','check_Pos2','check_Neg2','LR+','LR-','DOR','F1','FBeta','MCC','BM','MK'], 'Value':[TP,TN,FP,FN,Prevalence,Accuracy,Precision,NPV,FDR,FOR,check_Pos,check_Neg,Recall,FPR,FNR,TNR,check_Pos2,check_Neg2,LRPos,LRNeg,DOR,F1,FBeta,MCC,BM,MK]}) return (mat_met)
When we call matrix_metrix function:
beta = 0.4mat_met = matrix_metrix(real_values,pred_values,beta)print (mat_met)
TP = True positive
TN = True negative
FP = False positive — Equivalent with false alarm or Type I error1
FN = False negative — Equivalent with miss or Type II error 2
Prevalence: Serves to measure the balance of data within the total population. It is possible to measure the prevalence of positives or negatives and the sum of both quotients is = 1, a balanced data set would give coefficients close to 0.5If, on the contrary, one of the factors is close to 1 and the other to 0, we are going to have an unbalanced data set.
Accuracy: It is the measure of success of the system, the total of positive and negative achievements over the total population, indicates the degree of success of the model. According to the cost of the sensitivity3 of the case study, and the balance of the data (prevalence).
PPV — Positive predictive value o precisión
NPV — Negative predictive value
The PPV and NPV describe the performance of a diagnostic test or other statistical measure. A high result can be interpreted as indicating the accuracy of such a statistic. The PPV and NPV are not intrinsic to the test; they depend also on the prevalence. 4
FDR — False Discovery rate (Type I) [iv]
FOR — False Omission Rate
check_Pos: PPV + FDR = 1
check_Neg: FOR + NPV = 1
Recall, sensitivity, probability of detection, and power are the same measure, which assumes different names and applications depending on the field of study.In the literature referring to binary classification problems, the use of the term recall is more frequent.
“Sensitivity and specificity are statistical measures of the performance of a binary classification test, also known in statistics as a classification function, that are widely used in medicine:
· Sensitivity measures the proportion of actual positives that are correctly identified as such.
· Specificity (also called the true negative rate) measures the proportion of actual negatives that are correctly identified as such (e.g., the percentage of healthy people who are correctly identified as not having the condition).5
FPR — false positive ratio (or false alarm ratio) is the probability of falsely rejecting the null hypothesis for a particular test.
FNR — false negative rate is the proportion of positives which yield negative test outcomes with the test, i.e., the conditional probability of a negative test result given that the condition being looked for is present.
In statistical hypothesis testing, this fraction is given the letter β. The “power” (or the “sensitivity”) of the test is equal to 1−β.
Not to be confused with Likelihood-ratio test.
LR (+ -) Likelihood ratios: They are used for assessing the value of performing a diagnostic test. 6
DOR — diagnostic odds ratio is a measure of the effectiveness of a diagnostic test 7
From the matrix_metrix function used for Table 1, we also got the values for this Table 2:
In statistical analysis of binary classification, the F1 score (also F-score or F-measure) is a measure of a test’s accuracy. It considers both the precision p and the recall r of the test to compute the score: p is the number of correct positive results divided by the number of all positive results returned by the classifier, and r is the number of correct positive results divided by the number of all relevant samples (all samples that should have been identified as positive). The F1 score is the harmonic mean of the precision and recall, where an F1 score reaches its best value at 1 (perfect precision and recall) and worst at 0.8
Beta is a parameter for score analysis, if we use Beta equal to 1, we have the harmonic mean; then we have the F1 score:
We could take some Rules of Thumb:
To give more weight to the Precision, we must select a Beta value between 0–1 0 < Beta < 1
To give more weight to the Recall, we pick a Beta Value in the interval 1 < Beta < +infinite
We can find an excellent and very complete article regarding the concepts and implementation of these instruments.
ROC — Receive operating characteristic
It is a plot of the false positive rate (x-axis) versus the true positive rate (y-axis) for a number of different candidate threshold values between 0.0 and 1.0. Put another way, it plots the false alarm rate versus the hit rate.
Precision-recall curves
A precision-recall curve is a plot of the precision (y-axis) and the recall (x-axis) for different thresholds, much like the ROC curve. A no-skill classifier is one that cannot discriminate between the classes and would predict a random class or a constant class in all cases. The no-skill line changes based on the distribution of the positive to negative classes. It is a horizontal line with the value of the ratio of positive cases in the dataset. For a balanced dataset, this is 0.5.
AUC — Area under curve
The area under the curve (AUC) can be used as a summary of the model skill.
We based on the mentioned article for the following code
#ROC Implementationfrom sklearn.metrics import roc_curvefrom sklearn.metrics import roc_auc_scorefrom matplotlib import pyplotfpr, tpr, thresholds = roc_curve(real_values, prob_values)auc = roc_auc_score(real_values, prob_values)print('AUC: %.3f' % auc)pyplot.plot(fpr, tpr, linestyle='--', label='Roc curve')pyplot.xlabel('False Positive Rate')pyplot.ylabel('True Positive Rate')pyplot.legend()pyplot.show()
#Precision-recall implementationprecision, recall, thresholds = sklearn.metrics.precision_recall_curve(real_values,prob_values)pyplot.plot(recall, precision, linestyle='--', label='Precision versus Recall')pyplot.xlabel('Recall')pyplot.ylabel('Precision')pyplot.legend()pyplot.show()
Here a simple and fast report about binary classification values
And here a function for get many metrics directly from sklearn:
def sk_metrix(real_values,pred_values,beta): Accuracy = round( sklearn.metrics.accuracy_score(real_values,pred_values) ,4) Precision = round( sklearn.metrics.precision_score(real_values,pred_values),4 ) Recall = round( sklearn.metrics.recall_score(real_values,pred_values),4 ) F1 = round ( sklearn.metrics.f1_score(real_values,pred_values),4) FBeta = round ( sklearn.metrics.fbeta_score(real_values,pred_values,beta) ,4) MCC = round ( sklearn.metrics.matthews_corrcoef(real_values,pred_values) ,4) Hamming = round ( sklearn.metrics.hamming_loss(real_values,pred_values) ,4) Jaccard = round ( sklearn.metrics.jaccard_score(real_values,pred_values) ,4) Prec_Avg = round ( sklearn.metrics.average_precision_score(real_values,pred_values) ,4) Accu_Avg = round ( sklearn.metrics.balanced_accuracy_score(real_values,pred_values) ,4) mat_met = pd.DataFrame({'Metric': ['Accuracy','Precision','Recall','F1','FBeta','MCC','Hamming','Jaccard','Precision_Avg','Accuracy_Avg'],'Value': [Accuracy,Precision,Recall,F1,FBeta,MCC,Hamming,Jaccard,Prec_Avg,Accu_Avg]}) return (mat_met)
Calling sk_metrix function
sk_met = sk_metrix(real_values,pred_values,beta)
The number of metrics arising from the confusion matrix is quite large and may be challenging to cover to refine the use of each indicator according to the use case. The most common metrics may be F1-Score, ROC, precision-recall AUC, prevalence, and sensitivity.
This series of articles intended to create a table in which to quickly have a guide of the majority of metrics used for each case study; mastering their application exceeds our scope and also seems to be quite difficult.Remember that the table can be download in pdf format.
In the next article, we will see more classification metrics and specific metrics for recommendation systems in table 2.3
[*] https://en.wikipedia.org/wiki/Confusion_matrix
[1] type i error
[2] type ii error
[3] https://medium.com/mercadolibre-datablog/cost-sensitive-classification-in-fraud-prevention-263170d8fcfe
[4] The positive and negative predictive values (PPV and NPV respectively) are the proportions of positive and negative results in statistics and diagnostic tests that are true positive and true negative results, respectively.[1] “The PPV and NPV describe the performance of a diagnostic test or other statistical measure. A high result can be interpreted as indicating the accuracy of such a statistic. The PPV and NPV are not intrinsic to the test; they depend also on the prevalence.[2] The PPV can be derived using Bayes’ theorem. Although sometimes used synonymously, a positive predictive value generally refers to what is established by control groups, while a post-test probability refers to a probability for an individual. Still, if the individual’s pre-test probability of the target condition is the same as the prevalence in the control group used to establish the positive predictive value, the two are numerically equal. | [
{
"code": null,
"e": 493,
"s": 46,
"text": "We make a dataset with three arrays: real values, predicted values, and likelihood values.real_values: A data set with 1000 elements between 0 and 1.pred_values: A variation of the real dataset, emulates a prediction, changing only the first 150 values.prob_values: Is the pred_values array but contains the percent of probability of being zero or one, instead of the real value 0 or 1. It will be used for ROC charts and Recall versus Precision."
},
{
"code": null,
"e": 849,
"s": 493,
"text": "real_values = []prob_values = []pred_values = []for k in range(0,1000): value = random.uniform(0, 1) real_values.append(int(round(value,0))) if k < 150: value2 = random.uniform(0, 1) prob_values.append(value2) pred_values.append(int(round(value2,0))) else: prob_values.append(value) pred_values.append(int(round(value,0)))"
},
{
"code": null,
"e": 1028,
"s": 849,
"text": "The Confusion Matrix is not a metric in itself but is an essential tool for classifying real data and predictions, so its components are the trigger for the first set of metrics."
},
{
"code": null,
"e": 1223,
"s": 1028,
"text": "from sklearn.metrics import confusion_matriximport scikitplot as skpltprint(confusion_matrix(real_values, pred_values))skplt.metrics.plot_confusion_matrix(real_values, pred_values,figsize=(8,8))"
},
{
"code": null,
"e": 1323,
"s": 1223,
"text": "You can download complete file in https://kreilabs.com/wp-content/uploads/2019/12/Metrics_table.pdf"
},
{
"code": null,
"e": 1405,
"s": 1323,
"text": "Here we can see pyhton implementation for table metrics in matrix_metrix routine:"
},
{
"code": null,
"e": 2984,
"s": 1405,
"text": "import sklearn.metricsimport mathdef matrix_metrix(real_values,pred_values,beta): CM = confusion_matrix(real_values,pred_values) TN = CM[0][0] FN = CM[1][0] TP = CM[1][1] FP = CM[0][1] Population = TN+FN+TP+FP Prevalence = round( (TP+FP) / Population,2) Accuracy = round( (TP+TN) / Population,4) Precision = round( TP / (TP+FP),4 ) NPV = round( TN / (TN+FN),4 ) FDR = round( FP / (TP+FP),4 ) FOR = round( FN / (TN+FN),4 ) check_Pos = Precision + FDR check_Neg = NPV + FOR Recall = round( TP / (TP+FN),4 ) FPR = round( FP / (TN+FP),4 ) FNR = round( FN / (TP+FN),4 ) TNR = round( TN / (TN+FP),4 ) check_Pos2 = Recall + FNR check_Neg2 = FPR + TNR LRPos = round( Recall/FPR,4 ) LRNeg = round( FNR / TNR ,4 ) DOR = round( LRPos/LRNeg) F1 = round ( 2 * ((Precision*Recall)/(Precision+Recall)),4) FBeta = round ( (1+beta**2)*((Precision*Recall)/((beta**2 * Precision)+ Recall)) ,4) MCC = round ( ((TP*TN)-(FP*FN))/math.sqrt((TP+FP)*(TP+FN)*(TN+FP)*(TN+FN)) ,4) BM = Recall+TNR-1 MK = Precision+NPV-1 mat_met = pd.DataFrame({'Metric':['TP','TN','FP','FN','Prevalence','Accuracy','Precision','NPV','FDR','FOR','check_Pos','check_Neg','Recall','FPR','FNR','TNR','check_Pos2','check_Neg2','LR+','LR-','DOR','F1','FBeta','MCC','BM','MK'], 'Value':[TP,TN,FP,FN,Prevalence,Accuracy,Precision,NPV,FDR,FOR,check_Pos,check_Neg,Recall,FPR,FNR,TNR,check_Pos2,check_Neg2,LRPos,LRNeg,DOR,F1,FBeta,MCC,BM,MK]}) return (mat_met)"
},
{
"code": null,
"e": 3021,
"s": 2984,
"text": "When we call matrix_metrix function:"
},
{
"code": null,
"e": 3100,
"s": 3021,
"text": "beta = 0.4mat_met = matrix_metrix(real_values,pred_values,beta)print (mat_met)"
},
{
"code": null,
"e": 3119,
"s": 3100,
"text": "TP = True positive"
},
{
"code": null,
"e": 3138,
"s": 3119,
"text": "TN = True negative"
},
{
"code": null,
"e": 3205,
"s": 3138,
"text": "FP = False positive — Equivalent with false alarm or Type I error1"
},
{
"code": null,
"e": 3267,
"s": 3205,
"text": "FN = False negative — Equivalent with miss or Type II error 2"
},
{
"code": null,
"e": 3626,
"s": 3267,
"text": "Prevalence: Serves to measure the balance of data within the total population. It is possible to measure the prevalence of positives or negatives and the sum of both quotients is = 1, a balanced data set would give coefficients close to 0.5If, on the contrary, one of the factors is close to 1 and the other to 0, we are going to have an unbalanced data set."
},
{
"code": null,
"e": 3904,
"s": 3626,
"text": "Accuracy: It is the measure of success of the system, the total of positive and negative achievements over the total population, indicates the degree of success of the model. According to the cost of the sensitivity3 of the case study, and the balance of the data (prevalence)."
},
{
"code": null,
"e": 3949,
"s": 3904,
"text": "PPV — Positive predictive value o precisión"
},
{
"code": null,
"e": 3981,
"s": 3949,
"text": "NPV — Negative predictive value"
},
{
"code": null,
"e": 4239,
"s": 3981,
"text": "The PPV and NPV describe the performance of a diagnostic test or other statistical measure. A high result can be interpreted as indicating the accuracy of such a statistic. The PPV and NPV are not intrinsic to the test; they depend also on the prevalence. 4"
},
{
"code": null,
"e": 4280,
"s": 4239,
"text": "FDR — False Discovery rate (Type I) [iv]"
},
{
"code": null,
"e": 4306,
"s": 4280,
"text": "FOR — False Omission Rate"
},
{
"code": null,
"e": 4331,
"s": 4306,
"text": "check_Pos: PPV + FDR = 1"
},
{
"code": null,
"e": 4356,
"s": 4331,
"text": "check_Neg: FOR + NPV = 1"
},
{
"code": null,
"e": 4622,
"s": 4356,
"text": "Recall, sensitivity, probability of detection, and power are the same measure, which assumes different names and applications depending on the field of study.In the literature referring to binary classification problems, the use of the term recall is more frequent."
},
{
"code": null,
"e": 4817,
"s": 4622,
"text": "“Sensitivity and specificity are statistical measures of the performance of a binary classification test, also known in statistics as a classification function, that are widely used in medicine:"
},
{
"code": null,
"e": 4914,
"s": 4817,
"text": "· Sensitivity measures the proportion of actual positives that are correctly identified as such."
},
{
"code": null,
"e": 5147,
"s": 4914,
"text": "· Specificity (also called the true negative rate) measures the proportion of actual negatives that are correctly identified as such (e.g., the percentage of healthy people who are correctly identified as not having the condition).5"
},
{
"code": null,
"e": 5280,
"s": 5147,
"text": "FPR — false positive ratio (or false alarm ratio) is the probability of falsely rejecting the null hypothesis for a particular test."
},
{
"code": null,
"e": 5501,
"s": 5280,
"text": "FNR — false negative rate is the proportion of positives which yield negative test outcomes with the test, i.e., the conditional probability of a negative test result given that the condition being looked for is present."
},
{
"code": null,
"e": 5637,
"s": 5501,
"text": "In statistical hypothesis testing, this fraction is given the letter β. The “power” (or the “sensitivity”) of the test is equal to 1−β."
},
{
"code": null,
"e": 5684,
"s": 5637,
"text": "Not to be confused with Likelihood-ratio test."
},
{
"code": null,
"e": 5785,
"s": 5684,
"text": "LR (+ -) Likelihood ratios: They are used for assessing the value of performing a diagnostic test. 6"
},
{
"code": null,
"e": 5870,
"s": 5785,
"text": "DOR — diagnostic odds ratio is a measure of the effectiveness of a diagnostic test 7"
},
{
"code": null,
"e": 5961,
"s": 5870,
"text": "From the matrix_metrix function used for Table 1, we also got the values for this Table 2:"
},
{
"code": null,
"e": 6601,
"s": 5961,
"text": "In statistical analysis of binary classification, the F1 score (also F-score or F-measure) is a measure of a test’s accuracy. It considers both the precision p and the recall r of the test to compute the score: p is the number of correct positive results divided by the number of all positive results returned by the classifier, and r is the number of correct positive results divided by the number of all relevant samples (all samples that should have been identified as positive). The F1 score is the harmonic mean of the precision and recall, where an F1 score reaches its best value at 1 (perfect precision and recall) and worst at 0.8"
},
{
"code": null,
"e": 6722,
"s": 6601,
"text": "Beta is a parameter for score analysis, if we use Beta equal to 1, we have the harmonic mean; then we have the F1 score:"
},
{
"code": null,
"e": 6757,
"s": 6722,
"text": "We could take some Rules of Thumb:"
},
{
"code": null,
"e": 6848,
"s": 6757,
"text": "To give more weight to the Precision, we must select a Beta value between 0–1 0 < Beta < 1"
},
{
"code": null,
"e": 6941,
"s": 6848,
"text": "To give more weight to the Recall, we pick a Beta Value in the interval 1 < Beta < +infinite"
},
{
"code": null,
"e": 7056,
"s": 6941,
"text": "We can find an excellent and very complete article regarding the concepts and implementation of these instruments."
},
{
"code": null,
"e": 7095,
"s": 7056,
"text": "ROC — Receive operating characteristic"
},
{
"code": null,
"e": 7325,
"s": 7095,
"text": "It is a plot of the false positive rate (x-axis) versus the true positive rate (y-axis) for a number of different candidate threshold values between 0.0 and 1.0. Put another way, it plots the false alarm rate versus the hit rate."
},
{
"code": null,
"e": 7349,
"s": 7325,
"text": "Precision-recall curves"
},
{
"code": null,
"e": 7838,
"s": 7349,
"text": "A precision-recall curve is a plot of the precision (y-axis) and the recall (x-axis) for different thresholds, much like the ROC curve. A no-skill classifier is one that cannot discriminate between the classes and would predict a random class or a constant class in all cases. The no-skill line changes based on the distribution of the positive to negative classes. It is a horizontal line with the value of the ratio of positive cases in the dataset. For a balanced dataset, this is 0.5."
},
{
"code": null,
"e": 7861,
"s": 7838,
"text": "AUC — Area under curve"
},
{
"code": null,
"e": 7937,
"s": 7861,
"text": "The area under the curve (AUC) can be used as a summary of the model skill."
},
{
"code": null,
"e": 7994,
"s": 7937,
"text": "We based on the mentioned article for the following code"
},
{
"code": null,
"e": 8403,
"s": 7994,
"text": "#ROC Implementationfrom sklearn.metrics import roc_curvefrom sklearn.metrics import roc_auc_scorefrom matplotlib import pyplotfpr, tpr, thresholds = roc_curve(real_values, prob_values)auc = roc_auc_score(real_values, prob_values)print('AUC: %.3f' % auc)pyplot.plot(fpr, tpr, linestyle='--', label='Roc curve')pyplot.xlabel('False Positive Rate')pyplot.ylabel('True Positive Rate')pyplot.legend()pyplot.show()"
},
{
"code": null,
"e": 8687,
"s": 8403,
"text": "#Precision-recall implementationprecision, recall, thresholds = sklearn.metrics.precision_recall_curve(real_values,prob_values)pyplot.plot(recall, precision, linestyle='--', label='Precision versus Recall')pyplot.xlabel('Recall')pyplot.ylabel('Precision')pyplot.legend()pyplot.show()"
},
{
"code": null,
"e": 8752,
"s": 8687,
"text": "Here a simple and fast report about binary classification values"
},
{
"code": null,
"e": 8816,
"s": 8752,
"text": "And here a function for get many metrics directly from sklearn:"
},
{
"code": null,
"e": 9953,
"s": 8816,
"text": "def sk_metrix(real_values,pred_values,beta): Accuracy = round( sklearn.metrics.accuracy_score(real_values,pred_values) ,4) Precision = round( sklearn.metrics.precision_score(real_values,pred_values),4 ) Recall = round( sklearn.metrics.recall_score(real_values,pred_values),4 ) F1 = round ( sklearn.metrics.f1_score(real_values,pred_values),4) FBeta = round ( sklearn.metrics.fbeta_score(real_values,pred_values,beta) ,4) MCC = round ( sklearn.metrics.matthews_corrcoef(real_values,pred_values) ,4) Hamming = round ( sklearn.metrics.hamming_loss(real_values,pred_values) ,4) Jaccard = round ( sklearn.metrics.jaccard_score(real_values,pred_values) ,4) Prec_Avg = round ( sklearn.metrics.average_precision_score(real_values,pred_values) ,4) Accu_Avg = round ( sklearn.metrics.balanced_accuracy_score(real_values,pred_values) ,4) mat_met = pd.DataFrame({'Metric': ['Accuracy','Precision','Recall','F1','FBeta','MCC','Hamming','Jaccard','Precision_Avg','Accuracy_Avg'],'Value': [Accuracy,Precision,Recall,F1,FBeta,MCC,Hamming,Jaccard,Prec_Avg,Accu_Avg]}) return (mat_met)"
},
{
"code": null,
"e": 9980,
"s": 9953,
"text": "Calling sk_metrix function"
},
{
"code": null,
"e": 10029,
"s": 9980,
"text": "sk_met = sk_metrix(real_values,pred_values,beta)"
},
{
"code": null,
"e": 10292,
"s": 10029,
"text": "The number of metrics arising from the confusion matrix is quite large and may be challenging to cover to refine the use of each indicator according to the use case. The most common metrics may be F1-Score, ROC, precision-recall AUC, prevalence, and sensitivity."
},
{
"code": null,
"e": 10567,
"s": 10292,
"text": "This series of articles intended to create a table in which to quickly have a guide of the majority of metrics used for each case study; mastering their application exceeds our scope and also seems to be quite difficult.Remember that the table can be download in pdf format."
},
{
"code": null,
"e": 10689,
"s": 10567,
"text": "In the next article, we will see more classification metrics and specific metrics for recommendation systems in table 2.3"
},
{
"code": null,
"e": 10740,
"s": 10689,
"text": "[*] https://en.wikipedia.org/wiki/Confusion_matrix"
},
{
"code": null,
"e": 10757,
"s": 10740,
"text": "[1] type i error"
},
{
"code": null,
"e": 10775,
"s": 10757,
"text": "[2] type ii error"
},
{
"code": null,
"e": 10883,
"s": 10775,
"text": "[3] https://medium.com/mercadolibre-datablog/cost-sensitive-classification-in-fraud-prevention-263170d8fcfe"
}
]
|
Data preprocessing with Python Pandas | by Angelica Lo Duca | Towards Data Science | This tutorial explains how to preprocess data using the pandas library. Preprocessing is the process of doing a pre-analysis of data, in order to transform them into a standard and normalized format.
Preprocessing involves the following aspects:
missing values
data standardization
data normalization
data binning
In this tutorial we deal only with missing values.
You can download the source code of this tutorial as a Jupyter notebook from my Github Data Science Repository.
In this tutorial we will use the dataset related to Hepatitis, which can be downloaded from this link.
Firstly, import data using the pandas library and convert them into a dataframe. Through the head(10) method we print only the first 10 rows of the dataset
import pandas as pddf = pd.read_csv('hepatitis.csv')df.head(10)
We note that the dataset presents some problems. For example, the column email is not available for all the rows. In some cases it presents the NaN value, which means that the value is missing.
In order to check whether our dataset contains missing values, we can use the function isna(), which returns if an cell of the dataset if NaN or not. Then we can count how many missing values there are for each column.
df.isna().sum()
which gives the following output:
age 0sex 0steroid 1antivirals 0fatigue 1malaise 1anorexia 1liver_big 10liver_firm 11spleen_palpable 5spiders 5ascites 5varices 5bilirubin 6alk_phosphate 29sgot 4albumin 16protime 67histology 0class 0dtype: int64
Now we can count the percentage of missing values for each column, simply by dividing the previous result by the length of the dataset (len(df)) and multiplying per 100.
df.isna().sum()/len(df)*100
which gives the following output:
age 0.000000sex 0.000000steroid 0.645161antivirals 0.000000fatigue 0.645161malaise 0.645161anorexia 0.645161liver_big 6.451613liver_firm 7.096774spleen_palpable 3.225806spiders 3.225806ascites 3.225806varices 3.225806bilirubin 3.870968alk_phosphate 18.709677sgot 2.580645albumin 10.322581protime 43.225806histology 0.000000class 0.000000dtype: float64
When dealing with missing values, different alternatives can be applied:
check the source, for example by contacting the data source to correct the missing values
drop missing values
replace the missing value with a value
leave the missing value as it is.
Dropping missing values can be one of the following alternatives:
remove rows having missing values
remove the whole column containing missing values We can use the dropna() by specifying the axis to be considered. If we set axis = 0 we drop the entire row, if we set axis = 1 we drop the whole column. If we apply the function df.dropna(axis=0) 80 rows of the dataset remain. If we apply the function df.dropna(axis=1), only the columns age, sex, antivirals, histology and class remain. However, removed values are not applied to the original dataframe, but only to the result. We can use the argument inplace=True in order to store changes in the original dataframe df (df.dropna(axis=1,inplace=True)).
df.dropna(axis=1)
As an alternative, we can specify only the column on which the dropping operation must be applied. In the following example, only missing rows related to the column liver_big are considered. This can be achieved through the subset parameter, which permits to specify the subset of columns where to apply the dropping operation.
df.dropna(subset=['liver_big'],axis=0,inplace=True)
Now we can check whether there are still missing values for the column indirizzo.
df.isna().sum()/len(df)*100
Another alternative involves the dropping of columns where a certain percentage of not-null values is available. This can be achieved through the thresh parameter. In the following example we keep only columns where there are at least the 80% of not null values.
df.dropna(thresh=0.8*len(df),axis=1,inplace=True)
A good strategy when dealing with missing values involves their replacement with another value. Usually, the following strategies are adopted:
for numerical values replace the missing value with the average value of the column
for categorial values replace the missing value with the most frequent value of the column
use other functions
In order to replace missing values, three functions can be used: fillna(), replace() and interpolate(). The fillna() function replaces all the NaN values with the value passed as argument. For example, for numerical values, all the NaN values in the numeric columns could be replaced with the average value. In order to list the type of a column, we can use the attribute dtypes as follows:
df.dtypes
which gives the following output:
age int64sex objectsteroid objectantivirals boolfatigue objectmalaise objectanorexia objectliver_big objectliver_firm objectspleen_palpable objectspiders objectascites objectvarices objectbilirubin float64alk_phosphate float64sgot float64albumin float64histology boolclass objectdtype: object
Firstly, we select numeric columns.
import numpy as npnumeric = df.select_dtypes(include=np.number)numeric_columns = numeric.columns
Then, we fill the NaN values of numeric columns with the average value, given by the df.mean() function.
df[numeric_columns] = df[numeric_columns].fillna(df.mean())
Now, we can check whether the NaN values in numeric columns have been removed.
df.isna().sum()/len(df)*100
which gives the following output:
age 0.000000sex 0.000000steroid 0.689655antivirals 0.000000fatigue 0.000000malaise 0.000000anorexia 0.000000liver_big 0.000000liver_firm 0.689655spleen_palpable 0.689655spiders 0.689655ascites 0.689655varices 0.689655bilirubin 0.000000alk_phosphate 0.000000sgot 0.000000albumin 0.000000histology 0.000000class 0.000000dtype: float64
We note that in dtypes the categorial columns are described as objects. Thus we can select the object columns. We would like to consider only boolean columns. However the object type includes also the column class, which is a string. We select all the object columns, and then we remove from them the column class. Then we can convert the type of the result to bool.
boolean_columns = df.select_dtypes(include=np.object).columns.tolist()boolean_columns.remove('class')df[boolean_columns] = df[boolean_columns].astype('bool')
Now we can replace all the missing values for booleans with the most frequent value. We can use the mode() function to calculate the most frequent value. We use the fillna() function to replace missing values, but we could use also the replace(old_value,new_value) function.
df[boolean_columns].fillna(df.mode())
Now our dataset does not contain any missing value.
df.isna().sum()/len(df)*100
which gives the following output:
age 0.0sex 0.0steroid 0.0antivirals 0.0fatigue 0.0malaise 0.0anorexia 0.0liver_big 0.0liver_firm 0.0spleen_palpable 0.0spiders 0.0ascites 0.0varices 0.0bilirubin 0.0alk_phosphate 0.0sgot 0.0albumin 0.0histology 0.0class 0.0dtype: float64
Another solution to replace missing values involves the usage of other functions, such as linear interpolation. In this case, for example, we could replace a missing value over a column, with the interpolation between the previous and the next ones. This can be achieved through the use of the interpolate() function.
Since we have already managed all the missing values, we reload the dataset.
df = pd.read_csv('hepatitis.csv')df.isna().sum()/len(df)*100
We select only numeric columns.
numeric = df.select_dtypes(include=np.number)numeric_columns = numeric.columnsdf.head(10)
Now we can apply the interpolate() function to numeric columns, by setting also the limit direction to forward. This means that the linear interpolation is applied starting from the first row until the last one.
df[numeric_columns] = df[numeric_columns].interpolate(method ='linear', limit_direction ='forward')
For example, in line 6 the column bilirubin, which was NaN before the interpolation, now assumes the value 0.95, which is the interpolation between 0.90 (line 4) and 1.00 (line 6).
df.head(10)
In this tutorial we have seen one of the aspects of data preprocessing, which is dealing with missing data. Missing data can alter the data analysis process, thus they must be managed.
Three strategies can be used to deal with missing data:
drop missing data: this can be done when the dataset has a small number of missing datareplace missing data with other values, such as the mean or the most frequent valueleave missing data as they are.
drop missing data: this can be done when the dataset has a small number of missing data
replace missing data with other values, such as the mean or the most frequent value
leave missing data as they are.
If you would like to learn about the other aspects of data preprocessing, such as data standardization and data normalization, stay tuned...
If you wanted to be updated on my research and other activities, you can follow me on Twitter, Youtube and and Github. | [
{
"code": null,
"e": 372,
"s": 172,
"text": "This tutorial explains how to preprocess data using the pandas library. Preprocessing is the process of doing a pre-analysis of data, in order to transform them into a standard and normalized format."
},
{
"code": null,
"e": 418,
"s": 372,
"text": "Preprocessing involves the following aspects:"
},
{
"code": null,
"e": 433,
"s": 418,
"text": "missing values"
},
{
"code": null,
"e": 454,
"s": 433,
"text": "data standardization"
},
{
"code": null,
"e": 473,
"s": 454,
"text": "data normalization"
},
{
"code": null,
"e": 486,
"s": 473,
"text": "data binning"
},
{
"code": null,
"e": 537,
"s": 486,
"text": "In this tutorial we deal only with missing values."
},
{
"code": null,
"e": 649,
"s": 537,
"text": "You can download the source code of this tutorial as a Jupyter notebook from my Github Data Science Repository."
},
{
"code": null,
"e": 752,
"s": 649,
"text": "In this tutorial we will use the dataset related to Hepatitis, which can be downloaded from this link."
},
{
"code": null,
"e": 908,
"s": 752,
"text": "Firstly, import data using the pandas library and convert them into a dataframe. Through the head(10) method we print only the first 10 rows of the dataset"
},
{
"code": null,
"e": 972,
"s": 908,
"text": "import pandas as pddf = pd.read_csv('hepatitis.csv')df.head(10)"
},
{
"code": null,
"e": 1166,
"s": 972,
"text": "We note that the dataset presents some problems. For example, the column email is not available for all the rows. In some cases it presents the NaN value, which means that the value is missing."
},
{
"code": null,
"e": 1385,
"s": 1166,
"text": "In order to check whether our dataset contains missing values, we can use the function isna(), which returns if an cell of the dataset if NaN or not. Then we can count how many missing values there are for each column."
},
{
"code": null,
"e": 1401,
"s": 1385,
"text": "df.isna().sum()"
},
{
"code": null,
"e": 1435,
"s": 1401,
"text": "which gives the following output:"
},
{
"code": null,
"e": 1868,
"s": 1435,
"text": "age 0sex 0steroid 1antivirals 0fatigue 1malaise 1anorexia 1liver_big 10liver_firm 11spleen_palpable 5spiders 5ascites 5varices 5bilirubin 6alk_phosphate 29sgot 4albumin 16protime 67histology 0class 0dtype: int64"
},
{
"code": null,
"e": 2038,
"s": 1868,
"text": "Now we can count the percentage of missing values for each column, simply by dividing the previous result by the length of the dataset (len(df)) and multiplying per 100."
},
{
"code": null,
"e": 2066,
"s": 2038,
"text": "df.isna().sum()/len(df)*100"
},
{
"code": null,
"e": 2100,
"s": 2066,
"text": "which gives the following output:"
},
{
"code": null,
"e": 2675,
"s": 2100,
"text": "age 0.000000sex 0.000000steroid 0.645161antivirals 0.000000fatigue 0.645161malaise 0.645161anorexia 0.645161liver_big 6.451613liver_firm 7.096774spleen_palpable 3.225806spiders 3.225806ascites 3.225806varices 3.225806bilirubin 3.870968alk_phosphate 18.709677sgot 2.580645albumin 10.322581protime 43.225806histology 0.000000class 0.000000dtype: float64"
},
{
"code": null,
"e": 2748,
"s": 2675,
"text": "When dealing with missing values, different alternatives can be applied:"
},
{
"code": null,
"e": 2838,
"s": 2748,
"text": "check the source, for example by contacting the data source to correct the missing values"
},
{
"code": null,
"e": 2858,
"s": 2838,
"text": "drop missing values"
},
{
"code": null,
"e": 2897,
"s": 2858,
"text": "replace the missing value with a value"
},
{
"code": null,
"e": 2931,
"s": 2897,
"text": "leave the missing value as it is."
},
{
"code": null,
"e": 2997,
"s": 2931,
"text": "Dropping missing values can be one of the following alternatives:"
},
{
"code": null,
"e": 3031,
"s": 2997,
"text": "remove rows having missing values"
},
{
"code": null,
"e": 3636,
"s": 3031,
"text": "remove the whole column containing missing values We can use the dropna() by specifying the axis to be considered. If we set axis = 0 we drop the entire row, if we set axis = 1 we drop the whole column. If we apply the function df.dropna(axis=0) 80 rows of the dataset remain. If we apply the function df.dropna(axis=1), only the columns age, sex, antivirals, histology and class remain. However, removed values are not applied to the original dataframe, but only to the result. We can use the argument inplace=True in order to store changes in the original dataframe df (df.dropna(axis=1,inplace=True))."
},
{
"code": null,
"e": 3654,
"s": 3636,
"text": "df.dropna(axis=1)"
},
{
"code": null,
"e": 3982,
"s": 3654,
"text": "As an alternative, we can specify only the column on which the dropping operation must be applied. In the following example, only missing rows related to the column liver_big are considered. This can be achieved through the subset parameter, which permits to specify the subset of columns where to apply the dropping operation."
},
{
"code": null,
"e": 4034,
"s": 3982,
"text": "df.dropna(subset=['liver_big'],axis=0,inplace=True)"
},
{
"code": null,
"e": 4116,
"s": 4034,
"text": "Now we can check whether there are still missing values for the column indirizzo."
},
{
"code": null,
"e": 4144,
"s": 4116,
"text": "df.isna().sum()/len(df)*100"
},
{
"code": null,
"e": 4407,
"s": 4144,
"text": "Another alternative involves the dropping of columns where a certain percentage of not-null values is available. This can be achieved through the thresh parameter. In the following example we keep only columns where there are at least the 80% of not null values."
},
{
"code": null,
"e": 4457,
"s": 4407,
"text": "df.dropna(thresh=0.8*len(df),axis=1,inplace=True)"
},
{
"code": null,
"e": 4600,
"s": 4457,
"text": "A good strategy when dealing with missing values involves their replacement with another value. Usually, the following strategies are adopted:"
},
{
"code": null,
"e": 4684,
"s": 4600,
"text": "for numerical values replace the missing value with the average value of the column"
},
{
"code": null,
"e": 4775,
"s": 4684,
"text": "for categorial values replace the missing value with the most frequent value of the column"
},
{
"code": null,
"e": 4795,
"s": 4775,
"text": "use other functions"
},
{
"code": null,
"e": 5186,
"s": 4795,
"text": "In order to replace missing values, three functions can be used: fillna(), replace() and interpolate(). The fillna() function replaces all the NaN values with the value passed as argument. For example, for numerical values, all the NaN values in the numeric columns could be replaced with the average value. In order to list the type of a column, we can use the attribute dtypes as follows:"
},
{
"code": null,
"e": 5196,
"s": 5186,
"text": "df.dtypes"
},
{
"code": null,
"e": 5230,
"s": 5196,
"text": "which gives the following output:"
},
{
"code": null,
"e": 5738,
"s": 5230,
"text": "age int64sex objectsteroid objectantivirals boolfatigue objectmalaise objectanorexia objectliver_big objectliver_firm objectspleen_palpable objectspiders objectascites objectvarices objectbilirubin float64alk_phosphate float64sgot float64albumin float64histology boolclass objectdtype: object"
},
{
"code": null,
"e": 5774,
"s": 5738,
"text": "Firstly, we select numeric columns."
},
{
"code": null,
"e": 5871,
"s": 5774,
"text": "import numpy as npnumeric = df.select_dtypes(include=np.number)numeric_columns = numeric.columns"
},
{
"code": null,
"e": 5976,
"s": 5871,
"text": "Then, we fill the NaN values of numeric columns with the average value, given by the df.mean() function."
},
{
"code": null,
"e": 6036,
"s": 5976,
"text": "df[numeric_columns] = df[numeric_columns].fillna(df.mean())"
},
{
"code": null,
"e": 6115,
"s": 6036,
"text": "Now, we can check whether the NaN values in numeric columns have been removed."
},
{
"code": null,
"e": 6143,
"s": 6115,
"text": "df.isna().sum()/len(df)*100"
},
{
"code": null,
"e": 6177,
"s": 6143,
"text": "which gives the following output:"
},
{
"code": null,
"e": 6705,
"s": 6177,
"text": "age 0.000000sex 0.000000steroid 0.689655antivirals 0.000000fatigue 0.000000malaise 0.000000anorexia 0.000000liver_big 0.000000liver_firm 0.689655spleen_palpable 0.689655spiders 0.689655ascites 0.689655varices 0.689655bilirubin 0.000000alk_phosphate 0.000000sgot 0.000000albumin 0.000000histology 0.000000class 0.000000dtype: float64"
},
{
"code": null,
"e": 7072,
"s": 6705,
"text": "We note that in dtypes the categorial columns are described as objects. Thus we can select the object columns. We would like to consider only boolean columns. However the object type includes also the column class, which is a string. We select all the object columns, and then we remove from them the column class. Then we can convert the type of the result to bool."
},
{
"code": null,
"e": 7230,
"s": 7072,
"text": "boolean_columns = df.select_dtypes(include=np.object).columns.tolist()boolean_columns.remove('class')df[boolean_columns] = df[boolean_columns].astype('bool')"
},
{
"code": null,
"e": 7505,
"s": 7230,
"text": "Now we can replace all the missing values for booleans with the most frequent value. We can use the mode() function to calculate the most frequent value. We use the fillna() function to replace missing values, but we could use also the replace(old_value,new_value) function."
},
{
"code": null,
"e": 7543,
"s": 7505,
"text": "df[boolean_columns].fillna(df.mode())"
},
{
"code": null,
"e": 7595,
"s": 7543,
"text": "Now our dataset does not contain any missing value."
},
{
"code": null,
"e": 7623,
"s": 7595,
"text": "df.isna().sum()/len(df)*100"
},
{
"code": null,
"e": 7657,
"s": 7623,
"text": "which gives the following output:"
},
{
"code": null,
"e": 8090,
"s": 7657,
"text": "age 0.0sex 0.0steroid 0.0antivirals 0.0fatigue 0.0malaise 0.0anorexia 0.0liver_big 0.0liver_firm 0.0spleen_palpable 0.0spiders 0.0ascites 0.0varices 0.0bilirubin 0.0alk_phosphate 0.0sgot 0.0albumin 0.0histology 0.0class 0.0dtype: float64"
},
{
"code": null,
"e": 8408,
"s": 8090,
"text": "Another solution to replace missing values involves the usage of other functions, such as linear interpolation. In this case, for example, we could replace a missing value over a column, with the interpolation between the previous and the next ones. This can be achieved through the use of the interpolate() function."
},
{
"code": null,
"e": 8485,
"s": 8408,
"text": "Since we have already managed all the missing values, we reload the dataset."
},
{
"code": null,
"e": 8546,
"s": 8485,
"text": "df = pd.read_csv('hepatitis.csv')df.isna().sum()/len(df)*100"
},
{
"code": null,
"e": 8578,
"s": 8546,
"text": "We select only numeric columns."
},
{
"code": null,
"e": 8668,
"s": 8578,
"text": "numeric = df.select_dtypes(include=np.number)numeric_columns = numeric.columnsdf.head(10)"
},
{
"code": null,
"e": 8880,
"s": 8668,
"text": "Now we can apply the interpolate() function to numeric columns, by setting also the limit direction to forward. This means that the linear interpolation is applied starting from the first row until the last one."
},
{
"code": null,
"e": 8980,
"s": 8880,
"text": "df[numeric_columns] = df[numeric_columns].interpolate(method ='linear', limit_direction ='forward')"
},
{
"code": null,
"e": 9161,
"s": 8980,
"text": "For example, in line 6 the column bilirubin, which was NaN before the interpolation, now assumes the value 0.95, which is the interpolation between 0.90 (line 4) and 1.00 (line 6)."
},
{
"code": null,
"e": 9173,
"s": 9161,
"text": "df.head(10)"
},
{
"code": null,
"e": 9358,
"s": 9173,
"text": "In this tutorial we have seen one of the aspects of data preprocessing, which is dealing with missing data. Missing data can alter the data analysis process, thus they must be managed."
},
{
"code": null,
"e": 9414,
"s": 9358,
"text": "Three strategies can be used to deal with missing data:"
},
{
"code": null,
"e": 9616,
"s": 9414,
"text": "drop missing data: this can be done when the dataset has a small number of missing datareplace missing data with other values, such as the mean or the most frequent valueleave missing data as they are."
},
{
"code": null,
"e": 9704,
"s": 9616,
"text": "drop missing data: this can be done when the dataset has a small number of missing data"
},
{
"code": null,
"e": 9788,
"s": 9704,
"text": "replace missing data with other values, such as the mean or the most frequent value"
},
{
"code": null,
"e": 9820,
"s": 9788,
"text": "leave missing data as they are."
},
{
"code": null,
"e": 9961,
"s": 9820,
"text": "If you would like to learn about the other aspects of data preprocessing, such as data standardization and data normalization, stay tuned..."
}
]
|
How to input letters in capital letters in an edit box in Selenium with python? | We can input letters in capital letters in an edit box in Selenium with the
help of Action Chains class. These classes are generally used for automating
interactions like context menu click, mouse button actions, key press and mouse
movements.
These types of actions are mainly common in complex scenarios like drag and drop
and hovering over an element on the page. The methods of the Action Chains class
are utilized by advanced scripts. We can manipulate DOM with the help of Action
Chains in Selenium.
The action chain object implements the ActionChains in the form of a queue and
then executes the perform() method. On calling the method perform(), all the
actions on action chains will be performed.
The method of creating an Action Chain object is listed below −
First we need to import the Action Chain class and then the driver will be
passed as an argument to it.
First we need to import the Action Chain class and then the driver will be
passed as an argument to it.
Now all the operations of action chains can be done with the help of this
object.
Now all the operations of action chains can be done with the help of this
object.
Syntax for creating an object of Action Chains −
from selenium import webdriver
# import Action chains
from selenium.webdriver import ActionChains
# create webdriver object
driver = webdriver.Firefox()
# create action chain object
action = ActionChains(driver)
After creating an object of Action Chains, we can perform numerous operations
one by one like a chain which is queued.
In order to enter letters in upper case in the edit box, we need to first move to the
edit box, then perform click() action. Then press SHIFT and enter the letters using
send_keys() method. Finally use perform() to execute all these queued operations.
#element
source = driver.find_element_by_id("name")
#action chain object
action = ActionChains(driver)
# move the mouse to the element
action.move_to_element(source)
# perform click operation on the edit box
action.click()
# perform clicking on SHIFT button
action.key_down(Keys.SHIFT)
# input letters in the edit box
action.send_keys('tutorialspoint')
# perform the queued operation
action.perform()
Code Implementation for inputting letters in upper case.
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# identifying the source element
source= driver.find_element_by_xpath("//input[@name='search']");
# action chain object creation
action = ActionChains(driver)
# move the mouse to the element
action.move_to_element(source)
# perform click operation on the edit box
action.click()
# perform clicking on SHIFT button
action.key_down(Keys.SHIFT)
# input letters in the edit box
action.send_keys('tutorialspoint')
# perform the queued operation
action.perform()
#to close the browser
driver.close() | [
{
"code": null,
"e": 1306,
"s": 1062,
"text": "We can input letters in capital letters in an edit box in Selenium with the\nhelp of Action Chains class. These classes are generally used for automating\ninteractions like context menu click, mouse button actions, key press and mouse\nmovements."
},
{
"code": null,
"e": 1568,
"s": 1306,
"text": "These types of actions are mainly common in complex scenarios like drag and drop\nand hovering over an element on the page. The methods of the Action Chains class\nare utilized by advanced scripts. We can manipulate DOM with the help of Action\nChains in Selenium."
},
{
"code": null,
"e": 1768,
"s": 1568,
"text": "The action chain object implements the ActionChains in the form of a queue and\nthen executes the perform() method. On calling the method perform(), all the\nactions on action chains will be performed."
},
{
"code": null,
"e": 1832,
"s": 1768,
"text": "The method of creating an Action Chain object is listed below −"
},
{
"code": null,
"e": 1936,
"s": 1832,
"text": "First we need to import the Action Chain class and then the driver will be\npassed as an argument to it."
},
{
"code": null,
"e": 2040,
"s": 1936,
"text": "First we need to import the Action Chain class and then the driver will be\npassed as an argument to it."
},
{
"code": null,
"e": 2122,
"s": 2040,
"text": "Now all the operations of action chains can be done with the help of this\nobject."
},
{
"code": null,
"e": 2204,
"s": 2122,
"text": "Now all the operations of action chains can be done with the help of this\nobject."
},
{
"code": null,
"e": 2253,
"s": 2204,
"text": "Syntax for creating an object of Action Chains −"
},
{
"code": null,
"e": 2284,
"s": 2253,
"text": "from selenium import webdriver"
},
{
"code": null,
"e": 2465,
"s": 2284,
"text": "# import Action chains\nfrom selenium.webdriver import ActionChains\n# create webdriver object\ndriver = webdriver.Firefox()\n# create action chain object\naction = ActionChains(driver)"
},
{
"code": null,
"e": 2584,
"s": 2465,
"text": "After creating an object of Action Chains, we can perform numerous operations\none by one like a chain which is queued."
},
{
"code": null,
"e": 2836,
"s": 2584,
"text": "In order to enter letters in upper case in the edit box, we need to first move to the\nedit box, then perform click() action. Then press SHIFT and enter the letters using\nsend_keys() method. Finally use perform() to execute all these queued operations."
},
{
"code": null,
"e": 3237,
"s": 2836,
"text": "#element\nsource = driver.find_element_by_id(\"name\")\n#action chain object\naction = ActionChains(driver)\n# move the mouse to the element\naction.move_to_element(source)\n# perform click operation on the edit box\naction.click()\n# perform clicking on SHIFT button\naction.key_down(Keys.SHIFT)\n# input letters in the edit box\naction.send_keys('tutorialspoint')\n# perform the queued operation\naction.perform()"
},
{
"code": null,
"e": 3294,
"s": 3237,
"text": "Code Implementation for inputting letters in upper case."
},
{
"code": null,
"e": 4294,
"s": 3294,
"text": "from selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.keys import Keys\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then\n#invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#to refresh the browser\ndriver.refresh()\n# identifying the source element\nsource= driver.find_element_by_xpath(\"//input[@name='search']\");\n# action chain object creation\naction = ActionChains(driver)\n# move the mouse to the element\naction.move_to_element(source)\n# perform click operation on the edit box\naction.click()\n# perform clicking on SHIFT button\naction.key_down(Keys.SHIFT)\n# input letters in the edit box\naction.send_keys('tutorialspoint')\n# perform the queued operation\naction.perform()\n#to close the browser\ndriver.close()"
}
]
|
Imputer Class in Python from Scratch | by Lewi Uberg | Towards Data Science | 1
2
3
4
5
6
7
8
9
10
Powered by Play.ht
Create audio with Play.ht
Create Audio Narrations with Play.ht
The main focus of this report on laboratory work is demonstrating the understanding of object-oriented programming principles and how to apply them.
Every step of the implementation is explained; it is therefore assumed that additional code documentation is redundant. However, to demonstrate an understanding of the documentation conventions described in PEP 257, examples are included in the class Imputer.
Since the code is made for demonstration purposes and not intended for reuse, error handling is also reduced to two examples of raising errors in the class Imputer.
The Imputer will be implementing the strategy pattern for its choices of imputation, which enables the algorithm used to vary independently at runtime. Thereby applying Design Principle 1: Identify the aspects of your application that vary and separate them from what stays the same.
Importing a metaclass for defining abstract base classes, and a decorator indicating abstract methods from the abc module.
from abc import ABCMeta, abstractmethod
Importing deepcopy to enable making unique copies of compound objects.
from copy import deepcopy
Firstly the strategy interface is defined.
The ImputationStrategy class is the superclass all composite classes inherit from and defines an interface with a default set of behaviours equal to all concrete strategies. Thereby applying Design Principle 2: Program to an interface, not an implementation, as well as Design Principle 3: Favor composition over inheritance.
class ImputationStrategy(metaclass=ABCMeta): @abstractmethod def _imputation(self, my_list: list, missing_values: str) -> float: """Must be implemented in order to instanciate"""
Secondly, defining the concrete strategies. A family of algorithms is encapsulated in separate classes and made interchangeable through having the same interface.
Each family member can define new behaviors; however, they inherit all the superclass’ behaviors, which can be replaced by overriding them. Defining abstractmethods in the superclass demands any subclass to implement the specific behavior, thereby enforcing a common default interface.
Since these classes only have one single responsibility Design Principle 6: A class should have only one reason to change. is applied.
Impute by meanMean is the average sum of a group of numbers.
class ImputeByMean(ImputationStrategy): def _imputation(self, my_list: list, missing_values: str) -> float: temp_sum = 0 count = 0 for num in my_list: if num != missing_values: temp_sum += num count += 1 mean = (temp_sum/count) return round(mean, 2)
Impute by medianMedian is the middle of a sorted list of numbers.
class ImputeByMedian(ImputationStrategy): def _imputation(self, my_list: list, missing_values: str) -> float: temp_list = [] for num in my_list: if num != missing_values: temp_list.append(num) temp_list.sort() temp_len = len(temp_list) if temp_len % 2 == 0: median1 = temp_list[temp_len//2] median2 = temp_list[temp_len//2 - 1] median = (median1 + median2)/2 else: median = temp_list[temp_len//2] return round(median, 2)
Impute by modeMode is the most frequent value.
Note: Mode is included here for context but implemented below for demonstration purposes.
class ImputeByMode(ImputationStrategy): def _imputation(self, my_list: list, missing_values: str) -> float: frequency = {} for item in my_list: if item != missing_values: if (item in frequency): frequency[item] += 1 else: frequency[item] = 1 mode = max(frequency, key=frequency.get) return round(mode, 2)
By instantiating the class and referencing the object instance, only one object needs creation. Thereby applying Design Principle 5: Depend upon abstractions. Do not depend upon concrete classes.
If instead directly calling the class, new objects are getting defined on each occasion.
mean = ImputeByMean()median = ImputeByMedian()# mode = ImputeByMode()
The Imputer, which is the strategy patterns context, contains a reference to the instantiations of the concrete strategy objects.
The imputer uses the strategy interface to call the algorithm defined by a concrete strategy; each concrete strategy then implements an algorithm.Since this is the only connection between the imputer and the strategy interface Design Principle 4: Strive for loosely coupled designs between objects that interact, is applied.
When an operation is required, the concrete strategy object runs the algorithm without the imputer being aware of the strategy implementation.
If necessary, additional imputer objects can be instantiated to pass data from the imputer object to the strategy interface, thereby eliminating it as a singleton candidate.
class Imputer: """ The base class for imputer objects. Enables the user to specify which imputation method, and which "cells" to perform imputation on in a specific 2-dimensional list. A unique copy is made of the specified 2-dimensional list before transforming and returning it to the user. """ def __init__(self, strategy="mean", axis=0) -> None: """ Defining instanse attributes on instansiation. Args: strategy (str, optional): A concrete strategy. Defaults to "mean". axis (int, optional): Column=0 or Row=1. Defaults to 0. """ # Reference to the concrete strategy object being used. self._strategy = strategy # Calling internal method. self.__strategy_prosessor() # Reference to the axis orientation being used. self._axis = axis # Reference to the keyword for missing values. # Defined as public, as per convention. self.missing_values = "nan" # Defines which column or row to start. self._from_item = None # Defines which column or row to end. self._to_item = None def __strategy_prosessor(self) -> None: """ Internal method validating that selected strategy is allowed. If so, selecting its imputation method. Raises: AssertionError: If the selected strategy is not allowed. """ allowed_strategies = ["mean", "median", "mode"] if self._strategy == allowed_strategies[0]: self._strategy = mean._imputation elif self._strategy == allowed_strategies[1]: self._strategy = median._imputation elif self._strategy == allowed_strategies[2]: self._strategy = mode._imputation else: assert self._strategy in allowed_strategies, ( f"Can only use these strategies: {allowed_strategies}, " f"got strategy = {self._strategy}") def __transpose(self, my_matrix: list) -> list: """ Transposes 2-dimensional list. Args: my_matrix (list): 2-dimensional list. Returns: list: 2-dimensional list transposed. """ trans_matrix = [] temp_matrix = [[my_matrix[j][i] for j in range(len(my_matrix))] for i in range(len(my_matrix[0]))] for row in temp_matrix: trans_matrix.append(row) return trans_matrix def fit(self, my_matrix: list, from_item: int, to_item: int) -> object: """ Passes in the 2-dimensional list for imputation, and sets from which column to start with, and end by. Args: my_matrix (list): 2-dimensional list. from_item (int): The column to start with. to_item (int): The column to end by. Raises: ValueError: If axis is not equal to the defined options. Returns: object: The same imputer object that calls the method. """ self._to_item = to_item if self._axis == 0: self._array = my_matrix self._from_item = from_item - 1 elif self._axis == 1: self._array = self.__transpose(my_matrix) self._from_item = from_item else: raise ValueError( f"Can only use integer value 0 or 1: " f"got axis = {self._axis}") return self def __axis_lister(self, matrix: list, col: int) -> list: """ Generates a list for all values in a 2-dimensional list column. Args: matrix (list): 2-dimensional list. col (int): selected column to generat list from. Returns: list: All values in a 2-dimensional list column. """ temp_list = [] for row in range(len(matrix)): temp_list.append((matrix[row][col])) return temp_list def _imputation(self, my_list: list, missing_values: str) -> float: """ Passing a list to the concrete strategy object with the desired imputation algorithm. For this reason, the method cannot be private, but have to be public or protected. Args: my_list (list): The list to be calculated by the algorithm. missing_values (str): The keyword for the missing values. Returns: float: The calculated value to swap with the missing value keyword """ return_value = self._strategy(my_list, missing_values) return return_value def transform(self) -> list: """ Inserts the imputed column value in each column-row ("cell") of the 2-dimensional list where the missing value keyword exists. Returns: list: A unique copy of the selected 2-dimensional list after it has been imputed. """ return_matrix = deepcopy(self._array) for col in range(self._from_item, self._to_item): imputed_value = self._imputation( self.__axis_lister(self._array, col), self.missing_values) for row in range(len(return_matrix)): if return_matrix[row][col] == self.missing_values: return_matrix[row][col] = imputed_value if self._axis == 0: pass elif self._axis == 1: return_matrix = self.__transpose(return_matrix) return return_matrix def __str__(self) -> str: """ Provides users with an easy to read representation of the class. Returns: str: The class name. """ return f"{self.__class__.__name__}" def __repr__(self) -> str: """ Provides developers with unambigous information of the class. Returns: str: The class name and the state of instance variables. """ return "{self.__class__.__name__}" \ "(Strategy: {self._strategy}, " \ "Axis:{self._axis}, " \ "Missing value: {self.missing_values}, " \ "From:{self._from_item}, " \ "To:{self._to_item})".format(self=self)
A class with a method for transposing a 2-dimensional list and a method to print this list format with tabs based on word length is made an instantiated.
class Matrix: def transpose(self, my_matrix): trans_matrix = [] temp_matrix = [[my_matrix[j][i] for j in range(len(my_matrix))] for i in range(len(my_matrix[0]))] for row in temp_matrix: trans_matrix.append(row) return trans_matrix def printer(self, my_matrix, title=None, axis=0): my_matrix = deepcopy(my_matrix) if title is not None: if axis == 0: my_matrix.insert(0, title) elif axis == 1: for i in range(len(my_matrix)): my_matrix[i].insert(0, title[i]) str_matrix = [[str(entity) for entity in row] for row in my_matrix] max_len_col_str = [max(map(len, col)) for col in zip(*str_matrix)] form = "\t".join("{{:{}}}".format(x) for x in max_len_col_str) matrix_row = [form.format(*row) for row in str_matrix] return_matrix = "\n".join(matrix_row) print(return_matrix)matrix = Matrix()
A mock dataset for demonstrations is provided.
dataset = list([["Country", "Age", "Salary", "Children", "Cars"], ["Swe", 38.0, 47200.0, 1, 1], ["Den", 27.0, 48000.0, 0, 6], ["Nor", 30.0, 54000.0, 2, "nan"], ["Den", 38.0, 61000.0, "nan", 1], ["Nor", 40.0, "nan", 2, 1], ["Swe", 35.0, 58000.0, 1, 1], ["Den", "nan", 52000.0, 0, "nan"], ["Swe", 48.0, 67900.0, 2, 1], ["Nor", 50.0, 88300.0, 6, 2], ["Swe", 37.0, 67900.0, "nan", 2]])
Some data preprocessing is simulated. First, the title row is removed from the list and inserted into its own list for later use.
dataset_title_row = dataset.pop(0)display(dataset_title_row)display(dataset)['Country', 'Age', 'Salary', 'Children', 'Cars'][['Swe', 38.0, 47200.0, 1, 1], ['Den', 27.0, 48000.0, 0, 6], ['Nor', 30.0, 54000.0, 2, 'nan'], ['Den', 38.0, 61000.0, 'nan', 1], ['Nor', 40.0, 'nan', 2, 1], ['Swe', 35.0, 58000.0, 1, 1], ['Den', 'nan', 52000.0, 0, 'nan'], ['Swe', 48.0, 67900.0, 2, 1], ['Nor', 50.0, 88300.0, 6, 2], ['Swe', 37.0, 67900.0, 'nan', 2]]
Defining a transposed version of the dataset for later demonstrations on the axis feature.
dataset_trans = matrix.transpose(dataset)
After the simulated preprocessing is over, the matrix objects printer method is demonstrated; passing in the desired dataset as well as the optional title row.
matrix.printer(dataset, dataset_title_row)Country Age Salary Children CarsSwe 38.0 47200.0 1 1 Den 27.0 48000.0 0 6 Nor 30.0 54000.0 2 nan Den 38.0 61000.0 nan 1 Nor 40.0 nan 2 1 Swe 35.0 58000.0 1 1 Den nan 52000.0 0 nan Swe 48.0 67900.0 2 1 Nor 50.0 88300.0 6 2 Swe 37.0 67900.0 nan 2
Now, performing the same procedure for the transposed version. However, it is necessary to set the axis property to 1 to represent a transposed matrix, ensuring the proper output format.
Note: For the intended output to be displayed correctly for a transposed matrix, the web browser running Jupyter has to have the default zoom level.
matrix.printer(dataset_trans, dataset_title_row, 1)Country Swe Den Nor Den Nor Swe Den Swe Nor Swe Age 38.0 27.0 30.0 38.0 40.0 35.0 nan 48.0 50.0 37.0 Salary 47200.0 48000.0 54000.0 61000.0 nan 58000.0 52000.0 67900.0 88300.0 67900.0Children 1 0 2 nan 2 1 0 2 6 nan Cars 1 6 nan 1 1 1 nan 1 2 2
First, the default imputer is instantiated, imputation by mean, and column.
mean_imputer = Imputer()
Demonstrating the __str__ and __repr__ methods defined in the Imputer class.
print(mean_imputer) # <- __str__mean_imputer # <- __repr__ImputerImputer(Strategy: <bound method ImputeByMean._imputation of <__main__.ImputeByMean object at 0x10f3dbf50>>, Axis:0, Missing value: nan, From:None, To:None)
Defining which dataset the imputer should use as a source, and from which column to start and end.
mean_imputer = mean_imputer.fit(dataset, 2, 5)
The imputer now copies the 2-dimensional list, calculates all selected column or row value depending on the axis settings using the desired strategy object, then returns the result to the user.
dataset_by_mean = mean_imputer.transform()
Displaying the result of the imputation.
matrix.printer(dataset_by_mean, dataset_title_row)Country Age Salary Children CarsSwe 38.0 47200.0 1 1 Den 27.0 48000.0 0 6 Nor 30.0 54000.0 2 1.88Den 38.0 61000.0 1.75 1 Nor 40.0 60477.78 2 1 Swe 35.0 58000.0 1 1 Den 38.11 52000.0 0 1.88Swe 48.0 67900.0 2 1 Nor 50.0 88300.0 6 2 Swe 37.0 67900.0 1.75 2
Now demonstrating the transposed version of Imputed by Mean, in addition to the from and to settings. In this example, the last row is left out.
First, the mean imputer is instantiated, imputation by mean, and row. Then, performing the same steps as shown in Imputed by Mean.
mean_imputer_trans = Imputer("mean", 1)mean_imputer_trans = mean_imputer_trans.fit(dataset_trans, 1, 4)dataset_by_mean_trans = mean_imputer_trans.transform()matrix.printer(dataset_by_mean_trans, dataset_title_row, 1)Country Swe Den Nor Den Nor Swe Den Swe Nor Swe Age 38.0 27.0 30.0 38.0 40.0 35.0 38.11 48.0 50.0 37.0 Salary 47200.0 48000.0 54000.0 61000.0 60477.78 58000.0 52000.0 67900.0 88300.0 67900.0Children 1 0 2 1.75 2 1 0 2 6 1.75 Cars 1 6 nan 1 1 1 nan 1 2 2
First, the median imputer is instantiated, imputation by median, and column. Then, performing the same steps as shown in Imputed by Mean.
median_imputer = Imputer("median")median_imputer = median_imputer.fit(dataset, 2, 5)dataset_by_median = median_imputer.transform()matrix.printer(dataset_by_median, dataset_title_row)Country Age Salary Children CarsSwe 38.0 47200.0 1 1 Den 27.0 48000.0 0 6 Nor 30.0 54000.0 2 1.0 Den 38.0 61000.0 1.5 1 Nor 40.0 58000.0 2 1 Swe 35.0 58000.0 1 1 Den 38.0 52000.0 0 1.0 Swe 48.0 67900.0 2 1 Nor 50.0 88300.0 6 2 Swe 37.0 67900.0 1.5 2
A new concrete strategy class is defined to demonstrate that the imputer is extendable without affecting any of the existing strategies. The only code updated needed to enable the new strategy is adding as an option in the allowed_strategies list in the Imputer __strategy_prosessor method, as well as adding it as an option in the if statement in the same method.
class ImputeByMode(ImputationStrategy): def _imputation(self, my_list: list, missing_values: str) -> float: frequency = {} for item in my_list: if item != missing_values: if (item in frequency): frequency[item] += 1 else: frequency[item] = 1 mode = max(frequency, key=frequency.get) return round(mode, 2)
First, the mode imputer is instantiated, imputation by mode, and column. Then, performing the same steps as shown in Imputed by Mean.
mode = ImputeByMode()mode_imputer = Imputer("mode")mode_imputer = mode_imputer.fit(dataset, 2, 5)dataset_by_mode = mode_imputer.transform()matrix.printer(dataset_by_mode, dataset_title_row)Country Age Salary Children CarsSwe 38.0 47200.0 1 1 Den 27.0 48000.0 0 6 Nor 30.0 54000.0 2 1 Den 38.0 61000.0 2 1 Nor 40.0 67900.0 2 1 Swe 35.0 58000.0 1 1 Den 38.0 52000.0 0 1 Swe 48.0 67900.0 2 1 Nor 50.0 88300.0 6 2 Swe 37.0 67900.0 2 2
Demonstration of generating a UML Class diagram using PlantUML.
from zlib import compressimport base64import stringimport requests# This was taken from plantuml libraryplantuml_alphabet = string.digits + \ string.ascii_uppercase + string.ascii_lowercase + '-_'base64_alphabet = string.ascii_uppercase + \ string.ascii_lowercase + string.digits + '+/'b64_to_plantuml = bytes.maketrans(base64_alphabet.encode( 'utf-8'), plantuml_alphabet.encode('utf-8'))def deflate_and_encode(plantuml_text): """ zlib compress the plantuml text and encode it for the plantuml server. """ zlibbed_str = compress(plantuml_text.encode('utf-8')) compressed_string = zlibbed_str[2:-4] return base64.b64encode(compressed_string).translate(b64_to_plantuml).\ decode('utf-8')def render_uml(uml, fmt="svg"): uri = "http://www.plantuml.com/plantuml/{}/{}".format( fmt, deflate_and_encode(uml)) r = requests.get(uri) if r.ok: return r.contentdiagram = """@startumlskinparam class { BackgroundColor White ArrowColor Gray BorderColor Black}skinparam stereotypeCBackgroundColor Grayhide circletitle Imputer Strategy Patternclass Clienthide Client methodshide Client attributesclass ImputerImputer : +fit()Imputer : +transform()Imputer : #imputation()Imputer : -strategy_prosessor()Imputer : -transpose()Imputer : +missing_values : str = "nan"Imputer : #strategy : str = "mean"Imputer : #axis = int = 0Imputer : #from_item : intImputer : #to_item : intnote Top: Contextclass ImputerStrategy <<Interface>>ImputerStrategy : #imputation()class ImputByMeanImputByMean : #imputation()note Bottom: Concrete Strategy 1class ImputByMedianImputByMedian : #imputation()note Bottom: Concrete Strategy 2class ImputByModeImputByMode : #imputation()note Bottom: Concrete Strategy 3Imputer <-- Client : RequestsImputer *- ImputerStrategy : StrategyImputerStrategy <|-- ImputByMean : ExtendsImputerStrategy <|-- ImputByMedian : ExtendsImputerStrategy <|-- ImputByMode : Extends@enduml"""from IPython.display import SVGSVG(render_uml(diagram))
Exporting to png file format.
from IPython.display import ImageImage(render_uml(diagram, "png"))
While I would rather use sklearn for imputation, making an imputer from scratch has taught me a lot about object-oriented programming.
Lewi Uberg is a final year student in applied data science in Norway, with a background as a geek of all trades, an IT manager, and a CAD engineer. Feel free to follow him on medium or visit his website. | [
{
"code": null,
"e": 48,
"s": 46,
"text": "1"
},
{
"code": null,
"e": 50,
"s": 48,
"text": "2"
},
{
"code": null,
"e": 52,
"s": 50,
"text": "3"
},
{
"code": null,
"e": 54,
"s": 52,
"text": "4"
},
{
"code": null,
"e": 56,
"s": 54,
"text": "5"
},
{
"code": null,
"e": 58,
"s": 56,
"text": "6"
},
{
"code": null,
"e": 60,
"s": 58,
"text": "7"
},
{
"code": null,
"e": 62,
"s": 60,
"text": "8"
},
{
"code": null,
"e": 64,
"s": 62,
"text": "9"
},
{
"code": null,
"e": 67,
"s": 64,
"text": "10"
},
{
"code": null,
"e": 86,
"s": 67,
"text": "Powered by Play.ht"
},
{
"code": null,
"e": 112,
"s": 86,
"text": "Create audio with Play.ht"
},
{
"code": null,
"e": 149,
"s": 112,
"text": "Create Audio Narrations with Play.ht"
},
{
"code": null,
"e": 298,
"s": 149,
"text": "The main focus of this report on laboratory work is demonstrating the understanding of object-oriented programming principles and how to apply them."
},
{
"code": null,
"e": 558,
"s": 298,
"text": "Every step of the implementation is explained; it is therefore assumed that additional code documentation is redundant. However, to demonstrate an understanding of the documentation conventions described in PEP 257, examples are included in the class Imputer."
},
{
"code": null,
"e": 723,
"s": 558,
"text": "Since the code is made for demonstration purposes and not intended for reuse, error handling is also reduced to two examples of raising errors in the class Imputer."
},
{
"code": null,
"e": 1007,
"s": 723,
"text": "The Imputer will be implementing the strategy pattern for its choices of imputation, which enables the algorithm used to vary independently at runtime. Thereby applying Design Principle 1: Identify the aspects of your application that vary and separate them from what stays the same."
},
{
"code": null,
"e": 1130,
"s": 1007,
"text": "Importing a metaclass for defining abstract base classes, and a decorator indicating abstract methods from the abc module."
},
{
"code": null,
"e": 1170,
"s": 1130,
"text": "from abc import ABCMeta, abstractmethod"
},
{
"code": null,
"e": 1241,
"s": 1170,
"text": "Importing deepcopy to enable making unique copies of compound objects."
},
{
"code": null,
"e": 1267,
"s": 1241,
"text": "from copy import deepcopy"
},
{
"code": null,
"e": 1310,
"s": 1267,
"text": "Firstly the strategy interface is defined."
},
{
"code": null,
"e": 1636,
"s": 1310,
"text": "The ImputationStrategy class is the superclass all composite classes inherit from and defines an interface with a default set of behaviours equal to all concrete strategies. Thereby applying Design Principle 2: Program to an interface, not an implementation, as well as Design Principle 3: Favor composition over inheritance."
},
{
"code": null,
"e": 1828,
"s": 1636,
"text": "class ImputationStrategy(metaclass=ABCMeta): @abstractmethod def _imputation(self, my_list: list, missing_values: str) -> float: \"\"\"Must be implemented in order to instanciate\"\"\""
},
{
"code": null,
"e": 1991,
"s": 1828,
"text": "Secondly, defining the concrete strategies. A family of algorithms is encapsulated in separate classes and made interchangeable through having the same interface."
},
{
"code": null,
"e": 2277,
"s": 1991,
"text": "Each family member can define new behaviors; however, they inherit all the superclass’ behaviors, which can be replaced by overriding them. Defining abstractmethods in the superclass demands any subclass to implement the specific behavior, thereby enforcing a common default interface."
},
{
"code": null,
"e": 2412,
"s": 2277,
"text": "Since these classes only have one single responsibility Design Principle 6: A class should have only one reason to change. is applied."
},
{
"code": null,
"e": 2473,
"s": 2412,
"text": "Impute by meanMean is the average sum of a group of numbers."
},
{
"code": null,
"e": 2802,
"s": 2473,
"text": "class ImputeByMean(ImputationStrategy): def _imputation(self, my_list: list, missing_values: str) -> float: temp_sum = 0 count = 0 for num in my_list: if num != missing_values: temp_sum += num count += 1 mean = (temp_sum/count) return round(mean, 2)"
},
{
"code": null,
"e": 2868,
"s": 2802,
"text": "Impute by medianMedian is the middle of a sorted list of numbers."
},
{
"code": null,
"e": 3411,
"s": 2868,
"text": "class ImputeByMedian(ImputationStrategy): def _imputation(self, my_list: list, missing_values: str) -> float: temp_list = [] for num in my_list: if num != missing_values: temp_list.append(num) temp_list.sort() temp_len = len(temp_list) if temp_len % 2 == 0: median1 = temp_list[temp_len//2] median2 = temp_list[temp_len//2 - 1] median = (median1 + median2)/2 else: median = temp_list[temp_len//2] return round(median, 2)"
},
{
"code": null,
"e": 3458,
"s": 3411,
"text": "Impute by modeMode is the most frequent value."
},
{
"code": null,
"e": 3548,
"s": 3458,
"text": "Note: Mode is included here for context but implemented below for demonstration purposes."
},
{
"code": null,
"e": 3963,
"s": 3548,
"text": "class ImputeByMode(ImputationStrategy): def _imputation(self, my_list: list, missing_values: str) -> float: frequency = {} for item in my_list: if item != missing_values: if (item in frequency): frequency[item] += 1 else: frequency[item] = 1 mode = max(frequency, key=frequency.get) return round(mode, 2)"
},
{
"code": null,
"e": 4159,
"s": 3963,
"text": "By instantiating the class and referencing the object instance, only one object needs creation. Thereby applying Design Principle 5: Depend upon abstractions. Do not depend upon concrete classes."
},
{
"code": null,
"e": 4248,
"s": 4159,
"text": "If instead directly calling the class, new objects are getting defined on each occasion."
},
{
"code": null,
"e": 4318,
"s": 4248,
"text": "mean = ImputeByMean()median = ImputeByMedian()# mode = ImputeByMode()"
},
{
"code": null,
"e": 4448,
"s": 4318,
"text": "The Imputer, which is the strategy patterns context, contains a reference to the instantiations of the concrete strategy objects."
},
{
"code": null,
"e": 4773,
"s": 4448,
"text": "The imputer uses the strategy interface to call the algorithm defined by a concrete strategy; each concrete strategy then implements an algorithm.Since this is the only connection between the imputer and the strategy interface Design Principle 4: Strive for loosely coupled designs between objects that interact, is applied."
},
{
"code": null,
"e": 4916,
"s": 4773,
"text": "When an operation is required, the concrete strategy object runs the algorithm without the imputer being aware of the strategy implementation."
},
{
"code": null,
"e": 5090,
"s": 4916,
"text": "If necessary, additional imputer objects can be instantiated to pass data from the imputer object to the strategy interface, thereby eliminating it as a singleton candidate."
},
{
"code": null,
"e": 11160,
"s": 5090,
"text": "class Imputer: \"\"\" The base class for imputer objects. Enables the user to specify which imputation method, and which \"cells\" to perform imputation on in a specific 2-dimensional list. A unique copy is made of the specified 2-dimensional list before transforming and returning it to the user. \"\"\" def __init__(self, strategy=\"mean\", axis=0) -> None: \"\"\" Defining instanse attributes on instansiation. Args: strategy (str, optional): A concrete strategy. Defaults to \"mean\". axis (int, optional): Column=0 or Row=1. Defaults to 0. \"\"\" # Reference to the concrete strategy object being used. self._strategy = strategy # Calling internal method. self.__strategy_prosessor() # Reference to the axis orientation being used. self._axis = axis # Reference to the keyword for missing values. # Defined as public, as per convention. self.missing_values = \"nan\" # Defines which column or row to start. self._from_item = None # Defines which column or row to end. self._to_item = None def __strategy_prosessor(self) -> None: \"\"\" Internal method validating that selected strategy is allowed. If so, selecting its imputation method. Raises: AssertionError: If the selected strategy is not allowed. \"\"\" allowed_strategies = [\"mean\", \"median\", \"mode\"] if self._strategy == allowed_strategies[0]: self._strategy = mean._imputation elif self._strategy == allowed_strategies[1]: self._strategy = median._imputation elif self._strategy == allowed_strategies[2]: self._strategy = mode._imputation else: assert self._strategy in allowed_strategies, ( f\"Can only use these strategies: {allowed_strategies}, \" f\"got strategy = {self._strategy}\") def __transpose(self, my_matrix: list) -> list: \"\"\" Transposes 2-dimensional list. Args: my_matrix (list): 2-dimensional list. Returns: list: 2-dimensional list transposed. \"\"\" trans_matrix = [] temp_matrix = [[my_matrix[j][i] for j in range(len(my_matrix))] for i in range(len(my_matrix[0]))] for row in temp_matrix: trans_matrix.append(row) return trans_matrix def fit(self, my_matrix: list, from_item: int, to_item: int) -> object: \"\"\" Passes in the 2-dimensional list for imputation, and sets from which column to start with, and end by. Args: my_matrix (list): 2-dimensional list. from_item (int): The column to start with. to_item (int): The column to end by. Raises: ValueError: If axis is not equal to the defined options. Returns: object: The same imputer object that calls the method. \"\"\" self._to_item = to_item if self._axis == 0: self._array = my_matrix self._from_item = from_item - 1 elif self._axis == 1: self._array = self.__transpose(my_matrix) self._from_item = from_item else: raise ValueError( f\"Can only use integer value 0 or 1: \" f\"got axis = {self._axis}\") return self def __axis_lister(self, matrix: list, col: int) -> list: \"\"\" Generates a list for all values in a 2-dimensional list column. Args: matrix (list): 2-dimensional list. col (int): selected column to generat list from. Returns: list: All values in a 2-dimensional list column. \"\"\" temp_list = [] for row in range(len(matrix)): temp_list.append((matrix[row][col])) return temp_list def _imputation(self, my_list: list, missing_values: str) -> float: \"\"\" Passing a list to the concrete strategy object with the desired imputation algorithm. For this reason, the method cannot be private, but have to be public or protected. Args: my_list (list): The list to be calculated by the algorithm. missing_values (str): The keyword for the missing values. Returns: float: The calculated value to swap with the missing value keyword \"\"\" return_value = self._strategy(my_list, missing_values) return return_value def transform(self) -> list: \"\"\" Inserts the imputed column value in each column-row (\"cell\") of the 2-dimensional list where the missing value keyword exists. Returns: list: A unique copy of the selected 2-dimensional list after it has been imputed. \"\"\" return_matrix = deepcopy(self._array) for col in range(self._from_item, self._to_item): imputed_value = self._imputation( self.__axis_lister(self._array, col), self.missing_values) for row in range(len(return_matrix)): if return_matrix[row][col] == self.missing_values: return_matrix[row][col] = imputed_value if self._axis == 0: pass elif self._axis == 1: return_matrix = self.__transpose(return_matrix) return return_matrix def __str__(self) -> str: \"\"\" Provides users with an easy to read representation of the class. Returns: str: The class name. \"\"\" return f\"{self.__class__.__name__}\" def __repr__(self) -> str: \"\"\" Provides developers with unambigous information of the class. Returns: str: The class name and the state of instance variables. \"\"\" return \"{self.__class__.__name__}\" \\ \"(Strategy: {self._strategy}, \" \\ \"Axis:{self._axis}, \" \\ \"Missing value: {self.missing_values}, \" \\ \"From:{self._from_item}, \" \\ \"To:{self._to_item})\".format(self=self)"
},
{
"code": null,
"e": 11314,
"s": 11160,
"text": "A class with a method for transposing a 2-dimensional list and a method to print this list format with tabs based on word length is made an instantiated."
},
{
"code": null,
"e": 12295,
"s": 11314,
"text": "class Matrix: def transpose(self, my_matrix): trans_matrix = [] temp_matrix = [[my_matrix[j][i] for j in range(len(my_matrix))] for i in range(len(my_matrix[0]))] for row in temp_matrix: trans_matrix.append(row) return trans_matrix def printer(self, my_matrix, title=None, axis=0): my_matrix = deepcopy(my_matrix) if title is not None: if axis == 0: my_matrix.insert(0, title) elif axis == 1: for i in range(len(my_matrix)): my_matrix[i].insert(0, title[i]) str_matrix = [[str(entity) for entity in row] for row in my_matrix] max_len_col_str = [max(map(len, col)) for col in zip(*str_matrix)] form = \"\\t\".join(\"{{:{}}}\".format(x) for x in max_len_col_str) matrix_row = [form.format(*row) for row in str_matrix] return_matrix = \"\\n\".join(matrix_row) print(return_matrix)matrix = Matrix()"
},
{
"code": null,
"e": 12342,
"s": 12295,
"text": "A mock dataset for demonstrations is provided."
},
{
"code": null,
"e": 12874,
"s": 12342,
"text": "dataset = list([[\"Country\", \"Age\", \"Salary\", \"Children\", \"Cars\"], [\"Swe\", 38.0, 47200.0, 1, 1], [\"Den\", 27.0, 48000.0, 0, 6], [\"Nor\", 30.0, 54000.0, 2, \"nan\"], [\"Den\", 38.0, 61000.0, \"nan\", 1], [\"Nor\", 40.0, \"nan\", 2, 1], [\"Swe\", 35.0, 58000.0, 1, 1], [\"Den\", \"nan\", 52000.0, 0, \"nan\"], [\"Swe\", 48.0, 67900.0, 2, 1], [\"Nor\", 50.0, 88300.0, 6, 2], [\"Swe\", 37.0, 67900.0, \"nan\", 2]])"
},
{
"code": null,
"e": 13004,
"s": 12874,
"text": "Some data preprocessing is simulated. First, the title row is removed from the list and inserted into its own list for later use."
},
{
"code": null,
"e": 13444,
"s": 13004,
"text": "dataset_title_row = dataset.pop(0)display(dataset_title_row)display(dataset)['Country', 'Age', 'Salary', 'Children', 'Cars'][['Swe', 38.0, 47200.0, 1, 1], ['Den', 27.0, 48000.0, 0, 6], ['Nor', 30.0, 54000.0, 2, 'nan'], ['Den', 38.0, 61000.0, 'nan', 1], ['Nor', 40.0, 'nan', 2, 1], ['Swe', 35.0, 58000.0, 1, 1], ['Den', 'nan', 52000.0, 0, 'nan'], ['Swe', 48.0, 67900.0, 2, 1], ['Nor', 50.0, 88300.0, 6, 2], ['Swe', 37.0, 67900.0, 'nan', 2]]"
},
{
"code": null,
"e": 13535,
"s": 13444,
"text": "Defining a transposed version of the dataset for later demonstrations on the axis feature."
},
{
"code": null,
"e": 13577,
"s": 13535,
"text": "dataset_trans = matrix.transpose(dataset)"
},
{
"code": null,
"e": 13737,
"s": 13577,
"text": "After the simulated preprocessing is over, the matrix objects printer method is demonstrated; passing in the desired dataset as well as the optional title row."
},
{
"code": null,
"e": 14151,
"s": 13737,
"text": "matrix.printer(dataset, dataset_title_row)Country\tAge \tSalary \tChildren\tCarsSwe \t38.0\t47200.0\t1 \t1 Den \t27.0\t48000.0\t0 \t6 Nor \t30.0\t54000.0\t2 \tnan Den \t38.0\t61000.0\tnan \t1 Nor \t40.0\tnan \t2 \t1 Swe \t35.0\t58000.0\t1 \t1 Den \tnan \t52000.0\t0 \tnan Swe \t48.0\t67900.0\t2 \t1 Nor \t50.0\t88300.0\t6 \t2 Swe \t37.0\t67900.0\tnan \t2"
},
{
"code": null,
"e": 14338,
"s": 14151,
"text": "Now, performing the same procedure for the transposed version. However, it is necessary to set the axis property to 1 to represent a transposed matrix, ensuring the proper output format."
},
{
"code": null,
"e": 14487,
"s": 14338,
"text": "Note: For the intended output to be displayed correctly for a transposed matrix, the web browser running Jupyter has to have the default zoom level."
},
{
"code": null,
"e": 14958,
"s": 14487,
"text": "matrix.printer(dataset_trans, dataset_title_row, 1)Country \tSwe \tDen \tNor \tDen \tNor \tSwe \tDen \tSwe \tNor \tSwe Age \t38.0 \t27.0 \t30.0 \t38.0 \t40.0\t35.0 \tnan \t48.0 \t50.0 \t37.0 Salary \t47200.0\t48000.0\t54000.0\t61000.0\tnan \t58000.0\t52000.0\t67900.0\t88300.0\t67900.0Children\t1 \t0 \t2 \tnan \t2 \t1 \t0 \t2 \t6 \tnan Cars \t1 \t6 \tnan \t1 \t1 \t1 \tnan \t1 \t2 \t2"
},
{
"code": null,
"e": 15034,
"s": 14958,
"text": "First, the default imputer is instantiated, imputation by mean, and column."
},
{
"code": null,
"e": 15059,
"s": 15034,
"text": "mean_imputer = Imputer()"
},
{
"code": null,
"e": 15136,
"s": 15059,
"text": "Demonstrating the __str__ and __repr__ methods defined in the Imputer class."
},
{
"code": null,
"e": 15364,
"s": 15136,
"text": "print(mean_imputer) # <- __str__mean_imputer # <- __repr__ImputerImputer(Strategy: <bound method ImputeByMean._imputation of <__main__.ImputeByMean object at 0x10f3dbf50>>, Axis:0, Missing value: nan, From:None, To:None)"
},
{
"code": null,
"e": 15463,
"s": 15364,
"text": "Defining which dataset the imputer should use as a source, and from which column to start and end."
},
{
"code": null,
"e": 15510,
"s": 15463,
"text": "mean_imputer = mean_imputer.fit(dataset, 2, 5)"
},
{
"code": null,
"e": 15704,
"s": 15510,
"text": "The imputer now copies the 2-dimensional list, calculates all selected column or row value depending on the axis settings using the desired strategy object, then returns the result to the user."
},
{
"code": null,
"e": 15747,
"s": 15704,
"text": "dataset_by_mean = mean_imputer.transform()"
},
{
"code": null,
"e": 15788,
"s": 15747,
"text": "Displaying the result of the imputation."
},
{
"code": null,
"e": 16232,
"s": 15788,
"text": "matrix.printer(dataset_by_mean, dataset_title_row)Country\tAge \tSalary \tChildren\tCarsSwe \t38.0 \t47200.0 \t1 \t1 Den \t27.0 \t48000.0 \t0 \t6 Nor \t30.0 \t54000.0 \t2 \t1.88Den \t38.0 \t61000.0 \t1.75 \t1 Nor \t40.0 \t60477.78\t2 \t1 Swe \t35.0 \t58000.0 \t1 \t1 Den \t38.11\t52000.0 \t0 \t1.88Swe \t48.0 \t67900.0 \t2 \t1 Nor \t50.0 \t88300.0 \t6 \t2 Swe \t37.0 \t67900.0 \t1.75 \t2"
},
{
"code": null,
"e": 16377,
"s": 16232,
"text": "Now demonstrating the transposed version of Imputed by Mean, in addition to the from and to settings. In this example, the last row is left out."
},
{
"code": null,
"e": 16508,
"s": 16377,
"text": "First, the mean imputer is instantiated, imputation by mean, and row. Then, performing the same steps as shown in Imputed by Mean."
},
{
"code": null,
"e": 17164,
"s": 16508,
"text": "mean_imputer_trans = Imputer(\"mean\", 1)mean_imputer_trans = mean_imputer_trans.fit(dataset_trans, 1, 4)dataset_by_mean_trans = mean_imputer_trans.transform()matrix.printer(dataset_by_mean_trans, dataset_title_row, 1)Country \tSwe \tDen \tNor \tDen \tNor \tSwe \tDen \tSwe \tNor \tSwe Age \t38.0 \t27.0 \t30.0 \t38.0 \t40.0 \t35.0 \t38.11 \t48.0 \t50.0 \t37.0 Salary \t47200.0\t48000.0\t54000.0\t61000.0\t60477.78\t58000.0\t52000.0\t67900.0\t88300.0\t67900.0Children\t1 \t0 \t2 \t1.75 \t2 \t1 \t0 \t2 \t6 \t1.75 Cars \t1 \t6 \tnan \t1 \t1 \t1 \tnan \t1 \t2 \t2"
},
{
"code": null,
"e": 17302,
"s": 17164,
"text": "First, the median imputer is instantiated, imputation by median, and column. Then, performing the same steps as shown in Imputed by Mean."
},
{
"code": null,
"e": 17856,
"s": 17302,
"text": "median_imputer = Imputer(\"median\")median_imputer = median_imputer.fit(dataset, 2, 5)dataset_by_median = median_imputer.transform()matrix.printer(dataset_by_median, dataset_title_row)Country\tAge \tSalary \tChildren\tCarsSwe \t38.0\t47200.0\t1 \t1 Den \t27.0\t48000.0\t0 \t6 Nor \t30.0\t54000.0\t2 \t1.0 Den \t38.0\t61000.0\t1.5 \t1 Nor \t40.0\t58000.0\t2 \t1 Swe \t35.0\t58000.0\t1 \t1 Den \t38.0\t52000.0\t0 \t1.0 Swe \t48.0\t67900.0\t2 \t1 Nor \t50.0\t88300.0\t6 \t2 Swe \t37.0\t67900.0\t1.5 \t2"
},
{
"code": null,
"e": 18221,
"s": 17856,
"text": "A new concrete strategy class is defined to demonstrate that the imputer is extendable without affecting any of the existing strategies. The only code updated needed to enable the new strategy is adding as an option in the allowed_strategies list in the Imputer __strategy_prosessor method, as well as adding it as an option in the if statement in the same method."
},
{
"code": null,
"e": 18636,
"s": 18221,
"text": "class ImputeByMode(ImputationStrategy): def _imputation(self, my_list: list, missing_values: str) -> float: frequency = {} for item in my_list: if item != missing_values: if (item in frequency): frequency[item] += 1 else: frequency[item] = 1 mode = max(frequency, key=frequency.get) return round(mode, 2)"
},
{
"code": null,
"e": 18770,
"s": 18636,
"text": "First, the mode imputer is instantiated, imputation by mode, and column. Then, performing the same steps as shown in Imputed by Mean."
},
{
"code": null,
"e": 19331,
"s": 18770,
"text": "mode = ImputeByMode()mode_imputer = Imputer(\"mode\")mode_imputer = mode_imputer.fit(dataset, 2, 5)dataset_by_mode = mode_imputer.transform()matrix.printer(dataset_by_mode, dataset_title_row)Country\tAge \tSalary \tChildren\tCarsSwe \t38.0\t47200.0\t1 \t1 Den \t27.0\t48000.0\t0 \t6 Nor \t30.0\t54000.0\t2 \t1 Den \t38.0\t61000.0\t2 \t1 Nor \t40.0\t67900.0\t2 \t1 Swe \t35.0\t58000.0\t1 \t1 Den \t38.0\t52000.0\t0 \t1 Swe \t48.0\t67900.0\t2 \t1 Nor \t50.0\t88300.0\t6 \t2 Swe \t37.0\t67900.0\t2 \t2"
},
{
"code": null,
"e": 19395,
"s": 19331,
"text": "Demonstration of generating a UML Class diagram using PlantUML."
},
{
"code": null,
"e": 21391,
"s": 19395,
"text": "from zlib import compressimport base64import stringimport requests# This was taken from plantuml libraryplantuml_alphabet = string.digits + \\ string.ascii_uppercase + string.ascii_lowercase + '-_'base64_alphabet = string.ascii_uppercase + \\ string.ascii_lowercase + string.digits + '+/'b64_to_plantuml = bytes.maketrans(base64_alphabet.encode( 'utf-8'), plantuml_alphabet.encode('utf-8'))def deflate_and_encode(plantuml_text): \"\"\" zlib compress the plantuml text and encode it for the plantuml server. \"\"\" zlibbed_str = compress(plantuml_text.encode('utf-8')) compressed_string = zlibbed_str[2:-4] return base64.b64encode(compressed_string).translate(b64_to_plantuml).\\ decode('utf-8')def render_uml(uml, fmt=\"svg\"): uri = \"http://www.plantuml.com/plantuml/{}/{}\".format( fmt, deflate_and_encode(uml)) r = requests.get(uri) if r.ok: return r.contentdiagram = \"\"\"@startumlskinparam class { BackgroundColor White ArrowColor Gray BorderColor Black}skinparam stereotypeCBackgroundColor Grayhide circletitle Imputer Strategy Patternclass Clienthide Client methodshide Client attributesclass ImputerImputer : +fit()Imputer : +transform()Imputer : #imputation()Imputer : -strategy_prosessor()Imputer : -transpose()Imputer : +missing_values : str = \"nan\"Imputer : #strategy : str = \"mean\"Imputer : #axis = int = 0Imputer : #from_item : intImputer : #to_item : intnote Top: Contextclass ImputerStrategy <<Interface>>ImputerStrategy : #imputation()class ImputByMeanImputByMean : #imputation()note Bottom: Concrete Strategy 1class ImputByMedianImputByMedian : #imputation()note Bottom: Concrete Strategy 2class ImputByModeImputByMode : #imputation()note Bottom: Concrete Strategy 3Imputer <-- Client : RequestsImputer *- ImputerStrategy : StrategyImputerStrategy <|-- ImputByMean : ExtendsImputerStrategy <|-- ImputByMedian : ExtendsImputerStrategy <|-- ImputByMode : Extends@enduml\"\"\"from IPython.display import SVGSVG(render_uml(diagram))"
},
{
"code": null,
"e": 21421,
"s": 21391,
"text": "Exporting to png file format."
},
{
"code": null,
"e": 21488,
"s": 21421,
"text": "from IPython.display import ImageImage(render_uml(diagram, \"png\"))"
},
{
"code": null,
"e": 21623,
"s": 21488,
"text": "While I would rather use sklearn for imputation, making an imputer from scratch has taught me a lot about object-oriented programming."
}
]
|
Find the minimum value from an array associated with another array - GeeksforGeeks | 29 May, 2021
Given an integer array A[] and a character array B[] of equal lengths where every character of the array is from the set {‘a’, ‘b’, ‘c’}. Elements of both the arrays are associated with each other i.e. the value of B[i] is linked to A[i] for all valid values of i. The task is to find the value min(a + b, c).
Examples:
Input: A[] = {3, 6, 4, 5, 6}, B[] = {‘a’, ‘c’, ‘b’, ‘b’, ‘a’} Output: 6
Input: A[] = {4, 2, 6, 2, 3}, B[] = {‘b’, ‘a’, ‘c’, ‘a’, ‘b’} Output: 5
Approach: In order to minimize the required value, the values of a, b and c have to be minimized. So, traverse the array and find the minimum values of a, b, and c associated with these characters in the integer array and finally return min(a + b, c).Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to get the minimum required valueint getMinimum(int A[], char B[], int n){ // To store the minimum values // of 'a', 'b' and 'c' int minA = INT_MAX; int minB = INT_MAX; int minC = INT_MAX; // For every value of A[] for (int i = 0; i < n; i++) { switch (B[i]) { // Update the minimum values of 'a', // 'b' and 'c' case 'a': minA = min(A[i], minA); break; case 'b': minB = min(A[i], minB); break; case 'c': minC = min(A[i], minC); break; } } // Return the minimum required value return min(minA + minB, minC);} // Driver codeint main(){ int A[] = { 4, 2, 6, 2, 3 }; char B[] = { 'b', 'a', 'c', 'a', 'b' }; int n = sizeof(A) / sizeof(A[0]); cout << getMinimum(A, B, n);}
// Java implementation of the above approachclass GFG{ // Function to get the minimum required valuestatic int getMinimum(int A[], char B[], int n){ // To store the minimum values // of 'a', 'b' and 'c' int minA = Integer.MAX_VALUE; int minB = Integer.MAX_VALUE; int minC = Integer.MAX_VALUE; // For every value of A[] for (int i = 0; i < n; i++) { switch (B[i]) { // Update the minimum values of 'a', // 'b' and 'c' case 'a': minA = Math.min(A[i], minA); break; case 'b': minB = Math.min(A[i], minB); break; case 'c': minC = Math.min(A[i], minC); break; } } // Return the minimum required value return Math.min(minA + minB, minC);} // Driver codepublic static void main(String[] args){ int A[] = { 4, 2, 6, 2, 3 }; char B[] = { 'b', 'a', 'c', 'a', 'b' }; int n = A.length; System.out.println(getMinimum(A, B, n));}} // This code is contributed by Rajput-Ji
# Python3 implementation of the approach # Function to get the minimum required valuedef getMinimum(A, B, n): # To store the minimum values # of 'a', 'b' and 'c' minA = float('inf'); minB = float('inf'); minC = float('inf'); # For every value of A[] for i in range(n): if B[i]=='a': minA = min(A[i], minA) if B[i]=='b': minB = min(A[i], minB) if B[i]=='c': minB = min(A[i], minC) # Return the minimum required value return min(minA + minB, minC) # Driver codeif __name__ == '__main__': A = [ 4, 2, 6, 2, 3 ] B = [ 'b', 'a', 'c', 'a', 'b' ] n = len(A); print(getMinimum(A, B, n)) # This code is contributed by Ashutosh450
// C# implementation of the above approachusing System; class GFG{ // Function to get the minimum required value static int getMinimum(int []A, char []B, int n) { // To store the minimum values // of 'a', 'b' and 'c' int minA = int.MaxValue; int minB = int.MaxValue; int minC = int.MaxValue; // For every value of A[] for (int i = 0; i < n; i++) { switch (B[i]) { // Update the minimum values of 'a', // 'b' and 'c' case 'a': minA = Math.Min(A[i], minA); break; case 'b': minB = Math.Min(A[i], minB); break; case 'c': minC = Math.Min(A[i], minC); break; } } // Return the minimum required value return Math.Min(minA + minB, minC); } // Driver code public static void Main() { int []A = { 4, 2, 6, 2, 3 }; char []B = { 'b', 'a', 'c', 'a', 'b' }; int n = A.Length; Console.WriteLine(getMinimum(A, B, n)); }} // This code is contributed by AnkitRai01
<script> // Javascript implementation of the approach // Function to get the minimum required valuefunction getMinimum(A, B, n){ // To store the minimum values // of 'a', 'b' and 'c' var minA = 1000000000; var minB = 1000000000; var minC = 1000000000; // For every value of A[] for (var i = 0; i < n; i++) { switch (B[i]) { // Update the minimum values of 'a', // 'b' and 'c' case 'a': minA = Math.min(A[i], minA); break; case 'b': minB = Math.min(A[i], minB); break; case 'c': minC = Math.min(A[i], minC); break; } } // Return the minimum required value return Math.min(minA + minB, minC);} // Driver codevar A = [4, 2, 6, 2, 3 ];var B = ['b', 'a', 'c', 'a', 'b'];var n = A.length;document.write( getMinimum(A, B, n)); </script>
5
Rajput-Ji
ankthon
ashutosh450
rutvik_56
Arrays
Arrays
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
Move all negative numbers to beginning and positive to end with constant extra space
Program to find sum of elements in a given array
Building Heap from Array
Find duplicates in O(n) time and O(1) extra space | Set 1
Next Greater Element
Count pairs with given sum
Remove duplicates from sorted array | [
{
"code": null,
"e": 24796,
"s": 24768,
"text": "\n29 May, 2021"
},
{
"code": null,
"e": 25107,
"s": 24796,
"text": "Given an integer array A[] and a character array B[] of equal lengths where every character of the array is from the set {‘a’, ‘b’, ‘c’}. Elements of both the arrays are associated with each other i.e. the value of B[i] is linked to A[i] for all valid values of i. The task is to find the value min(a + b, c). "
},
{
"code": null,
"e": 25118,
"s": 25107,
"text": "Examples: "
},
{
"code": null,
"e": 25190,
"s": 25118,
"text": "Input: A[] = {3, 6, 4, 5, 6}, B[] = {‘a’, ‘c’, ‘b’, ‘b’, ‘a’} Output: 6"
},
{
"code": null,
"e": 25264,
"s": 25190,
"text": "Input: A[] = {4, 2, 6, 2, 3}, B[] = {‘b’, ‘a’, ‘c’, ‘a’, ‘b’} Output: 5 "
},
{
"code": null,
"e": 25567,
"s": 25264,
"text": "Approach: In order to minimize the required value, the values of a, b and c have to be minimized. So, traverse the array and find the minimum values of a, b, and c associated with these characters in the integer array and finally return min(a + b, c).Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25571,
"s": 25567,
"text": "C++"
},
{
"code": null,
"e": 25576,
"s": 25571,
"text": "Java"
},
{
"code": null,
"e": 25584,
"s": 25576,
"text": "Python3"
},
{
"code": null,
"e": 25587,
"s": 25584,
"text": "C#"
},
{
"code": null,
"e": 25598,
"s": 25587,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to get the minimum required valueint getMinimum(int A[], char B[], int n){ // To store the minimum values // of 'a', 'b' and 'c' int minA = INT_MAX; int minB = INT_MAX; int minC = INT_MAX; // For every value of A[] for (int i = 0; i < n; i++) { switch (B[i]) { // Update the minimum values of 'a', // 'b' and 'c' case 'a': minA = min(A[i], minA); break; case 'b': minB = min(A[i], minB); break; case 'c': minC = min(A[i], minC); break; } } // Return the minimum required value return min(minA + minB, minC);} // Driver codeint main(){ int A[] = { 4, 2, 6, 2, 3 }; char B[] = { 'b', 'a', 'c', 'a', 'b' }; int n = sizeof(A) / sizeof(A[0]); cout << getMinimum(A, B, n);}",
"e": 26523,
"s": 25598,
"text": null
},
{
"code": "// Java implementation of the above approachclass GFG{ // Function to get the minimum required valuestatic int getMinimum(int A[], char B[], int n){ // To store the minimum values // of 'a', 'b' and 'c' int minA = Integer.MAX_VALUE; int minB = Integer.MAX_VALUE; int minC = Integer.MAX_VALUE; // For every value of A[] for (int i = 0; i < n; i++) { switch (B[i]) { // Update the minimum values of 'a', // 'b' and 'c' case 'a': minA = Math.min(A[i], minA); break; case 'b': minB = Math.min(A[i], minB); break; case 'c': minC = Math.min(A[i], minC); break; } } // Return the minimum required value return Math.min(minA + minB, minC);} // Driver codepublic static void main(String[] args){ int A[] = { 4, 2, 6, 2, 3 }; char B[] = { 'b', 'a', 'c', 'a', 'b' }; int n = A.length; System.out.println(getMinimum(A, B, n));}} // This code is contributed by Rajput-Ji",
"e": 27632,
"s": 26523,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to get the minimum required valuedef getMinimum(A, B, n): # To store the minimum values # of 'a', 'b' and 'c' minA = float('inf'); minB = float('inf'); minC = float('inf'); # For every value of A[] for i in range(n): if B[i]=='a': minA = min(A[i], minA) if B[i]=='b': minB = min(A[i], minB) if B[i]=='c': minB = min(A[i], minC) # Return the minimum required value return min(minA + minB, minC) # Driver codeif __name__ == '__main__': A = [ 4, 2, 6, 2, 3 ] B = [ 'b', 'a', 'c', 'a', 'b' ] n = len(A); print(getMinimum(A, B, n)) # This code is contributed by Ashutosh450",
"e": 28350,
"s": 27632,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ // Function to get the minimum required value static int getMinimum(int []A, char []B, int n) { // To store the minimum values // of 'a', 'b' and 'c' int minA = int.MaxValue; int minB = int.MaxValue; int minC = int.MaxValue; // For every value of A[] for (int i = 0; i < n; i++) { switch (B[i]) { // Update the minimum values of 'a', // 'b' and 'c' case 'a': minA = Math.Min(A[i], minA); break; case 'b': minB = Math.Min(A[i], minB); break; case 'c': minC = Math.Min(A[i], minC); break; } } // Return the minimum required value return Math.Min(minA + minB, minC); } // Driver code public static void Main() { int []A = { 4, 2, 6, 2, 3 }; char []B = { 'b', 'a', 'c', 'a', 'b' }; int n = A.Length; Console.WriteLine(getMinimum(A, B, n)); }} // This code is contributed by AnkitRai01",
"e": 29631,
"s": 28350,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to get the minimum required valuefunction getMinimum(A, B, n){ // To store the minimum values // of 'a', 'b' and 'c' var minA = 1000000000; var minB = 1000000000; var minC = 1000000000; // For every value of A[] for (var i = 0; i < n; i++) { switch (B[i]) { // Update the minimum values of 'a', // 'b' and 'c' case 'a': minA = Math.min(A[i], minA); break; case 'b': minB = Math.min(A[i], minB); break; case 'c': minC = Math.min(A[i], minC); break; } } // Return the minimum required value return Math.min(minA + minB, minC);} // Driver codevar A = [4, 2, 6, 2, 3 ];var B = ['b', 'a', 'c', 'a', 'b'];var n = A.length;document.write( getMinimum(A, B, n)); </script>",
"e": 30513,
"s": 29631,
"text": null
},
{
"code": null,
"e": 30515,
"s": 30513,
"text": "5"
},
{
"code": null,
"e": 30527,
"s": 30517,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 30535,
"s": 30527,
"text": "ankthon"
},
{
"code": null,
"e": 30547,
"s": 30535,
"text": "ashutosh450"
},
{
"code": null,
"e": 30557,
"s": 30547,
"text": "rutvik_56"
},
{
"code": null,
"e": 30564,
"s": 30557,
"text": "Arrays"
},
{
"code": null,
"e": 30571,
"s": 30564,
"text": "Arrays"
},
{
"code": null,
"e": 30669,
"s": 30571,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30694,
"s": 30669,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 30714,
"s": 30694,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 30752,
"s": 30714,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 30837,
"s": 30752,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 30886,
"s": 30837,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 30911,
"s": 30886,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 30969,
"s": 30911,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 30990,
"s": 30969,
"text": "Next Greater Element"
},
{
"code": null,
"e": 31017,
"s": 30990,
"text": "Count pairs with given sum"
}
]
|
Assigning multiple variables in one line in Python - GeeksforGeeks | 02 Dec, 2021
A variable is a named memory space that is used to store some data which will in-turn be used in some processing. All programming languages have some mechanism for variable declaration but one thing that stays common in all is the name and the data to be assigned to it. They are capable of storing values of data types.
Assignment operator(=) assigns the value provided to its right to the variable name given to its left. Given is the basic syntax of variable declaration:
Syntax:
var_name = value
Example:
a = 4
Given above is the mechanism for assigning just variables in Python but it is possible to assign multiple variables at the same time. Python assigns values from right to left. When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should to the right of the assignment operator.
While declaring variables in this fashion one must be careful with the order of the names and their corresponding value first variable name to the left of the assignment operator is assigned with the first value to its right and so on.
Example 1:
Python3
a, b = 4, 8print("value assigned to a")print(a)print("value assigned to b")print(b)
Output:
value assigned to a
4
value assigned to b
8
Variable assignment in a single line can also be done for different data types.
Example 2:
Python3
print("assigning values of different datatypes")a, b, c, d = 4, "geeks", 3.14, Trueprint(a)print(b)print(c)print(d)
Output:
assigning values of different datatypes
4
geeks
3.14
True
Not just simple variable assignment, assignment after performing some operation can also be done in the same way.
Example 3:
Python3
a, b = 8, 3add, pro = (a+b), (a*b)print(add)print(pro)
Output:
11
24
Example 4:
Python3
string = "Geeks"a, b, c = string[0], string[1:4], string[4] print(a)print(b)print(c)
Output:
G
eek
s
sweetyty
python-basics
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 24222,
"s": 23901,
"text": "A variable is a named memory space that is used to store some data which will in-turn be used in some processing. All programming languages have some mechanism for variable declaration but one thing that stays common in all is the name and the data to be assigned to it. They are capable of storing values of data types."
},
{
"code": null,
"e": 24376,
"s": 24222,
"text": "Assignment operator(=) assigns the value provided to its right to the variable name given to its left. Given is the basic syntax of variable declaration:"
},
{
"code": null,
"e": 24384,
"s": 24376,
"text": "Syntax:"
},
{
"code": null,
"e": 24401,
"s": 24384,
"text": "var_name = value"
},
{
"code": null,
"e": 24410,
"s": 24401,
"text": "Example:"
},
{
"code": null,
"e": 24416,
"s": 24410,
"text": "a = 4"
},
{
"code": null,
"e": 24845,
"s": 24416,
"text": "Given above is the mechanism for assigning just variables in Python but it is possible to assign multiple variables at the same time. Python assigns values from right to left. When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should to the right of the assignment operator."
},
{
"code": null,
"e": 25082,
"s": 24845,
"text": "While declaring variables in this fashion one must be careful with the order of the names and their corresponding value first variable name to the left of the assignment operator is assigned with the first value to its right and so on. "
},
{
"code": null,
"e": 25093,
"s": 25082,
"text": "Example 1:"
},
{
"code": null,
"e": 25101,
"s": 25093,
"text": "Python3"
},
{
"code": "a, b = 4, 8print(\"value assigned to a\")print(a)print(\"value assigned to b\")print(b)",
"e": 25185,
"s": 25101,
"text": null
},
{
"code": null,
"e": 25193,
"s": 25185,
"text": "Output:"
},
{
"code": null,
"e": 25237,
"s": 25193,
"text": "value assigned to a\n4\nvalue assigned to b\n8"
},
{
"code": null,
"e": 25317,
"s": 25237,
"text": "Variable assignment in a single line can also be done for different data types."
},
{
"code": null,
"e": 25328,
"s": 25317,
"text": "Example 2:"
},
{
"code": null,
"e": 25336,
"s": 25328,
"text": "Python3"
},
{
"code": "print(\"assigning values of different datatypes\")a, b, c, d = 4, \"geeks\", 3.14, Trueprint(a)print(b)print(c)print(d)",
"e": 25452,
"s": 25336,
"text": null
},
{
"code": null,
"e": 25460,
"s": 25452,
"text": "Output:"
},
{
"code": null,
"e": 25518,
"s": 25460,
"text": "assigning values of different datatypes\n4\ngeeks\n3.14\nTrue"
},
{
"code": null,
"e": 25632,
"s": 25518,
"text": "Not just simple variable assignment, assignment after performing some operation can also be done in the same way."
},
{
"code": null,
"e": 25643,
"s": 25632,
"text": "Example 3:"
},
{
"code": null,
"e": 25651,
"s": 25643,
"text": "Python3"
},
{
"code": "a, b = 8, 3add, pro = (a+b), (a*b)print(add)print(pro)",
"e": 25706,
"s": 25651,
"text": null
},
{
"code": null,
"e": 25714,
"s": 25706,
"text": "Output:"
},
{
"code": null,
"e": 25720,
"s": 25714,
"text": "11\n24"
},
{
"code": null,
"e": 25731,
"s": 25720,
"text": "Example 4:"
},
{
"code": null,
"e": 25739,
"s": 25731,
"text": "Python3"
},
{
"code": "string = \"Geeks\"a, b, c = string[0], string[1:4], string[4] print(a)print(b)print(c)",
"e": 25824,
"s": 25739,
"text": null
},
{
"code": null,
"e": 25832,
"s": 25824,
"text": "Output:"
},
{
"code": null,
"e": 25840,
"s": 25832,
"text": "G\neek\ns"
},
{
"code": null,
"e": 25849,
"s": 25840,
"text": "sweetyty"
},
{
"code": null,
"e": 25863,
"s": 25849,
"text": "python-basics"
},
{
"code": null,
"e": 25887,
"s": 25863,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 25894,
"s": 25887,
"text": "Python"
},
{
"code": null,
"e": 25913,
"s": 25894,
"text": "Technical Scripter"
},
{
"code": null,
"e": 26011,
"s": 25913,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26020,
"s": 26011,
"text": "Comments"
},
{
"code": null,
"e": 26033,
"s": 26020,
"text": "Old Comments"
},
{
"code": null,
"e": 26065,
"s": 26033,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26121,
"s": 26065,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26163,
"s": 26121,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26205,
"s": 26163,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26241,
"s": 26205,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26263,
"s": 26241,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26302,
"s": 26263,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26329,
"s": 26302,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26360,
"s": 26329,
"text": "Python | os.path.join() method"
}
]
|
C# program to convert time from 12 hour to 24 hour format | Firstly, set the 12 hr format date.
DateTime d = DateTime.Parse("05:00 PM");
Now let us convert it into 24-hr format.
d.ToString("HH:mm"));
The following is the code to covert time from 12 hour to 24 hour format −
Live Demo
using System;
namespace Demo {
public class Program {
public static void Main(string[] args) {
DateTime d = DateTime.Parse("05:00 PM");
Console.WriteLine(d.ToString("HH:mm"));
}
}
}
17:00 | [
{
"code": null,
"e": 1098,
"s": 1062,
"text": "Firstly, set the 12 hr format date."
},
{
"code": null,
"e": 1139,
"s": 1098,
"text": "DateTime d = DateTime.Parse(\"05:00 PM\");"
},
{
"code": null,
"e": 1180,
"s": 1139,
"text": "Now let us convert it into 24-hr format."
},
{
"code": null,
"e": 1202,
"s": 1180,
"text": "d.ToString(\"HH:mm\"));"
},
{
"code": null,
"e": 1276,
"s": 1202,
"text": "The following is the code to covert time from 12 hour to 24 hour format −"
},
{
"code": null,
"e": 1287,
"s": 1276,
"text": " Live Demo"
},
{
"code": null,
"e": 1505,
"s": 1287,
"text": "using System;\nnamespace Demo {\n public class Program {\n public static void Main(string[] args) {\n DateTime d = DateTime.Parse(\"05:00 PM\");\n Console.WriteLine(d.ToString(\"HH:mm\"));\n }\n }\n}"
},
{
"code": null,
"e": 1511,
"s": 1505,
"text": "17:00"
}
]
|
How to write the plot title in multiple lines using plot function in R? | Mostly, the main title of a plot is short but we might have a long line to write for the main title of the plot. For example, a short version might be “Scatterplot” and a longer version might be “Scatterplot between X and Y”. Therefore, in plot function of R we can use line breaks for the main title as "Scatterplot \n between \n X and Y".
set.seed(123)
x <-rnorm(10)
y <-rnorm(10,2.5)
Creating a simple scatterplot between x and y with main title −
plot(x,y,main="Scatterplot between X and Y")
Creating a simple scatterplot between x and y with main title in multiple lines −
plot(x,y,main="Scatterplot \n between \n X and Y") | [
{
"code": null,
"e": 1403,
"s": 1062,
"text": "Mostly, the main title of a plot is short but we might have a long line to write for the main title of the plot. For example, a short version might be “Scatterplot” and a longer version might be “Scatterplot between X and Y”. Therefore, in plot function of R we can use line breaks for the main title as \"Scatterplot \\n between \\n X and Y\"."
},
{
"code": null,
"e": 1449,
"s": 1403,
"text": "set.seed(123)\nx <-rnorm(10)\ny <-rnorm(10,2.5)"
},
{
"code": null,
"e": 1513,
"s": 1449,
"text": "Creating a simple scatterplot between x and y with main title −"
},
{
"code": null,
"e": 1558,
"s": 1513,
"text": "plot(x,y,main=\"Scatterplot between X and Y\")"
},
{
"code": null,
"e": 1640,
"s": 1558,
"text": "Creating a simple scatterplot between x and y with main title in multiple lines −"
},
{
"code": null,
"e": 1691,
"s": 1640,
"text": "plot(x,y,main=\"Scatterplot \\n between \\n X and Y\")"
}
]
|
Iterate over a dictionary in Python | 01 Jul, 2022
In this article, we will cover How to Iterate Through a Dictionary in Python.
Dictionary in Python is an unordered collection of data values, used to store data values like a map, unlike other Data Types that hold only a single value as an element, Dictionary holds the key: value pair.
There are multiple ways to iterate over a dictionary in Python.
Access key using the build .keys()
Access key without using a key()
Iterate through all values using .values()
Iterate through all key, and value pairs using items()
Access both key and value without using items()
Print items in Key-Value in pair
In this example, you will see that we are using an in-build. keys() method which helps us to print all the keys in the dictionary.
Python3
# Python3 code to iterate through all values in a dictionary statesAndCapitals = { 'Gujarat': 'Gandhinagar', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur', 'Bihar': 'Patna'} keys = statesAndCapitals.keys()print(keys)
Output:
dict_keys(['Gujarat', 'Maharashtra', 'Rajasthan', 'Bihar'])
Iterating over dictionaries using ‘for’ loops for iterating our keys and printing all the keys present in the Dictionary.
Python3
# Python3 code to iterate through all keys in a dictionary statesAndCapitals = { 'Gujarat': 'Gandhinagar', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur', 'Bihar': 'Patna'} print('List Of given states:\n') # Iterating over keysfor state in statesAndCapitals: print(state)
Output:
List Of given states:
Gujarat
Maharashtra
Rajasthan
Bihar
In this example, we are using the values() method to print all the values present in the dictionary.
Python3
# Python3 code to iterate through all values in a dictionary statesAndCapitals = { 'Gujarat': 'Gandhinagar', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur', 'Bihar': 'Patna'} print('List Of given capitals:\n') # Iterating over valuesfor capital in statesAndCapitals.values(): print(capital)
Output:
List Of given capitals:
Gandhinagar
Mumbai
Jaipur
Patna
In this example, we are printing all the key and value pairs present in a dictionary using a items() method.
Python3
# Python3 code to iterate through all key, value# pairs in a dictionary statesAndCapitals = { 'Gujarat': 'Gandhinagar', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur', 'Bihar': 'Patna'} print('List Of given states and their capitals:\n') # Iterating over valuesfor state, capital in statesAndCapitals.items(): print(state, ":", capital)
Output:
List Of given states and their capitals:
Gujarat : Gandhinagar
Maharashtra : Mumbai
Rajasthan : Jaipur
Bihar : Patna
In this example, we are using a Python Loop Through a Dictionary, and with each iteration, we are obtaining the key of the directory after that, we are printing key data and we are using a key as an index to print values from the directory.
Python3
# Python3 code to iterate through all values in a dictionary statesAndCapitals = { 'Gujarat': 'Gandhinagar', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur', 'Bihar': 'Patna'} for i in statesAndCapitals: print(i, '->', statesAndCapitals[i])
Output:
Gujarat -> Gandhinagar
Maharashtra -> Mumbai
Rajasthan -> Jaipur
Bihar -> Patna
In this example, we are printing the key values data in the form of pairs and all the pair are enclosed in a dictionary.
Python3
# Python3 code to iterate through all values in a dictionary statesAndCapitals = { 'Gujarat': 'Gandhinagar', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur', 'Bihar': 'Patna'} keys = statesAndCapitals.items()print(keys)
Output:
dict_items([('Gujarat', 'Gandhinagar'), ('Maharashtra', 'Mumbai'),
('Rajasthan', 'Jaipur'), ('Bihar', 'Patna')])
surajkumarguptaintern
Picked
python-dict
Technical Scripter 2018
Python
Technical Scripter
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Jul, 2022"
},
{
"code": null,
"e": 131,
"s": 52,
"text": "In this article, we will cover How to Iterate Through a Dictionary in Python. "
},
{
"code": null,
"e": 341,
"s": 131,
"text": "Dictionary in Python is an unordered collection of data values, used to store data values like a map, unlike other Data Types that hold only a single value as an element, Dictionary holds the key: value pair. "
},
{
"code": null,
"e": 405,
"s": 341,
"text": "There are multiple ways to iterate over a dictionary in Python."
},
{
"code": null,
"e": 441,
"s": 405,
"text": "Access key using the build .keys() "
},
{
"code": null,
"e": 475,
"s": 441,
"text": "Access key without using a key() "
},
{
"code": null,
"e": 518,
"s": 475,
"text": "Iterate through all values using .values()"
},
{
"code": null,
"e": 573,
"s": 518,
"text": "Iterate through all key, and value pairs using items()"
},
{
"code": null,
"e": 621,
"s": 573,
"text": "Access both key and value without using items()"
},
{
"code": null,
"e": 655,
"s": 621,
"text": "Print items in Key-Value in pair "
},
{
"code": null,
"e": 786,
"s": 655,
"text": "In this example, you will see that we are using an in-build. keys() method which helps us to print all the keys in the dictionary."
},
{
"code": null,
"e": 794,
"s": 786,
"text": "Python3"
},
{
"code": "# Python3 code to iterate through all values in a dictionary statesAndCapitals = { 'Gujarat': 'Gandhinagar', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur', 'Bihar': 'Patna'} keys = statesAndCapitals.keys()print(keys)",
"e": 1024,
"s": 794,
"text": null
},
{
"code": null,
"e": 1032,
"s": 1024,
"text": "Output:"
},
{
"code": null,
"e": 1092,
"s": 1032,
"text": "dict_keys(['Gujarat', 'Maharashtra', 'Rajasthan', 'Bihar'])"
},
{
"code": null,
"e": 1214,
"s": 1092,
"text": "Iterating over dictionaries using ‘for’ loops for iterating our keys and printing all the keys present in the Dictionary."
},
{
"code": null,
"e": 1222,
"s": 1214,
"text": "Python3"
},
{
"code": "# Python3 code to iterate through all keys in a dictionary statesAndCapitals = { 'Gujarat': 'Gandhinagar', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur', 'Bihar': 'Patna'} print('List Of given states:\\n') # Iterating over keysfor state in statesAndCapitals: print(state)",
"e": 1509,
"s": 1222,
"text": null
},
{
"code": null,
"e": 1517,
"s": 1509,
"text": "Output:"
},
{
"code": null,
"e": 1576,
"s": 1517,
"text": "List Of given states:\n\nGujarat\nMaharashtra\nRajasthan\nBihar"
},
{
"code": null,
"e": 1677,
"s": 1576,
"text": "In this example, we are using the values() method to print all the values present in the dictionary."
},
{
"code": null,
"e": 1685,
"s": 1677,
"text": "Python3"
},
{
"code": "# Python3 code to iterate through all values in a dictionary statesAndCapitals = { 'Gujarat': 'Gandhinagar', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur', 'Bihar': 'Patna'} print('List Of given capitals:\\n') # Iterating over valuesfor capital in statesAndCapitals.values(): print(capital)",
"e": 1991,
"s": 1685,
"text": null
},
{
"code": null,
"e": 1999,
"s": 1991,
"text": "Output:"
},
{
"code": null,
"e": 2056,
"s": 1999,
"text": "List Of given capitals:\n\nGandhinagar\nMumbai\nJaipur\nPatna"
},
{
"code": null,
"e": 2165,
"s": 2056,
"text": "In this example, we are printing all the key and value pairs present in a dictionary using a items() method."
},
{
"code": null,
"e": 2173,
"s": 2165,
"text": "Python3"
},
{
"code": "# Python3 code to iterate through all key, value# pairs in a dictionary statesAndCapitals = { 'Gujarat': 'Gandhinagar', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur', 'Bihar': 'Patna'} print('List Of given states and their capitals:\\n') # Iterating over valuesfor state, capital in statesAndCapitals.items(): print(state, \":\", capital)",
"e": 2525,
"s": 2173,
"text": null
},
{
"code": null,
"e": 2533,
"s": 2525,
"text": "Output:"
},
{
"code": null,
"e": 2651,
"s": 2533,
"text": "List Of given states and their capitals:\n\nGujarat : Gandhinagar\nMaharashtra : Mumbai\nRajasthan : Jaipur\nBihar : Patna"
},
{
"code": null,
"e": 2893,
"s": 2651,
"text": "In this example, we are using a Python Loop Through a Dictionary, and with each iteration, we are obtaining the key of the directory after that, we are printing key data and we are using a key as an index to print values from the directory. "
},
{
"code": null,
"e": 2901,
"s": 2893,
"text": "Python3"
},
{
"code": "# Python3 code to iterate through all values in a dictionary statesAndCapitals = { 'Gujarat': 'Gandhinagar', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur', 'Bihar': 'Patna'} for i in statesAndCapitals: print(i, '->', statesAndCapitals[i])",
"e": 3156,
"s": 2901,
"text": null
},
{
"code": null,
"e": 3164,
"s": 3156,
"text": "Output:"
},
{
"code": null,
"e": 3244,
"s": 3164,
"text": "Gujarat -> Gandhinagar\nMaharashtra -> Mumbai\nRajasthan -> Jaipur\nBihar -> Patna"
},
{
"code": null,
"e": 3366,
"s": 3244,
"text": "In this example, we are printing the key values data in the form of pairs and all the pair are enclosed in a dictionary. "
},
{
"code": null,
"e": 3374,
"s": 3366,
"text": "Python3"
},
{
"code": "# Python3 code to iterate through all values in a dictionary statesAndCapitals = { 'Gujarat': 'Gandhinagar', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur', 'Bihar': 'Patna'} keys = statesAndCapitals.items()print(keys)",
"e": 3605,
"s": 3374,
"text": null
},
{
"code": null,
"e": 3613,
"s": 3605,
"text": "Output:"
},
{
"code": null,
"e": 3727,
"s": 3613,
"text": "dict_items([('Gujarat', 'Gandhinagar'), ('Maharashtra', 'Mumbai'), \n('Rajasthan', 'Jaipur'), ('Bihar', 'Patna')])"
},
{
"code": null,
"e": 3749,
"s": 3727,
"text": "surajkumarguptaintern"
},
{
"code": null,
"e": 3756,
"s": 3749,
"text": "Picked"
},
{
"code": null,
"e": 3768,
"s": 3756,
"text": "python-dict"
},
{
"code": null,
"e": 3792,
"s": 3768,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 3799,
"s": 3792,
"text": "Python"
},
{
"code": null,
"e": 3818,
"s": 3799,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3830,
"s": 3818,
"text": "python-dict"
},
{
"code": null,
"e": 3928,
"s": 3830,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3946,
"s": 3928,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3988,
"s": 3946,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4023,
"s": 3988,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4049,
"s": 4023,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4081,
"s": 4049,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4110,
"s": 4081,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4137,
"s": 4110,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4158,
"s": 4137,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4194,
"s": 4158,
"text": "Convert integer to string in Python"
}
]
|
Result of comma operator as l-value in C and C++ | 28 May, 2017
Using result of comma operator as l-value is not valid in C. But in C++, result of comma operator can be used as l-value if the right operand of the comma operator is l-value.
For example, if we compile the following program as a C++ program, then it works and prints b = 30. And if we compile the same program as C program, then it gives warning/error in compilation (Warning in Dev C++ and error in Code Blocks).
#include<stdio.h> int main(){ int a = 10, b = 20; (a, b) = 30; // Since b is l-value, this statement is valid in C++, but not in C. printf("b = %d", b); getchar(); return 0;}
C++ Output:b = 30
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Operators
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)
vector erase() and clear() in C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 May, 2017"
},
{
"code": null,
"e": 230,
"s": 54,
"text": "Using result of comma operator as l-value is not valid in C. But in C++, result of comma operator can be used as l-value if the right operand of the comma operator is l-value."
},
{
"code": null,
"e": 469,
"s": 230,
"text": "For example, if we compile the following program as a C++ program, then it works and prints b = 30. And if we compile the same program as C program, then it gives warning/error in compilation (Warning in Dev C++ and error in Code Blocks)."
},
{
"code": "#include<stdio.h> int main(){ int a = 10, b = 20; (a, b) = 30; // Since b is l-value, this statement is valid in C++, but not in C. printf(\"b = %d\", b); getchar(); return 0;}",
"e": 650,
"s": 469,
"text": null
},
{
"code": null,
"e": 668,
"s": 650,
"text": "C++ Output:b = 30"
},
{
"code": null,
"e": 793,
"s": 668,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 805,
"s": 793,
"text": "C-Operators"
},
{
"code": null,
"e": 816,
"s": 805,
"text": "C Language"
},
{
"code": null,
"e": 820,
"s": 816,
"text": "C++"
},
{
"code": null,
"e": 824,
"s": 820,
"text": "CPP"
},
{
"code": null,
"e": 922,
"s": 824,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 939,
"s": 922,
"text": "Substring in C++"
},
{
"code": null,
"e": 961,
"s": 939,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 996,
"s": 961,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 1042,
"s": 996,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 1087,
"s": 1042,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 1105,
"s": 1087,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 1148,
"s": 1105,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1194,
"s": 1148,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 1237,
"s": 1194,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
How to loop through each row of dataFrame in PySpark ? | 30 Sep, 2021
In this article, we are going to see how to loop through each row of Dataframe in PySpark. Looping through each row helps us to perform complex operations on the RDD or Dataframe.
Creating Dataframe for demonstration:
Python3
# importing necessary librariesimport pysparkfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \ .master("local") \ .appName("employee_profile.com") \ .getOrCreate() return spk def create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == "__main__": # calling function to create SparkSession spark = create_session() input_data = [(1, "Shivansh", "Data Scientist", "Noida"), (2, "Rishabh", "Software Developer", "Banglore"), (3, "Swati", "Data Analyst", "Hyderabad"), (4, "Amar", "Data Analyst", "Noida"), (5, "Arpit", "Android Developer", "Pune"), (6, "Ranjeet", "Python Developer", "Gurugram"), (7, "Priyanka", "Full Stack Developer", "Banglore")] schema = ["Id", "Name", "Job Profile", "City"] # calling function to create dataframe df = create_df(spark, input_data, schema) # retrieving all the elements of # the dataframe using collect() # Storing in the variable data_collect = df.collect() df.show()
Output:
We can use collect() action operation for retrieving all the elements of the Dataset to the driver function then loop through it using for loop.
Python3
# retrieving all the elements# of the dataframe using collect()# Storing in the variabledata_collect = df.collect() # looping thorough each row of the dataframefor row in data_collect: # while looping through each # row printing the data of Id, Name and City print(row["Id"],row["Name"]," ",row["City"])
Output:
We can use toLocalIterator(). This returns an iterator that contains all the rows in the DataFrame. It is similar to collect(). The only difference is that collect() returns the list whereas toLocalIterator() returns an iterator.
Python
data_itr = df.rdd.toLocalIterator() # looping thorough each row of the dataframefor row in data_itr: # while looping through each row printing # the data of Id, Job Profile and City print(row["Id"]," ",row["Job Profile"]," ",row["City"])
Output:
Note: This function is similar to collect() function as used in the above example the only difference is that this function returns the iterator whereas the collect() function returns the list.
The iterrows() function for iterating through each row of the Dataframe, is the function of pandas library, so first, we have to convert the PySpark Dataframe into Pandas Dataframe using toPandas() function. Then loop through it using for loop.
Python
pd_df = df.toPandas() # looping through each row using iterrows()# used to iterate over dataframe rows as index,# series pairfor index, row in pd_df.iterrows(): # while looping through each row # printing the Id, Name and Salary # by passing index instead of Name # of the column print(row[0],row[1]," ",row[3])
Output:
map() function with lambda function for iterating through each row of Dataframe. For looping through each row using map() first we have to convert the PySpark dataframe into RDD because map() is performed on RDD’s only, so first convert into RDD it then use map() in which, lambda function for iterating through each row and stores the new RDD in some variable then convert back that new RDD into Dataframe using toDF() by passing schema into it.
Python
# importing necessary librariesimport pysparkfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \ .master("local") \ .appName("employee_profile.com") \ .getOrCreate() return spk def create_df(spark,data,schema): df1 = spark.createDataFrame(data,schema) return df1 if __name__ == "__main__": # calling function to create SparkSession spark = create_session() input_data = [(1,"Shivansh","Data Scientist",2000000,"Noida"), (2,"Rishabh","Software Developer",1500000,"Banglore"), (3,"Swati","Data Analyst",1000000,"Hyderabad"), (4,"Amar","Data Analyst",950000,"Noida"), (5,"Arpit","Android Developer",1600000,"Pune"), (6,"Ranjeet","Python Developer",1800000,"Gurugram"), (7,"Priyanka","Full Stack Developer",2200000,"Banglore")] schema = ["Id","Name","Job Profile","Salary","City"] # calling function to create dataframe df = create_df(spark,input_data,schema) # map() is only be performed on rdd # so converting the dataframe into rdd using df.rdd rdd = df.rdd.map(lambda loop: ( loop["Id"],loop["Name"],loop["Salary"],loop["City"]) ) # after looping the getting the data from each row # converting back from RDD to Dataframe df2 = rdd.toDF(["Id","Name","Salary","City"]) # showing the new Dataframe df2.show()
Output:
We can use list comprehension for looping through each row which we will discuss in the example.
Python
# using list comprehension for looping# through each row storing the list of# data in the variable table = [x["Job Profile"] for x in df.rdd.collect()] # looping the list for printing for row in table: print(row)
Output:
The select() function is used to select the number of columns. After selecting the columns, we are using the collect() function that returns the list of rows that contains only the data of selected columns.
Python
# importing necessary librariesimport pysparkfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \ .master("local") \ .appName("employee_profile.com") \ .getOrCreate() return spk def create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == "__main__": # calling function to create SparkSession spark = create_session() input_data = [(1, "Shivansh", "Data Scientist", 2000000, "Noida"), (2, "Rishabh", "Software Developer", 1500000, "Banglore"), (3, "Swati", "Data Analyst", 1000000, "Hyderabad"), (4, "Amar", "Data Analyst", 950000, "Noida"), (5, "Arpit", "Android Developer", 1600000, "Pune"), (6, "Ranjeet", "Python Developer", 1800000, "Gurugram"), (7, "Priyanka", "Full Stack Developer", 2200000, "Banglore")] schema = ["Id", "Name", "Job Profile", "Salary", "City"] # calling function to create dataframe df = create_df(spark, input_data, schema) # getting each row of dataframe containing # only selected columns Selected columns are # 'Name' and 'Salary' getting the list of rows # with selected column data using collect() rows_looped = df.select("Name", "Salary").collect() # printing the data of each row for rows in rows_looped: # here index 0 and 1 refers to the data # of 'Name' column and 'Salary' column print(rows[0], rows[1])
Output:
sagartomar9927
anikaseth98
Picked
Python-Pyspark
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
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
Introduction To PYTHON | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 208,
"s": 28,
"text": "In this article, we are going to see how to loop through each row of Dataframe in PySpark. Looping through each row helps us to perform complex operations on the RDD or Dataframe."
},
{
"code": null,
"e": 246,
"s": 208,
"text": "Creating Dataframe for demonstration:"
},
{
"code": null,
"e": 254,
"s": 246,
"text": "Python3"
},
{
"code": "# importing necessary librariesimport pysparkfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"employee_profile.com\") \\ .getOrCreate() return spk def create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == \"__main__\": # calling function to create SparkSession spark = create_session() input_data = [(1, \"Shivansh\", \"Data Scientist\", \"Noida\"), (2, \"Rishabh\", \"Software Developer\", \"Banglore\"), (3, \"Swati\", \"Data Analyst\", \"Hyderabad\"), (4, \"Amar\", \"Data Analyst\", \"Noida\"), (5, \"Arpit\", \"Android Developer\", \"Pune\"), (6, \"Ranjeet\", \"Python Developer\", \"Gurugram\"), (7, \"Priyanka\", \"Full Stack Developer\", \"Banglore\")] schema = [\"Id\", \"Name\", \"Job Profile\", \"City\"] # calling function to create dataframe df = create_df(spark, input_data, schema) # retrieving all the elements of # the dataframe using collect() # Storing in the variable data_collect = df.collect() df.show()",
"e": 1453,
"s": 254,
"text": null
},
{
"code": null,
"e": 1461,
"s": 1453,
"text": "Output:"
},
{
"code": null,
"e": 1606,
"s": 1461,
"text": "We can use collect() action operation for retrieving all the elements of the Dataset to the driver function then loop through it using for loop."
},
{
"code": null,
"e": 1614,
"s": 1606,
"text": "Python3"
},
{
"code": "# retrieving all the elements# of the dataframe using collect()# Storing in the variabledata_collect = df.collect() # looping thorough each row of the dataframefor row in data_collect: # while looping through each # row printing the data of Id, Name and City print(row[\"Id\"],row[\"Name\"],\" \",row[\"City\"])",
"e": 1928,
"s": 1614,
"text": null
},
{
"code": null,
"e": 1937,
"s": 1928,
"text": " Output:"
},
{
"code": null,
"e": 2167,
"s": 1937,
"text": "We can use toLocalIterator(). This returns an iterator that contains all the rows in the DataFrame. It is similar to collect(). The only difference is that collect() returns the list whereas toLocalIterator() returns an iterator."
},
{
"code": null,
"e": 2174,
"s": 2167,
"text": "Python"
},
{
"code": "data_itr = df.rdd.toLocalIterator() # looping thorough each row of the dataframefor row in data_itr: # while looping through each row printing # the data of Id, Job Profile and City print(row[\"Id\"],\" \",row[\"Job Profile\"],\" \",row[\"City\"])",
"e": 2425,
"s": 2174,
"text": null
},
{
"code": null,
"e": 2433,
"s": 2425,
"text": "Output:"
},
{
"code": null,
"e": 2627,
"s": 2433,
"text": "Note: This function is similar to collect() function as used in the above example the only difference is that this function returns the iterator whereas the collect() function returns the list."
},
{
"code": null,
"e": 2872,
"s": 2627,
"text": "The iterrows() function for iterating through each row of the Dataframe, is the function of pandas library, so first, we have to convert the PySpark Dataframe into Pandas Dataframe using toPandas() function. Then loop through it using for loop."
},
{
"code": null,
"e": 2879,
"s": 2872,
"text": "Python"
},
{
"code": "pd_df = df.toPandas() # looping through each row using iterrows()# used to iterate over dataframe rows as index,# series pairfor index, row in pd_df.iterrows(): # while looping through each row # printing the Id, Name and Salary # by passing index instead of Name # of the column print(row[0],row[1],\" \",row[3])",
"e": 3209,
"s": 2879,
"text": null
},
{
"code": null,
"e": 3217,
"s": 3209,
"text": "Output:"
},
{
"code": null,
"e": 3664,
"s": 3217,
"text": "map() function with lambda function for iterating through each row of Dataframe. For looping through each row using map() first we have to convert the PySpark dataframe into RDD because map() is performed on RDD’s only, so first convert into RDD it then use map() in which, lambda function for iterating through each row and stores the new RDD in some variable then convert back that new RDD into Dataframe using toDF() by passing schema into it."
},
{
"code": null,
"e": 3671,
"s": 3664,
"text": "Python"
},
{
"code": "# importing necessary librariesimport pysparkfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"employee_profile.com\") \\ .getOrCreate() return spk def create_df(spark,data,schema): df1 = spark.createDataFrame(data,schema) return df1 if __name__ == \"__main__\": # calling function to create SparkSession spark = create_session() input_data = [(1,\"Shivansh\",\"Data Scientist\",2000000,\"Noida\"), (2,\"Rishabh\",\"Software Developer\",1500000,\"Banglore\"), (3,\"Swati\",\"Data Analyst\",1000000,\"Hyderabad\"), (4,\"Amar\",\"Data Analyst\",950000,\"Noida\"), (5,\"Arpit\",\"Android Developer\",1600000,\"Pune\"), (6,\"Ranjeet\",\"Python Developer\",1800000,\"Gurugram\"), (7,\"Priyanka\",\"Full Stack Developer\",2200000,\"Banglore\")] schema = [\"Id\",\"Name\",\"Job Profile\",\"Salary\",\"City\"] # calling function to create dataframe df = create_df(spark,input_data,schema) # map() is only be performed on rdd # so converting the dataframe into rdd using df.rdd rdd = df.rdd.map(lambda loop: ( loop[\"Id\"],loop[\"Name\"],loop[\"Salary\"],loop[\"City\"]) ) # after looping the getting the data from each row # converting back from RDD to Dataframe df2 = rdd.toDF([\"Id\",\"Name\",\"Salary\",\"City\"]) # showing the new Dataframe df2.show()",
"e": 5055,
"s": 3671,
"text": null
},
{
"code": null,
"e": 5065,
"s": 5055,
"text": " Output: "
},
{
"code": null,
"e": 5162,
"s": 5065,
"text": "We can use list comprehension for looping through each row which we will discuss in the example."
},
{
"code": null,
"e": 5169,
"s": 5162,
"text": "Python"
},
{
"code": "# using list comprehension for looping# through each row storing the list of# data in the variable table = [x[\"Job Profile\"] for x in df.rdd.collect()] # looping the list for printing for row in table: print(row)",
"e": 5386,
"s": 5169,
"text": null
},
{
"code": null,
"e": 5395,
"s": 5386,
"text": " Output:"
},
{
"code": null,
"e": 5602,
"s": 5395,
"text": "The select() function is used to select the number of columns. After selecting the columns, we are using the collect() function that returns the list of rows that contains only the data of selected columns."
},
{
"code": null,
"e": 5609,
"s": 5602,
"text": "Python"
},
{
"code": "# importing necessary librariesimport pysparkfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"employee_profile.com\") \\ .getOrCreate() return spk def create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == \"__main__\": # calling function to create SparkSession spark = create_session() input_data = [(1, \"Shivansh\", \"Data Scientist\", 2000000, \"Noida\"), (2, \"Rishabh\", \"Software Developer\", 1500000, \"Banglore\"), (3, \"Swati\", \"Data Analyst\", 1000000, \"Hyderabad\"), (4, \"Amar\", \"Data Analyst\", 950000, \"Noida\"), (5, \"Arpit\", \"Android Developer\", 1600000, \"Pune\"), (6, \"Ranjeet\", \"Python Developer\", 1800000, \"Gurugram\"), (7, \"Priyanka\", \"Full Stack Developer\", 2200000, \"Banglore\")] schema = [\"Id\", \"Name\", \"Job Profile\", \"Salary\", \"City\"] # calling function to create dataframe df = create_df(spark, input_data, schema) # getting each row of dataframe containing # only selected columns Selected columns are # 'Name' and 'Salary' getting the list of rows # with selected column data using collect() rows_looped = df.select(\"Name\", \"Salary\").collect() # printing the data of each row for rows in rows_looped: # here index 0 and 1 refers to the data # of 'Name' column and 'Salary' column print(rows[0], rows[1])",
"e": 7176,
"s": 5609,
"text": null
},
{
"code": null,
"e": 7184,
"s": 7176,
"text": "Output:"
},
{
"code": null,
"e": 7199,
"s": 7184,
"text": "sagartomar9927"
},
{
"code": null,
"e": 7211,
"s": 7199,
"text": "anikaseth98"
},
{
"code": null,
"e": 7218,
"s": 7211,
"text": "Picked"
},
{
"code": null,
"e": 7233,
"s": 7218,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 7240,
"s": 7233,
"text": "Python"
},
{
"code": null,
"e": 7338,
"s": 7240,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7356,
"s": 7338,
"text": "Python Dictionary"
},
{
"code": null,
"e": 7398,
"s": 7356,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 7420,
"s": 7398,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 7452,
"s": 7420,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 7481,
"s": 7452,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 7508,
"s": 7481,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 7544,
"s": 7508,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 7575,
"s": 7544,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 7612,
"s": 7575,
"text": "Create a Pandas DataFrame from Lists"
}
]
|
PostgreSQL - NULL Values | The PostgreSQL NULL is the term used to represent a missing value. A NULL value in a table is a value in a field that appears to be blank.
A field with a NULL value is a field with no value. It is very important to understand that a NULL value is different from a zero value or a field that contains spaces.
The basic syntax of using NULL while creating a table is as follows −
CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
Here, NOT NULL signifies that column should always accept an explicit value of the given data type. There are two columns where we did not use NOT NULL. Hence, this means these columns could be NULL.
A field with a NULL value is one that has been left blank during record creation.
The NULL value can cause problems when selecting data, because when comparing an unknown value to any other value, the result is always unknown and not included in the final results. Consider the following table, COMPANY having the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Let us use the UPDATE statement to set few nullable values as NULL as follows −
testdb=# UPDATE COMPANY SET ADDRESS = NULL, SALARY = NULL where ID IN(6,7);
Now, COMPANY table should have the following records −
id | name | age | address | salary
----+-------+-----+-------------+--------
1 | Paul | 32 | California | 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | |
7 | James | 24 | |
(7 rows)
Next, let us see the usage of IS NOT NULL operator to list down all the records where SALARY is not NULL −
testdb=# SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM COMPANY
WHERE SALARY IS NOT NULL;
The above given PostgreSQL statement will produce the following result −
id | name | age | address | salary
----+-------+-----+------------+--------
1 | Paul | 32 | California | 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
(5 rows)
The following is the usage of IS NULL operator which will list down all the records where SALARY is NULL −
testdb=# SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM COMPANY
WHERE SALARY IS NULL;
The above given PostgreSQL statement will produce the following result −
id | name | age | address | salary
----+-------+-----+---------+--------
6 | Kim | 22 | |
7 | James | 24 | | | [
{
"code": null,
"e": 3098,
"s": 2959,
"text": "The PostgreSQL NULL is the term used to represent a missing value. A NULL value in a table is a value in a field that appears to be blank."
},
{
"code": null,
"e": 3267,
"s": 3098,
"text": "A field with a NULL value is a field with no value. It is very important to understand that a NULL value is different from a zero value or a field that contains spaces."
},
{
"code": null,
"e": 3337,
"s": 3267,
"text": "The basic syntax of using NULL while creating a table is as follows −"
},
{
"code": null,
"e": 3522,
"s": 3337,
"text": "CREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL\n);\n"
},
{
"code": null,
"e": 3724,
"s": 3522,
"text": "Here, NOT NULL signifies that column should always accept an explicit value of the given data type. There are two columns where we did not use NOT NULL. Hence, this means these columns could be NULL.\n"
},
{
"code": null,
"e": 3806,
"s": 3724,
"text": "A field with a NULL value is one that has been left blank during record creation."
},
{
"code": null,
"e": 4058,
"s": 3806,
"text": "The NULL value can cause problems when selecting data, because when comparing an unknown value to any other value, the result is always unknown and not included in the final results. Consider the following table, COMPANY having the following records −"
},
{
"code": null,
"e": 4564,
"s": 4058,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 4644,
"s": 4564,
"text": "Let us use the UPDATE statement to set few nullable values as NULL as follows −"
},
{
"code": null,
"e": 4720,
"s": 4644,
"text": "testdb=# UPDATE COMPANY SET ADDRESS = NULL, SALARY = NULL where ID IN(6,7);"
},
{
"code": null,
"e": 4775,
"s": 4720,
"text": "Now, COMPANY table should have the following records −"
},
{
"code": null,
"e": 5140,
"s": 4775,
"text": " id | name | age | address | salary\n----+-------+-----+-------------+--------\n 1 | Paul | 32 | California | 20000\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n 6 | Kim | 22 | |\n 7 | James | 24 | |\n(7 rows)"
},
{
"code": null,
"e": 5247,
"s": 5140,
"text": "Next, let us see the usage of IS NOT NULL operator to list down all the records where SALARY is not NULL −"
},
{
"code": null,
"e": 5341,
"s": 5247,
"text": "testdb=# SELECT ID, NAME, AGE, ADDRESS, SALARY\n FROM COMPANY\n WHERE SALARY IS NOT NULL;"
},
{
"code": null,
"e": 5414,
"s": 5341,
"text": "The above given PostgreSQL statement will produce the following result −"
},
{
"code": null,
"e": 5705,
"s": 5414,
"text": " id | name | age | address | salary\n----+-------+-----+------------+--------\n 1 | Paul | 32 | California | 20000\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n(5 rows)\n"
},
{
"code": null,
"e": 5813,
"s": 5705,
"text": "The following is the usage of IS NULL operator which will list down all the records where SALARY is NULL −"
},
{
"code": null,
"e": 5913,
"s": 5813,
"text": "testdb=# SELECT ID, NAME, AGE, ADDRESS, SALARY\n FROM COMPANY\n WHERE SALARY IS NULL;"
},
{
"code": null,
"e": 5986,
"s": 5913,
"text": "The above given PostgreSQL statement will produce the following result −"
}
]
|
Python | fsum() function | 18 Sep, 2018
fsum() is inbuilt function in Python, used to find sum between some range or an iterable. To use this function we need to import the math library.
Syntax :
maths.fsum( iterable )
Parameter :
iterable : Here we pass some value
which is iterable like arrays, list.
Use :
fsum() is used to find the sum
of some range, array , list.
Return Type :
The function return a
floating point number.
Code demonstrating fsum() :
# Python code to demonstrate use # of math.fsum() function # fsum() is found in math libraryimport math # range(10)print(math.fsum(range(10))) # Integer listarr = [1, 4, 6]print(math.fsum(arr)) # Floating point listarr = [2.5, 2.4, 3.09]print(math.fsum(arr))
Output :
45.0
11.0
7.99
Python-Functions
python-list
python-list-functions
Python
python-list
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": "\n18 Sep, 2018"
},
{
"code": null,
"e": 175,
"s": 28,
"text": "fsum() is inbuilt function in Python, used to find sum between some range or an iterable. To use this function we need to import the math library."
},
{
"code": null,
"e": 184,
"s": 175,
"text": "Syntax :"
},
{
"code": null,
"e": 208,
"s": 184,
"text": "maths.fsum( iterable )\n"
},
{
"code": null,
"e": 220,
"s": 208,
"text": "Parameter :"
},
{
"code": null,
"e": 292,
"s": 220,
"text": "iterable : Here we pass some value\nwhich is iterable like arrays, list."
},
{
"code": null,
"e": 298,
"s": 292,
"text": "Use :"
},
{
"code": null,
"e": 358,
"s": 298,
"text": "fsum() is used to find the sum\nof some range, array , list."
},
{
"code": null,
"e": 372,
"s": 358,
"text": "Return Type :"
},
{
"code": null,
"e": 417,
"s": 372,
"text": "The function return a\nfloating point number."
},
{
"code": null,
"e": 447,
"s": 419,
"text": "Code demonstrating fsum() :"
},
{
"code": "# Python code to demonstrate use # of math.fsum() function # fsum() is found in math libraryimport math # range(10)print(math.fsum(range(10))) # Integer listarr = [1, 4, 6]print(math.fsum(arr)) # Floating point listarr = [2.5, 2.4, 3.09]print(math.fsum(arr))",
"e": 711,
"s": 447,
"text": null
},
{
"code": null,
"e": 720,
"s": 711,
"text": "Output :"
},
{
"code": null,
"e": 736,
"s": 720,
"text": "45.0\n11.0\n7.99\n"
},
{
"code": null,
"e": 753,
"s": 736,
"text": "Python-Functions"
},
{
"code": null,
"e": 765,
"s": 753,
"text": "python-list"
},
{
"code": null,
"e": 787,
"s": 765,
"text": "python-list-functions"
},
{
"code": null,
"e": 794,
"s": 787,
"text": "Python"
},
{
"code": null,
"e": 806,
"s": 794,
"text": "python-list"
},
{
"code": null,
"e": 904,
"s": 806,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 936,
"s": 904,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 963,
"s": 936,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 994,
"s": 963,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1017,
"s": 994,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1038,
"s": 1017,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1094,
"s": 1038,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1136,
"s": 1094,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1178,
"s": 1136,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1217,
"s": 1178,
"text": "Python | Get unique values from a list"
}
]
|
SQLite - Perl | In this chapter, you will learn how to use SQLite in Perl programs.
SQLite3 can be integrated with Perl using Perl DBI module, which is a database access module for the Perl programming language. It defines a set of methods, variables, and conventions that provide a standard database interface.
Following are simple steps to install DBI module on your Linux/UNIX machine −
$ wget http://search.cpan.org/CPAN/authors/id/T/TI/TIMB/DBI-1.625.tar.gz
$ tar xvfz DBI-1.625.tar.gz
$ cd DBI-1.625
$ perl Makefile.PL
$ make
$ make install
If you need to install SQLite driver for DBI, then it can be installed as follows −
$ wget http://search.cpan.org/CPAN/authors/id/M/MS/MSERGEANT/DBD-SQLite-1.11.tar.gz
$ tar xvfz DBD-SQLite-1.11.tar.gz
$ cd DBD-SQLite-1.11
$ perl Makefile.PL
$ make
$ make install
Following are important DBI routines, which can suffice your requirement to work with SQLite database from your Perl program. If you are looking for a more sophisticated application, then you can look into Perl DBI official documentation.
DBI->connect($data_source, "", "", \%attr)
Establishes a database connection, or session, to the requested $data_source. Returns a database handle object if the connection succeeds.
Datasource has the form like − DBI:SQLite:dbname = 'test.db' where SQLite is SQLite driver name and test.db is the name of SQLite database file. If the filename is given as ':memory:', it will create an in-memory database in RAM that lasts only for the duration of the session.
If the filename is actual device file name, then it attempts to open the database file by using its value. If no file by that name exists, then a new database file by that name gets created.
You keep second and third parameter as blank strings and the last parameter is to pass various attributes as shown in the following example.
$dbh->do($sql)
This routine prepares and executes a single SQL statement. Returns the number of rows affected or undef on error. A return value of -1 means the number of rows is not known, not applicable, or not available. Here, $dbh is a handle returned by DBI->connect() call.
$dbh->prepare($sql)
This routine prepares a statement for later execution by the database engine and returns a reference to a statement handle object.
$sth->execute()
This routine performs whatever processing is necessary to execute the prepared statement. An undef is returned if an error occurs. A successful execute always returns true regardless of the number of rows affected. Here, $sth is a statement handle returned by $dbh->prepare($sql) call.
$sth->fetchrow_array()
This routine fetches the next row of data and returns it as a list containing the field values. Null fields are returned as undef values in the list.
$DBI::err
This is equivalent to $h->err, where $h is any of the handle types like $dbh, $sth, or $drh. This returns native database engine error code from the last driver method called.
$DBI::errstr
This is equivalent to $h->errstr, where $h is any of the handle types like $dbh, $sth, or $drh. This returns the native database engine error message from the last DBI method called.
$dbh->disconnect()
This routine closes a database connection previously opened by a call to DBI->connect().
Following Perl code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned.
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
Now, let's run the above program to create our database test.db in the current directory. You can change your path as per your requirement. Keep the above code in sqlite.pl file and execute it as shown below. If the database is successfully created, then it will display the following message −
$ chmod +x sqlite.pl
$ ./sqlite.pl
Open database successfully
Following Perl program is used to create a table in the previously created database.
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
my $stmt = qq(CREATE TABLE COMPANY
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL););
my $rv = $dbh->do($stmt);
if($rv < 0) {
print $DBI::errstr;
} else {
print "Table created successfully\n";
}
$dbh->disconnect();
When the above program is executed, it will create COMPANY table in your test.db and it will display the following messages −
Opened database successfully
Table created successfully
NOTE − In case you see the following error in any of the operation −
DBD::SQLite::st execute failed: not an error(21) at dbdimp.c line 398
In such case, open dbdimp.c file available in DBD-SQLite installation and find out sqlite3_prepare() function and change its third argument to -1 instead of 0. Finally, install DBD::SQLite using make and do make install to resolve the problem.
Following Perl program shows how to create records in the COMPANY table created in the above example.
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
my $stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Paul', 32, 'California', 20000.00 ));
my $rv = $dbh->do($stmt) or die $DBI::errstr;
$stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Allen', 25, 'Texas', 15000.00 ));
$rv = $dbh->do($stmt) or die $DBI::errstr;
$stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'Teddy', 23, 'Norway', 20000.00 ));
$rv = $dbh->do($stmt) or die $DBI::errstr;
$stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 ););
$rv = $dbh->do($stmt) or die $DBI::errstr;
print "Records created successfully\n";
$dbh->disconnect();
When the above program is executed, it will create the given records in the COMPANY table and it will display the following two lines −
Opened database successfully
Records created successfully
Following Perl program shows how to fetch and display records from the COMPANY table created in the above example.
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
my $stmt = qq(SELECT id, name, address, salary from COMPANY;);
my $sth = $dbh->prepare( $stmt );
my $rv = $sth->execute() or die $DBI::errstr;
if($rv < 0) {
print $DBI::errstr;
}
while(my @row = $sth->fetchrow_array()) {
print "ID = ". $row[0] . "\n";
print "NAME = ". $row[1] ."\n";
print "ADDRESS = ". $row[2] ."\n";
print "SALARY = ". $row[3] ."\n\n";
}
print "Operation done successfully\n";
$dbh->disconnect();
When the above program is executed, it will produce the following result.
Opened database successfully
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
Operation done successfully
Following Perl code shows how to UPDATE statement to update any record and then fetch and display the updated records from the COMPANY table.
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
my $stmt = qq(UPDATE COMPANY set SALARY = 25000.00 where ID=1;);
my $rv = $dbh->do($stmt) or die $DBI::errstr;
if( $rv < 0 ) {
print $DBI::errstr;
} else {
print "Total number of rows updated : $rv\n";
}
$stmt = qq(SELECT id, name, address, salary from COMPANY;);
my $sth = $dbh->prepare( $stmt );
$rv = $sth->execute() or die $DBI::errstr;
if($rv < 0) {
print $DBI::errstr;
}
while(my @row = $sth->fetchrow_array()) {
print "ID = ". $row[0] . "\n";
print "NAME = ". $row[1] ."\n";
print "ADDRESS = ". $row[2] ."\n";
print "SALARY = ". $row[3] ."\n\n";
}
print "Operation done successfully\n";
$dbh->disconnect();
When the above program is executed, it will produce the following result.
Opened database successfully
Total number of rows updated : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 25000
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
Operation done successfully
Following Perl code shows how to use DELETE statement to delete any record and then fetch and display the remaining records from the COMPANY table −
#!/usr/bin/perl
use DBI;
use strict;
my $driver = "SQLite";
my $database = "test.db";
my $dsn = "DBI:$driver:dbname=$database";
my $userid = "";
my $password = "";
my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })
or die $DBI::errstr;
print "Opened database successfully\n";
my $stmt = qq(DELETE from COMPANY where ID = 2;);
my $rv = $dbh->do($stmt) or die $DBI::errstr;
if( $rv < 0 ) {
print $DBI::errstr;
} else {
print "Total number of rows deleted : $rv\n";
}
$stmt = qq(SELECT id, name, address, salary from COMPANY;);
my $sth = $dbh->prepare( $stmt );
$rv = $sth->execute() or die $DBI::errstr;
if($rv < 0) {
print $DBI::errstr;
}
while(my @row = $sth->fetchrow_array()) {
print "ID = ". $row[0] . "\n";
print "NAME = ". $row[1] ."\n";
print "ADDRESS = ". $row[2] ."\n";
print "SALARY = ". $row[3] ."\n\n";
}
print "Operation done successfully\n";
$dbh->disconnect();
When the above program is executed, it will produce the following result.
Opened database successfully
Total number of rows deleted : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 25000
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000
Operation done successfully | [
{
"code": null,
"e": 2840,
"s": 2772,
"text": "In this chapter, you will learn how to use SQLite in Perl programs."
},
{
"code": null,
"e": 3068,
"s": 2840,
"text": "SQLite3 can be integrated with Perl using Perl DBI module, which is a database access module for the Perl programming language. It defines a set of methods, variables, and conventions that provide a standard database interface."
},
{
"code": null,
"e": 3146,
"s": 3068,
"text": "Following are simple steps to install DBI module on your Linux/UNIX machine −"
},
{
"code": null,
"e": 3303,
"s": 3146,
"text": "$ wget http://search.cpan.org/CPAN/authors/id/T/TI/TIMB/DBI-1.625.tar.gz\n$ tar xvfz DBI-1.625.tar.gz\n$ cd DBI-1.625\n$ perl Makefile.PL\n$ make\n$ make install"
},
{
"code": null,
"e": 3387,
"s": 3303,
"text": "If you need to install SQLite driver for DBI, then it can be installed as follows −"
},
{
"code": null,
"e": 3567,
"s": 3387,
"text": "$ wget http://search.cpan.org/CPAN/authors/id/M/MS/MSERGEANT/DBD-SQLite-1.11.tar.gz\n$ tar xvfz DBD-SQLite-1.11.tar.gz\n$ cd DBD-SQLite-1.11\n$ perl Makefile.PL\n$ make\n$ make install"
},
{
"code": null,
"e": 3806,
"s": 3567,
"text": "Following are important DBI routines, which can suffice your requirement to work with SQLite database from your Perl program. If you are looking for a more sophisticated application, then you can look into Perl DBI official documentation."
},
{
"code": null,
"e": 3849,
"s": 3806,
"text": "DBI->connect($data_source, \"\", \"\", \\%attr)"
},
{
"code": null,
"e": 3988,
"s": 3849,
"text": "Establishes a database connection, or session, to the requested $data_source. Returns a database handle object if the connection succeeds."
},
{
"code": null,
"e": 4266,
"s": 3988,
"text": "Datasource has the form like − DBI:SQLite:dbname = 'test.db' where SQLite is SQLite driver name and test.db is the name of SQLite database file. If the filename is given as ':memory:', it will create an in-memory database in RAM that lasts only for the duration of the session."
},
{
"code": null,
"e": 4457,
"s": 4266,
"text": "If the filename is actual device file name, then it attempts to open the database file by using its value. If no file by that name exists, then a new database file by that name gets created."
},
{
"code": null,
"e": 4598,
"s": 4457,
"text": "You keep second and third parameter as blank strings and the last parameter is to pass various attributes as shown in the following example."
},
{
"code": null,
"e": 4613,
"s": 4598,
"text": "$dbh->do($sql)"
},
{
"code": null,
"e": 4877,
"s": 4613,
"text": "This routine prepares and executes a single SQL statement. Returns the number of rows affected or undef on error. A return value of -1 means the number of rows is not known, not applicable, or not available. Here, $dbh is a handle returned by DBI->connect() call."
},
{
"code": null,
"e": 4897,
"s": 4877,
"text": "$dbh->prepare($sql)"
},
{
"code": null,
"e": 5028,
"s": 4897,
"text": "This routine prepares a statement for later execution by the database engine and returns a reference to a statement handle object."
},
{
"code": null,
"e": 5044,
"s": 5028,
"text": "$sth->execute()"
},
{
"code": null,
"e": 5330,
"s": 5044,
"text": "This routine performs whatever processing is necessary to execute the prepared statement. An undef is returned if an error occurs. A successful execute always returns true regardless of the number of rows affected. Here, $sth is a statement handle returned by $dbh->prepare($sql) call."
},
{
"code": null,
"e": 5353,
"s": 5330,
"text": "$sth->fetchrow_array()"
},
{
"code": null,
"e": 5503,
"s": 5353,
"text": "This routine fetches the next row of data and returns it as a list containing the field values. Null fields are returned as undef values in the list."
},
{
"code": null,
"e": 5513,
"s": 5503,
"text": "$DBI::err"
},
{
"code": null,
"e": 5689,
"s": 5513,
"text": "This is equivalent to $h->err, where $h is any of the handle types like $dbh, $sth, or $drh. This returns native database engine error code from the last driver method called."
},
{
"code": null,
"e": 5702,
"s": 5689,
"text": "$DBI::errstr"
},
{
"code": null,
"e": 5885,
"s": 5702,
"text": "This is equivalent to $h->errstr, where $h is any of the handle types like $dbh, $sth, or $drh. This returns the native database engine error message from the last DBI method called."
},
{
"code": null,
"e": 5904,
"s": 5885,
"text": "$dbh->disconnect()"
},
{
"code": null,
"e": 5993,
"s": 5904,
"text": "This routine closes a database connection previously opened by a call to DBI->connect()."
},
{
"code": null,
"e": 6163,
"s": 5993,
"text": "Following Perl code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned."
},
{
"code": null,
"e": 6468,
"s": 6163,
"text": "#!/usr/bin/perl\n\nuse DBI;\nuse strict;\n\nmy $driver = \"SQLite\"; \nmy $database = \"test.db\";\nmy $dsn = \"DBI:$driver:dbname=$database\";\nmy $userid = \"\";\nmy $password = \"\";\nmy $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 }) \n or die $DBI::errstr;\n\nprint \"Opened database successfully\\n\";"
},
{
"code": null,
"e": 6763,
"s": 6468,
"text": "Now, let's run the above program to create our database test.db in the current directory. You can change your path as per your requirement. Keep the above code in sqlite.pl file and execute it as shown below. If the database is successfully created, then it will display the following message −"
},
{
"code": null,
"e": 6825,
"s": 6763,
"text": "$ chmod +x sqlite.pl\n$ ./sqlite.pl\nOpen database successfully"
},
{
"code": null,
"e": 6910,
"s": 6825,
"text": "Following Perl program is used to create a table in the previously created database."
},
{
"code": null,
"e": 7560,
"s": 6910,
"text": "#!/usr/bin/perl\n\nuse DBI;\nuse strict;\n\nmy $driver = \"SQLite\";\nmy $database = \"test.db\";\nmy $dsn = \"DBI:$driver:dbname=$database\";\nmy $userid = \"\";\nmy $password = \"\";\nmy $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })\n or die $DBI::errstr;\nprint \"Opened database successfully\\n\";\n\nmy $stmt = qq(CREATE TABLE COMPANY\n (ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL););\n\nmy $rv = $dbh->do($stmt);\nif($rv < 0) {\n print $DBI::errstr;\n} else {\n print \"Table created successfully\\n\";\n}\n$dbh->disconnect();"
},
{
"code": null,
"e": 7686,
"s": 7560,
"text": "When the above program is executed, it will create COMPANY table in your test.db and it will display the following messages −"
},
{
"code": null,
"e": 7743,
"s": 7686,
"text": "Opened database successfully\nTable created successfully\n"
},
{
"code": null,
"e": 7812,
"s": 7743,
"text": "NOTE − In case you see the following error in any of the operation −"
},
{
"code": null,
"e": 7883,
"s": 7812,
"text": "DBD::SQLite::st execute failed: not an error(21) at dbdimp.c line 398\n"
},
{
"code": null,
"e": 8127,
"s": 7883,
"text": "In such case, open dbdimp.c file available in DBD-SQLite installation and find out sqlite3_prepare() function and change its third argument to -1 instead of 0. Finally, install DBD::SQLite using make and do make install to resolve the problem."
},
{
"code": null,
"e": 8229,
"s": 8127,
"text": "Following Perl program shows how to create records in the COMPANY table created in the above example."
},
{
"code": null,
"e": 9270,
"s": 8229,
"text": "#!/usr/bin/perl\n\nuse DBI;\nuse strict;\n\nmy $driver = \"SQLite\";\nmy $database = \"test.db\";\nmy $dsn = \"DBI:$driver:dbname=$database\";\nmy $userid = \"\";\nmy $password = \"\";\nmy $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })\n or die $DBI::errstr;\nprint \"Opened database successfully\\n\";\n\nmy $stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\n VALUES (1, 'Paul', 32, 'California', 20000.00 ));\nmy $rv = $dbh->do($stmt) or die $DBI::errstr;\n\n$stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\n VALUES (2, 'Allen', 25, 'Texas', 15000.00 ));\n$rv = $dbh->do($stmt) or die $DBI::errstr;\n\n$stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\n VALUES (3, 'Teddy', 23, 'Norway', 20000.00 ));\n\n$rv = $dbh->do($stmt) or die $DBI::errstr;\n\n$stmt = qq(INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\n VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 ););\n\n$rv = $dbh->do($stmt) or die $DBI::errstr;\n\nprint \"Records created successfully\\n\";\n$dbh->disconnect();"
},
{
"code": null,
"e": 9406,
"s": 9270,
"text": "When the above program is executed, it will create the given records in the COMPANY table and it will display the following two lines −"
},
{
"code": null,
"e": 9465,
"s": 9406,
"text": "Opened database successfully\nRecords created successfully\n"
},
{
"code": null,
"e": 9580,
"s": 9465,
"text": "Following Perl program shows how to fetch and display records from the COMPANY table created in the above example."
},
{
"code": null,
"e": 10327,
"s": 9580,
"text": "#!/usr/bin/perl\n\nuse DBI;\nuse strict;\n\nmy $driver = \"SQLite\";\nmy $database = \"test.db\";\nmy $dsn = \"DBI:$driver:dbname=$database\";\nmy $userid = \"\";\nmy $password = \"\";\nmy $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })\n or die $DBI::errstr;\nprint \"Opened database successfully\\n\";\n\nmy $stmt = qq(SELECT id, name, address, salary from COMPANY;);\nmy $sth = $dbh->prepare( $stmt );\nmy $rv = $sth->execute() or die $DBI::errstr;\n\nif($rv < 0) {\n print $DBI::errstr;\n}\n\nwhile(my @row = $sth->fetchrow_array()) {\n print \"ID = \". $row[0] . \"\\n\";\n print \"NAME = \". $row[1] .\"\\n\";\n print \"ADDRESS = \". $row[2] .\"\\n\";\n print \"SALARY = \". $row[3] .\"\\n\\n\";\n}\nprint \"Operation done successfully\\n\";\n$dbh->disconnect();"
},
{
"code": null,
"e": 10401,
"s": 10327,
"text": "When the above program is executed, it will produce the following result."
},
{
"code": null,
"e": 10679,
"s": 10401,
"text": "Opened database successfully\nID = 1\nNAME = Paul\nADDRESS = California\nSALARY = 20000\n\nID = 2\nNAME = Allen\nADDRESS = Texas\nSALARY = 15000\n\nID = 3\nNAME = Teddy\nADDRESS = Norway\nSALARY = 20000\n\nID = 4\nNAME = Mark\nADDRESS = Rich-Mond\nSALARY = 65000\n\nOperation done successfully\n"
},
{
"code": null,
"e": 10821,
"s": 10679,
"text": "Following Perl code shows how to UPDATE statement to update any record and then fetch and display the updated records from the COMPANY table."
},
{
"code": null,
"e": 11775,
"s": 10821,
"text": "#!/usr/bin/perl\n\nuse DBI;\nuse strict;\n\nmy $driver = \"SQLite\";\nmy $database = \"test.db\";\nmy $dsn = \"DBI:$driver:dbname=$database\";\nmy $userid = \"\";\nmy $password = \"\";\nmy $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })\n or die $DBI::errstr;\nprint \"Opened database successfully\\n\";\n\nmy $stmt = qq(UPDATE COMPANY set SALARY = 25000.00 where ID=1;);\nmy $rv = $dbh->do($stmt) or die $DBI::errstr;\n\nif( $rv < 0 ) {\n print $DBI::errstr;\n} else {\n print \"Total number of rows updated : $rv\\n\";\n}\n$stmt = qq(SELECT id, name, address, salary from COMPANY;);\nmy $sth = $dbh->prepare( $stmt );\n$rv = $sth->execute() or die $DBI::errstr;\n\nif($rv < 0) {\n print $DBI::errstr;\n}\n\nwhile(my @row = $sth->fetchrow_array()) {\n print \"ID = \". $row[0] . \"\\n\";\n print \"NAME = \". $row[1] .\"\\n\";\n print \"ADDRESS = \". $row[2] .\"\\n\";\n print \"SALARY = \". $row[3] .\"\\n\\n\";\n}\nprint \"Operation done successfully\\n\";\n$dbh->disconnect();"
},
{
"code": null,
"e": 11849,
"s": 11775,
"text": "When the above program is executed, it will produce the following result."
},
{
"code": null,
"e": 12160,
"s": 11849,
"text": "Opened database successfully\nTotal number of rows updated : 1\nID = 1\nNAME = Paul\nADDRESS = California\nSALARY = 25000\n\nID = 2\nNAME = Allen\nADDRESS = Texas\nSALARY = 15000\n\nID = 3\nNAME = Teddy\nADDRESS = Norway\nSALARY = 20000\n\nID = 4\nNAME = Mark\nADDRESS = Rich-Mond\nSALARY = 65000\n\nOperation done successfully\n"
},
{
"code": null,
"e": 12309,
"s": 12160,
"text": "Following Perl code shows how to use DELETE statement to delete any record and then fetch and display the remaining records from the COMPANY table −"
},
{
"code": null,
"e": 13249,
"s": 12309,
"text": "#!/usr/bin/perl\n\nuse DBI;\nuse strict;\n\nmy $driver = \"SQLite\";\nmy $database = \"test.db\";\nmy $dsn = \"DBI:$driver:dbname=$database\";\nmy $userid = \"\";\nmy $password = \"\";\nmy $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 })\n or die $DBI::errstr;\nprint \"Opened database successfully\\n\";\n\nmy $stmt = qq(DELETE from COMPANY where ID = 2;);\nmy $rv = $dbh->do($stmt) or die $DBI::errstr;\n\nif( $rv < 0 ) {\n print $DBI::errstr;\n} else {\n print \"Total number of rows deleted : $rv\\n\";\n}\n\n$stmt = qq(SELECT id, name, address, salary from COMPANY;);\nmy $sth = $dbh->prepare( $stmt );\n$rv = $sth->execute() or die $DBI::errstr;\n\nif($rv < 0) {\n print $DBI::errstr;\n}\n\nwhile(my @row = $sth->fetchrow_array()) {\n print \"ID = \". $row[0] . \"\\n\";\n print \"NAME = \". $row[1] .\"\\n\";\n print \"ADDRESS = \". $row[2] .\"\\n\";\n print \"SALARY = \". $row[3] .\"\\n\\n\";\n}\nprint \"Operation done successfully\\n\";\n$dbh->disconnect();"
},
{
"code": null,
"e": 13323,
"s": 13249,
"text": "When the above program is executed, it will produce the following result."
}
]
|
Graph Coloring | Set 2 (Greedy Algorithm) | 24 Nov, 2021
We introduced graph coloring and applications in previous post. As discussed in the previous post, graph coloring is widely used. Unfortunately, there is no efficient algorithm available for coloring a graph with minimum number of colors as the problem is a known NP Complete problem. There are approximate algorithms to solve the problem though. Following is the basic Greedy Algorithm to assign colors. It doesn’t guarantee to use minimum colors, but it guarantees an upper bound on the number of colors. The basic algorithm never uses more than d+1 colors where d is the maximum degree of a vertex in the given graph.
Basic Greedy Coloring Algorithm:
1. Color first vertex with first color. 2. Do following for remaining V-1 vertices. ..... a) Consider the currently picked vertex and color it with the lowest numbered color that has not been used on any previously colored vertices adjacent to it. If all previously used colors appear on vertices adjacent to v, assign a new color to it.
Following is the implementation of the above Greedy Algorithm.
C++
Java
Python3
Javascript
// A C++ program to implement greedy algorithm for graph coloring#include <iostream>#include <list>using namespace std; // A class that represents an undirected graphclass Graph{ int V; // No. of vertices list<int> *adj; // A dynamic array of adjacency listspublic: // Constructor and destructor Graph(int V) { this->V = V; adj = new list<int>[V]; } ~Graph() { delete [] adj; } // function to add an edge to graph void addEdge(int v, int w); // Prints greedy coloring of the vertices void greedyColoring();}; void Graph::addEdge(int v, int w){ adj[v].push_back(w); adj[w].push_back(v); // Note: the graph is undirected} // Assigns colors (starting from 0) to all vertices and prints// the assignment of colorsvoid Graph::greedyColoring(){ int result[V]; // Assign the first color to first vertex result[0] = 0; // Initialize remaining V-1 vertices as unassigned for (int u = 1; u < V; u++) result[u] = -1; // no color is assigned to u // A temporary array to store the available colors. True // value of available[cr] would mean that the color cr is // assigned to one of its adjacent vertices bool available[V]; for (int cr = 0; cr < V; cr++) available[cr] = false; // Assign colors to remaining V-1 vertices for (int u = 1; u < V; u++) { // Process all adjacent vertices and flag their colors // as unavailable list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) if (result[*i] != -1) available[result[*i]] = true; // Find the first available color int cr; for (cr = 0; cr < V; cr++) if (available[cr] == false) break; result[u] = cr; // Assign the found color // Reset the values back to false for the next iteration for (i = adj[u].begin(); i != adj[u].end(); ++i) if (result[*i] != -1) available[result[*i]] = false; } // print the result for (int u = 0; u < V; u++) cout << "Vertex " << u << " ---> Color " << result[u] << endl;} // Driver program to test above functionint main(){ Graph g1(5); g1.addEdge(0, 1); g1.addEdge(0, 2); g1.addEdge(1, 2); g1.addEdge(1, 3); g1.addEdge(2, 3); g1.addEdge(3, 4); cout << "Coloring of graph 1 \n"; g1.greedyColoring(); Graph g2(5); g2.addEdge(0, 1); g2.addEdge(0, 2); g2.addEdge(1, 2); g2.addEdge(1, 4); g2.addEdge(2, 4); g2.addEdge(4, 3); cout << "\nColoring of graph 2 \n"; g2.greedyColoring(); return 0;}
// A Java program to implement greedy algorithm for graph coloringimport java.io.*;import java.util.*;import java.util.LinkedList; // This class represents an undirected graph using adjacency listclass Graph{ private int V; // No. of vertices private LinkedList<Integer> adj[]; //Adjacency List //Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } //Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); adj[w].add(v); //Graph is undirected } // Assigns colors (starting from 0) to all vertices and // prints the assignment of colors void greedyColoring() { int result[] = new int[V]; // Initialize all vertices as unassigned Arrays.fill(result, -1); // Assign the first color to first vertex result[0] = 0; // A temporary array to store the available colors. False // value of available[cr] would mean that the color cr is // assigned to one of its adjacent vertices boolean available[] = new boolean[V]; // Initially, all colors are available Arrays.fill(available, true); // Assign colors to remaining V-1 vertices for (int u = 1; u < V; u++) { // Process all adjacent vertices and flag their colors // as unavailable Iterator<Integer> it = adj[u].iterator() ; while (it.hasNext()) { int i = it.next(); if (result[i] != -1) available[result[i]] = false; } // Find the first available color int cr; for (cr = 0; cr < V; cr++){ if (available[cr]) break; } result[u] = cr; // Assign the found color // Reset the values back to true for the next iteration Arrays.fill(available, true); } // print the result for (int u = 0; u < V; u++) System.out.println("Vertex " + u + " ---> Color " + result[u]); } // Driver method public static void main(String args[]) { Graph g1 = new Graph(5); g1.addEdge(0, 1); g1.addEdge(0, 2); g1.addEdge(1, 2); g1.addEdge(1, 3); g1.addEdge(2, 3); g1.addEdge(3, 4); System.out.println("Coloring of graph 1"); g1.greedyColoring(); System.out.println(); Graph g2 = new Graph(5); g2.addEdge(0, 1); g2.addEdge(0, 2); g2.addEdge(1, 2); g2.addEdge(1, 4); g2.addEdge(2, 4); g2.addEdge(4, 3); System.out.println("Coloring of graph 2 "); g2.greedyColoring(); }}// This code is contributed by Aakash Hasija
# Python3 program to implement greedy# algorithm for graph coloring def addEdge(adj, v, w): adj[v].append(w) # Note: the graph is undirected adj[w].append(v) return adj # Assigns colors (starting from 0) to all# vertices and prints the assignment of colorsdef greedyColoring(adj, V): result = [-1] * V # Assign the first color to first vertex result[0] = 0; # A temporary array to store the available colors. # True value of available[cr] would mean that the # color cr is assigned to one of its adjacent vertices available = [False] * V # Assign colors to remaining V-1 vertices for u in range(1, V): # Process all adjacent vertices and # flag their colors as unavailable for i in adj[u]: if (result[i] != -1): available[result[i]] = True # Find the first available color cr = 0 while cr < V: if (available[cr] == False): break cr += 1 # Assign the found color result[u] = cr # Reset the values back to false # for the next iteration for i in adj[u]: if (result[i] != -1): available[result[i]] = False # Print the result for u in range(V): print("Vertex", u, " ---> Color", result[u]) # Driver Codeif __name__ == '__main__': g1 = [[] for i in range(5)] g1 = addEdge(g1, 0, 1) g1 = addEdge(g1, 0, 2) g1 = addEdge(g1, 1, 2) g1 = addEdge(g1, 1, 3) g1 = addEdge(g1, 2, 3) g1 = addEdge(g1, 3, 4) print("Coloring of graph 1 ") greedyColoring(g1, 5) g2 = [[] for i in range(5)] g2 = addEdge(g2, 0, 1) g2 = addEdge(g2, 0, 2) g2 = addEdge(g2, 1, 2) g2 = addEdge(g2, 1, 4) g2 = addEdge(g2, 2, 4) g2 = addEdge(g2, 4, 3) print("\nColoring of graph 2") greedyColoring(g2, 5) # This code is contributed by mohit kumar 29
<script> // Javascript program to implement greedy// algorithm for graph coloring // This class represents a directed graph// using adjacency list representationclass Graph{ // Constructorconstructor(v){ this.V = v; this.adj = new Array(v); for(let i = 0; i < v; ++i) this.adj[i] = []; this.Time = 0;} // Function to add an edge into the graphaddEdge(v,w){ this.adj[v].push(w); // Graph is undirected this.adj[w].push(v);} // Assigns colors (starting from 0) to all// vertices and prints the assignment of colorsgreedyColoring(){ let result = new Array(this.V); // Initialize all vertices as unassigned for(let i = 0; i < this.V; i++) result[i] = -1; // Assign the first color to first vertex result[0] = 0; // A temporary array to store the available // colors. False value of available[cr] would // mean that the color cr is assigned to one // of its adjacent vertices let available = new Array(this.V); // Initially, all colors are available for(let i = 0; i < this.V; i++) available[i] = true; // Assign colors to remaining V-1 vertices for(let u = 1; u < this.V; u++) { // Process all adjacent vertices and // flag their colors as unavailable for(let it of this.adj[u]) { let i = it; if (result[i] != -1) available[result[i]] = false; } // Find the first available color let cr; for(cr = 0; cr < this.V; cr++) { if (available[cr]) break; } // Assign the found color result[u] = cr; // Reset the values back to true // for the next iteration for(let i = 0; i < this.V; i++) available[i] = true; } // print the result for(let u = 0; u < this.V; u++) document.write("Vertex " + u + " ---> Color " + result[u] + "<br>");}} // Driver codelet g1 = new Graph(5);g1.addEdge(0, 1);g1.addEdge(0, 2);g1.addEdge(1, 2);g1.addEdge(1, 3);g1.addEdge(2, 3);g1.addEdge(3, 4);document.write("Coloring of graph 1<br>");g1.greedyColoring(); document.write("<br>");let g2 = new Graph(5);g2.addEdge(0, 1);g2.addEdge(0, 2);g2.addEdge(1, 2);g2.addEdge(1, 4);g2.addEdge(2, 4);g2.addEdge(4, 3);document.write("Coloring of graph 2<br> ");g2.greedyColoring(); // This code is contributed by avanitrachhadiya2155 </script>
Output:
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.
Coloring of graph 1
Vertex 0 ---> Color 0
Vertex 1 ---> Color 1
Vertex 2 ---> Color 2
Vertex 3 ---> Color 0
Vertex 4 ---> Color 1
Coloring of graph 2
Vertex 0 ---> Color 0
Vertex 1 ---> Color 1
Vertex 2 ---> Color 2
Vertex 3 ---> Color 0
Vertex 4 ---> Color 3
Time Complexity: O(V^2 + E) in worst case.
Analysis of Basic Algorithm The above algorithm doesn’t always use minimum number of colors. Also, the number of colors used sometime depend on the order in which vertices are processed. For example, consider the following two graphs. Note that in graph on right side, vertices 3 and 4 are swapped. If we consider the vertices 0, 1, 2, 3, 4 in left graph, we can color the graph using 3 colors. But if we consider the vertices 0, 1, 2, 3, 4 in right graph, we need 4 colors.
So the order in which the vertices are picked is important. Many people have suggested different ways to find an ordering that work better than the basic algorithm on average. The most common is Welsh–Powell Algorithm which considers vertices in descending order of degrees.
How does the basic algorithm guarantee an upper bound of d+1? Here d is the maximum degree in the given graph. Since d is maximum degree, a vertex cannot be attached to more than d vertices. When we color a vertex, at most d colors could have already been used by its adjacent. To color this vertex, we need to pick the smallest numbered color that is not used by the adjacent vertices. If colors are numbered like 1, 2, ...., then the value of such smallest number must be between 1 to d+1 (Note that d numbers are already picked by adjacent vertices). This can also be proved using induction. See this video lecture for proof. We will soon be discussing some interesting facts about chromatic number and graph coloring.
Graph Coloring | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersGraph Coloring | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:34•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=_sdVx_dWnlk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
ChamanJhinga
mohit kumar 29
avanitrachhadiya2155
kapoorsagar226
Graph Coloring
Graph
Greedy
Greedy
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Breadth First Search or BFS for a Graph
Depth First Search or DFS for a Graph
Graph and its representations
Topological Sorting
Detect Cycle in a Directed Graph
Program for array rotation
Write a program to print all permutations of a given string
Coin Change | DP-7
Minimum Number of Platforms Required for a Railway/Bus Station
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 675,
"s": 54,
"text": "We introduced graph coloring and applications in previous post. As discussed in the previous post, graph coloring is widely used. Unfortunately, there is no efficient algorithm available for coloring a graph with minimum number of colors as the problem is a known NP Complete problem. There are approximate algorithms to solve the problem though. Following is the basic Greedy Algorithm to assign colors. It doesn’t guarantee to use minimum colors, but it guarantees an upper bound on the number of colors. The basic algorithm never uses more than d+1 colors where d is the maximum degree of a vertex in the given graph."
},
{
"code": null,
"e": 709,
"s": 675,
"text": "Basic Greedy Coloring Algorithm: "
},
{
"code": null,
"e": 1047,
"s": 709,
"text": "1. Color first vertex with first color. 2. Do following for remaining V-1 vertices. ..... a) Consider the currently picked vertex and color it with the lowest numbered color that has not been used on any previously colored vertices adjacent to it. If all previously used colors appear on vertices adjacent to v, assign a new color to it."
},
{
"code": null,
"e": 1110,
"s": 1047,
"text": "Following is the implementation of the above Greedy Algorithm."
},
{
"code": null,
"e": 1114,
"s": 1110,
"text": "C++"
},
{
"code": null,
"e": 1119,
"s": 1114,
"text": "Java"
},
{
"code": null,
"e": 1127,
"s": 1119,
"text": "Python3"
},
{
"code": null,
"e": 1138,
"s": 1127,
"text": "Javascript"
},
{
"code": "// A C++ program to implement greedy algorithm for graph coloring#include <iostream>#include <list>using namespace std; // A class that represents an undirected graphclass Graph{ int V; // No. of vertices list<int> *adj; // A dynamic array of adjacency listspublic: // Constructor and destructor Graph(int V) { this->V = V; adj = new list<int>[V]; } ~Graph() { delete [] adj; } // function to add an edge to graph void addEdge(int v, int w); // Prints greedy coloring of the vertices void greedyColoring();}; void Graph::addEdge(int v, int w){ adj[v].push_back(w); adj[w].push_back(v); // Note: the graph is undirected} // Assigns colors (starting from 0) to all vertices and prints// the assignment of colorsvoid Graph::greedyColoring(){ int result[V]; // Assign the first color to first vertex result[0] = 0; // Initialize remaining V-1 vertices as unassigned for (int u = 1; u < V; u++) result[u] = -1; // no color is assigned to u // A temporary array to store the available colors. True // value of available[cr] would mean that the color cr is // assigned to one of its adjacent vertices bool available[V]; for (int cr = 0; cr < V; cr++) available[cr] = false; // Assign colors to remaining V-1 vertices for (int u = 1; u < V; u++) { // Process all adjacent vertices and flag their colors // as unavailable list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) if (result[*i] != -1) available[result[*i]] = true; // Find the first available color int cr; for (cr = 0; cr < V; cr++) if (available[cr] == false) break; result[u] = cr; // Assign the found color // Reset the values back to false for the next iteration for (i = adj[u].begin(); i != adj[u].end(); ++i) if (result[*i] != -1) available[result[*i]] = false; } // print the result for (int u = 0; u < V; u++) cout << \"Vertex \" << u << \" ---> Color \" << result[u] << endl;} // Driver program to test above functionint main(){ Graph g1(5); g1.addEdge(0, 1); g1.addEdge(0, 2); g1.addEdge(1, 2); g1.addEdge(1, 3); g1.addEdge(2, 3); g1.addEdge(3, 4); cout << \"Coloring of graph 1 \\n\"; g1.greedyColoring(); Graph g2(5); g2.addEdge(0, 1); g2.addEdge(0, 2); g2.addEdge(1, 2); g2.addEdge(1, 4); g2.addEdge(2, 4); g2.addEdge(4, 3); cout << \"\\nColoring of graph 2 \\n\"; g2.greedyColoring(); return 0;}",
"e": 3760,
"s": 1138,
"text": null
},
{
"code": "// A Java program to implement greedy algorithm for graph coloringimport java.io.*;import java.util.*;import java.util.LinkedList; // This class represents an undirected graph using adjacency listclass Graph{ private int V; // No. of vertices private LinkedList<Integer> adj[]; //Adjacency List //Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } //Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); adj[w].add(v); //Graph is undirected } // Assigns colors (starting from 0) to all vertices and // prints the assignment of colors void greedyColoring() { int result[] = new int[V]; // Initialize all vertices as unassigned Arrays.fill(result, -1); // Assign the first color to first vertex result[0] = 0; // A temporary array to store the available colors. False // value of available[cr] would mean that the color cr is // assigned to one of its adjacent vertices boolean available[] = new boolean[V]; // Initially, all colors are available Arrays.fill(available, true); // Assign colors to remaining V-1 vertices for (int u = 1; u < V; u++) { // Process all adjacent vertices and flag their colors // as unavailable Iterator<Integer> it = adj[u].iterator() ; while (it.hasNext()) { int i = it.next(); if (result[i] != -1) available[result[i]] = false; } // Find the first available color int cr; for (cr = 0; cr < V; cr++){ if (available[cr]) break; } result[u] = cr; // Assign the found color // Reset the values back to true for the next iteration Arrays.fill(available, true); } // print the result for (int u = 0; u < V; u++) System.out.println(\"Vertex \" + u + \" ---> Color \" + result[u]); } // Driver method public static void main(String args[]) { Graph g1 = new Graph(5); g1.addEdge(0, 1); g1.addEdge(0, 2); g1.addEdge(1, 2); g1.addEdge(1, 3); g1.addEdge(2, 3); g1.addEdge(3, 4); System.out.println(\"Coloring of graph 1\"); g1.greedyColoring(); System.out.println(); Graph g2 = new Graph(5); g2.addEdge(0, 1); g2.addEdge(0, 2); g2.addEdge(1, 2); g2.addEdge(1, 4); g2.addEdge(2, 4); g2.addEdge(4, 3); System.out.println(\"Coloring of graph 2 \"); g2.greedyColoring(); }}// This code is contributed by Aakash Hasija",
"e": 6621,
"s": 3760,
"text": null
},
{
"code": "# Python3 program to implement greedy# algorithm for graph coloring def addEdge(adj, v, w): adj[v].append(w) # Note: the graph is undirected adj[w].append(v) return adj # Assigns colors (starting from 0) to all# vertices and prints the assignment of colorsdef greedyColoring(adj, V): result = [-1] * V # Assign the first color to first vertex result[0] = 0; # A temporary array to store the available colors. # True value of available[cr] would mean that the # color cr is assigned to one of its adjacent vertices available = [False] * V # Assign colors to remaining V-1 vertices for u in range(1, V): # Process all adjacent vertices and # flag their colors as unavailable for i in adj[u]: if (result[i] != -1): available[result[i]] = True # Find the first available color cr = 0 while cr < V: if (available[cr] == False): break cr += 1 # Assign the found color result[u] = cr # Reset the values back to false # for the next iteration for i in adj[u]: if (result[i] != -1): available[result[i]] = False # Print the result for u in range(V): print(\"Vertex\", u, \" ---> Color\", result[u]) # Driver Codeif __name__ == '__main__': g1 = [[] for i in range(5)] g1 = addEdge(g1, 0, 1) g1 = addEdge(g1, 0, 2) g1 = addEdge(g1, 1, 2) g1 = addEdge(g1, 1, 3) g1 = addEdge(g1, 2, 3) g1 = addEdge(g1, 3, 4) print(\"Coloring of graph 1 \") greedyColoring(g1, 5) g2 = [[] for i in range(5)] g2 = addEdge(g2, 0, 1) g2 = addEdge(g2, 0, 2) g2 = addEdge(g2, 1, 2) g2 = addEdge(g2, 1, 4) g2 = addEdge(g2, 2, 4) g2 = addEdge(g2, 4, 3) print(\"\\nColoring of graph 2\") greedyColoring(g2, 5) # This code is contributed by mohit kumar 29",
"e": 8566,
"s": 6621,
"text": null
},
{
"code": "<script> // Javascript program to implement greedy// algorithm for graph coloring // This class represents a directed graph// using adjacency list representationclass Graph{ // Constructorconstructor(v){ this.V = v; this.adj = new Array(v); for(let i = 0; i < v; ++i) this.adj[i] = []; this.Time = 0;} // Function to add an edge into the graphaddEdge(v,w){ this.adj[v].push(w); // Graph is undirected this.adj[w].push(v);} // Assigns colors (starting from 0) to all// vertices and prints the assignment of colorsgreedyColoring(){ let result = new Array(this.V); // Initialize all vertices as unassigned for(let i = 0; i < this.V; i++) result[i] = -1; // Assign the first color to first vertex result[0] = 0; // A temporary array to store the available // colors. False value of available[cr] would // mean that the color cr is assigned to one // of its adjacent vertices let available = new Array(this.V); // Initially, all colors are available for(let i = 0; i < this.V; i++) available[i] = true; // Assign colors to remaining V-1 vertices for(let u = 1; u < this.V; u++) { // Process all adjacent vertices and // flag their colors as unavailable for(let it of this.adj[u]) { let i = it; if (result[i] != -1) available[result[i]] = false; } // Find the first available color let cr; for(cr = 0; cr < this.V; cr++) { if (available[cr]) break; } // Assign the found color result[u] = cr; // Reset the values back to true // for the next iteration for(let i = 0; i < this.V; i++) available[i] = true; } // print the result for(let u = 0; u < this.V; u++) document.write(\"Vertex \" + u + \" ---> Color \" + result[u] + \"<br>\");}} // Driver codelet g1 = new Graph(5);g1.addEdge(0, 1);g1.addEdge(0, 2);g1.addEdge(1, 2);g1.addEdge(1, 3);g1.addEdge(2, 3);g1.addEdge(3, 4);document.write(\"Coloring of graph 1<br>\");g1.greedyColoring(); document.write(\"<br>\");let g2 = new Graph(5);g2.addEdge(0, 1);g2.addEdge(0, 2);g2.addEdge(1, 2);g2.addEdge(1, 4);g2.addEdge(2, 4);g2.addEdge(4, 3);document.write(\"Coloring of graph 2<br> \");g2.greedyColoring(); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 11023,
"s": 8566,
"text": null
},
{
"code": null,
"e": 11032,
"s": 11023,
"text": "Output: "
},
{
"code": null,
"e": 11041,
"s": 11032,
"text": "Chapters"
},
{
"code": null,
"e": 11068,
"s": 11041,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 11118,
"s": 11068,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 11141,
"s": 11118,
"text": "captions off, selected"
},
{
"code": null,
"e": 11149,
"s": 11141,
"text": "English"
},
{
"code": null,
"e": 11173,
"s": 11149,
"text": "This is a modal window."
},
{
"code": null,
"e": 11242,
"s": 11173,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 11264,
"s": 11242,
"text": "End of dialog window."
},
{
"code": null,
"e": 11535,
"s": 11264,
"text": "Coloring of graph 1\nVertex 0 ---> Color 0\nVertex 1 ---> Color 1\nVertex 2 ---> Color 2\nVertex 3 ---> Color 0\nVertex 4 ---> Color 1\n\nColoring of graph 2\nVertex 0 ---> Color 0\nVertex 1 ---> Color 1\nVertex 2 ---> Color 2\nVertex 3 ---> Color 0\nVertex 4 ---> Color 3"
},
{
"code": null,
"e": 11578,
"s": 11535,
"text": "Time Complexity: O(V^2 + E) in worst case."
},
{
"code": null,
"e": 12055,
"s": 11578,
"text": "Analysis of Basic Algorithm The above algorithm doesn’t always use minimum number of colors. Also, the number of colors used sometime depend on the order in which vertices are processed. For example, consider the following two graphs. Note that in graph on right side, vertices 3 and 4 are swapped. If we consider the vertices 0, 1, 2, 3, 4 in left graph, we can color the graph using 3 colors. But if we consider the vertices 0, 1, 2, 3, 4 in right graph, we need 4 colors. "
},
{
"code": null,
"e": 12331,
"s": 12055,
"text": "So the order in which the vertices are picked is important. Many people have suggested different ways to find an ordering that work better than the basic algorithm on average. The most common is Welsh–Powell Algorithm which considers vertices in descending order of degrees. "
},
{
"code": null,
"e": 13054,
"s": 12331,
"text": "How does the basic algorithm guarantee an upper bound of d+1? Here d is the maximum degree in the given graph. Since d is maximum degree, a vertex cannot be attached to more than d vertices. When we color a vertex, at most d colors could have already been used by its adjacent. To color this vertex, we need to pick the smallest numbered color that is not used by the adjacent vertices. If colors are numbered like 1, 2, ...., then the value of such smallest number must be between 1 to d+1 (Note that d numbers are already picked by adjacent vertices). This can also be proved using induction. See this video lecture for proof. We will soon be discussing some interesting facts about chromatic number and graph coloring. "
},
{
"code": null,
"e": 13900,
"s": 13054,
"text": "Graph Coloring | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersGraph Coloring | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:34•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=_sdVx_dWnlk\" 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": 14025,
"s": 13900,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 14038,
"s": 14025,
"text": "ChamanJhinga"
},
{
"code": null,
"e": 14053,
"s": 14038,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 14074,
"s": 14053,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 14089,
"s": 14074,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 14104,
"s": 14089,
"text": "Graph Coloring"
},
{
"code": null,
"e": 14110,
"s": 14104,
"text": "Graph"
},
{
"code": null,
"e": 14117,
"s": 14110,
"text": "Greedy"
},
{
"code": null,
"e": 14124,
"s": 14117,
"text": "Greedy"
},
{
"code": null,
"e": 14130,
"s": 14124,
"text": "Graph"
},
{
"code": null,
"e": 14228,
"s": 14130,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14268,
"s": 14228,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 14306,
"s": 14268,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 14336,
"s": 14306,
"text": "Graph and its representations"
},
{
"code": null,
"e": 14356,
"s": 14336,
"text": "Topological Sorting"
},
{
"code": null,
"e": 14389,
"s": 14356,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 14416,
"s": 14389,
"text": "Program for array rotation"
},
{
"code": null,
"e": 14476,
"s": 14416,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 14495,
"s": 14476,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 14558,
"s": 14495,
"text": "Minimum Number of Platforms Required for a Railway/Bus Station"
}
]
|
Find Shortest distance from a guard in a Bank | 04 Jul, 2022
Given a matrix that is filled with ‘O’, ‘G’, and ‘W’ where ‘O’ represents open space, ‘G’ represents guards and ‘W’ represents walls in a Bank. Replace all of the O’s in the matrix with their shortest distance from a guard, without being able to go through any walls. Also, replace the guards with 0 and walls with -1 in output matrix.
Expected Time complexity is O(MN) for a M x N matrix.Expected Auxiliary Space is O(MN) for a M x N matrix.
Examples:
O ==> Open Space
G ==> Guard
W ==> Wall
Input:
O O O O G
O W W O O
O O O W O
G W W W O
O O O O G
Output:
3 3 2 1 0
2 -1 -1 2 1
1 2 3 -1 2
0 -1 -1 -1 1
1 2 2 1 0
The idea is to do BFS. We first enqueue all cells containing the guards and loop till queue is not empty. For each iteration of the loop, we dequeue the front cell from the queue and for each of its four adjacent cells, if cell is an open area and its distance from guard is not calculated yet, we update its distance and enqueue it. Finally after BFS procedure is over, we print the distance matrix.
Below are implementation of above idea –
C++
Java
Python3
C#
Javascript
// C++ program to replace all of the O's in the matrix// with their shortest distance from a guard#include <bits/stdc++.h>using namespace std; // store dimensions of the matrix#define M 5#define N 5 // An Data Structure for queue used in BFSstruct queueNode{ // i, j and distance stores x and y-coordinates // of a matrix cell and its distance from guard // respectively int i, j, distance;}; // These arrays are used to get row and column// numbers of 4 neighbors of a given cellint row[] = { -1, 0, 1, 0};int col[] = { 0, 1, 0, -1 }; // return true if row number and column number// is in rangebool isValid(int i, int j){ if ((i < 0 || i > M - 1) || (j < 0 || j > N - 1)) return false; return true;} // return true if current cell is an open area and its// distance from guard is not calculated yetbool isSafe(int i, int j, char matrix[][N], int output[][N]){ if (matrix[i][j] != 'O' || output[i][j] != -1) return false; return true;} // Function to replace all of the O's in the matrix// with their shortest distance from a guardvoid findDistance(char matrix[][N]){ int output[M][N]; queue<queueNode> q; // finding Guards location and adding into queue for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { // initialize each cell as -1 output[i][j] = -1; if (matrix[i][j] == 'G') { queueNode pos = {i, j, 0}; q.push(pos); // guard has 0 distance output[i][j] = 0; } } } // do till queue is empty while (!q.empty()) { // get the front cell in the queue and update // its adjacent cells queueNode curr = q.front(); int x = curr.i, y = curr.j, dist = curr.distance; // do for each adjacent cell for (int i = 0; i < 4; i++) { // if adjacent cell is valid, has path and // not visited yet, en-queue it. if (isSafe(x + row[i], y + col[i], matrix, output) && isValid(x + row[i], y + col[i])) { output[x + row[i]][y + col[i]] = dist + 1; queueNode pos = {x + row[i], y + col[i], dist + 1}; q.push(pos); } } // dequeue the front cell as its distance is found q.pop(); } // print output matrix for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) cout << std::setw(3) << output[i][j]; cout << endl; }} // Driver codeint main(){ char matrix[][N] = { {'O', 'O', 'O', 'O', 'G'}, {'O', 'W', 'W', 'O', 'O'}, {'O', 'O', 'O', 'W', 'O'}, {'G', 'W', 'W', 'W', 'O'}, {'O', 'O', 'O', 'O', 'G'} }; findDistance(matrix); return 0;}
// Java program to replace all of the O's// in the matrix with their shortest// distance from a guardpackage Graphs; import java.util.LinkedList;import java.util.Queue; public class MinDistanceFromaGuardInBank{ // Store dimensions of the matrixint M = 5;int N = 5; class Node{ int i, j, dist; Node(int i, int j, int dist) { this.i = i; this.j = j; this.dist = dist; }} // These arrays are used to get row// and column numbers of 4 neighbors// of a given cellint row[] = { -1, 0, 1, 0 };int col[] = { 0, 1, 0, -1 }; // Return true if row number and// column number is in rangeboolean isValid(int i, int j){ if ((i < 0 || i > M - 1) || (j < 0 || j > N - 1)) return false; return true;} // Return true if current cell is// an open area and its distance// from guard is not calculated yetboolean isSafe(int i, int j, char matrix[][], int output[][]){ if (matrix[i][j] != 'O' || output[i][j] != -1) return false; return true;} // Function to replace all of the O's// in the matrix with their shortest// distance from a guardvoid findDistance(char matrix[][]){ int output[][] = new int[M][N]; Queue<Node> q = new LinkedList<Node>(); // Finding Guards location and // adding into queue for(int i = 0; i < M; i++) { for(int j = 0; j < N; j++) { // Initialize each cell as -1 output[i][j] = -1; if (matrix[i][j] == 'G') { q.add(new Node(i, j, 0)); // Guard has 0 distance output[i][j] = 0; } } } // Do till queue is empty while (!q.isEmpty()) { // Get the front cell in the queue // and update its adjacent cells Node curr = q.peek(); int x = curr.i; int y = curr.j; int dist = curr.dist; // Do for each adjacent cell for (int i = 0; i < 4; i++) { // If adjacent cell is valid, has // path and not visited yet, // en-queue it. if (isValid(x + row[i], y + col[i])) { if (isSafe(x + row[i], y + col[i], matrix, output)) { output[x + row[i]][y + col[i]] = dist + 1; q.add(new Node(x + row[i], y + col[i], dist + 1)); } } } // Dequeue the front cell as // its distance is found q.poll(); } // Print output matrix for(int i = 0; i < M; i++) { for(int j = 0; j < N; j++) { System.out.print(output[i][j] + " "); } System.out.println(); }} // Driver codepublic static void main(String args[]){ char matrix[][] = { { 'O', 'O', 'O', 'O', 'G' }, { 'O', 'W', 'W', 'O', 'O' }, { 'O', 'O', 'O', 'W', 'O' }, { 'G', 'W', 'W', 'W', 'O' }, { 'O', 'O', 'O', 'O', 'G' } }; MinDistanceFromaGuardInBank g = new MinDistanceFromaGuardInBank(); g.findDistance(matrix);}} // This code is contributed by Shobhit Yadav
# Python3 program to replace all of the O's in the matrix# with their shortest distance from a guardfrom collections import deque as queue # store dimensions of the matrixM = 5N = 5 # These arrays are used to get row and column# numbers of 4 neighbors of a given cellrow = [-1, 0, 1, 0]col = [0, 1, 0, -1] # return true if row number and column number# is in rangedef isValid(i, j): if ((i < 0 or i > M - 1) or (j < 0 or j > N - 1)): return False return True # return true if current cell is an open area and its# distance from guard is not calculated yetdef isSafe(i, j,matrix, output): if (matrix[i][j] != 'O' or output[i][j] != -1): return False return True # Function to replace all of the O's in the matrix# with their shortest distance from a guarddef findDistance(matrix): output = [[ -1 for i in range(N)]for i in range(M)] q = queue() # finding Guards location and adding into queue for i in range(M): for j in range(N): # initialize each cell as -1 output[i][j] = -1 if (matrix[i][j] == 'G'): pos = [i, j, 0] q.appendleft(pos) # guard has 0 distance output[i][j] = 0 # do till queue is empty while (len(q) > 0): # get the front cell in the queue and update # its adjacent cells curr = q.pop() x, y, dist = curr[0], curr[1], curr[2] # do for each adjacent cell for i in range(4): # if adjacent cell is valid, has path and # not visited yet, en-queue it. if isValid(x + row[i], y + col[i]) and isSafe(x + row[i], y + col[i], matrix, output) : output[x + row[i]][y + col[i]] = dist + 1 pos = [x + row[i], y + col[i], dist + 1] q.appendleft(pos) # print output matrix for i in range(M): for j in range(N): if output[i][j] > 0: print(output[i][j], end=" ") else: print(output[i][j],end=" ") print() # Driver code matrix = [['O', 'O', 'O', 'O', 'G'], ['O', 'W', 'W', 'O', 'O'], ['O', 'O', 'O', 'W', 'O'], ['G', 'W', 'W', 'W', 'O'], ['O', 'O', 'O', 'O', 'G']] findDistance(matrix) # This code is contributed by mohit kumar 29
// C# program to replace all of the O's// in the matrix with their shortest// distance from a guardusing System;using System.Collections.Generic;public class Node{ public int i, j, dist; public Node(int i, int j, int dist) { this.i = i; this.j = j; this.dist = dist; }} public class MinDistanceFromaGuardInBank{ // Store dimensions of the matrix static int M = 5; static int N = 5; // These arrays are used to get row // and column numbers of 4 neighbors // of a given cell static int[] row = { -1, 0, 1, 0 }; static int[] col = { 0, 1, 0, -1 }; // Return true if row number and // column number is in range static bool isValid(int i, int j) { if ((i < 0 || i > M - 1) || (j < 0 || j > N - 1)) return false; return true; } // Return true if current cell is // an open area and its distance // from guard is not calculated yet static bool isSafe(int i, int j, char[,] matrix,int[,] output) { if (matrix[i,j] != 'O' || output[i,j] != -1) { return false; } return true; } // Function to replace all of the O's // in the matrix with their shortest // distance from a guard static void findDistance(char[,] matrix) { int[,] output = new int[M,N]; Queue<Node> q = new Queue<Node>(); // Finding Guards location and // adding into queue for(int i = 0; i < M; i++) { for(int j = 0; j < N; j++) { // Initialize each cell as -1 output[i, j] = -1; if (matrix[i, j] == 'G') { q.Enqueue(new Node(i, j, 0)); // Guard has 0 distance output[i, j] = 0; } } } // Do till queue is empty while (q.Count != 0) { // Get the front cell in the queue // and update its adjacent cells Node curr = q.Peek(); int x = curr.i; int y = curr.j; int dist = curr.dist; // Do for each adjacent cell for (int i = 0; i < 4; i++) { // If adjacent cell is valid, has // path and not visited yet, // en-queue it. if (isValid(x + row[i], y + col[i])) { if (isSafe(x + row[i], y + col[i],matrix, output)) { output[x + row[i] , y + col[i]] = dist + 1; q.Enqueue(new Node(x + row[i],y + col[i],dist + 1)); } } } // Dequeue the front cell as // its distance is found q.Dequeue(); } // Print output matrix for(int i = 0; i < M; i++) { for(int j = 0; j < N; j++) { Console.Write(output[i,j] + " "); } Console.WriteLine(); } } // Driver code static public void Main () { char[,] matrix ={ { 'O', 'O', 'O', 'O', 'G' }, { 'O', 'W', 'W', 'O', 'O' }, { 'O', 'O', 'O', 'W', 'O' }, { 'G', 'W', 'W', 'W', 'O' }, { 'O', 'O', 'O', 'O', 'G' } }; findDistance(matrix); }} // This code is contributed by avanitrachhadiya2155
<script>// Javascript program to replace all of the O's// in the matrix with their shortest// distance from a guard // Store dimensions of the matrixlet M = 5;let N = 5; class Node{ constructor(i,j,dist) { this.i = i; this.j = j; this.dist = dist; }} // These arrays are used to get row// and column numbers of 4 neighbors// of a given celllet row=[-1, 0, 1, 0];let col=[0, 1, 0, -1 ]; // Return true if row number and// column number is in rangefunction isValid(i,j){ if ((i < 0 || i > M - 1) || (j < 0 || j > N - 1)) return false; return true;} // Return true if current cell is// an open area and its distance// from guard is not calculated yetfunction isSafe(i,j,matrix,output){ if (matrix[i][j] != 'O' || output[i][j] != -1) return false; return true;} // Function to replace all of the O's// in the matrix with their shortest// distance from a guardfunction findDistance(matrix){ let output = new Array(M); for(let i=0;i<M;i++) { output[i]=new Array(N); } let q = []; // Finding Guards location and // adding into queue for(let i = 0; i < M; i++) { for(let j = 0; j < N; j++) { // Initialize each cell as -1 output[i][j] = -1; if (matrix[i][j] == 'G') { q.push(new Node(i, j, 0)); // Guard has 0 distance output[i][j] = 0; } } } // Do till queue is empty while (q.length!=0) { // Get the front cell in the queue // and update its adjacent cells let curr = q[0]; let x = curr.i; let y = curr.j; let dist = curr.dist; // Do for each adjacent cell for (let i = 0; i < 4; i++) { // If adjacent cell is valid, has // path and not visited yet, // en-queue it. if (isValid(x + row[i], y + col[i])) { if (isSafe(x + row[i], y + col[i], matrix, output)) { output[x + row[i]][y + col[i]] = dist + 1; q.push(new Node(x + row[i], y + col[i], dist + 1)); } } } // Dequeue the front cell as // its distance is found q.shift(); } // Print output matrix for(let i = 0; i < M; i++) { for(let j = 0; j < N; j++) { document.write(output[i][j] + " "); } document.write("<br>"); }} // Driver codelet matrix=[[ 'O', 'O', 'O', 'O', 'G' ], [ 'O', 'W', 'W', 'O', 'O' ], [ 'O', 'O', 'O', 'W', 'O' ], [ 'G', 'W', 'W', 'W', 'O' ], [ 'O', 'O', 'O', 'O', 'G' ]];findDistance(matrix); // This code is contributed by ab2127</script>
3 3 2 1 0
2 -1 -1 2 1
1 2 3 -1 2
0 -1 -1 -1 1
1 2 2 1 0
Time Complexity: O(n*m)Auxiliary Space: O(n*m)
This article is contributed by Aditya Goel. 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.
mohit kumar 29
shobhit999000
avanitrachhadiya2155
ab2127
simmytarika5
shivamanandrj9
hardikkoriintern
Shortest Path
Graph
Matrix
Matrix
Graph
Shortest Path
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 390,
"s": 54,
"text": "Given a matrix that is filled with ‘O’, ‘G’, and ‘W’ where ‘O’ represents open space, ‘G’ represents guards and ‘W’ represents walls in a Bank. Replace all of the O’s in the matrix with their shortest distance from a guard, without being able to go through any walls. Also, replace the guards with 0 and walls with -1 in output matrix."
},
{
"code": null,
"e": 497,
"s": 390,
"text": "Expected Time complexity is O(MN) for a M x N matrix.Expected Auxiliary Space is O(MN) for a M x N matrix."
},
{
"code": null,
"e": 507,
"s": 497,
"text": "Examples:"
},
{
"code": null,
"e": 727,
"s": 507,
"text": "O ==> Open Space\nG ==> Guard\nW ==> Wall\n\nInput: \n O O O O G\n O W W O O\n O O O W O\n G W W W O\n O O O O G\n\nOutput: \n 3 3 2 1 0\n 2 -1 -1 2 1\n 1 2 3 -1 2\n 0 -1 -1 -1 1\n 1 2 2 1 0"
},
{
"code": null,
"e": 1129,
"s": 727,
"text": "The idea is to do BFS. We first enqueue all cells containing the guards and loop till queue is not empty. For each iteration of the loop, we dequeue the front cell from the queue and for each of its four adjacent cells, if cell is an open area and its distance from guard is not calculated yet, we update its distance and enqueue it. Finally after BFS procedure is over, we print the distance matrix. "
},
{
"code": null,
"e": 1172,
"s": 1129,
"text": "Below are implementation of above idea – "
},
{
"code": null,
"e": 1176,
"s": 1172,
"text": "C++"
},
{
"code": null,
"e": 1181,
"s": 1176,
"text": "Java"
},
{
"code": null,
"e": 1189,
"s": 1181,
"text": "Python3"
},
{
"code": null,
"e": 1192,
"s": 1189,
"text": "C#"
},
{
"code": null,
"e": 1203,
"s": 1192,
"text": "Javascript"
},
{
"code": "// C++ program to replace all of the O's in the matrix// with their shortest distance from a guard#include <bits/stdc++.h>using namespace std; // store dimensions of the matrix#define M 5#define N 5 // An Data Structure for queue used in BFSstruct queueNode{ // i, j and distance stores x and y-coordinates // of a matrix cell and its distance from guard // respectively int i, j, distance;}; // These arrays are used to get row and column// numbers of 4 neighbors of a given cellint row[] = { -1, 0, 1, 0};int col[] = { 0, 1, 0, -1 }; // return true if row number and column number// is in rangebool isValid(int i, int j){ if ((i < 0 || i > M - 1) || (j < 0 || j > N - 1)) return false; return true;} // return true if current cell is an open area and its// distance from guard is not calculated yetbool isSafe(int i, int j, char matrix[][N], int output[][N]){ if (matrix[i][j] != 'O' || output[i][j] != -1) return false; return true;} // Function to replace all of the O's in the matrix// with their shortest distance from a guardvoid findDistance(char matrix[][N]){ int output[M][N]; queue<queueNode> q; // finding Guards location and adding into queue for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { // initialize each cell as -1 output[i][j] = -1; if (matrix[i][j] == 'G') { queueNode pos = {i, j, 0}; q.push(pos); // guard has 0 distance output[i][j] = 0; } } } // do till queue is empty while (!q.empty()) { // get the front cell in the queue and update // its adjacent cells queueNode curr = q.front(); int x = curr.i, y = curr.j, dist = curr.distance; // do for each adjacent cell for (int i = 0; i < 4; i++) { // if adjacent cell is valid, has path and // not visited yet, en-queue it. if (isSafe(x + row[i], y + col[i], matrix, output) && isValid(x + row[i], y + col[i])) { output[x + row[i]][y + col[i]] = dist + 1; queueNode pos = {x + row[i], y + col[i], dist + 1}; q.push(pos); } } // dequeue the front cell as its distance is found q.pop(); } // print output matrix for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) cout << std::setw(3) << output[i][j]; cout << endl; }} // Driver codeint main(){ char matrix[][N] = { {'O', 'O', 'O', 'O', 'G'}, {'O', 'W', 'W', 'O', 'O'}, {'O', 'O', 'O', 'W', 'O'}, {'G', 'W', 'W', 'W', 'O'}, {'O', 'O', 'O', 'O', 'G'} }; findDistance(matrix); return 0;}",
"e": 4013,
"s": 1203,
"text": null
},
{
"code": "// Java program to replace all of the O's// in the matrix with their shortest// distance from a guardpackage Graphs; import java.util.LinkedList;import java.util.Queue; public class MinDistanceFromaGuardInBank{ // Store dimensions of the matrixint M = 5;int N = 5; class Node{ int i, j, dist; Node(int i, int j, int dist) { this.i = i; this.j = j; this.dist = dist; }} // These arrays are used to get row// and column numbers of 4 neighbors// of a given cellint row[] = { -1, 0, 1, 0 };int col[] = { 0, 1, 0, -1 }; // Return true if row number and// column number is in rangeboolean isValid(int i, int j){ if ((i < 0 || i > M - 1) || (j < 0 || j > N - 1)) return false; return true;} // Return true if current cell is// an open area and its distance// from guard is not calculated yetboolean isSafe(int i, int j, char matrix[][], int output[][]){ if (matrix[i][j] != 'O' || output[i][j] != -1) return false; return true;} // Function to replace all of the O's// in the matrix with their shortest// distance from a guardvoid findDistance(char matrix[][]){ int output[][] = new int[M][N]; Queue<Node> q = new LinkedList<Node>(); // Finding Guards location and // adding into queue for(int i = 0; i < M; i++) { for(int j = 0; j < N; j++) { // Initialize each cell as -1 output[i][j] = -1; if (matrix[i][j] == 'G') { q.add(new Node(i, j, 0)); // Guard has 0 distance output[i][j] = 0; } } } // Do till queue is empty while (!q.isEmpty()) { // Get the front cell in the queue // and update its adjacent cells Node curr = q.peek(); int x = curr.i; int y = curr.j; int dist = curr.dist; // Do for each adjacent cell for (int i = 0; i < 4; i++) { // If adjacent cell is valid, has // path and not visited yet, // en-queue it. if (isValid(x + row[i], y + col[i])) { if (isSafe(x + row[i], y + col[i], matrix, output)) { output[x + row[i]][y + col[i]] = dist + 1; q.add(new Node(x + row[i], y + col[i], dist + 1)); } } } // Dequeue the front cell as // its distance is found q.poll(); } // Print output matrix for(int i = 0; i < M; i++) { for(int j = 0; j < N; j++) { System.out.print(output[i][j] + \" \"); } System.out.println(); }} // Driver codepublic static void main(String args[]){ char matrix[][] = { { 'O', 'O', 'O', 'O', 'G' }, { 'O', 'W', 'W', 'O', 'O' }, { 'O', 'O', 'O', 'W', 'O' }, { 'G', 'W', 'W', 'W', 'O' }, { 'O', 'O', 'O', 'O', 'G' } }; MinDistanceFromaGuardInBank g = new MinDistanceFromaGuardInBank(); g.findDistance(matrix);}} // This code is contributed by Shobhit Yadav",
"e": 7382,
"s": 4013,
"text": null
},
{
"code": "# Python3 program to replace all of the O's in the matrix# with their shortest distance from a guardfrom collections import deque as queue # store dimensions of the matrixM = 5N = 5 # These arrays are used to get row and column# numbers of 4 neighbors of a given cellrow = [-1, 0, 1, 0]col = [0, 1, 0, -1] # return true if row number and column number# is in rangedef isValid(i, j): if ((i < 0 or i > M - 1) or (j < 0 or j > N - 1)): return False return True # return true if current cell is an open area and its# distance from guard is not calculated yetdef isSafe(i, j,matrix, output): if (matrix[i][j] != 'O' or output[i][j] != -1): return False return True # Function to replace all of the O's in the matrix# with their shortest distance from a guarddef findDistance(matrix): output = [[ -1 for i in range(N)]for i in range(M)] q = queue() # finding Guards location and adding into queue for i in range(M): for j in range(N): # initialize each cell as -1 output[i][j] = -1 if (matrix[i][j] == 'G'): pos = [i, j, 0] q.appendleft(pos) # guard has 0 distance output[i][j] = 0 # do till queue is empty while (len(q) > 0): # get the front cell in the queue and update # its adjacent cells curr = q.pop() x, y, dist = curr[0], curr[1], curr[2] # do for each adjacent cell for i in range(4): # if adjacent cell is valid, has path and # not visited yet, en-queue it. if isValid(x + row[i], y + col[i]) and isSafe(x + row[i], y + col[i], matrix, output) : output[x + row[i]][y + col[i]] = dist + 1 pos = [x + row[i], y + col[i], dist + 1] q.appendleft(pos) # print output matrix for i in range(M): for j in range(N): if output[i][j] > 0: print(output[i][j], end=\" \") else: print(output[i][j],end=\" \") print() # Driver code matrix = [['O', 'O', 'O', 'O', 'G'], ['O', 'W', 'W', 'O', 'O'], ['O', 'O', 'O', 'W', 'O'], ['G', 'W', 'W', 'W', 'O'], ['O', 'O', 'O', 'O', 'G']] findDistance(matrix) # This code is contributed by mohit kumar 29",
"e": 9725,
"s": 7382,
"text": null
},
{
"code": "// C# program to replace all of the O's// in the matrix with their shortest// distance from a guardusing System;using System.Collections.Generic;public class Node{ public int i, j, dist; public Node(int i, int j, int dist) { this.i = i; this.j = j; this.dist = dist; }} public class MinDistanceFromaGuardInBank{ // Store dimensions of the matrix static int M = 5; static int N = 5; // These arrays are used to get row // and column numbers of 4 neighbors // of a given cell static int[] row = { -1, 0, 1, 0 }; static int[] col = { 0, 1, 0, -1 }; // Return true if row number and // column number is in range static bool isValid(int i, int j) { if ((i < 0 || i > M - 1) || (j < 0 || j > N - 1)) return false; return true; } // Return true if current cell is // an open area and its distance // from guard is not calculated yet static bool isSafe(int i, int j, char[,] matrix,int[,] output) { if (matrix[i,j] != 'O' || output[i,j] != -1) { return false; } return true; } // Function to replace all of the O's // in the matrix with their shortest // distance from a guard static void findDistance(char[,] matrix) { int[,] output = new int[M,N]; Queue<Node> q = new Queue<Node>(); // Finding Guards location and // adding into queue for(int i = 0; i < M; i++) { for(int j = 0; j < N; j++) { // Initialize each cell as -1 output[i, j] = -1; if (matrix[i, j] == 'G') { q.Enqueue(new Node(i, j, 0)); // Guard has 0 distance output[i, j] = 0; } } } // Do till queue is empty while (q.Count != 0) { // Get the front cell in the queue // and update its adjacent cells Node curr = q.Peek(); int x = curr.i; int y = curr.j; int dist = curr.dist; // Do for each adjacent cell for (int i = 0; i < 4; i++) { // If adjacent cell is valid, has // path and not visited yet, // en-queue it. if (isValid(x + row[i], y + col[i])) { if (isSafe(x + row[i], y + col[i],matrix, output)) { output[x + row[i] , y + col[i]] = dist + 1; q.Enqueue(new Node(x + row[i],y + col[i],dist + 1)); } } } // Dequeue the front cell as // its distance is found q.Dequeue(); } // Print output matrix for(int i = 0; i < M; i++) { for(int j = 0; j < N; j++) { Console.Write(output[i,j] + \" \"); } Console.WriteLine(); } } // Driver code static public void Main () { char[,] matrix ={ { 'O', 'O', 'O', 'O', 'G' }, { 'O', 'W', 'W', 'O', 'O' }, { 'O', 'O', 'O', 'W', 'O' }, { 'G', 'W', 'W', 'W', 'O' }, { 'O', 'O', 'O', 'O', 'G' } }; findDistance(matrix); }} // This code is contributed by avanitrachhadiya2155",
"e": 12678,
"s": 9725,
"text": null
},
{
"code": "<script>// Javascript program to replace all of the O's// in the matrix with their shortest// distance from a guard // Store dimensions of the matrixlet M = 5;let N = 5; class Node{ constructor(i,j,dist) { this.i = i; this.j = j; this.dist = dist; }} // These arrays are used to get row// and column numbers of 4 neighbors// of a given celllet row=[-1, 0, 1, 0];let col=[0, 1, 0, -1 ]; // Return true if row number and// column number is in rangefunction isValid(i,j){ if ((i < 0 || i > M - 1) || (j < 0 || j > N - 1)) return false; return true;} // Return true if current cell is// an open area and its distance// from guard is not calculated yetfunction isSafe(i,j,matrix,output){ if (matrix[i][j] != 'O' || output[i][j] != -1) return false; return true;} // Function to replace all of the O's// in the matrix with their shortest// distance from a guardfunction findDistance(matrix){ let output = new Array(M); for(let i=0;i<M;i++) { output[i]=new Array(N); } let q = []; // Finding Guards location and // adding into queue for(let i = 0; i < M; i++) { for(let j = 0; j < N; j++) { // Initialize each cell as -1 output[i][j] = -1; if (matrix[i][j] == 'G') { q.push(new Node(i, j, 0)); // Guard has 0 distance output[i][j] = 0; } } } // Do till queue is empty while (q.length!=0) { // Get the front cell in the queue // and update its adjacent cells let curr = q[0]; let x = curr.i; let y = curr.j; let dist = curr.dist; // Do for each adjacent cell for (let i = 0; i < 4; i++) { // If adjacent cell is valid, has // path and not visited yet, // en-queue it. if (isValid(x + row[i], y + col[i])) { if (isSafe(x + row[i], y + col[i], matrix, output)) { output[x + row[i]][y + col[i]] = dist + 1; q.push(new Node(x + row[i], y + col[i], dist + 1)); } } } // Dequeue the front cell as // its distance is found q.shift(); } // Print output matrix for(let i = 0; i < M; i++) { for(let j = 0; j < N; j++) { document.write(output[i][j] + \" \"); } document.write(\"<br>\"); }} // Driver codelet matrix=[[ 'O', 'O', 'O', 'O', 'G' ], [ 'O', 'W', 'W', 'O', 'O' ], [ 'O', 'O', 'O', 'W', 'O' ], [ 'G', 'W', 'W', 'W', 'O' ], [ 'O', 'O', 'O', 'O', 'G' ]];findDistance(matrix); // This code is contributed by ab2127</script>",
"e": 15727,
"s": 12678,
"text": null
},
{
"code": null,
"e": 15808,
"s": 15727,
"text": " 3 3 2 1 0\n 2 -1 -1 2 1\n 1 2 3 -1 2\n 0 -1 -1 -1 1\n 1 2 2 1 0\n"
},
{
"code": null,
"e": 15855,
"s": 15808,
"text": "Time Complexity: O(n*m)Auxiliary Space: O(n*m)"
},
{
"code": null,
"e": 16151,
"s": 15855,
"text": "This article is contributed by Aditya Goel. 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": 16166,
"s": 16151,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 16180,
"s": 16166,
"text": "shobhit999000"
},
{
"code": null,
"e": 16201,
"s": 16180,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 16208,
"s": 16201,
"text": "ab2127"
},
{
"code": null,
"e": 16221,
"s": 16208,
"text": "simmytarika5"
},
{
"code": null,
"e": 16236,
"s": 16221,
"text": "shivamanandrj9"
},
{
"code": null,
"e": 16253,
"s": 16236,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 16267,
"s": 16253,
"text": "Shortest Path"
},
{
"code": null,
"e": 16273,
"s": 16267,
"text": "Graph"
},
{
"code": null,
"e": 16280,
"s": 16273,
"text": "Matrix"
},
{
"code": null,
"e": 16287,
"s": 16280,
"text": "Matrix"
},
{
"code": null,
"e": 16293,
"s": 16287,
"text": "Graph"
},
{
"code": null,
"e": 16307,
"s": 16293,
"text": "Shortest Path"
}
]
|
How to insert elements in C++ STL List? | Suppose we have one STL list in C++. There are few elements. We have to insert a new element into the list. We can insert at the end, or beginning or at any position. Let us see one code to get better understanding. To insert at beginning we will use push_front(), To insert at end, we will use push_end() and to insert at any position, we have to use some operations. we have to initialize one iterator, then move that iterator to correct position, then insert into that place using insert() method.
Live Demo
#include<iostream>
#include<list>
using namespace std;
void display(list<int> my_list){
for (auto it = my_list.begin(); it != my_list.end(); ++it)
cout << *it << " ";
}
int main() {
int arr[] = {10, 41, 54, 20, 23, 69, 84, 75};
int n = sizeof(arr)/sizeof(arr[0]);
list<int> my_list;
for(int i = 0; i<n; i++){
my_list.push_back(arr[i]);
}
cout << "List before insertion: ";
display(my_list);
//insert 100 at front
my_list.push_front(100);
//insert 500 at back
my_list.push_back(500);
//insert 1000 at index 5
list<int>::iterator it = my_list.begin();
advance(it, 5);
my_list.insert(it, 1000);
cout << "\nList after insertion: ";
display(my_list);
}
List before insertion: 10 41 54 20 23 69 84 75
List after insertion: 100 10 41 54 20 1000 23 69 84 75 500 | [
{
"code": null,
"e": 1563,
"s": 1062,
"text": "Suppose we have one STL list in C++. There are few elements. We have to insert a new element into the list. We can insert at the end, or beginning or at any position. Let us see one code to get better understanding. To insert at beginning we will use push_front(), To insert at end, we will use push_end() and to insert at any position, we have to use some operations. we have to initialize one iterator, then move that iterator to correct position, then insert into that place using insert() method."
},
{
"code": null,
"e": 1574,
"s": 1563,
"text": " Live Demo"
},
{
"code": null,
"e": 2285,
"s": 1574,
"text": "#include<iostream>\n#include<list>\nusing namespace std;\nvoid display(list<int> my_list){\n for (auto it = my_list.begin(); it != my_list.end(); ++it)\n cout << *it << \" \";\n}\nint main() {\n int arr[] = {10, 41, 54, 20, 23, 69, 84, 75};\n int n = sizeof(arr)/sizeof(arr[0]);\n list<int> my_list;\n for(int i = 0; i<n; i++){\n my_list.push_back(arr[i]);\n }\n cout << \"List before insertion: \";\n display(my_list);\n //insert 100 at front\n my_list.push_front(100);\n //insert 500 at back\n my_list.push_back(500);\n //insert 1000 at index 5\n list<int>::iterator it = my_list.begin();\n advance(it, 5);\n my_list.insert(it, 1000);\n cout << \"\\nList after insertion: \";\n display(my_list);\n}"
},
{
"code": null,
"e": 2391,
"s": 2285,
"text": "List before insertion: 10 41 54 20 23 69 84 75\nList after insertion: 100 10 41 54 20 1000 23 69 84 75 500"
}
]
|
Single-Source Shortest Paths, Arbitrary Weights | The single source shortest path algorithm (for arbitrary weight positive or negative) is also known Bellman-Ford algorithm is used to find minimum distance from source vertex to any other vertex. The main difference between this algorithm with Dijkstra’s algorithm is, in Dijkstra’s algorithm we cannot handle the negative weight, but here we can handle it easily.
Bellman-Ford algorithm finds the distance in bottom up manner. At first it finds those distances which have only one edge in the path. After that increase the path length to find all possible solutions.
Input − The cost matrix of the graph:
0 6 ∞ 7 ∞
∞ 0 5 8 -4
∞ -2 0 ∞ ∞
∞ ∞ -3 0 9
2 ∞ 7 ∞ 0
Output − Source Vertex: 2Vert: 0 1 2 3 4Dist: -4 -2 0 3 -6Pred: 4 2 -1 0 1The graph has no negative edge cycle
Input − Distance list, predecessor list and the source vertex.
Output − True, when a negative cycle is found.
Begin
iCount := 1
maxEdge := n * (n - 1) / 2 //n is number of vertices
for all vertices v of the graph, do
dist[v] := ∞
pred[v] := φ
done
dist[source] := 0
eCount := number of edges present in the graph
create edge list named edgeList
while iCount < n, do
for i := 0 to eCount, do
if dist[edgeList[i].v] > dist[edgeList[i].u] + (cost[u,v] for edge i)
dist[edgeList[i].v] > dist[edgeList[i].u] + (cost[u,v] for edge i)
pred[edgeList[i].v] := edgeList[i].u
done
done
iCount := iCount + 1
for all vertices i in the graph, do
if dist[edgeList[i].v] > dist[edgeList[i].u] + (cost[u,v] for edge i), then
return true
done
return false
End
#include<iostream>
#include<iomanip>
#define V 5
#define INF 999
using namespace std;
//Cost matrix of the graph (directed) vertex 5
int costMat[V][V] = {
{0, 6, INF, 7, INF},
{INF, 0, 5, 8, -4},
{INF, -2, 0, INF, INF},
{INF, INF, -3, 0, 9},
{2, INF, 7, INF, 0}
};
typedef struct{
int u, v, cost;
}edge;
int isDiagraph(){
//check the graph is directed graph or not
int i, j;
for(i = 0; i<V; i++){
for(j = 0; j<V; j++){
if(costMat[i][j] != costMat[j][i]){
return 1;//graph is directed
}
}
}
return 0;//graph is undirected
}
int makeEdgeList(edge *eList){
//create edgelist from the edges of graph
int count = -1;
if(isDiagraph()){
for(int i = 0; i<V; i++){
for(int j = 0; j<V; j++){
if(costMat[i][j] != 0 && costMat[i][j] != INF){
count++;//edge find when graph is directed
eList[count].u = i; eList[count].v = j;
eList[count].cost = costMat[i][j];
}
}
}
}else{
for(int i = 0; i<V; i++){
for(int j = 0; j<i; j++){
if(costMat[i][j] != INF){
count++;//edge find when graph is undirected
eList[count].u = i; eList[count].v = j;
eList[count].cost = costMat[i][j];
}
}
}
}
return count+1;
}
int bellmanFord(int *dist, int *pred,int src){
int icount = 1, ecount, max = V*(V-1)/2;
edge edgeList[max];
for(int i = 0; i<V; i++){
dist[i] = INF;//initialize with infinity
pred[i] = -1;//no predecessor found.
}
dist[src] = 0;//for starting vertex, distance is 0
ecount = makeEdgeList(edgeList); //edgeList formation
while(icount < V){ //number of iteration is (Vertex - 1)
for(int i = 0; i<ecount; i++){
if(dist[edgeList[i].v] > dist[edgeList[i].u] + costMat[edgeList[i].u][edgeList[i].v]){
//relax edge and set predecessor
dist[edgeList[i].v] = dist[edgeList[i].u] + costMat[edgeList[i].u][edgeList[i].v];
pred[edgeList[i].v] = edgeList[i].u;
}
}
icount++;
}
//test for negative cycle
for(int i = 0; i<ecount; i++){
if(dist[edgeList[i].v] > dist[edgeList[i].u] + costMat[edgeList[i].u][edgeList[i].v]){
return 1;//indicates the graph has negative cycle
}
}
return 0;//no negative cycle
}
void display(int *dist, int *pred){
cout << "Vert: ";
for(int i = 0; i<V; i++)
cout <<setw(3) << i << " ";
cout << endl;
cout << "Dist: ";
for(int i = 0; i<V; i++)
cout << setw(3) << dist[i] << " ";
cout << endl;
cout << "Pred: ";
for(int i = 0; i<V; i++)
cout << setw(3) << pred[i] << " ";
cout << endl;
}
int main(){
int dist[V], pred[V], source, report;
source = 2;
report = bellmanFord(dist, pred, source);
cout << "Source Vertex: " << source<<endl;
display(dist, pred);
if(report)
cout << "The graph has a negative edge cycle" << endl;
else
cout << "The graph has no negative edge cycle" << endl;
}
Source Vertex: 2
Vert: 0 1 2 3 4
Dist: -4 -2 0 3 -6
Pred: 4 2 -1 0 1
The graph has no negative edge cycle | [
{
"code": null,
"e": 1427,
"s": 1062,
"text": "The single source shortest path algorithm (for arbitrary weight positive or negative) is also known Bellman-Ford algorithm is used to find minimum distance from source vertex to any other vertex. The main difference between this algorithm with Dijkstra’s algorithm is, in Dijkstra’s algorithm we cannot handle the negative weight, but here we can handle it easily."
},
{
"code": null,
"e": 1630,
"s": 1427,
"text": "Bellman-Ford algorithm finds the distance in bottom up manner. At first it finds those distances which have only one edge in the path. After that increase the path length to find all possible solutions."
},
{
"code": null,
"e": 1668,
"s": 1630,
"text": "Input − The cost matrix of the graph:"
},
{
"code": null,
"e": 1721,
"s": 1668,
"text": "0 6 ∞ 7 ∞\n∞ 0 5 8 -4\n∞ -2 0 ∞ ∞\n∞ ∞ -3 0 9\n2 ∞ 7 ∞ 0"
},
{
"code": null,
"e": 1832,
"s": 1721,
"text": "Output − Source Vertex: 2Vert: 0 1 2 3 4Dist: -4 -2 0 3 -6Pred: 4 2 -1 0 1The graph has no negative edge cycle"
},
{
"code": null,
"e": 1895,
"s": 1832,
"text": "Input − Distance list, predecessor list and the source vertex."
},
{
"code": null,
"e": 1942,
"s": 1895,
"text": "Output − True, when a negative cycle is found."
},
{
"code": null,
"e": 2676,
"s": 1942,
"text": "Begin\n iCount := 1\n maxEdge := n * (n - 1) / 2 //n is number of vertices\n for all vertices v of the graph, do\n dist[v] := ∞\n pred[v] := φ\n done\n dist[source] := 0\n eCount := number of edges present in the graph\n create edge list named edgeList\n while iCount < n, do\n for i := 0 to eCount, do\n if dist[edgeList[i].v] > dist[edgeList[i].u] + (cost[u,v] for edge i)\n dist[edgeList[i].v] > dist[edgeList[i].u] + (cost[u,v] for edge i)\n pred[edgeList[i].v] := edgeList[i].u\n done\n done\n iCount := iCount + 1\n for all vertices i in the graph, do\n if dist[edgeList[i].v] > dist[edgeList[i].u] + (cost[u,v] for edge i), then\n return true\n done\n return false\nEnd"
},
{
"code": null,
"e": 5767,
"s": 2676,
"text": "#include<iostream>\n#include<iomanip>\n#define V 5\n#define INF 999\nusing namespace std;\n//Cost matrix of the graph (directed) vertex 5\nint costMat[V][V] = {\n {0, 6, INF, 7, INF},\n {INF, 0, 5, 8, -4},\n {INF, -2, 0, INF, INF},\n {INF, INF, -3, 0, 9},\n {2, INF, 7, INF, 0}\n};\ntypedef struct{\n int u, v, cost;\n}edge;\nint isDiagraph(){\n //check the graph is directed graph or not\n int i, j;\n for(i = 0; i<V; i++){\n for(j = 0; j<V; j++){\n if(costMat[i][j] != costMat[j][i]){\n return 1;//graph is directed\n }\n }\n }\n return 0;//graph is undirected\n}\nint makeEdgeList(edge *eList){\n //create edgelist from the edges of graph\n int count = -1;\n if(isDiagraph()){\n for(int i = 0; i<V; i++){\n for(int j = 0; j<V; j++){\n if(costMat[i][j] != 0 && costMat[i][j] != INF){\n count++;//edge find when graph is directed\n eList[count].u = i; eList[count].v = j;\n eList[count].cost = costMat[i][j];\n }\n }\n }\n }else{\n for(int i = 0; i<V; i++){\n for(int j = 0; j<i; j++){\n if(costMat[i][j] != INF){\n count++;//edge find when graph is undirected\n eList[count].u = i; eList[count].v = j;\n eList[count].cost = costMat[i][j];\n }\n }\n }\n }\n return count+1;\n}\nint bellmanFord(int *dist, int *pred,int src){\n int icount = 1, ecount, max = V*(V-1)/2;\n edge edgeList[max];\n for(int i = 0; i<V; i++){\n dist[i] = INF;//initialize with infinity\n pred[i] = -1;//no predecessor found.\n }\n dist[src] = 0;//for starting vertex, distance is 0\n ecount = makeEdgeList(edgeList); //edgeList formation\n while(icount < V){ //number of iteration is (Vertex - 1)\n for(int i = 0; i<ecount; i++){\n if(dist[edgeList[i].v] > dist[edgeList[i].u] + costMat[edgeList[i].u][edgeList[i].v]){\n //relax edge and set predecessor\n dist[edgeList[i].v] = dist[edgeList[i].u] + costMat[edgeList[i].u][edgeList[i].v];\n pred[edgeList[i].v] = edgeList[i].u;\n }\n }\n icount++;\n }\n //test for negative cycle\n for(int i = 0; i<ecount; i++){\n if(dist[edgeList[i].v] > dist[edgeList[i].u] + costMat[edgeList[i].u][edgeList[i].v]){\n return 1;//indicates the graph has negative cycle\n }\n }\n return 0;//no negative cycle\n}\nvoid display(int *dist, int *pred){\n cout << \"Vert: \";\n for(int i = 0; i<V; i++)\n cout <<setw(3) << i << \" \";\n cout << endl;\n cout << \"Dist: \";\n for(int i = 0; i<V; i++)\n cout << setw(3) << dist[i] << \" \";\n cout << endl;\n cout << \"Pred: \";\n for(int i = 0; i<V; i++)\n cout << setw(3) << pred[i] << \" \";\n cout << endl;\n}\nint main(){\n int dist[V], pred[V], source, report;\n source = 2;\n report = bellmanFord(dist, pred, source);\n cout << \"Source Vertex: \" << source<<endl;\n display(dist, pred);\n if(report)\n cout << \"The graph has a negative edge cycle\" << endl;\n else\n cout << \"The graph has no negative edge cycle\" << endl;\n}"
},
{
"code": null,
"e": 5873,
"s": 5767,
"text": "Source Vertex: 2\nVert: 0 1 2 3 4\nDist: -4 -2 0 3 -6\nPred: 4 2 -1 0 1\nThe graph has no negative edge cycle"
}
]
|
Sum of series 1^2 + 3^2 + 5^2 + . . . + (2*n – 1)^2 | 15 Jun, 2022
Given a series 12 + 32 + 52 + 72 + . . . + (2*n – 1)2, find sum of the series.Examples:
Input : n = 4
Output : 84
Explanation :
sum = 12 + 32 + 52 + 72
= 1 + 9 + 25 + 49
= 84
Input : n = 10
Output : 1330
Explanation :
sum = 12 + 32 + 52 + 72 + 92 + 112 + 132 + 152 + 172 + 192
= 1 + 9 + 24 + 49 + . . . + 361
= 1330
C++
Java
Python3
C#
PHP
Javascript
// Program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2.#include <bits/stdc++.h>using namespace std; // Function to find sum of series.int sumOfSeries(int n){ int sum = 0; for (int i = 1; i <= n; i++) sum = sum + (2 * i - 1) * (2 * i - 1); return sum;} // Driver codeint main(){ int n = 10; cout << sumOfSeries(n); return 0;}
// Program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2. import java.io.*; class GFG { // Function to find sum of series. static int sumOfSeries(int n){ int sum = 0; for (int i = 1; i <= n; i++) sum = sum + (2 * i - 1) * (2 * i - 1); return sum;} // Driver code public static void main(String[] args){ int n = 10; System.out.println( sumOfSeries(n)); } }
# Python Program to find sum of series# 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2. import math # Function to find sum of series.def sumOfSeries(n): sum = 0 for i in range(1,n+1): sum = sum + (2 * i - 1) * (2 * i - 1) return sum # driver coden= 10print(sumOfSeries(n)) # This code is contributed by Gitanjali.
// C# Program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2.using System; class GFG { // Function to find sum of series.static int sumOfSeries(int n){ int sum = 0; for (int i = 1; i <= n; i++) sum = sum + (2 * i - 1) * (2 * i - 1); return sum;} // Driver codepublic static void Main(){ int n = 10; Console.Write( sumOfSeries(n));}} /* This code is contributed by vt_m*/
<?php// PHP Program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2. // Function to find sum of series.function sumOfSeries($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) $sum = $sum + (2 * $i - 1) * (2 * $i - 1); return $sum;} // Driver code$n = 10;echo(sumOfSeries($n)); // This code is contributed by Ajit.?>
<script> // JavaScript program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2. // Function to find sum of series.function sumOfSeries(n){ let sum = 0; for(let i = 1; i <= n; i++) sum = sum + (2 * i - 1) * (2 * i - 1); return sum;} // Driver Codelet n = 10; document.write(sumOfSeries(n)); // This code is contributed by avijitmondal1998 </script>
1330
Time Complexity : O(n)
Auxiliary Space: O(1)
Another approach : Using formula to find sum of series :
12 + 32 + 52 +
72 + . . . + (2*n - 1)2
= (n * (2 * n - 1) * (2 * n + 1)) / 3.
Please refer sum of squares of even and odd numbers for proof.
C++
Java
Python3
C#
PHP
Javascript
// Program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2.#include <bits/stdc++.h>using namespace std; // Function that find sum of series.int sumOfSeries(int n){ // Formula to find sum of series. return (n * (2 * n - 1) * (2 * n + 1)) / 3;} // Driver codeint main(){ int n = 10; cout << sumOfSeries(n); return 0;}
// Java Program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2. import java.io.*;import java.util.*; class GFG { // Function to find sum of series.static int sumOfSeries(int n){ // Formula to find sum of series. return (n * (2 * n - 1) * (2 * n + 1)) / 3; } // Driver function public static void main (String[] args) { int n=10; System.out.println(sumOfSeries(n)); } } // This code is contributed by Gitanjali.
# Python Program to find sum of series# 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2. import math # Function to find sum of series.def sumOfSeries(n): # Formula to find sum of series. return int((n * (2 * n - 1) * (2 * n + 1)) / 3) # driver coden=10print(sumOfSeries(n)) # This code is contributed by Gitanjali.
// C# Program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2.using System; class GFG { // Function to find sum of series.static int sumOfSeries(int n){ // Formula to find sum of series. return (n * (2 * n - 1) * (2 * n + 1)) / 3;} // Driver functionpublic static void Main (){ int n = 10; Console.Write(sumOfSeries(n));}} // This code is contributed by vt_m.
<?php// PHP Program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2. // Function that find sum of series.function sumOfSeries($n){ // Formula to find sum of series. return ($n * (2 * $n - 1) * (2 * $n + 1)) / 3;} // Driver code$n = 10;echo(sumOfSeries($n)); // This code is contributed by Ajit.?>
<script>// Javascript Program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2. // Function that find sum of series.function sumOfSeries(n){ // Formula to find sum of series. return (n * (2 * n - 1) * (2 * n + 1)) / 3;} // Driver codelet n = 10;document.write(sumOfSeries(n)); // This code is contributed by _saurabh_jaiswal. </script>
1330
Time Complexity: O(1)
Auxiliary space: O(1) since using constant variables
jit_t
avijitmondal1998
_saurabh_jaiswal
polymatir3j
series
series-sum
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 117,
"s": 28,
"text": "Given a series 12 + 32 + 52 + 72 + . . . + (2*n – 1)2, find sum of the series.Examples: "
},
{
"code": null,
"e": 364,
"s": 117,
"text": "Input : n = 4\nOutput : 84\nExplanation : \nsum = 12 + 32 + 52 + 72\n = 1 + 9 + 25 + 49\n = 84\n\nInput : n = 10 \nOutput : 1330\nExplanation :\nsum = 12 + 32 + 52 + 72 + 92 + 112 + 132 + 152 + 172 + 192\n = 1 + 9 + 24 + 49 + . . . + 361\n = 1330"
},
{
"code": null,
"e": 368,
"s": 364,
"text": "C++"
},
{
"code": null,
"e": 373,
"s": 368,
"text": "Java"
},
{
"code": null,
"e": 381,
"s": 373,
"text": "Python3"
},
{
"code": null,
"e": 384,
"s": 381,
"text": "C#"
},
{
"code": null,
"e": 388,
"s": 384,
"text": "PHP"
},
{
"code": null,
"e": 399,
"s": 388,
"text": "Javascript"
},
{
"code": "// Program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2.#include <bits/stdc++.h>using namespace std; // Function to find sum of series.int sumOfSeries(int n){ int sum = 0; for (int i = 1; i <= n; i++) sum = sum + (2 * i - 1) * (2 * i - 1); return sum;} // Driver codeint main(){ int n = 10; cout << sumOfSeries(n); return 0;}",
"e": 769,
"s": 399,
"text": null
},
{
"code": "// Program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2. import java.io.*; class GFG { // Function to find sum of series. static int sumOfSeries(int n){ int sum = 0; for (int i = 1; i <= n; i++) sum = sum + (2 * i - 1) * (2 * i - 1); return sum;} // Driver code public static void main(String[] args){ int n = 10; System.out.println( sumOfSeries(n)); } }",
"e": 1173,
"s": 769,
"text": null
},
{
"code": "# Python Program to find sum of series# 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2. import math # Function to find sum of series.def sumOfSeries(n): sum = 0 for i in range(1,n+1): sum = sum + (2 * i - 1) * (2 * i - 1) return sum # driver coden= 10print(sumOfSeries(n)) # This code is contributed by Gitanjali.",
"e": 1499,
"s": 1173,
"text": null
},
{
"code": "// C# Program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2.using System; class GFG { // Function to find sum of series.static int sumOfSeries(int n){ int sum = 0; for (int i = 1; i <= n; i++) sum = sum + (2 * i - 1) * (2 * i - 1); return sum;} // Driver codepublic static void Main(){ int n = 10; Console.Write( sumOfSeries(n));}} /* This code is contributed by vt_m*/",
"e": 1916,
"s": 1499,
"text": null
},
{
"code": "<?php// PHP Program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2. // Function to find sum of series.function sumOfSeries($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) $sum = $sum + (2 * $i - 1) * (2 * $i - 1); return $sum;} // Driver code$n = 10;echo(sumOfSeries($n)); // This code is contributed by Ajit.?>",
"e": 2276,
"s": 1916,
"text": null
},
{
"code": "<script> // JavaScript program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2. // Function to find sum of series.function sumOfSeries(n){ let sum = 0; for(let i = 1; i <= n; i++) sum = sum + (2 * i - 1) * (2 * i - 1); return sum;} // Driver Codelet n = 10; document.write(sumOfSeries(n)); // This code is contributed by avijitmondal1998 </script>",
"e": 2682,
"s": 2276,
"text": null
},
{
"code": null,
"e": 2687,
"s": 2682,
"text": "1330"
},
{
"code": null,
"e": 2712,
"s": 2689,
"text": "Time Complexity : O(n)"
},
{
"code": null,
"e": 2734,
"s": 2712,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2792,
"s": 2734,
"text": "Another approach : Using formula to find sum of series : "
},
{
"code": null,
"e": 2952,
"s": 2792,
"text": " 12 + 32 + 52 + \n 72 + . . . + (2*n - 1)2 \n = (n * (2 * n - 1) * (2 * n + 1)) / 3.\n\n\nPlease refer sum of squares of even and odd numbers for proof."
},
{
"code": null,
"e": 2956,
"s": 2952,
"text": "C++"
},
{
"code": null,
"e": 2961,
"s": 2956,
"text": "Java"
},
{
"code": null,
"e": 2969,
"s": 2961,
"text": "Python3"
},
{
"code": null,
"e": 2972,
"s": 2969,
"text": "C#"
},
{
"code": null,
"e": 2976,
"s": 2972,
"text": "PHP"
},
{
"code": null,
"e": 2987,
"s": 2976,
"text": "Javascript"
},
{
"code": "// Program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2.#include <bits/stdc++.h>using namespace std; // Function that find sum of series.int sumOfSeries(int n){ // Formula to find sum of series. return (n * (2 * n - 1) * (2 * n + 1)) / 3;} // Driver codeint main(){ int n = 10; cout << sumOfSeries(n); return 0;}",
"e": 3332,
"s": 2987,
"text": null
},
{
"code": "// Java Program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2. import java.io.*;import java.util.*; class GFG { // Function to find sum of series.static int sumOfSeries(int n){ // Formula to find sum of series. return (n * (2 * n - 1) * (2 * n + 1)) / 3; } // Driver function public static void main (String[] args) { int n=10; System.out.println(sumOfSeries(n)); } } // This code is contributed by Gitanjali.",
"e": 3778,
"s": 3332,
"text": null
},
{
"code": "# Python Program to find sum of series# 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2. import math # Function to find sum of series.def sumOfSeries(n): # Formula to find sum of series. return int((n * (2 * n - 1) * (2 * n + 1)) / 3) # driver coden=10print(sumOfSeries(n)) # This code is contributed by Gitanjali.",
"e": 4090,
"s": 3778,
"text": null
},
{
"code": "// C# Program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2.using System; class GFG { // Function to find sum of series.static int sumOfSeries(int n){ // Formula to find sum of series. return (n * (2 * n - 1) * (2 * n + 1)) / 3;} // Driver functionpublic static void Main (){ int n = 10; Console.Write(sumOfSeries(n));}} // This code is contributed by vt_m.",
"e": 4480,
"s": 4090,
"text": null
},
{
"code": "<?php// PHP Program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2. // Function that find sum of series.function sumOfSeries($n){ // Formula to find sum of series. return ($n * (2 * $n - 1) * (2 * $n + 1)) / 3;} // Driver code$n = 10;echo(sumOfSeries($n)); // This code is contributed by Ajit.?>",
"e": 4813,
"s": 4480,
"text": null
},
{
"code": "<script>// Javascript Program to find sum of series// 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2. // Function that find sum of series.function sumOfSeries(n){ // Formula to find sum of series. return (n * (2 * n - 1) * (2 * n + 1)) / 3;} // Driver codelet n = 10;document.write(sumOfSeries(n)); // This code is contributed by _saurabh_jaiswal. </script>",
"e": 5184,
"s": 4813,
"text": null
},
{
"code": null,
"e": 5189,
"s": 5184,
"text": "1330"
},
{
"code": null,
"e": 5213,
"s": 5191,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 5267,
"s": 5213,
"text": "Auxiliary space: O(1) since using constant variables "
},
{
"code": null,
"e": 5273,
"s": 5267,
"text": "jit_t"
},
{
"code": null,
"e": 5290,
"s": 5273,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 5307,
"s": 5290,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 5319,
"s": 5307,
"text": "polymatir3j"
},
{
"code": null,
"e": 5326,
"s": 5319,
"text": "series"
},
{
"code": null,
"e": 5337,
"s": 5326,
"text": "series-sum"
},
{
"code": null,
"e": 5350,
"s": 5337,
"text": "Mathematical"
},
{
"code": null,
"e": 5363,
"s": 5350,
"text": "Mathematical"
},
{
"code": null,
"e": 5370,
"s": 5363,
"text": "series"
}
]
|
How to generate Json File in PHP ? | 21 May, 2021
In this article, we are going to generate a JSON file in PHP by using an array. JSON stands for JavaScript object notation, which is used for storing and exchanging data. JSON is text, written with JavaScript object notation.
Structure:
{"data":[
{ "sub_data1":"value1", "sub_data2":"value2","sub_data_n":"value n" },
{ "sub_data2":"value2","sub_data2":"value2", "sub_data_n":"value n" },
{ "sub_data n":"value n ", "sub_data2":"value2","sub_data_n":"value n" }
]}
Example:
[{"id":"7020","name":"Bobby","Subject":"Java"},
{"id":"7021","name":"ojaswi","Subject":"sql"}]
Properties:
JSON doesn’t use an end tagIt is shorter.It is quicker to read and write.It can use arrays.
JSON doesn’t use an end tag
It is shorter.
It is quicker to read and write.
It can use arrays.
Approach: In this article, we can generate JSON data using an array., create an array
Syntax:
$array = Array (
"number" => Array (
"data1" => "value1",
"data2" => "value2",
"data n" => "valuen"
),
"number" => Array (
"data1" => "value1",
"data2" => "value2",
"data n" => "valuen"
)
);
Example:
$array = Array (
"0" => Array (
"id" => "7020",
"name" => "Bobby",
"Subject" => "Java"
),
"1" => Array (
"id" => "7021",
"name" => "ojaswi",
"Subject" => "sql"
)
);
Use json_encode() to convert array to JSON. It is used to convert array to JSON
Syntax:
json_encode(array_input);
Example: Place the file in the path using file_put_contents()
$json = json_encode($array);
The file_name is the JSON to be saved and json_object is the object after JSON from the array is created.
Syntax:
file_put_contents(file_name.json.json_object);
Example:
file_put_contents("geeks_data.json", $json);
PHP code:
PHP
<?php // input data through array$array = Array ( "0" => Array ( "id" => "7020", "name" => "Bobby", "Subject" => "Java" ), "1" => Array ( "id" => "7021", "name" => "ojaswi", "Subject" => "sql" )); // encode array to json$json = json_encode($array);//display it echo "$json";//generate json filefile_put_contents("geeks_data.json", $json); ?>
Output:
[{"id":"7020","name":"Bobby","Subject":"Java"},
{"id":"7021","name":"ojaswi","Subject":"sql"}]
The JSON file is created in your path.
The JSON file is created in your path.
The data present in the created filegeeks_data
The data present in the created file
geeks_data
JSON
PHP-function
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
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": "\n21 May, 2021"
},
{
"code": null,
"e": 254,
"s": 28,
"text": "In this article, we are going to generate a JSON file in PHP by using an array. JSON stands for JavaScript object notation, which is used for storing and exchanging data. JSON is text, written with JavaScript object notation."
},
{
"code": null,
"e": 265,
"s": 254,
"text": "Structure:"
},
{
"code": null,
"e": 496,
"s": 265,
"text": "{\"data\":[\n { \"sub_data1\":\"value1\", \"sub_data2\":\"value2\",\"sub_data_n\":\"value n\" },\n { \"sub_data2\":\"value2\",\"sub_data2\":\"value2\", \"sub_data_n\":\"value n\" },\n { \"sub_data n\":\"value n \", \"sub_data2\":\"value2\",\"sub_data_n\":\"value n\" }\n]}"
},
{
"code": null,
"e": 505,
"s": 496,
"text": "Example:"
},
{
"code": null,
"e": 601,
"s": 505,
"text": "[{\"id\":\"7020\",\"name\":\"Bobby\",\"Subject\":\"Java\"},\n {\"id\":\"7021\",\"name\":\"ojaswi\",\"Subject\":\"sql\"}]"
},
{
"code": null,
"e": 613,
"s": 601,
"text": "Properties:"
},
{
"code": null,
"e": 705,
"s": 613,
"text": "JSON doesn’t use an end tagIt is shorter.It is quicker to read and write.It can use arrays."
},
{
"code": null,
"e": 733,
"s": 705,
"text": "JSON doesn’t use an end tag"
},
{
"code": null,
"e": 748,
"s": 733,
"text": "It is shorter."
},
{
"code": null,
"e": 781,
"s": 748,
"text": "It is quicker to read and write."
},
{
"code": null,
"e": 800,
"s": 781,
"text": "It can use arrays."
},
{
"code": null,
"e": 886,
"s": 800,
"text": "Approach: In this article, we can generate JSON data using an array., create an array"
},
{
"code": null,
"e": 894,
"s": 886,
"text": "Syntax:"
},
{
"code": null,
"e": 1136,
"s": 894,
"text": "$array = Array (\n \"number\" => Array (\n \"data1\" => \"value1\",\n \"data2\" => \"value2\",\n \"data n\" => \"valuen\"\n ),\n \"number\" => Array (\n \"data1\" => \"value1\",\n \"data2\" => \"value2\",\n \"data n\" => \"valuen\"\n )\n);"
},
{
"code": null,
"e": 1145,
"s": 1136,
"text": "Example:"
},
{
"code": null,
"e": 1365,
"s": 1145,
"text": "$array = Array (\n \"0\" => Array (\n \"id\" => \"7020\",\n \"name\" => \"Bobby\",\n \"Subject\" => \"Java\"\n ),\n \"1\" => Array (\n \"id\" => \"7021\",\n \"name\" => \"ojaswi\",\n \"Subject\" => \"sql\"\n )\n);"
},
{
"code": null,
"e": 1445,
"s": 1365,
"text": "Use json_encode() to convert array to JSON. It is used to convert array to JSON"
},
{
"code": null,
"e": 1453,
"s": 1445,
"text": "Syntax:"
},
{
"code": null,
"e": 1479,
"s": 1453,
"text": "json_encode(array_input);"
},
{
"code": null,
"e": 1541,
"s": 1479,
"text": "Example: Place the file in the path using file_put_contents()"
},
{
"code": null,
"e": 1570,
"s": 1541,
"text": "$json = json_encode($array);"
},
{
"code": null,
"e": 1676,
"s": 1570,
"text": "The file_name is the JSON to be saved and json_object is the object after JSON from the array is created."
},
{
"code": null,
"e": 1684,
"s": 1676,
"text": "Syntax:"
},
{
"code": null,
"e": 1731,
"s": 1684,
"text": "file_put_contents(file_name.json.json_object);"
},
{
"code": null,
"e": 1740,
"s": 1731,
"text": "Example:"
},
{
"code": null,
"e": 1785,
"s": 1740,
"text": "file_put_contents(\"geeks_data.json\", $json);"
},
{
"code": null,
"e": 1795,
"s": 1785,
"text": "PHP code:"
},
{
"code": null,
"e": 1799,
"s": 1795,
"text": "PHP"
},
{
"code": "<?php // input data through array$array = Array ( \"0\" => Array ( \"id\" => \"7020\", \"name\" => \"Bobby\", \"Subject\" => \"Java\" ), \"1\" => Array ( \"id\" => \"7021\", \"name\" => \"ojaswi\", \"Subject\" => \"sql\" )); // encode array to json$json = json_encode($array);//display it echo \"$json\";//generate json filefile_put_contents(\"geeks_data.json\", $json); ?>",
"e": 2203,
"s": 1799,
"text": null
},
{
"code": null,
"e": 2211,
"s": 2203,
"text": "Output:"
},
{
"code": null,
"e": 2307,
"s": 2211,
"text": "[{\"id\":\"7020\",\"name\":\"Bobby\",\"Subject\":\"Java\"},\n {\"id\":\"7021\",\"name\":\"ojaswi\",\"Subject\":\"sql\"}]"
},
{
"code": null,
"e": 2346,
"s": 2307,
"text": "The JSON file is created in your path."
},
{
"code": null,
"e": 2385,
"s": 2346,
"text": "The JSON file is created in your path."
},
{
"code": null,
"e": 2432,
"s": 2385,
"text": "The data present in the created filegeeks_data"
},
{
"code": null,
"e": 2469,
"s": 2432,
"text": "The data present in the created file"
},
{
"code": null,
"e": 2480,
"s": 2469,
"text": "geeks_data"
},
{
"code": null,
"e": 2485,
"s": 2480,
"text": "JSON"
},
{
"code": null,
"e": 2498,
"s": 2485,
"text": "PHP-function"
},
{
"code": null,
"e": 2512,
"s": 2498,
"text": "PHP-Questions"
},
{
"code": null,
"e": 2519,
"s": 2512,
"text": "Picked"
},
{
"code": null,
"e": 2523,
"s": 2519,
"text": "PHP"
},
{
"code": null,
"e": 2540,
"s": 2523,
"text": "Web Technologies"
},
{
"code": null,
"e": 2544,
"s": 2540,
"text": "PHP"
},
{
"code": null,
"e": 2642,
"s": 2544,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2687,
"s": 2642,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 2711,
"s": 2687,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 2763,
"s": 2711,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 2813,
"s": 2763,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2853,
"s": 2813,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2886,
"s": 2853,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2948,
"s": 2886,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3009,
"s": 2948,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3059,
"s": 3009,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Difference between array.size() and array.length in JavaScript | 10 Apr, 2022
The array.size() method is functionally equivalent to the array.length property and it can be only used in jQuery. Here in JavaScript array.size() is invalid method so array.length property should be used. Below examples implement the above concept:
Example 1: This example demonstrates array.size() method and array.length property.
html
<!DOCTYPE html><html> <head> <title> Difference between array.size() method and array.length property </title></head> <body> <p> Click the button to display the length of array. </p> <button onclick="findLength()"> Try it </button> <p> Length of the array is: <span id="demo"></span> </p> <script> var arr = ['geeks', 'for', 'geeks']; function findLength() { document.getElementById("demo").innerHTML = arr.length; document.getElementById("demo").innerHTML = arr.size(); } </script></body> </html>
Output:
Length of the array is: 3
error on console: TypeError: arr.size is not a function
Note: The array.length property returns value of last_key+1 for Arrays with numeric index value. This property doesn’t guarantee to find the number of items in the array.
Example 2: This example display how Array.length property works.
html
<!DOCTYPE html><html> <head> <title> Array.length property </title></head> <body> <p> Click the button to display the length of array. </p> <button onclick="findLength()"> Try it </button> <p> Length of array the is: <span id="demo"></span> </p> <script> var arr = ['geeks', 'for', 'geeks']; arr[50] = 'article'; function findLength() { document.getElementById("demo") .innerHTML = arr.length; } </script></body> </html>
Output:
Length of the array is: 51
Example 3: This example display how array.length property works when index key is non numeric.
html
<!DOCTYPE html><html> <head> <title> array.length property with non-numeric index key </title></head> <body> <p> Click the button to display the length of array. </p> <button onclick="findLength()"> Try it </button> <p> Length of array the is: <span id="demo"></span> </p> <script> var arr = new Array(); arr['a'] = 1; arr['b'] = 2; arr['c'] = 3; function findLength() { document.getElementById("demo") .innerHTML = arr.length; } </script></body> </html>
Output:
Length of the array is: 0
Let us see the differences in a tabular form -:
Its syntax is -:
array.size()
Its syntax is -:
array.length
Its supported browsers are -:
Chrome , Internet Explorer, Firefox, Safari, Opera Microsoft Edge
Its supported browsers are -:
Chrome , Internet Explorer, Firefox, Safari, Opera, Microsoft Edge
karthi03
mayank007rawa
JavaScript-Misc
Picked
Technical Scripter 2019
JavaScript
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Apr, 2022"
},
{
"code": null,
"e": 305,
"s": 54,
"text": "The array.size() method is functionally equivalent to the array.length property and it can be only used in jQuery. Here in JavaScript array.size() is invalid method so array.length property should be used. Below examples implement the above concept: "
},
{
"code": null,
"e": 390,
"s": 305,
"text": "Example 1: This example demonstrates array.size() method and array.length property. "
},
{
"code": null,
"e": 395,
"s": 390,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Difference between array.size() method and array.length property </title></head> <body> <p> Click the button to display the length of array. </p> <button onclick=\"findLength()\"> Try it </button> <p> Length of the array is: <span id=\"demo\"></span> </p> <script> var arr = ['geeks', 'for', 'geeks']; function findLength() { document.getElementById(\"demo\").innerHTML = arr.length; document.getElementById(\"demo\").innerHTML = arr.size(); } </script></body> </html>",
"e": 1082,
"s": 395,
"text": null
},
{
"code": null,
"e": 1090,
"s": 1082,
"text": "Output:"
},
{
"code": null,
"e": 1172,
"s": 1090,
"text": "Length of the array is: 3\nerror on console: TypeError: arr.size is not a function"
},
{
"code": null,
"e": 1344,
"s": 1172,
"text": "Note: The array.length property returns value of last_key+1 for Arrays with numeric index value. This property doesn’t guarantee to find the number of items in the array. "
},
{
"code": null,
"e": 1410,
"s": 1344,
"text": "Example 2: This example display how Array.length property works. "
},
{
"code": null,
"e": 1415,
"s": 1410,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Array.length property </title></head> <body> <p> Click the button to display the length of array. </p> <button onclick=\"findLength()\"> Try it </button> <p> Length of array the is: <span id=\"demo\"></span> </p> <script> var arr = ['geeks', 'for', 'geeks']; arr[50] = 'article'; function findLength() { document.getElementById(\"demo\") .innerHTML = arr.length; } </script></body> </html>",
"e": 1986,
"s": 1415,
"text": null
},
{
"code": null,
"e": 1994,
"s": 1986,
"text": "Output:"
},
{
"code": null,
"e": 2021,
"s": 1994,
"text": "Length of the array is: 51"
},
{
"code": null,
"e": 2117,
"s": 2021,
"text": "Example 3: This example display how array.length property works when index key is non numeric. "
},
{
"code": null,
"e": 2122,
"s": 2117,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> array.length property with non-numeric index key </title></head> <body> <p> Click the button to display the length of array. </p> <button onclick=\"findLength()\"> Try it </button> <p> Length of array the is: <span id=\"demo\"></span> </p> <script> var arr = new Array(); arr['a'] = 1; arr['b'] = 2; arr['c'] = 3; function findLength() { document.getElementById(\"demo\") .innerHTML = arr.length; } </script></body> </html>",
"e": 2744,
"s": 2122,
"text": null
},
{
"code": null,
"e": 2752,
"s": 2744,
"text": "Output:"
},
{
"code": null,
"e": 2778,
"s": 2752,
"text": "Length of the array is: 0"
},
{
"code": null,
"e": 2826,
"s": 2778,
"text": "Let us see the differences in a tabular form -:"
},
{
"code": null,
"e": 2843,
"s": 2826,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 2856,
"s": 2843,
"text": "array.size()"
},
{
"code": null,
"e": 2873,
"s": 2856,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 2886,
"s": 2873,
"text": "array.length"
},
{
"code": null,
"e": 2916,
"s": 2886,
"text": "Its supported browsers are -:"
},
{
"code": null,
"e": 2982,
"s": 2916,
"text": "Chrome , Internet Explorer, Firefox, Safari, Opera Microsoft Edge"
},
{
"code": null,
"e": 3012,
"s": 2982,
"text": "Its supported browsers are -:"
},
{
"code": null,
"e": 3079,
"s": 3012,
"text": "Chrome , Internet Explorer, Firefox, Safari, Opera, Microsoft Edge"
},
{
"code": null,
"e": 3088,
"s": 3079,
"text": "karthi03"
},
{
"code": null,
"e": 3102,
"s": 3088,
"text": "mayank007rawa"
},
{
"code": null,
"e": 3118,
"s": 3102,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3125,
"s": 3118,
"text": "Picked"
},
{
"code": null,
"e": 3149,
"s": 3125,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 3160,
"s": 3149,
"text": "JavaScript"
},
{
"code": null,
"e": 3179,
"s": 3160,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3196,
"s": 3179,
"text": "Web Technologies"
},
{
"code": null,
"e": 3223,
"s": 3196,
"text": "Web technologies Questions"
}
]
|
Ruby | DateTime strptime() function | 09 Jan, 2020
DateTime#strptime() : strptime() is a DateTime class method which parses the given representation of date and time with the given template
Syntax: DateTime.strptime()
Parameter: DateTime values
Return: parses the given representation of date and time with the given template
Example #1 :
# Ruby code for DateTime.strptime() method # loading libraryrequire 'date' # declaring DateTime valuedate_a = DateTime.strptime('10-02-2015 05:05:06 PM', '%d-%m-%Y %I:%M:%S %p') # declaring DateTime valuedate_b = DateTime.strptime('2018 02 3 07 10 09 +7', '%Y %U %w %H %M %S %z') # strptime methodputs "DateTime strptime form : #{date_a}\n\n" puts "DateTime strptime form : #{date_b}\n\n"
Output :
DateTime strptime form : 2015-02-10T17:05:06+00:00
DateTime strptime form : 2018-01-17T07:10:09+07:00
Example #2 :
# Ruby code for DateTime.strptime() method # Ruby code for DateTime.strptime() method # loading libraryrequire 'date' # declaring DateTime valuedate_a = DateTime.strptime('2010 04 6 04 05 06 +7', '%Y %U %w %H %M %S %z') # declaring DateTime valuedate_b = DateTime.strptime('-1', '%s') # strptime methodputs "DateTime strptime form : #{date_a}\n\n" puts "DateTime strptime form : #{date_b}\n\n"
Output :
DateTime strptime form : 2010-01-30T04:05:06+07:00
DateTime strptime form : 1969-12-31T23:59:59+00:00
Ruby DateTime-class
Ruby-Methods
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 | Enumerator each_with_index function
Ruby | unless Statement and unless Modifier
Ruby For Beginners
Ruby | Array class find_index() operation
Ruby | String concat Method
Ruby on Rails Introduction
Ruby | Types of Variables
Ruby | Array shift() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Jan, 2020"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "DateTime#strptime() : strptime() is a DateTime class method which parses the given representation of date and time with the given template"
},
{
"code": null,
"e": 195,
"s": 167,
"text": "Syntax: DateTime.strptime()"
},
{
"code": null,
"e": 222,
"s": 195,
"text": "Parameter: DateTime values"
},
{
"code": null,
"e": 303,
"s": 222,
"text": "Return: parses the given representation of date and time with the given template"
},
{
"code": null,
"e": 316,
"s": 303,
"text": "Example #1 :"
},
{
"code": "# Ruby code for DateTime.strptime() method # loading libraryrequire 'date' # declaring DateTime valuedate_a = DateTime.strptime('10-02-2015 05:05:06 PM', '%d-%m-%Y %I:%M:%S %p') # declaring DateTime valuedate_b = DateTime.strptime('2018 02 3 07 10 09 +7', '%Y %U %w %H %M %S %z') # strptime methodputs \"DateTime strptime form : #{date_a}\\n\\n\" puts \"DateTime strptime form : #{date_b}\\n\\n\"",
"e": 713,
"s": 316,
"text": null
},
{
"code": null,
"e": 722,
"s": 713,
"text": "Output :"
},
{
"code": null,
"e": 827,
"s": 722,
"text": "DateTime strptime form : 2015-02-10T17:05:06+00:00\n\nDateTime strptime form : 2018-01-17T07:10:09+07:00\n\n"
},
{
"code": null,
"e": 840,
"s": 827,
"text": "Example #2 :"
},
{
"code": "# Ruby code for DateTime.strptime() method # Ruby code for DateTime.strptime() method # loading libraryrequire 'date' # declaring DateTime valuedate_a = DateTime.strptime('2010 04 6 04 05 06 +7', '%Y %U %w %H %M %S %z') # declaring DateTime valuedate_b = DateTime.strptime('-1', '%s') # strptime methodputs \"DateTime strptime form : #{date_a}\\n\\n\" puts \"DateTime strptime form : #{date_b}\\n\\n\"",
"e": 1243,
"s": 840,
"text": null
},
{
"code": null,
"e": 1252,
"s": 1243,
"text": "Output :"
},
{
"code": null,
"e": 1357,
"s": 1252,
"text": "DateTime strptime form : 2010-01-30T04:05:06+07:00\n\nDateTime strptime form : 1969-12-31T23:59:59+00:00\n\n"
},
{
"code": null,
"e": 1377,
"s": 1357,
"text": "Ruby DateTime-class"
},
{
"code": null,
"e": 1390,
"s": 1377,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 1395,
"s": 1390,
"text": "Ruby"
},
{
"code": null,
"e": 1493,
"s": 1395,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1539,
"s": 1493,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 1582,
"s": 1539,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 1626,
"s": 1582,
"text": "Ruby | unless Statement and unless Modifier"
},
{
"code": null,
"e": 1645,
"s": 1626,
"text": "Ruby For Beginners"
},
{
"code": null,
"e": 1687,
"s": 1645,
"text": "Ruby | Array class find_index() operation"
},
{
"code": null,
"e": 1715,
"s": 1687,
"text": "Ruby | String concat Method"
},
{
"code": null,
"e": 1742,
"s": 1715,
"text": "Ruby on Rails Introduction"
},
{
"code": null,
"e": 1768,
"s": 1742,
"text": "Ruby | Types of Variables"
}
]
|
Left() and Right() Function in MS Access | 02 Sep, 2020
1. Left() Function :In MS Access the Left() function extract the string from the left of the string. In Left() function The string and the no of the string will be passed. And it will return the string of size the pass number from the left of the string.
Syntax :
Left(string, number_of_chars)
Example-1 :
SELECT Left("GEEKSFORGEEKS", 3) AS ExtractString;
Output –
Example-2 :
SELECT Left("GEEKSFORGEEKS", 10) AS ExtractString;
Output –
2. Right() Function :The Right() function works like Left() function but it extracts the string from the right end of the string. In this, the string and the size of the string that will be extracted will pass as a parameter.
Syntax :
Right(string, number_of_chars)
Example-1 :
SELECT Right("GEEKSFORGEEKS", 4) AS ExtractString;
Output –
Example-2 :
SELECT Right("GEEKSFORGEEKS", 8) AS ExtractString;
Output –
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 283,
"s": 28,
"text": "1. Left() Function :In MS Access the Left() function extract the string from the left of the string. In Left() function The string and the no of the string will be passed. And it will return the string of size the pass number from the left of the string."
},
{
"code": null,
"e": 292,
"s": 283,
"text": "Syntax :"
},
{
"code": null,
"e": 322,
"s": 292,
"text": "Left(string, number_of_chars)"
},
{
"code": null,
"e": 334,
"s": 322,
"text": "Example-1 :"
},
{
"code": null,
"e": 384,
"s": 334,
"text": "SELECT Left(\"GEEKSFORGEEKS\", 3) AS ExtractString;"
},
{
"code": null,
"e": 393,
"s": 384,
"text": "Output –"
},
{
"code": null,
"e": 405,
"s": 393,
"text": "Example-2 :"
},
{
"code": null,
"e": 456,
"s": 405,
"text": "SELECT Left(\"GEEKSFORGEEKS\", 10) AS ExtractString;"
},
{
"code": null,
"e": 465,
"s": 456,
"text": "Output –"
},
{
"code": null,
"e": 691,
"s": 465,
"text": "2. Right() Function :The Right() function works like Left() function but it extracts the string from the right end of the string. In this, the string and the size of the string that will be extracted will pass as a parameter."
},
{
"code": null,
"e": 700,
"s": 691,
"text": "Syntax :"
},
{
"code": null,
"e": 731,
"s": 700,
"text": "Right(string, number_of_chars)"
},
{
"code": null,
"e": 743,
"s": 731,
"text": "Example-1 :"
},
{
"code": null,
"e": 794,
"s": 743,
"text": "SELECT Right(\"GEEKSFORGEEKS\", 4) AS ExtractString;"
},
{
"code": null,
"e": 803,
"s": 794,
"text": "Output –"
},
{
"code": null,
"e": 815,
"s": 803,
"text": "Example-2 :"
},
{
"code": null,
"e": 866,
"s": 815,
"text": "SELECT Right(\"GEEKSFORGEEKS\", 8) AS ExtractString;"
},
{
"code": null,
"e": 875,
"s": 866,
"text": "Output –"
},
{
"code": null,
"e": 884,
"s": 875,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 888,
"s": 884,
"text": "SQL"
},
{
"code": null,
"e": 892,
"s": 888,
"text": "SQL"
}
]
|
Loops in C and C++
| 01 Jun, 2022
In programming, sometimes there is a need to perform some operation more than once or (say) n number of times. Loops come into use when we need to repeatedly execute a block of statements.
For example: Suppose we want to print “Hello World” 10 times. This can be done in two ways as shown below:
Manually we have to write the print() for C and cout for the C++ statement 10 times. Let’s say you have to write it 20 times (it would surely take more time to write 20 statements) now imagine you have to write it 100 times, it would be really hectic to re-write the same statement again and again. So, here loops have their role.
C
C++
// C program to illustrate need of loops
#include <stdio.h>
int main()
{
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
printf( "Hello World\n");
return 0;
}
// C++ program to illustrate need of loops
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
return 0;
}
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown below. In computer programming, a loop is a sequence of instructions that is repeated until a certain condition is reached.
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.
An operation is done, such as getting an item of data and changing it, and then some condition is checked such as whether a counter has reached a prescribed number.
Counter not Reached: If the counter has not reached the desired number, the next instruction in the sequence returns to the first instruction in the sequence and repeats it.
Counter reached: If the condition has been reached, the next instruction “falls through” to the next sequential instruction or branches outside the loop.
There are mainly two types of loops:
Entry Controlled loops: In this type of loop, the test condition is tested before entering the loop body. For Loop and While Loop is entry-controlled loops.
Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. the do-while loop is exit controlled loop.
Entry Controlled loops: In this type of loop, the test condition is tested before entering the loop body. For Loop and While Loop is entry-controlled loops.
Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. the do-while loop is exit controlled loop.
A for loop is a repetition control structure that allows us to write a loop that is executed a specific number of times. The loop enables us to perform n number of steps together in one line. Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
Example:
for(int i = 0; i < n; i++){
}
In for loop, a loop variable is used to control the loop. First, initialize this loop variable to some value, then check whether this variable is less than or greater than the counter value. If the statement is true, then the loop body is executed and the loop variable gets updated. Steps are repeated till the exit condition comes.
Initialization Expression: In this expression, we have to initialize the loop counter to some value. for example: int i=1;
Test Expression: In this expression, we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression otherwise we will exit from the for a loop. For example: i <= 10;
Update Expression: After executing the loop body this expression increments/decrements the loop variable by some value. for example: i++;
Equivalent Flow Diagram for loop:
Example:
C
C++
// C program to illustrate for loop
#include <stdio.h>
int main()
{
int i=0;
for (i = 1; i <= 10; i++)
{
printf( "Hello World\n");
}
return 0;
}
// C++ program to illustrate for loop
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 10; i++)
{
cout << "Hello World\n";
}
return 0;
}
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
While studying for loop we have seen that the number of iterations is known beforehand, i.e. the number of times the loop body is needed to be executed is known to us. while loops are used in situations where we do not know the exact number of iterations of the loop beforehand. The loop execution is terminated on the basis of the test conditions.Syntax: We have already stated that a loop mainly consists of three statements – initialization expression, test expression, and update expression. The syntax of the three loops – For, while, and do while mainly differs in the placement of these three statements.
initialization expression;
while (test_expression)
{
// statements
update_expression;
}
Flow Diagram:
Example:
C
C++
// C program to illustrate while loop
#include <stdio.h>
int main()
{
// initialization expression
int i = 1;
// test expression
while (i < 6)
{
printf( "Hello World\n");
// update expression
i++;
}
return 0;
}
// C++ program to illustrate while loop
#include <iostream>
using namespace std;
int main()
{
// initialization expression
int i = 1;
// test expression
while (i < 6)
{
cout << "Hello World\n";
// update expression
i++;
}
return 0;
}
Hello World
Hello World
Hello World
Hello World
Hello World
In do-while loops also the loop execution is terminated on the basis of test conditions. The main difference between a do-while loop and the while loop is in the do-while loop the condition is tested at the end of the loop body, i.e do-while loop is exit controlled whereas the other two loops are entry controlled loops. Note: In a do-while loop, the loop body will execute at least once irrespective of the test condition.Syntax:
initialization expression;
do
{
// statements
update_expression;
} while (test_expression);
Note: Notice the semi – colon(“;”) in the end of loop.Flow Diagram:
Example:
C
C++
// C program to illustrate do-while loop
#include <stdio.h>
int main()
{
int i = 2; // Initialization expression
do
{
// loop body
printf( "Hello World\n");
// update expression
i++;
} while (i < 1); // test expression
return 0;
}
// C++ program to illustrate do-while loop
#include <iostream>
using namespace std;
int main()
{
int i = 2; // Initialization expression
do
{
// loop body
cout << "Hello World\n";
// update expression
i++;
} while (i < 1); // test expression
return 0;
}
Hello World
In the above program, the test condition (i<1) evaluates to false. But still, as the loop is an exit – controlled the loop body will execute once.
An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks a functional exit so that it repeats indefinitely. An infinite loop occurs when a condition is always evaluated to be true. Usually, this is an error. Using For loop:
C
C++
// C program to demonstrate infinite loops
// using for and while
// Uncomment the sections to see the output
#include <stdio.h>
int main ()
{
int i;
// This is an infinite for loop as the condition
// expression is blank
for ( ; ; )
{
printf("This loop will run forever.\n");
}
// This is an infinite for loop as the condition
// given in while loop will keep repeating infinitely
/*
while (i != 0)
{
i-- ;
printf( "This loop will run forever.\n");
}
*/
// This is an infinite for loop as the condition
// given in while loop is "true"
/*
while (true)
{
printf( "This loop will run forever.\n");
}
*/
}
// C++ program to demonstrate infinite loops
// using for and while
// Uncomment the sections to see the output
#include <iostream>
using namespace std;
int main ()
{
int i;
// This is an infinite for loop as the condition
// expression is blank
for ( ; ; )
{
cout << "This loop will run forever.\n";
}
// This is an infinite for loop as the condition
// given in while loop will keep repeating infinitely
/*
while (i != 0)
{
i-- ;
cout << "This loop will run forever.\n";
}
*/
// This is an infinite for loop as the condition
// given in while loop is "true"
/*
while (true)
{
cout << "This loop will run forever.\n";
}
*/
}
Output:
This loop will run forever.
This loop will run forever.
...................
Using While loop:
C
C++
#include <stdio.h>
int main() {
while (1)
printf("This loop will run forever.\n");
return 0;
}
#include <iostream>
using namespace std;
int main()
{
while (1)
cout << "This loop will run forever.\n";
return 0;
}
Output:
This loop will run forever.
This loop will run forever.
...................
Using Do-While loop:
C
C++
#include <stdio.h>
int main() {
do{
printf("This loop will run forever.\n");
}
while(1);
return 0;
}
#include <iostream>
using namespace std;
int main() {
do{
cout << "This loop will run forever.\n";
} while(1);
return 0;
}
Output:
This loop will run forever.
This loop will run forever.
...................
More Advanced Looping Techniques
Range-based for loop in C++
for_each loop in C++
Important Points:
Use for loop when a number of iterations are known beforehand, i.e. the number of times the loop body is needed to be executed is known.
Use while loops, where an exact number of iterations is not known but the loop termination condition, is known.
Use do while loop if the code needs to be executed at least once like in Menu-driven programs
Related Articles:
What happens if loop till Maximum of Signed and Unsigned in C/C++?
Quiz on Loops
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
RishabhPrabhu
sackshamsharmaintern
susobhanakhuli
C Basics
CBSE - Class 11
CPP-Basics
school-programming
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 57,
"s": 26,
"text": " \n01 Jun, 2022\n"
},
{
"code": null,
"e": 247,
"s": 57,
"text": "In programming, sometimes there is a need to perform some operation more than once or (say) n number of times. Loops come into use when we need to repeatedly execute a block of statements. "
},
{
"code": null,
"e": 355,
"s": 247,
"text": "For example: Suppose we want to print “Hello World” 10 times. This can be done in two ways as shown below: "
},
{
"code": null,
"e": 686,
"s": 355,
"text": "Manually we have to write the print() for C and cout for the C++ statement 10 times. Let’s say you have to write it 20 times (it would surely take more time to write 20 statements) now imagine you have to write it 100 times, it would be really hectic to re-write the same statement again and again. So, here loops have their role."
},
{
"code": null,
"e": 688,
"s": 686,
"text": "C"
},
{
"code": null,
"e": 692,
"s": 688,
"text": "C++"
},
{
"code": "\n\n\n\n\n\n\n// C program to illustrate need of loops\n#include <stdio.h>\n \nint main()\n{\n printf( \"Hello World\\n\");\n printf( \"Hello World\\n\");\n printf( \"Hello World\\n\");\n printf( \"Hello World\\n\");\n printf( \"Hello World\\n\");\n printf( \"Hello World\\n\");\n printf( \"Hello World\\n\");\n printf( \"Hello World\\n\");\n printf( \"Hello World\\n\");\n printf( \"Hello World\\n\");\n \n return 0;\n}\n\n\n\n\n\n",
"e": 1112,
"s": 702,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C++ program to illustrate need of loops\n#include <iostream>\nusing namespace std;\n \nint main()\n{\n cout << \"Hello World\\n\";\n cout << \"Hello World\\n\";\n cout << \"Hello World\\n\";\n cout << \"Hello World\\n\";\n cout << \"Hello World\\n\";\n cout << \"Hello World\\n\";\n cout << \"Hello World\\n\";\n cout << \"Hello World\\n\";\n cout << \"Hello World\\n\";\n cout << \"Hello World\\n\";\n return 0;\n}\n\n\n\n\n\n",
"e": 1540,
"s": 1122,
"text": null
},
{
"code": null,
"e": 1660,
"s": 1540,
"text": "Hello World\nHello World\nHello World\nHello World\nHello World\nHello World\nHello World\nHello World\nHello World\nHello World"
},
{
"code": null,
"e": 1889,
"s": 1662,
"text": "In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown below. In computer programming, a loop is a sequence of instructions that is repeated until a certain condition is reached. "
},
{
"code": null,
"e": 1898,
"s": 1889,
"text": "Chapters"
},
{
"code": null,
"e": 1925,
"s": 1898,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1975,
"s": 1925,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1998,
"s": 1975,
"text": "captions off, selected"
},
{
"code": null,
"e": 2006,
"s": 1998,
"text": "English"
},
{
"code": null,
"e": 2030,
"s": 2006,
"text": "This is a modal window."
},
{
"code": null,
"e": 2099,
"s": 2030,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 2121,
"s": 2099,
"text": "End of dialog window."
},
{
"code": null,
"e": 2286,
"s": 2121,
"text": "An operation is done, such as getting an item of data and changing it, and then some condition is checked such as whether a counter has reached a prescribed number."
},
{
"code": null,
"e": 2460,
"s": 2286,
"text": "Counter not Reached: If the counter has not reached the desired number, the next instruction in the sequence returns to the first instruction in the sequence and repeats it."
},
{
"code": null,
"e": 2614,
"s": 2460,
"text": "Counter reached: If the condition has been reached, the next instruction “falls through” to the next sequential instruction or branches outside the loop."
},
{
"code": null,
"e": 2653,
"s": 2614,
"text": "There are mainly two types of loops: "
},
{
"code": null,
"e": 3084,
"s": 2653,
"text": "\nEntry Controlled loops: In this type of loop, the test condition is tested before entering the loop body. For Loop and While Loop is entry-controlled loops.\nExit Controlled Loops: In this type of loop the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. the do-while loop is exit controlled loop.\n"
},
{
"code": null,
"e": 3241,
"s": 3084,
"text": "Entry Controlled loops: In this type of loop, the test condition is tested before entering the loop body. For Loop and While Loop is entry-controlled loops."
},
{
"code": null,
"e": 3513,
"s": 3241,
"text": "Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. the do-while loop is exit controlled loop."
},
{
"code": null,
"e": 3714,
"s": 3513,
"text": "A for loop is a repetition control structure that allows us to write a loop that is executed a specific number of times. The loop enables us to perform n number of steps together in one line. Syntax: "
},
{
"code": null,
"e": 3835,
"s": 3714,
"text": "for (initialization expr; test expr; update expr)\n{ \n // body of the loop\n // statements we want to execute\n}"
},
{
"code": null,
"e": 3844,
"s": 3835,
"text": "Example:"
},
{
"code": null,
"e": 3874,
"s": 3844,
"text": "for(int i = 0; i < n; i++){\n}"
},
{
"code": null,
"e": 4209,
"s": 3874,
"text": "In for loop, a loop variable is used to control the loop. First, initialize this loop variable to some value, then check whether this variable is less than or greater than the counter value. If the statement is true, then the loop body is executed and the loop variable gets updated. Steps are repeated till the exit condition comes. "
},
{
"code": null,
"e": 4332,
"s": 4209,
"text": "Initialization Expression: In this expression, we have to initialize the loop counter to some value. for example: int i=1;"
},
{
"code": null,
"e": 4571,
"s": 4332,
"text": "Test Expression: In this expression, we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression otherwise we will exit from the for a loop. For example: i <= 10;"
},
{
"code": null,
"e": 4709,
"s": 4571,
"text": "Update Expression: After executing the loop body this expression increments/decrements the loop variable by some value. for example: i++;"
},
{
"code": null,
"e": 4745,
"s": 4709,
"text": "Equivalent Flow Diagram for loop: "
},
{
"code": null,
"e": 4755,
"s": 4745,
"text": "Example: "
},
{
"code": null,
"e": 4757,
"s": 4755,
"text": "C"
},
{
"code": null,
"e": 4761,
"s": 4757,
"text": "C++"
},
{
"code": "\n\n\n\n\n\n\n// C program to illustrate for loop\n#include <stdio.h>\n \nint main()\n{\n int i=0;\n \n for (i = 1; i <= 10; i++)\n {\n printf( \"Hello World\\n\"); \n }\n \n return 0;\n}\n\n\n\n\n\n",
"e": 4971,
"s": 4771,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C++ program to illustrate for loop\n#include <iostream>\nusing namespace std;\n \nint main()\n{\n for (int i = 1; i <= 10; i++)\n {\n cout << \"Hello World\\n\";\n }\n \n return 0;\n}\n\n\n\n\n\n",
"e": 5185,
"s": 4981,
"text": null
},
{
"code": null,
"e": 5305,
"s": 5185,
"text": "Hello World\nHello World\nHello World\nHello World\nHello World\nHello World\nHello World\nHello World\nHello World\nHello World"
},
{
"code": null,
"e": 5920,
"s": 5307,
"text": "While studying for loop we have seen that the number of iterations is known beforehand, i.e. the number of times the loop body is needed to be executed is known to us. while loops are used in situations where we do not know the exact number of iterations of the loop beforehand. The loop execution is terminated on the basis of the test conditions.Syntax: We have already stated that a loop mainly consists of three statements – initialization expression, test expression, and update expression. The syntax of the three loops – For, while, and do while mainly differs in the placement of these three statements. "
},
{
"code": null,
"e": 6015,
"s": 5920,
"text": "initialization expression;\nwhile (test_expression)\n{\n // statements\n \n update_expression;\n}"
},
{
"code": null,
"e": 6031,
"s": 6015,
"text": "Flow Diagram: "
},
{
"code": null,
"e": 6041,
"s": 6031,
"text": "Example: "
},
{
"code": null,
"e": 6043,
"s": 6041,
"text": "C"
},
{
"code": null,
"e": 6047,
"s": 6043,
"text": "C++"
},
{
"code": "\n\n\n\n\n\n\n// C program to illustrate while loop\n#include <stdio.h>\n \nint main()\n{\n // initialization expression\n int i = 1;\n \n // test expression\n while (i < 6)\n {\n printf( \"Hello World\\n\"); \n \n // update expression\n i++;\n }\n \n return 0;\n}\n\n\n\n\n\n",
"e": 6345,
"s": 6057,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C++ program to illustrate while loop\n#include <iostream>\nusing namespace std;\n \nint main()\n{\n // initialization expression\n int i = 1;\n \n // test expression\n while (i < 6)\n {\n cout << \"Hello World\\n\";\n \n // update expression\n i++;\n }\n \n return 0;\n}\n\n\n\n\n\n",
"e": 6662,
"s": 6355,
"text": null
},
{
"code": null,
"e": 6722,
"s": 6662,
"text": "Hello World\nHello World\nHello World\nHello World\nHello World"
},
{
"code": null,
"e": 7157,
"s": 6724,
"text": "In do-while loops also the loop execution is terminated on the basis of test conditions. The main difference between a do-while loop and the while loop is in the do-while loop the condition is tested at the end of the loop body, i.e do-while loop is exit controlled whereas the other two loops are entry controlled loops. Note: In a do-while loop, the loop body will execute at least once irrespective of the test condition.Syntax: "
},
{
"code": null,
"e": 7256,
"s": 7157,
"text": "initialization expression;\ndo\n{\n // statements\n\n update_expression;\n} while (test_expression);"
},
{
"code": null,
"e": 7326,
"s": 7256,
"text": "Note: Notice the semi – colon(“;”) in the end of loop.Flow Diagram: "
},
{
"code": null,
"e": 7336,
"s": 7326,
"text": "Example: "
},
{
"code": null,
"e": 7338,
"s": 7336,
"text": "C"
},
{
"code": null,
"e": 7342,
"s": 7338,
"text": "C++"
},
{
"code": "\n\n\n\n\n\n\n// C program to illustrate do-while loop\n#include <stdio.h>\n \nint main()\n{\n int i = 2; // Initialization expression\n \n do\n {\n // loop body\n printf( \"Hello World\\n\"); \n \n // update expression\n i++;\n \n } while (i < 1); // test expression\n \n return 0;\n}\n\n\n\n\n\n",
"e": 7665,
"s": 7352,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C++ program to illustrate do-while loop\n#include <iostream>\nusing namespace std;\n \nint main()\n{\n int i = 2; // Initialization expression\n \n do\n {\n // loop body\n cout << \"Hello World\\n\";\n \n // update expression\n i++;\n \n } while (i < 1); // test expression\n \n return 0;\n}\n\n\n\n\n\n",
"e": 8007,
"s": 7675,
"text": null
},
{
"code": null,
"e": 8019,
"s": 8007,
"text": "Hello World"
},
{
"code": null,
"e": 8169,
"s": 8021,
"text": "In the above program, the test condition (i<1) evaluates to false. But still, as the loop is an exit – controlled the loop body will execute once. "
},
{
"code": null,
"e": 8421,
"s": 8169,
"text": "An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks a functional exit so that it repeats indefinitely. An infinite loop occurs when a condition is always evaluated to be true. Usually, this is an error. Using For loop:"
},
{
"code": null,
"e": 8423,
"s": 8421,
"text": "C"
},
{
"code": null,
"e": 8427,
"s": 8423,
"text": "C++"
},
{
"code": "\n\n\n\n\n\n\n// C program to demonstrate infinite loops\n// using for and while\n// Uncomment the sections to see the output\n \n#include <stdio.h>\n \nint main ()\n{\n int i;\n \n // This is an infinite for loop as the condition\n // expression is blank\n for ( ; ; )\n {\n printf(\"This loop will run forever.\\n\");\n }\n \n // This is an infinite for loop as the condition\n // given in while loop will keep repeating infinitely\n /*\n while (i != 0)\n {\n i-- ;\n printf( \"This loop will run forever.\\n\");\n }\n */\n \n // This is an infinite for loop as the condition\n // given in while loop is \"true\"\n /*\n while (true)\n {\n printf( \"This loop will run forever.\\n\");\n }\n */\n}\n\n\n\n\n\n",
"e": 9176,
"s": 8437,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C++ program to demonstrate infinite loops\n// using for and while\n// Uncomment the sections to see the output\n \n#include <iostream>\nusing namespace std;\nint main ()\n{\n int i;\n \n // This is an infinite for loop as the condition\n // expression is blank\n for ( ; ; )\n {\n cout << \"This loop will run forever.\\n\";\n }\n \n // This is an infinite for loop as the condition\n // given in while loop will keep repeating infinitely\n /*\n while (i != 0)\n {\n i-- ;\n cout << \"This loop will run forever.\\n\";\n }\n */\n \n // This is an infinite for loop as the condition\n // given in while loop is \"true\"\n /*\n while (true)\n {\n cout << \"This loop will run forever.\\n\";\n }\n */\n}\n\n\n\n\n\n",
"e": 9946,
"s": 9186,
"text": null
},
{
"code": null,
"e": 9956,
"s": 9946,
"text": "Output: "
},
{
"code": null,
"e": 10033,
"s": 9956,
"text": "This loop will run forever.\nThis loop will run forever.\n................... "
},
{
"code": null,
"e": 10051,
"s": 10033,
"text": "Using While loop:"
},
{
"code": null,
"e": 10053,
"s": 10051,
"text": "C"
},
{
"code": null,
"e": 10057,
"s": 10053,
"text": "C++"
},
{
"code": "\n\n\n\n\n\n\n#include <stdio.h>\n \nint main() {\n \n while (1)\n printf(\"This loop will run forever.\\n\");\n return 0;\n}\n\n\n\n\n\n",
"e": 10195,
"s": 10067,
"text": null
},
{
"code": "\n\n\n\n\n\n\n#include <iostream>\nusing namespace std;\n \nint main()\n{\n \n while (1)\n cout << \"This loop will run forever.\\n\";\n return 0;\n}\n\n\n\n\n\n",
"e": 10355,
"s": 10205,
"text": null
},
{
"code": null,
"e": 10365,
"s": 10355,
"text": "Output: "
},
{
"code": null,
"e": 10442,
"s": 10365,
"text": "This loop will run forever.\nThis loop will run forever.\n................... "
},
{
"code": null,
"e": 10463,
"s": 10442,
"text": "Using Do-While loop:"
},
{
"code": null,
"e": 10465,
"s": 10463,
"text": "C"
},
{
"code": null,
"e": 10469,
"s": 10465,
"text": "C++"
},
{
"code": "\n\n\n\n\n\n\n#include <stdio.h>\n \nint main() {\n \n do{\n printf(\"This loop will run forever.\\n\");\n }\n while(1);\n return 0;\n}\n\n\n\n\n\n",
"e": 10623,
"s": 10479,
"text": null
},
{
"code": "\n\n\n\n\n\n\n#include <iostream>\nusing namespace std;\n \nint main() {\n \n do{\n cout << \"This loop will run forever.\\n\";\n } while(1);\n \n return 0;\n}\n\n\n\n\n\n",
"e": 10797,
"s": 10633,
"text": null
},
{
"code": null,
"e": 10805,
"s": 10797,
"text": "Output:"
},
{
"code": null,
"e": 10882,
"s": 10805,
"text": "This loop will run forever.\nThis loop will run forever.\n................... "
},
{
"code": null,
"e": 10915,
"s": 10882,
"text": "More Advanced Looping Techniques"
},
{
"code": null,
"e": 10943,
"s": 10915,
"text": "Range-based for loop in C++"
},
{
"code": null,
"e": 10964,
"s": 10943,
"text": "for_each loop in C++"
},
{
"code": null,
"e": 10982,
"s": 10964,
"text": "Important Points:"
},
{
"code": null,
"e": 11119,
"s": 10982,
"text": "Use for loop when a number of iterations are known beforehand, i.e. the number of times the loop body is needed to be executed is known."
},
{
"code": null,
"e": 11231,
"s": 11119,
"text": "Use while loops, where an exact number of iterations is not known but the loop termination condition, is known."
},
{
"code": null,
"e": 11325,
"s": 11231,
"text": "Use do while loop if the code needs to be executed at least once like in Menu-driven programs"
},
{
"code": null,
"e": 11343,
"s": 11325,
"text": "Related Articles:"
},
{
"code": null,
"e": 11410,
"s": 11343,
"text": "What happens if loop till Maximum of Signed and Unsigned in C/C++?"
},
{
"code": null,
"e": 11424,
"s": 11410,
"text": "Quiz on Loops"
},
{
"code": null,
"e": 11849,
"s": 11424,
"text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 11863,
"s": 11849,
"text": "RishabhPrabhu"
},
{
"code": null,
"e": 11884,
"s": 11863,
"text": "sackshamsharmaintern"
},
{
"code": null,
"e": 11899,
"s": 11884,
"text": "susobhanakhuli"
},
{
"code": null,
"e": 11910,
"s": 11899,
"text": "\nC Basics\n"
},
{
"code": null,
"e": 11928,
"s": 11910,
"text": "\nCBSE - Class 11\n"
},
{
"code": null,
"e": 11941,
"s": 11928,
"text": "\nCPP-Basics\n"
},
{
"code": null,
"e": 11962,
"s": 11941,
"text": "\nschool-programming\n"
},
{
"code": null,
"e": 11968,
"s": 11962,
"text": "\nC++\n"
},
{
"code": null,
"e": 11989,
"s": 11968,
"text": "\nSchool Programming\n"
},
{
"code": null,
"e": 11993,
"s": 11989,
"text": "CPP"
}
]
|
HTML | <th> valign Attribute | 22 Feb, 2022
The HTML <th> valign Attribute is used to specify the vertical alignment of text content in a header cell. It is not supported by HTML 5.
Syntax:
<th valign="top | middle | bottom | baseline">
Attribute Value:
top: It sets the table header content to top-align.
middle: It sets the table header content to middle-align.
bottom: It sets the table header content to bottom-align.
baseline: It sets the table header content to baseline. The baseline is the line where most of the characters sit. It is a default value.
Example:
<!DOCTYPE html><html> <head> <title> HTML th valign Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML th valign Attribute</h2> <table border="1" width="500"> <tr style="height:100px;"> <th valign="top">NAME</th> <th valign="center">AGE</th> <th valign="bottom">BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> <tr> <td>RAKESH</td> <td>25</td> <td>EC</td> </tr> </table></body> </html>
Output:
Supported Browsers: The browser supported by HTML <th> valign attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
chhabradhanvi
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
HTTP headers | Content-Type
How to Insert Form Data into Database using PHP ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Feb, 2022"
},
{
"code": null,
"e": 166,
"s": 28,
"text": "The HTML <th> valign Attribute is used to specify the vertical alignment of text content in a header cell. It is not supported by HTML 5."
},
{
"code": null,
"e": 174,
"s": 166,
"text": "Syntax:"
},
{
"code": null,
"e": 221,
"s": 174,
"text": "<th valign=\"top | middle | bottom | baseline\">"
},
{
"code": null,
"e": 238,
"s": 221,
"text": "Attribute Value:"
},
{
"code": null,
"e": 290,
"s": 238,
"text": "top: It sets the table header content to top-align."
},
{
"code": null,
"e": 348,
"s": 290,
"text": "middle: It sets the table header content to middle-align."
},
{
"code": null,
"e": 406,
"s": 348,
"text": "bottom: It sets the table header content to bottom-align."
},
{
"code": null,
"e": 544,
"s": 406,
"text": "baseline: It sets the table header content to baseline. The baseline is the line where most of the characters sit. It is a default value."
},
{
"code": null,
"e": 553,
"s": 544,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML th valign Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML th valign Attribute</h2> <table border=\"1\" width=\"500\"> <tr style=\"height:100px;\"> <th valign=\"top\">NAME</th> <th valign=\"center\">AGE</th> <th valign=\"bottom\">BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> <tr> <td>RAKESH</td> <td>25</td> <td>EC</td> </tr> </table></body> </html>",
"e": 1150,
"s": 553,
"text": null
},
{
"code": null,
"e": 1158,
"s": 1150,
"text": "Output:"
},
{
"code": null,
"e": 1248,
"s": 1158,
"text": "Supported Browsers: The browser supported by HTML <th> valign attribute are listed below:"
},
{
"code": null,
"e": 1262,
"s": 1248,
"text": "Google Chrome"
},
{
"code": null,
"e": 1280,
"s": 1262,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1288,
"s": 1280,
"text": "Firefox"
},
{
"code": null,
"e": 1295,
"s": 1288,
"text": "Safari"
},
{
"code": null,
"e": 1301,
"s": 1295,
"text": "Opera"
},
{
"code": null,
"e": 1315,
"s": 1301,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 1331,
"s": 1315,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1336,
"s": 1331,
"text": "HTML"
},
{
"code": null,
"e": 1353,
"s": 1336,
"text": "Web Technologies"
},
{
"code": null,
"e": 1358,
"s": 1353,
"text": "HTML"
},
{
"code": null,
"e": 1456,
"s": 1358,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1480,
"s": 1456,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1517,
"s": 1480,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 1556,
"s": 1517,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1584,
"s": 1556,
"text": "HTTP headers | Content-Type"
},
{
"code": null,
"e": 1634,
"s": 1584,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 1667,
"s": 1634,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1728,
"s": 1667,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1771,
"s": 1728,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1843,
"s": 1771,
"text": "Differences between Functional Components and Class Components in React"
}
]
|
Scala Stack apply() method with example | 03 Nov, 2019
In Scala Stack class, the apply() method is utilized to return an element at a given position in the stack. The top of the stack corresponds to the element at 0th position and so on.
Method Definition: def apply(idx: Int): A
Return Type: It returns an element at a given position in the stack.
Example #1:
// Scala program of apply() // method import scala.collection.mutable.Stack // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a stack val s1 = Stack(1, 2, 3, 4, 5) // Print the stack println(s1) // Applying apply method val result = s1.apply(0) // Display output println("Element at 0th position: " + result) } }
Stack(1, 2, 3, 4, 5)
Element at 0th position: 1
Example #2:
// Scala program of apply() // method import scala.collection.mutable.Stack // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a stack val s1 = Stack("C++", "Java", "Python", "Scala") // Print the stack println(s1) // Applying apply method val result = s1.apply(2) // Display output println("Element at 2nd position: " + result) } }
Stack(C++, Java, Python, Scala)
Element at 2nd position: Python
Scala
scala-collection
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install Scala with VSCode?
Inheritance in Scala
Hello World in Scala
Scala | Traits
Scala | Option
Scala ListBuffer
Scala | Functions - Basics
Introduction to Scala
Scala Sequence
Scala | Case Class and Case Object | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Nov, 2019"
},
{
"code": null,
"e": 211,
"s": 28,
"text": "In Scala Stack class, the apply() method is utilized to return an element at a given position in the stack. The top of the stack corresponds to the element at 0th position and so on."
},
{
"code": null,
"e": 253,
"s": 211,
"text": "Method Definition: def apply(idx: Int): A"
},
{
"code": null,
"e": 322,
"s": 253,
"text": "Return Type: It returns an element at a given position in the stack."
},
{
"code": null,
"e": 334,
"s": 322,
"text": "Example #1:"
},
{
"code": "// Scala program of apply() // method import scala.collection.mutable.Stack // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a stack val s1 = Stack(1, 2, 3, 4, 5) // Print the stack println(s1) // Applying apply method val result = s1.apply(0) // Display output println(\"Element at 0th position: \" + result) } } ",
"e": 822,
"s": 334,
"text": null
},
{
"code": null,
"e": 871,
"s": 822,
"text": "Stack(1, 2, 3, 4, 5)\nElement at 0th position: 1\n"
},
{
"code": null,
"e": 883,
"s": 871,
"text": "Example #2:"
},
{
"code": "// Scala program of apply() // method import scala.collection.mutable.Stack // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a stack val s1 = Stack(\"C++\", \"Java\", \"Python\", \"Scala\") // Print the stack println(s1) // Applying apply method val result = s1.apply(2) // Display output println(\"Element at 2nd position: \" + result) } } ",
"e": 1390,
"s": 883,
"text": null
},
{
"code": null,
"e": 1455,
"s": 1390,
"text": "Stack(C++, Java, Python, Scala)\nElement at 2nd position: Python\n"
},
{
"code": null,
"e": 1461,
"s": 1455,
"text": "Scala"
},
{
"code": null,
"e": 1478,
"s": 1461,
"text": "scala-collection"
},
{
"code": null,
"e": 1491,
"s": 1478,
"text": "Scala-Method"
},
{
"code": null,
"e": 1497,
"s": 1491,
"text": "Scala"
},
{
"code": null,
"e": 1595,
"s": 1497,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1629,
"s": 1595,
"text": "How to Install Scala with VSCode?"
},
{
"code": null,
"e": 1650,
"s": 1629,
"text": "Inheritance in Scala"
},
{
"code": null,
"e": 1671,
"s": 1650,
"text": "Hello World in Scala"
},
{
"code": null,
"e": 1686,
"s": 1671,
"text": "Scala | Traits"
},
{
"code": null,
"e": 1701,
"s": 1686,
"text": "Scala | Option"
},
{
"code": null,
"e": 1718,
"s": 1701,
"text": "Scala ListBuffer"
},
{
"code": null,
"e": 1745,
"s": 1718,
"text": "Scala | Functions - Basics"
},
{
"code": null,
"e": 1767,
"s": 1745,
"text": "Introduction to Scala"
},
{
"code": null,
"e": 1782,
"s": 1767,
"text": "Scala Sequence"
}
]
|
Difference between DROP and TRUNCATE in SQL | 16 Apr, 2020
Prerequisite – DROP, and TRUNCATE in SQL
1. DROP :DROP is a DDL(Data Definition Language) command and is used to remove table definition and indexes, data, constraints, triggers etc for that table. Performance-wise the DROP command is quick to perform but slower than TRUNCATE because it gives rise to complications. Unlike DELETE we can’t rollback the data after using the DROP command. In the DROP command, table space is freed from memory because it permanently delete table as well as all its contents.
Syntax of DROP command –
DROP TABLE table_name;
2. TRUNCATE :TRUNCATE is a DDL(Data Definition Language) command. It is used to delete all the tuples from the table. Like the DROP command, the TRUNCATE command also does not contain a WHERE clause. The TRUNCATE command is faster than both the DROP and the DELETE command. Like the DROP command we also can’t rollback the data after using the this command.
Syntax of TRUNCATE command –
TRUNCATE TABLE table_name;
Let’s see the difference between DROP and TRUNCATE command in SQL:-
MKS075
SQL-Clauses
DBMS
Difference Between
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
File Organization in DBMS | Set 1
File Organization in DBMS | Set 2
File Organization in DBMS | Set 3
Record-Based Data Model
Introduction of B+ Tree
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Apr, 2020"
},
{
"code": null,
"e": 93,
"s": 52,
"text": "Prerequisite – DROP, and TRUNCATE in SQL"
},
{
"code": null,
"e": 559,
"s": 93,
"text": "1. DROP :DROP is a DDL(Data Definition Language) command and is used to remove table definition and indexes, data, constraints, triggers etc for that table. Performance-wise the DROP command is quick to perform but slower than TRUNCATE because it gives rise to complications. Unlike DELETE we can’t rollback the data after using the DROP command. In the DROP command, table space is freed from memory because it permanently delete table as well as all its contents."
},
{
"code": null,
"e": 584,
"s": 559,
"text": "Syntax of DROP command –"
},
{
"code": null,
"e": 607,
"s": 584,
"text": "DROP TABLE table_name;"
},
{
"code": null,
"e": 965,
"s": 607,
"text": "2. TRUNCATE :TRUNCATE is a DDL(Data Definition Language) command. It is used to delete all the tuples from the table. Like the DROP command, the TRUNCATE command also does not contain a WHERE clause. The TRUNCATE command is faster than both the DROP and the DELETE command. Like the DROP command we also can’t rollback the data after using the this command."
},
{
"code": null,
"e": 994,
"s": 965,
"text": "Syntax of TRUNCATE command –"
},
{
"code": null,
"e": 1022,
"s": 994,
"text": "TRUNCATE TABLE table_name; "
},
{
"code": null,
"e": 1090,
"s": 1022,
"text": "Let’s see the difference between DROP and TRUNCATE command in SQL:-"
},
{
"code": null,
"e": 1097,
"s": 1090,
"text": "MKS075"
},
{
"code": null,
"e": 1109,
"s": 1097,
"text": "SQL-Clauses"
},
{
"code": null,
"e": 1114,
"s": 1109,
"text": "DBMS"
},
{
"code": null,
"e": 1133,
"s": 1114,
"text": "Difference Between"
},
{
"code": null,
"e": 1137,
"s": 1133,
"text": "SQL"
},
{
"code": null,
"e": 1142,
"s": 1137,
"text": "DBMS"
},
{
"code": null,
"e": 1146,
"s": 1142,
"text": "SQL"
},
{
"code": null,
"e": 1244,
"s": 1146,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1278,
"s": 1244,
"text": "File Organization in DBMS | Set 1"
},
{
"code": null,
"e": 1312,
"s": 1278,
"text": "File Organization in DBMS | Set 2"
},
{
"code": null,
"e": 1346,
"s": 1312,
"text": "File Organization in DBMS | Set 3"
},
{
"code": null,
"e": 1370,
"s": 1346,
"text": "Record-Based Data Model"
},
{
"code": null,
"e": 1394,
"s": 1370,
"text": "Introduction of B+ Tree"
},
{
"code": null,
"e": 1434,
"s": 1394,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 1465,
"s": 1434,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 1526,
"s": 1465,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1594,
"s": 1526,
"text": "Difference Between Method Overloading and Method Overriding in Java"
}
]
|
HTML <dd> Tag | 17 Mar, 2022
The <dd> tag in HTML stands for definition description and is used to denote the description or definition of an item in a description list. Paragraphs, line breaks, images, links, lists can be inserted inside a <dd> tag. The <dd> tag in HTML is used along with <dl> tag which defines the description list and <dt> tag which defines the terms in the description list. The <dd> tag requires a starting, but the end tag is optional.
Syntax:
<dd> Contents... </dd>
Example 1: Below programs illustrate the <dd> element in HTML.
HTML
<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML dd Tag</h2> <dl> <dt>Geeks Classes</dt> <dd>It is an extensive classroom programme for enhancing DS and Algo concepts.</dd> <br> <dt>Fork Python</dt> <dd>It is a course designed for beginners in python.</dd> <br> <dt>Interview Preparation</dt> <dd>It is a course designed for preparation of interviews in top product based companies.</dd> </dl> </body></html>
Output:
Example 2: This example uses the <dd> tag with display property.
HTML
<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML dd Tag</h2> <dl> <dt>Geeks Classes</dt> <dd style="display: inline; margin-left: 60px"> It is an extensive classroom programme for enhancing DS and Algo concepts. </dd> </dl> </body></html>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
arorakashish0911
shubhamyadav4
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 Mar, 2022"
},
{
"code": null,
"e": 484,
"s": 53,
"text": "The <dd> tag in HTML stands for definition description and is used to denote the description or definition of an item in a description list. Paragraphs, line breaks, images, links, lists can be inserted inside a <dd> tag. The <dd> tag in HTML is used along with <dl> tag which defines the description list and <dt> tag which defines the terms in the description list. The <dd> tag requires a starting, but the end tag is optional."
},
{
"code": null,
"e": 493,
"s": 484,
"text": "Syntax: "
},
{
"code": null,
"e": 516,
"s": 493,
"text": "<dd> Contents... </dd>"
},
{
"code": null,
"e": 579,
"s": 516,
"text": "Example 1: Below programs illustrate the <dd> element in HTML."
},
{
"code": null,
"e": 584,
"s": 579,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML dd Tag</h2> <dl> <dt>Geeks Classes</dt> <dd>It is an extensive classroom programme for enhancing DS and Algo concepts.</dd> <br> <dt>Fork Python</dt> <dd>It is a course designed for beginners in python.</dd> <br> <dt>Interview Preparation</dt> <dd>It is a course designed for preparation of interviews in top product based companies.</dd> </dl> </body></html> ",
"e": 1186,
"s": 584,
"text": null
},
{
"code": null,
"e": 1196,
"s": 1186,
"text": "Output: "
},
{
"code": null,
"e": 1263,
"s": 1196,
"text": "Example 2: This example uses the <dd> tag with display property. "
},
{
"code": null,
"e": 1268,
"s": 1263,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>HTML dd Tag</h2> <dl> <dt>Geeks Classes</dt> <dd style=\"display: inline; margin-left: 60px\"> It is an extensive classroom programme for enhancing DS and Algo concepts. </dd> </dl> </body></html> ",
"e": 1635,
"s": 1268,
"text": null
},
{
"code": null,
"e": 1645,
"s": 1635,
"text": "Output: "
},
{
"code": null,
"e": 1666,
"s": 1645,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 1680,
"s": 1666,
"text": "Google Chrome"
},
{
"code": null,
"e": 1698,
"s": 1680,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1706,
"s": 1698,
"text": "Firefox"
},
{
"code": null,
"e": 1712,
"s": 1706,
"text": "Opera"
},
{
"code": null,
"e": 1719,
"s": 1712,
"text": "Safari"
},
{
"code": null,
"e": 1736,
"s": 1719,
"text": "arorakashish0911"
},
{
"code": null,
"e": 1750,
"s": 1736,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 1760,
"s": 1750,
"text": "HTML-Tags"
},
{
"code": null,
"e": 1765,
"s": 1760,
"text": "HTML"
},
{
"code": null,
"e": 1770,
"s": 1765,
"text": "HTML"
},
{
"code": null,
"e": 1868,
"s": 1770,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1916,
"s": 1868,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 1978,
"s": 1916,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2028,
"s": 1978,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2052,
"s": 2028,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2105,
"s": 2052,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2165,
"s": 2105,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 2226,
"s": 2165,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 2276,
"s": 2226,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 2313,
"s": 2276,
"text": "Types of CSS (Cascading Style Sheet)"
}
]
|
move cmd command | 20 Oct, 2020
The move is an internal command found in the Windows Command Interpreter (cmd) that is used to move files and folders/directories. The command is robust than a regular move operation, as it allows for pattern matching via the inclusion of Wildcards in the source path.
The command is a very generic one and is available (in one form or the other) in almost every single operating system out there (under different aliases). In this article, we will learn about the move command and would learn various uses/applications of it.
Description of the Command :
MOVE [/Y | /-Y] [drive:][path]dirname1 dirname2
[drive:][path]filename1 –Specifies the location and name of the file or files you want to move.
destination –Specifies the new location of the file. The destination can consist of a drive letter and colon, a directory name, or a combination. If you are moving only one file, you can also include a filename if you want to rename the file when you move it.
[drive:][path]dirname1 –Specifies the directory you want to rename.
dirname2 –Specifies the new name of the directory.
/Y –Suppresses prompting to confirm you want to overwrite an existing destination file.
/Y –Causes prompting to confirm you want to overwrite an existing destination file.
The switch /Y may be present in the COPYCMD environment variable. This may be overridden with /-Y on the command line. The default is to prompt on overwrites unless the MOVE command is being executed from within a batch script. The above output can be obtained by executing the command move /? in cmd.The above text is a little cryptic at first, but the command is really basic and follows the minimal blueprint.
Syntax :
MOVE [options] (Source) (Target)
Key :
[option] –An optional flag denoted by /Y or /-Y, that is used to suppress the confirmation prompt on overwritten files. The default is to prompt on overwrites unless the MOVE command is being executed from within a batch script.
(Source) –A path of the file/files that would be used to move them. This path can contain wildcards ( * ? ) in the path. If more then files are made to move, then wildcards are used.
(Target) –A path for the new location of the file.
Using the Command :Throughout this section, we would take the following directory as example for demonstrating the usage of move command.
Moving a File from One Folder to Another :
move source_path destination_path
source_path –It is the path of the file which we are willing to move, and the destination_path is the location to which we want the file to be moved.
Example :
The Dir /b command is used to list all the files and folders inside a directory.
In the above example, we have moved an extension-less file named salute from C:\suga to C:\suga\apples directory.
Moving Multiple Files from One Path to Another :
move source_path destination_path
source_path –It is a path containing wildcards that will allow more than one file to be taken as a source. The destination_path is now a path to a directory where the moved files would reside (should not contain wildcards).
Example :
In the above example we have moved all the files inside C:\suga folder which matches the pattern *.* to C:\suga\Apples directory.
It should be noted that wildcard in source_path should match with the file(s) otherwise it would result in source_path being null, and a subsequent error.
Moving Directory from One Path to Another :
move source_dir_path Destination_dir_path
source_dir_path –It is the path to the directory to which we are moving, and destination_dir_path is the new location where it would be moved to.
Example :
In the above example, we have moved the C:\suga\apples directory to C:\Users\Public directory.
Multiple Directories can be moved using the method described in Moving multiple files from one path to another (with little modification to make is eligible for directories).
Moving a File to Another Folder with a Same Name File already existing :
There are two ways to tackle this situation –
Abort the move process.Continue the move process, by overwriting the existing file with the newer one.
Abort the move process.
Continue the move process, by overwriting the existing file with the newer one.
By default, the move command upon encountering any name collisions would prompt the user, asking whether he wants to rewrite the existing file with the new one, or stop the move process (via a Y/N prompt). To abort the move process, the user can simply enter N in the prompt input, stating that the file should not be overwritten. The prompt seeking for user input (for overwrite of files) appears as follows –
Overwrite {full_file_path}? (Yes/No/All):
When the users enter N in the prompt the output appears as follows –
Overwrite {full_file_path}? (Yes/No/All): N
0 file(s) moved.
When the user enters Y in the prompt the output appears as follows –
Overwrite {full_file_path}? (Yes/No/All): Y
1 file(s) moved.
To continue the move process by overwriting existing files (on all name collisions), a /Y switch needs to be added to the command as follows –
move /Y source_path destination_path
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Oct, 2020"
},
{
"code": null,
"e": 321,
"s": 52,
"text": "The move is an internal command found in the Windows Command Interpreter (cmd) that is used to move files and folders/directories. The command is robust than a regular move operation, as it allows for pattern matching via the inclusion of Wildcards in the source path."
},
{
"code": null,
"e": 579,
"s": 321,
"text": "The command is a very generic one and is available (in one form or the other) in almost every single operating system out there (under different aliases). In this article, we will learn about the move command and would learn various uses/applications of it."
},
{
"code": null,
"e": 608,
"s": 579,
"text": "Description of the Command :"
},
{
"code": null,
"e": 657,
"s": 608,
"text": "MOVE [/Y | /-Y] [drive:][path]dirname1 dirname2 "
},
{
"code": null,
"e": 753,
"s": 657,
"text": "[drive:][path]filename1 –Specifies the location and name of the file or files you want to move."
},
{
"code": null,
"e": 1013,
"s": 753,
"text": "destination –Specifies the new location of the file. The destination can consist of a drive letter and colon, a directory name, or a combination. If you are moving only one file, you can also include a filename if you want to rename the file when you move it."
},
{
"code": null,
"e": 1081,
"s": 1013,
"text": "[drive:][path]dirname1 –Specifies the directory you want to rename."
},
{
"code": null,
"e": 1132,
"s": 1081,
"text": "dirname2 –Specifies the new name of the directory."
},
{
"code": null,
"e": 1220,
"s": 1132,
"text": "/Y –Suppresses prompting to confirm you want to overwrite an existing destination file."
},
{
"code": null,
"e": 1304,
"s": 1220,
"text": "/Y –Causes prompting to confirm you want to overwrite an existing destination file."
},
{
"code": null,
"e": 1717,
"s": 1304,
"text": "The switch /Y may be present in the COPYCMD environment variable. This may be overridden with /-Y on the command line. The default is to prompt on overwrites unless the MOVE command is being executed from within a batch script. The above output can be obtained by executing the command move /? in cmd.The above text is a little cryptic at first, but the command is really basic and follows the minimal blueprint."
},
{
"code": null,
"e": 1726,
"s": 1717,
"text": "Syntax :"
},
{
"code": null,
"e": 1760,
"s": 1726,
"text": "MOVE [options] (Source) (Target) "
},
{
"code": null,
"e": 1766,
"s": 1760,
"text": "Key :"
},
{
"code": null,
"e": 1995,
"s": 1766,
"text": "[option] –An optional flag denoted by /Y or /-Y, that is used to suppress the confirmation prompt on overwritten files. The default is to prompt on overwrites unless the MOVE command is being executed from within a batch script."
},
{
"code": null,
"e": 2178,
"s": 1995,
"text": "(Source) –A path of the file/files that would be used to move them. This path can contain wildcards ( * ? ) in the path. If more then files are made to move, then wildcards are used."
},
{
"code": null,
"e": 2229,
"s": 2178,
"text": "(Target) –A path for the new location of the file."
},
{
"code": null,
"e": 2367,
"s": 2229,
"text": "Using the Command :Throughout this section, we would take the following directory as example for demonstrating the usage of move command."
},
{
"code": null,
"e": 2410,
"s": 2367,
"text": "Moving a File from One Folder to Another :"
},
{
"code": null,
"e": 2444,
"s": 2410,
"text": "move source_path destination_path"
},
{
"code": null,
"e": 2594,
"s": 2444,
"text": "source_path –It is the path of the file which we are willing to move, and the destination_path is the location to which we want the file to be moved."
},
{
"code": null,
"e": 2604,
"s": 2594,
"text": "Example :"
},
{
"code": null,
"e": 2685,
"s": 2604,
"text": "The Dir /b command is used to list all the files and folders inside a directory."
},
{
"code": null,
"e": 2799,
"s": 2685,
"text": "In the above example, we have moved an extension-less file named salute from C:\\suga to C:\\suga\\apples directory."
},
{
"code": null,
"e": 2848,
"s": 2799,
"text": "Moving Multiple Files from One Path to Another :"
},
{
"code": null,
"e": 2882,
"s": 2848,
"text": "move source_path destination_path"
},
{
"code": null,
"e": 3106,
"s": 2882,
"text": "source_path –It is a path containing wildcards that will allow more than one file to be taken as a source. The destination_path is now a path to a directory where the moved files would reside (should not contain wildcards)."
},
{
"code": null,
"e": 3116,
"s": 3106,
"text": "Example :"
},
{
"code": null,
"e": 3246,
"s": 3116,
"text": "In the above example we have moved all the files inside C:\\suga folder which matches the pattern *.* to C:\\suga\\Apples directory."
},
{
"code": null,
"e": 3401,
"s": 3246,
"text": "It should be noted that wildcard in source_path should match with the file(s) otherwise it would result in source_path being null, and a subsequent error."
},
{
"code": null,
"e": 3445,
"s": 3401,
"text": "Moving Directory from One Path to Another :"
},
{
"code": null,
"e": 3487,
"s": 3445,
"text": "move source_dir_path Destination_dir_path"
},
{
"code": null,
"e": 3633,
"s": 3487,
"text": "source_dir_path –It is the path to the directory to which we are moving, and destination_dir_path is the new location where it would be moved to."
},
{
"code": null,
"e": 3643,
"s": 3633,
"text": "Example :"
},
{
"code": null,
"e": 3738,
"s": 3643,
"text": "In the above example, we have moved the C:\\suga\\apples directory to C:\\Users\\Public directory."
},
{
"code": null,
"e": 3913,
"s": 3738,
"text": "Multiple Directories can be moved using the method described in Moving multiple files from one path to another (with little modification to make is eligible for directories)."
},
{
"code": null,
"e": 3986,
"s": 3913,
"text": "Moving a File to Another Folder with a Same Name File already existing :"
},
{
"code": null,
"e": 4032,
"s": 3986,
"text": "There are two ways to tackle this situation –"
},
{
"code": null,
"e": 4135,
"s": 4032,
"text": "Abort the move process.Continue the move process, by overwriting the existing file with the newer one."
},
{
"code": null,
"e": 4159,
"s": 4135,
"text": "Abort the move process."
},
{
"code": null,
"e": 4239,
"s": 4159,
"text": "Continue the move process, by overwriting the existing file with the newer one."
},
{
"code": null,
"e": 4650,
"s": 4239,
"text": "By default, the move command upon encountering any name collisions would prompt the user, asking whether he wants to rewrite the existing file with the new one, or stop the move process (via a Y/N prompt). To abort the move process, the user can simply enter N in the prompt input, stating that the file should not be overwritten. The prompt seeking for user input (for overwrite of files) appears as follows –"
},
{
"code": null,
"e": 4693,
"s": 4650,
"text": "Overwrite {full_file_path}? (Yes/No/All): "
},
{
"code": null,
"e": 4762,
"s": 4693,
"text": "When the users enter N in the prompt the output appears as follows –"
},
{
"code": null,
"e": 4824,
"s": 4762,
"text": "Overwrite {full_file_path}? (Yes/No/All): N\n\n0 file(s) moved."
},
{
"code": null,
"e": 4893,
"s": 4824,
"text": "When the user enters Y in the prompt the output appears as follows –"
},
{
"code": null,
"e": 4955,
"s": 4893,
"text": "Overwrite {full_file_path}? (Yes/No/All): Y\n\n1 file(s) moved."
},
{
"code": null,
"e": 5098,
"s": 4955,
"text": "To continue the move process by overwriting existing files (on all name collisions), a /Y switch needs to be added to the command as follows –"
},
{
"code": null,
"e": 5137,
"s": 5098,
"text": "move /Y source_path destination_path "
},
{
"code": null,
"e": 5155,
"s": 5137,
"text": "Operating Systems"
},
{
"code": null,
"e": 5173,
"s": 5155,
"text": "Operating Systems"
}
]
|
SQL Server | Convert tables in T-SQL into XML | 09 Mar, 2021
In this, we will focus on how tables will be converted in T-SQL into XML in SQL server. And you will be able to understand how you can convert it with the help of command. Let’s discuss it one by one.
Overview :XML (Extensible Markup Language) is a markup language similar to HTML which was designed to share information between different platforms. And here, you will understand how you can Convert tables in T-SQL into XML.
Example –Here is a below sample XML Document as follows.
<email>
<to>Manager</to>
<from>Sruti</from>
<heading>Work Status</heading>
<body>Work Completed</body>
</email>
Converting tables in T-SQL into XML :To Convert tables in T-SQL into XML by using the following steps as follows. Let’s first generate an Employee_Table to store data of few Employees in order to create XML documents.
Creating table – Employee_Table
CREATE TABLE Employee_Table
(
EmpId int identity(1,1) primary key,
Name varchar(100),
Salary int ,
City varchar(20)
)
Inserting data into Employee_Table –
insert into Employee_Table ( Name,City,Salary)
VALUES
('Sruti','Dhanbad',20000),
('Raj','Kerala',25000),
('Rajsekar','Jaipur',50000),
('Prafull','Kochi',250000),
('Tripti','Kolkata',10000),
('Aditya','Mumbai',5000),
('Kiran','Indore',21000)
Reading data to verify –
SELECT * FROM Employee_Table
Output :
Methods of converting tables in T-SQL into XML :There are two common ways to convert data from SQL tables into XML format as follows.
With FOR XML AUTO –The FOR XML AUTO class creates an XML document where each column is an attribute.
SELECT * FROM Employee_Table
FOR XML AUTO
Output :
This query will create a hyperlink as an output. On clicking the link, we will see the following document in a new query window of SSMS as follows.
With FOR XML PATH clauses –FOR XML PATH will create an XML document where each row is embedded into <row> and </row> clause. In each row, each column value is embedded into <ColumnName> and </ColumnName> clauses.
SELECT * FROM Car
FOR XML PATH
Output :
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Mar, 2021"
},
{
"code": null,
"e": 229,
"s": 28,
"text": "In this, we will focus on how tables will be converted in T-SQL into XML in SQL server. And you will be able to understand how you can convert it with the help of command. Let’s discuss it one by one."
},
{
"code": null,
"e": 454,
"s": 229,
"text": "Overview :XML (Extensible Markup Language) is a markup language similar to HTML which was designed to share information between different platforms. And here, you will understand how you can Convert tables in T-SQL into XML."
},
{
"code": null,
"e": 511,
"s": 454,
"text": "Example –Here is a below sample XML Document as follows."
},
{
"code": null,
"e": 627,
"s": 511,
"text": "<email>\n <to>Manager</to>\n <from>Sruti</from>\n <heading>Work Status</heading>\n <body>Work Completed</body>\n</email>"
},
{
"code": null,
"e": 846,
"s": 627,
"text": "Converting tables in T-SQL into XML :To Convert tables in T-SQL into XML by using the following steps as follows. Let’s first generate an Employee_Table to store data of few Employees in order to create XML documents. "
},
{
"code": null,
"e": 879,
"s": 846,
"text": "Creating table – Employee_Table "
},
{
"code": null,
"e": 1011,
"s": 879,
"text": "CREATE TABLE Employee_Table \n( \nEmpId int identity(1,1) primary key, \nName varchar(100), \nSalary int , \nCity varchar(20) \n) "
},
{
"code": null,
"e": 1048,
"s": 1011,
"text": "Inserting data into Employee_Table –"
},
{
"code": null,
"e": 1289,
"s": 1048,
"text": "insert into Employee_Table ( Name,City,Salary)\nVALUES\n('Sruti','Dhanbad',20000),\n('Raj','Kerala',25000),\n('Rajsekar','Jaipur',50000),\n('Prafull','Kochi',250000),\n('Tripti','Kolkata',10000),\n('Aditya','Mumbai',5000),\n('Kiran','Indore',21000)"
},
{
"code": null,
"e": 1314,
"s": 1289,
"text": "Reading data to verify –"
},
{
"code": null,
"e": 1343,
"s": 1314,
"text": "SELECT * FROM Employee_Table"
},
{
"code": null,
"e": 1352,
"s": 1343,
"text": "Output :"
},
{
"code": null,
"e": 1486,
"s": 1352,
"text": "Methods of converting tables in T-SQL into XML :There are two common ways to convert data from SQL tables into XML format as follows."
},
{
"code": null,
"e": 1587,
"s": 1486,
"text": "With FOR XML AUTO –The FOR XML AUTO class creates an XML document where each column is an attribute."
},
{
"code": null,
"e": 1629,
"s": 1587,
"text": "SELECT * FROM Employee_Table\nFOR XML AUTO"
},
{
"code": null,
"e": 1638,
"s": 1629,
"text": "Output :"
},
{
"code": null,
"e": 1786,
"s": 1638,
"text": "This query will create a hyperlink as an output. On clicking the link, we will see the following document in a new query window of SSMS as follows."
},
{
"code": null,
"e": 1999,
"s": 1786,
"text": "With FOR XML PATH clauses –FOR XML PATH will create an XML document where each row is embedded into <row> and </row> clause. In each row, each column value is embedded into <ColumnName> and </ColumnName> clauses."
},
{
"code": null,
"e": 2030,
"s": 1999,
"text": "SELECT * FROM Car\nFOR XML PATH"
},
{
"code": null,
"e": 2039,
"s": 2030,
"text": "Output :"
},
{
"code": null,
"e": 2048,
"s": 2039,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 2059,
"s": 2048,
"text": "SQL-Server"
},
{
"code": null,
"e": 2063,
"s": 2059,
"text": "SQL"
},
{
"code": null,
"e": 2067,
"s": 2063,
"text": "SQL"
}
]
|
Internal Working of ArrayList in Java | 31 May, 2022
ArrayList is a resizable array implementation in java. ArrayList grows dynamically and ensures that there is always a space to add elements. The backing data structure of ArrayList is an array of Object classes. ArrayList class in Java has 3 constructors. It has its own version of readObject and writeObject methods. Object Array in ArrayList is transient. It implements RandomAccess, Cloneable, and java.io.Serializable (which are Marker Interface in Java)
Syntax:
public class ArrayList<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
Internally an ArrayList uses an Object[] Array which is an array of objects. All operation like deleting, adding, and updating the elements happens in this Object[] array.
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
The above code is from Java 8 in Java 7 the array is declared as a Private transient Object but in Java 8 it’s not Private because non-private is to simplify access for a nested class like Itr, ListItr, SubList.
List<String> arrayList = new ArrayList<String>();
while declaring ArrayList below code is executed as the default constructor of the ArrayList class is invoked.
In Java 7
public ArrayList() {
this(10);
}
Hereby default capacity of the Array size is 10.
In Java 8
private static final int DEFAULT_CAPACITY = 10;\\ Default initial capacity.
// Shared empty array instance used for empty instances.
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
Here, the List is initialized with a default capacity of 10. Array List with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA will be expanded to DEFAULT_CAPACITY when the first element is inserted into the Array list ( Adding 1st element to ArrayList).
To create an ArrayList, First need to create an object of the ArrayList class. ArrayList contains 3 types of constructors in Java 8
ArrayList(): This constructor is to initialize an empty List.ArrayList(int capacity): In this constructor, we can pass capacity as a parameter, used to initialize the capacity by the user.ArrayList(Collection c): In this constructor, we can pass a Collection c as a parameter, In which an Array list will contain the elements of Collection c.
ArrayList(): This constructor is to initialize an empty List.
ArrayList(int capacity): In this constructor, we can pass capacity as a parameter, used to initialize the capacity by the user.
ArrayList(Collection c): In this constructor, we can pass a Collection c as a parameter, In which an Array list will contain the elements of Collection c.
ArrayList(): This constructor is used to create an empty ArrayList with an initial capacity of 10 and this is a default constructor. We can create an empty Array list by reference name arr_name object of ArrayList class as shown below.
ArrayList arr_name = new ArrayList();
Below is the internal code for this constructor(In Java 8):
// Constructs an empty Arraylist with an initial capacity of ten.
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
In the above code, DEFAULTCAPACITY_EMPTY_ELEMENTDATA will be changed to DEFAULT_CAPACITY when we add the first element into the array list. (DEFAULT_CAPACITY =10).
ArrayList(int capacity): This constructor is used to create an ArrayList with the initial capacity given by the user. If we want to create an ArrayList with some specified size we can pass the value through this constructor. Internally Array of objects is created with the size given by the user. For Example, if a user wants the Array list size should be 7, then the value 7 can be passed in the constructor, it can be created as shown here:
ArrayList arr = new ArrayList(7);
Below is the internal code for this constructor(In Java 8):
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
}
}
In the above code, the size that can be passed into the constructor is greater than 0 (initialCapacity>0) the Array of objects created will be in the given capacity. If the capacity passed is equal to 0(initialCapacity==0) then an empty Arraylist will be created. If the initial Capacity is less than 0 (initialCapacity<0) then IllegalArgumentException will be thrown.
ArrayList(Collection<? extends E> c ): This constructor is used to create an array list initialized with the elements from the collection passed into the constructor (Collection c ). The object of the ArrayList can be created upon the specific collection passed into the constructor.
ArrayList<String> arrayList = new ArrayList<String>(new LinkedList());
Below is the internal code for this constructor(In Java 8):
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[]
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
The elements from the collection should be placed in the Array list. This code will check the size of the passed collection, If the size is greater than zero then Arrays.copyOf() method is used to copy the collection to the array. NullPointerException is thrown if the collection that passed into the constructor is null.
Example:
Java
import java.util.ArrayList;import java.util.Collection; public class Main { public static void main(String args[]) { Collection<Integer> arr = new ArrayList<Integer>(); arr.add(1); arr.add(2); arr.add(3); arr.add(4); arr.add(5); System.out.println("This is arr " + arr); ArrayList<Integer> newList = new ArrayList<Integer>(arr); System.out.println("This is newList " + newList); newList.add(7); newList.add(700); System.out.println( "This is newList after adding elements " + newList); }}
This is arr [1, 2, 3, 4, 5]
This is newList [1, 2, 3, 4, 5]
This is newList after adding elements [1, 2, 3, 4, 5, 7, 700]
Here the elements in the arr are passed to newList. So elements of arr were copied to newList this is shown in the above example.
Let’s deep dive into how to add method that works in Array list with help of the internal Java 8 code of ArrayList. If we try to add an element using the add() method in the array list Internally then it checks for the capacity to store the new element or not, If not then the new capacity is calculated as shown in the internal code of the add() method.
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Size Increments
elementData[size++] = e;
return true;
}
Here in the add(Object ) method object is passed and the size is increased. Internal capacity of the array is ensured by the ensureCapacityInternal() method
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
This ensureExplicitCapacity method determines what is the current size of elements and what is the maximum size of the array. here Minimum capacity will be the maximum of default capacity and mincapacity then goes for ensureExplicitCapacity method mincapacity as an argument.
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
Here if the (mincapacity – arraylength) is greater than 0(>0) then the Array size will grow by calling the grow() method and mincapacity as the argument passed.
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
The grow method in the ArrayList class gives the new size array. In Java 8 and later The new capacity is calculated which is 50% more than the old capacity and the array is increased by that capacity. It uses Arrays.copyOf which gives the array increased to the new length by right shift operator also it will grow by 50% of old capacity.
int newCapacity = oldCapacity + (oldCapacity >> 1);
For example, if the Array size is 10 and already all the rooms were filled by the elements, while we are adding a new element now the array capacity will be increased as 10+ (10>>1) => 10+ 5 => 15. Here the size is increased from 10 to 15. To increase the size by 50% we use the right shift operator. While in Java 6 it’s totally different from the above calculation on increasing the size of the Array, in java 6 the capacity increases by the amount to 1.5X
int newCapacity = (oldCapacity * 3)/2 + 1;
To remove an element from ArrayList in Java , we can use either remove(int i) [0 index based] or remove(Object o) . while removing any element from an ArrayList, internally all the subsequent elements are to be shifted left to fill the gap created by the removed element in the array then subtracts one from their indices. size of the array will be decreased by 1 ( – – size).
// Removes the element at the specified position in this list.
// Shifts any subsequent elements to the left (subtracts one from their indices).
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index, numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
System.arrayCopy method is used for this purpose. Here index+1 is the initial position and index is the final position. Since the element at the position index is removed so elements starting from index+1 are copied to the destination starting from the index.
System.arraycopy(elementData, index+1, elementData, index, numMoved);
This is how ArrayList shrinks automatically.
Whenever we create an ArrayList and it reaches its threshold, Internally creates a new ArrayList object with a new capacity and copies all old elements from the old ArrayList to a new object. This process will take more space and time even it provides flexibility to do.
Threshold
Threshold = (Current Capacity) * (Load Factor)
The load factor is the measure that decides when to increase the capacity of the ArrayList. The default load factor of an ArrayList is 0.75f. For example, current capacity is 10. So, loadfactor = 10*0.75=7 while adding the 7th element array size will increase. So, It would be good practice if we choose the initial capacity, by keeping the number of expected elements in mind as approx.
The time complexity of the common operations in ArrayList java.
add(): For adding a single element O(1) . Adding n element in the array list takes O(n).
add(index, element): adding element in particular index in average runs in O(n) time.
get(): is always a constant time O(1) operation.
remove(): runs in linear O(n) time. We have to iterate the entire array to find the element fit for removal.
indexOf(): It runs over the whole array and iterates through each and every element worst case will be the size of the array n .so, it requires O(n) time.
contains(): implementation is based on indexOf(). So it will also run in O(n) time.
The size, isEmpty, set, iterator, and listIterator operations run in constant time O(1)
Note:
ArrayList is a resizable array implementation in java.
The backing data structure of ArrayList is an array of Object class.
When creating an ArrayList you can provide initial capacity then the array is declared with the given capacity.
The default capacity value is 10. If the initial capacity is not specified by the user then the default capacity is used to create an array of objects.
When an element is added to an ArrayList it first checks whether the new element has room to fill or it needs to grow the size of the internal array, If capacity has to be increased then the new capacity is calculated which is 50% more than the old capacity and the array is increased by that capacity.
vinayakg100
Java-ArrayList
Java-Collections
Technical Scripter 2020
Java
Technical Scripter
Java
Java-Collections
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": 513,
"s": 54,
"text": "ArrayList is a resizable array implementation in java. ArrayList grows dynamically and ensures that there is always a space to add elements. The backing data structure of ArrayList is an array of Object classes. ArrayList class in Java has 3 constructors. It has its own version of readObject and writeObject methods. Object Array in ArrayList is transient. It implements RandomAccess, Cloneable, and java.io.Serializable (which are Marker Interface in Java)"
},
{
"code": null,
"e": 521,
"s": 513,
"text": "Syntax:"
},
{
"code": null,
"e": 645,
"s": 521,
"text": "public class ArrayList<E> \nextends AbstractList<E> \nimplements List<E>, RandomAccess, Cloneable, java.io.Serializable "
},
{
"code": null,
"e": 817,
"s": 645,
"text": "Internally an ArrayList uses an Object[] Array which is an array of objects. All operation like deleting, adding, and updating the elements happens in this Object[] array."
},
{
"code": null,
"e": 1215,
"s": 817,
"text": "/**\n * The array buffer into which the elements of the ArrayList are stored.\n * The capacity of the ArrayList is the length of this array buffer. Any\n * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA\n * will be expanded to DEFAULT_CAPACITY when the first element is added.\n */\ntransient Object[] elementData; // non-private to simplify nested class access "
},
{
"code": null,
"e": 1427,
"s": 1215,
"text": "The above code is from Java 8 in Java 7 the array is declared as a Private transient Object but in Java 8 it’s not Private because non-private is to simplify access for a nested class like Itr, ListItr, SubList."
},
{
"code": null,
"e": 1477,
"s": 1427,
"text": "List<String> arrayList = new ArrayList<String>();"
},
{
"code": null,
"e": 1588,
"s": 1477,
"text": "while declaring ArrayList below code is executed as the default constructor of the ArrayList class is invoked."
},
{
"code": null,
"e": 1598,
"s": 1588,
"text": "In Java 7"
},
{
"code": null,
"e": 1636,
"s": 1598,
"text": "public ArrayList() {\n this(10);\n}"
},
{
"code": null,
"e": 1686,
"s": 1636,
"text": "Hereby default capacity of the Array size is 10."
},
{
"code": null,
"e": 1696,
"s": 1686,
"text": "In Java 8"
},
{
"code": null,
"e": 2156,
"s": 1696,
"text": "private static final int DEFAULT_CAPACITY = 10;\\\\ Default initial capacity.\n \n// Shared empty array instance used for empty instances.\nprivate static final Object[] EMPTY_ELEMENTDATA = {};\n\n /**\n * Shared empty array instance used for default sized empty instances. We\n * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when\n * first element is added.\n */\n \nprivate static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};"
},
{
"code": null,
"e": 2410,
"s": 2156,
"text": "Here, the List is initialized with a default capacity of 10. Array List with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA will be expanded to DEFAULT_CAPACITY when the first element is inserted into the Array list ( Adding 1st element to ArrayList)."
},
{
"code": null,
"e": 2544,
"s": 2410,
"text": "To create an ArrayList, First need to create an object of the ArrayList class. ArrayList contains 3 types of constructors in Java 8 "
},
{
"code": null,
"e": 2887,
"s": 2544,
"text": "ArrayList(): This constructor is to initialize an empty List.ArrayList(int capacity): In this constructor, we can pass capacity as a parameter, used to initialize the capacity by the user.ArrayList(Collection c): In this constructor, we can pass a Collection c as a parameter, In which an Array list will contain the elements of Collection c."
},
{
"code": null,
"e": 2949,
"s": 2887,
"text": "ArrayList(): This constructor is to initialize an empty List."
},
{
"code": null,
"e": 3077,
"s": 2949,
"text": "ArrayList(int capacity): In this constructor, we can pass capacity as a parameter, used to initialize the capacity by the user."
},
{
"code": null,
"e": 3232,
"s": 3077,
"text": "ArrayList(Collection c): In this constructor, we can pass a Collection c as a parameter, In which an Array list will contain the elements of Collection c."
},
{
"code": null,
"e": 3468,
"s": 3232,
"text": "ArrayList(): This constructor is used to create an empty ArrayList with an initial capacity of 10 and this is a default constructor. We can create an empty Array list by reference name arr_name object of ArrayList class as shown below."
},
{
"code": null,
"e": 3508,
"s": 3468,
"text": "ArrayList arr_name = new ArrayList(); "
},
{
"code": null,
"e": 3573,
"s": 3508,
"text": "Below is the internal code for this constructor(In Java 8): "
},
{
"code": null,
"e": 3726,
"s": 3573,
"text": "// Constructs an empty Arraylist with an initial capacity of ten.\n \npublic ArrayList() {\n this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;\n}"
},
{
"code": null,
"e": 3891,
"s": 3726,
"text": "In the above code, DEFAULTCAPACITY_EMPTY_ELEMENTDATA will be changed to DEFAULT_CAPACITY when we add the first element into the array list. (DEFAULT_CAPACITY =10)."
},
{
"code": null,
"e": 4335,
"s": 3891,
"text": "ArrayList(int capacity): This constructor is used to create an ArrayList with the initial capacity given by the user. If we want to create an ArrayList with some specified size we can pass the value through this constructor. Internally Array of objects is created with the size given by the user. For Example, if a user wants the Array list size should be 7, then the value 7 can be passed in the constructor, it can be created as shown here:"
},
{
"code": null,
"e": 4369,
"s": 4335,
"text": "ArrayList arr = new ArrayList(7);"
},
{
"code": null,
"e": 4432,
"s": 4369,
"text": "Below is the internal code for this constructor(In Java 8): "
},
{
"code": null,
"e": 4801,
"s": 4432,
"text": "public ArrayList(int initialCapacity) {\n\n if (initialCapacity > 0) {\n this.elementData = new Object[initialCapacity]; \n \n } else if (initialCapacity == 0) {\n \n this.elementData = EMPTY_ELEMENTDATA;\n } else {\n \n throw new IllegalArgumentException(\"Illegal Capacity: \"+ initialCapacity);\n }\n}"
},
{
"code": null,
"e": 5174,
"s": 4801,
"text": "In the above code, the size that can be passed into the constructor is greater than 0 (initialCapacity>0) the Array of objects created will be in the given capacity. If the capacity passed is equal to 0(initialCapacity==0) then an empty Arraylist will be created. If the initial Capacity is less than 0 (initialCapacity<0) then IllegalArgumentException will be thrown. "
},
{
"code": null,
"e": 5458,
"s": 5174,
"text": "ArrayList(Collection<? extends E> c ): This constructor is used to create an array list initialized with the elements from the collection passed into the constructor (Collection c ). The object of the ArrayList can be created upon the specific collection passed into the constructor."
},
{
"code": null,
"e": 5529,
"s": 5458,
"text": "ArrayList<String> arrayList = new ArrayList<String>(new LinkedList());"
},
{
"code": null,
"e": 5593,
"s": 5529,
"text": " Below is the internal code for this constructor(In Java 8): "
},
{
"code": null,
"e": 6057,
"s": 5593,
"text": "public ArrayList(Collection<? extends E> c) {\n elementData = c.toArray();\n if ((size = elementData.length) != 0) {\n \n // c.toArray might (incorrectly) not return Object[] \n if (elementData.getClass() != Object[].class)\n elementData = Arrays.copyOf(elementData, size, Object[].class);\n } else {\n \n // replace with empty array.\n this.elementData = EMPTY_ELEMENTDATA; \n }\n }"
},
{
"code": null,
"e": 6380,
"s": 6057,
"text": "The elements from the collection should be placed in the Array list. This code will check the size of the passed collection, If the size is greater than zero then Arrays.copyOf() method is used to copy the collection to the array. NullPointerException is thrown if the collection that passed into the constructor is null. "
},
{
"code": null,
"e": 6389,
"s": 6380,
"text": "Example:"
},
{
"code": null,
"e": 6394,
"s": 6389,
"text": "Java"
},
{
"code": "import java.util.ArrayList;import java.util.Collection; public class Main { public static void main(String args[]) { Collection<Integer> arr = new ArrayList<Integer>(); arr.add(1); arr.add(2); arr.add(3); arr.add(4); arr.add(5); System.out.println(\"This is arr \" + arr); ArrayList<Integer> newList = new ArrayList<Integer>(arr); System.out.println(\"This is newList \" + newList); newList.add(7); newList.add(700); System.out.println( \"This is newList after adding elements \" + newList); }}",
"e": 7009,
"s": 6394,
"text": null
},
{
"code": null,
"e": 7131,
"s": 7009,
"text": "This is arr [1, 2, 3, 4, 5]\nThis is newList [1, 2, 3, 4, 5]\nThis is newList after adding elements [1, 2, 3, 4, 5, 7, 700]"
},
{
"code": null,
"e": 7261,
"s": 7131,
"text": "Here the elements in the arr are passed to newList. So elements of arr were copied to newList this is shown in the above example."
},
{
"code": null,
"e": 7617,
"s": 7261,
"text": "Let’s deep dive into how to add method that works in Array list with help of the internal Java 8 code of ArrayList. If we try to add an element using the add() method in the array list Internally then it checks for the capacity to store the new element or not, If not then the new capacity is calculated as shown in the internal code of the add() method."
},
{
"code": null,
"e": 7804,
"s": 7617,
"text": "public boolean add(E e) {\n ensureCapacityInternal(size + 1); // Size Increments\n elementData[size++] = e;\n return true;\n} "
},
{
"code": null,
"e": 7963,
"s": 7804,
"text": " Here in the add(Object ) method object is passed and the size is increased. Internal capacity of the array is ensured by the ensureCapacityInternal() method "
},
{
"code": null,
"e": 8203,
"s": 7963,
"text": "private void ensureCapacityInternal(int minCapacity) {\n\n if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {\n minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);\n }\n ensureExplicitCapacity(minCapacity);\n}"
},
{
"code": null,
"e": 8479,
"s": 8203,
"text": "This ensureExplicitCapacity method determines what is the current size of elements and what is the maximum size of the array. here Minimum capacity will be the maximum of default capacity and mincapacity then goes for ensureExplicitCapacity method mincapacity as an argument."
},
{
"code": null,
"e": 8676,
"s": 8479,
"text": "private void ensureExplicitCapacity(int minCapacity) {\n modCount++;\n \n // overflow-conscious code\n if (minCapacity - elementData.length > 0)\n grow(minCapacity);\n}"
},
{
"code": null,
"e": 8837,
"s": 8676,
"text": "Here if the (mincapacity – arraylength) is greater than 0(>0) then the Array size will grow by calling the grow() method and mincapacity as the argument passed."
},
{
"code": null,
"e": 9531,
"s": 8837,
"text": "/**\n * Increases the capacity to ensure that it can hold at least the\n * number of elements specified by the minimum capacity argument.\n *\n * @param minCapacity the desired minimum capacity\n */\n private void grow(int minCapacity) {\n // overflow-conscious code\n int oldCapacity = elementData.length;\n int newCapacity = oldCapacity + (oldCapacity >> 1);\n if (newCapacity - minCapacity < 0)\n newCapacity = minCapacity;\n if (newCapacity - MAX_ARRAY_SIZE > 0)\n newCapacity = hugeCapacity(minCapacity);\n // minCapacity is usually close to size, so this is a win:\n elementData = Arrays.copyOf(elementData, newCapacity);\n}"
},
{
"code": null,
"e": 9870,
"s": 9531,
"text": "The grow method in the ArrayList class gives the new size array. In Java 8 and later The new capacity is calculated which is 50% more than the old capacity and the array is increased by that capacity. It uses Arrays.copyOf which gives the array increased to the new length by right shift operator also it will grow by 50% of old capacity."
},
{
"code": null,
"e": 9922,
"s": 9870,
"text": "int newCapacity = oldCapacity + (oldCapacity >> 1);"
},
{
"code": null,
"e": 10381,
"s": 9922,
"text": "For example, if the Array size is 10 and already all the rooms were filled by the elements, while we are adding a new element now the array capacity will be increased as 10+ (10>>1) => 10+ 5 => 15. Here the size is increased from 10 to 15. To increase the size by 50% we use the right shift operator. While in Java 6 it’s totally different from the above calculation on increasing the size of the Array, in java 6 the capacity increases by the amount to 1.5X"
},
{
"code": null,
"e": 10424,
"s": 10381,
"text": "int newCapacity = (oldCapacity * 3)/2 + 1;"
},
{
"code": null,
"e": 10804,
"s": 10424,
"text": "To remove an element from ArrayList in Java , we can use either remove(int i) [0 index based] or remove(Object o) . while removing any element from an ArrayList, internally all the subsequent elements are to be shifted left to fill the gap created by the removed element in the array then subtracts one from their indices. size of the array will be decreased by 1 ( – – size)."
},
{
"code": null,
"e": 11251,
"s": 10804,
"text": "// Removes the element at the specified position in this list.\n// Shifts any subsequent elements to the left (subtracts one from their indices).\npublic E remove(int index) {\n rangeCheck(index);\n modCount++;\n E oldValue = elementData(index);\n int numMoved = size - index - 1;\n if (numMoved > 0)\n System.arraycopy(elementData, index+1, elementData, index, numMoved);\n elementData[--size] = null; // clear to let GC do its work\n return oldValue;\n}"
},
{
"code": null,
"e": 11512,
"s": 11251,
"text": "System.arrayCopy method is used for this purpose. Here index+1 is the initial position and index is the final position. Since the element at the position index is removed so elements starting from index+1 are copied to the destination starting from the index. "
},
{
"code": null,
"e": 11582,
"s": 11512,
"text": "System.arraycopy(elementData, index+1, elementData, index, numMoved);"
},
{
"code": null,
"e": 11627,
"s": 11582,
"text": "This is how ArrayList shrinks automatically."
},
{
"code": null,
"e": 11898,
"s": 11627,
"text": "Whenever we create an ArrayList and it reaches its threshold, Internally creates a new ArrayList object with a new capacity and copies all old elements from the old ArrayList to a new object. This process will take more space and time even it provides flexibility to do."
},
{
"code": null,
"e": 11908,
"s": 11898,
"text": "Threshold"
},
{
"code": null,
"e": 11955,
"s": 11908,
"text": "Threshold = (Current Capacity) * (Load Factor)"
},
{
"code": null,
"e": 12345,
"s": 11955,
"text": "The load factor is the measure that decides when to increase the capacity of the ArrayList. The default load factor of an ArrayList is 0.75f. For example, current capacity is 10. So, loadfactor = 10*0.75=7 while adding the 7th element array size will increase. So, It would be good practice if we choose the initial capacity, by keeping the number of expected elements in mind as approx."
},
{
"code": null,
"e": 12409,
"s": 12345,
"text": "The time complexity of the common operations in ArrayList java."
},
{
"code": null,
"e": 12498,
"s": 12409,
"text": "add(): For adding a single element O(1) . Adding n element in the array list takes O(n)."
},
{
"code": null,
"e": 12584,
"s": 12498,
"text": "add(index, element): adding element in particular index in average runs in O(n) time."
},
{
"code": null,
"e": 12633,
"s": 12584,
"text": "get(): is always a constant time O(1) operation."
},
{
"code": null,
"e": 12742,
"s": 12633,
"text": "remove(): runs in linear O(n) time. We have to iterate the entire array to find the element fit for removal."
},
{
"code": null,
"e": 12898,
"s": 12742,
"text": "indexOf(): It runs over the whole array and iterates through each and every element worst case will be the size of the array n .so, it requires O(n) time."
},
{
"code": null,
"e": 12982,
"s": 12898,
"text": "contains(): implementation is based on indexOf(). So it will also run in O(n) time."
},
{
"code": null,
"e": 13070,
"s": 12982,
"text": "The size, isEmpty, set, iterator, and listIterator operations run in constant time O(1)"
},
{
"code": null,
"e": 13076,
"s": 13070,
"text": "Note:"
},
{
"code": null,
"e": 13131,
"s": 13076,
"text": "ArrayList is a resizable array implementation in java."
},
{
"code": null,
"e": 13200,
"s": 13131,
"text": "The backing data structure of ArrayList is an array of Object class."
},
{
"code": null,
"e": 13312,
"s": 13200,
"text": "When creating an ArrayList you can provide initial capacity then the array is declared with the given capacity."
},
{
"code": null,
"e": 13464,
"s": 13312,
"text": "The default capacity value is 10. If the initial capacity is not specified by the user then the default capacity is used to create an array of objects."
},
{
"code": null,
"e": 13767,
"s": 13464,
"text": "When an element is added to an ArrayList it first checks whether the new element has room to fill or it needs to grow the size of the internal array, If capacity has to be increased then the new capacity is calculated which is 50% more than the old capacity and the array is increased by that capacity."
},
{
"code": null,
"e": 13779,
"s": 13767,
"text": "vinayakg100"
},
{
"code": null,
"e": 13794,
"s": 13779,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 13811,
"s": 13794,
"text": "Java-Collections"
},
{
"code": null,
"e": 13835,
"s": 13811,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 13840,
"s": 13835,
"text": "Java"
},
{
"code": null,
"e": 13859,
"s": 13840,
"text": "Technical Scripter"
},
{
"code": null,
"e": 13864,
"s": 13859,
"text": "Java"
},
{
"code": null,
"e": 13881,
"s": 13864,
"text": "Java-Collections"
}
]
|
Converting all strings in list to integers in Python | Sometimes we can have a list containing strings but the strings themselves are numbers and closing quotes. In such a list we want to convert the string elements into actual integers.
The int function takes in parameters and converts it to integers if it is already a number. So we design a for loop to go through each element of the list and apply the in function. We store the final result into a new list.
Live Demo
listA = ['5', '2','-43', '23']
# Given list
print("Given list with strings : \n",listA)
# using int
res = [int(i) for i in listA]
# Result
print("The converted list with integers : \n",res)
Running the above code gives us the following result −
Given list with strings :
['5', '2', '-43', '23']
The converted list with integers :
[5, 2, -43, 23]
The map function can be used to apply int function into every element that is present as a string in the given list.
Live Demo
listA = ['5', '2','-43', '23']
# Given list
print("Given list with strings : \n",listA)
# using map and int
res = list(map(int, listA))
# Result
print("The converted list with integers : \n",res)
Running the above code gives us the following result −
Given list with strings :
['5', '2', '-43', '23']
The converted list with integers :
[5, 2, -43, 23] | [
{
"code": null,
"e": 1370,
"s": 1187,
"text": "Sometimes we can have a list containing strings but the strings themselves are numbers and closing quotes. In such a list we want to convert the string elements into actual integers."
},
{
"code": null,
"e": 1595,
"s": 1370,
"text": "The int function takes in parameters and converts it to integers if it is already a number. So we design a for loop to go through each element of the list and apply the in function. We store the final result into a new list."
},
{
"code": null,
"e": 1606,
"s": 1595,
"text": " Live Demo"
},
{
"code": null,
"e": 1796,
"s": 1606,
"text": "listA = ['5', '2','-43', '23']\n# Given list\nprint(\"Given list with strings : \\n\",listA)\n# using int\nres = [int(i) for i in listA]\n# Result\nprint(\"The converted list with integers : \\n\",res)"
},
{
"code": null,
"e": 1851,
"s": 1796,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1952,
"s": 1851,
"text": "Given list with strings :\n['5', '2', '-43', '23']\nThe converted list with integers :\n[5, 2, -43, 23]"
},
{
"code": null,
"e": 2069,
"s": 1952,
"text": "The map function can be used to apply int function into every element that is present as a string in the given list."
},
{
"code": null,
"e": 2080,
"s": 2069,
"text": " Live Demo"
},
{
"code": null,
"e": 2276,
"s": 2080,
"text": "listA = ['5', '2','-43', '23']\n# Given list\nprint(\"Given list with strings : \\n\",listA)\n# using map and int\nres = list(map(int, listA))\n# Result\nprint(\"The converted list with integers : \\n\",res)"
},
{
"code": null,
"e": 2331,
"s": 2276,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2432,
"s": 2331,
"text": "Given list with strings :\n['5', '2', '-43', '23']\nThe converted list with integers :\n[5, 2, -43, 23]"
}
]
|
Explain use of Meta tags in HTML ? | 24 Aug, 2021
Meta Tag (<meta/>) is a HTML component that gives the metadata about a HTML document. MetaData can be characterized as data that gives the data of different information or basic information about information. It is an empty tag, for example, it just has an initial tag and no end tag. They are always present inside the <Head> tag and are utilized to portray Page portrayals, Certain Keywords, Author of the Document, viewport settings, determining character sets, and so on.They are used by Web Browsers, Search Engines, and other Web Services to rank the web pages accordingly.
Syntax :
<head>
<meta attribute-name = "value"/>
</head>
Attributes:
name: This attribute is used for indicating the character encoding for the HTML Document.
http-equiv: This attribute is used to get the HTTP response message header.
content: This attribute is used to specify properties value.
charset: This is used for indicating the character encoding for the HTML Document.
Example:
HTML
<!DOCTYPE html><html> <head> <meta charset="UTF-8" /> <meta name="description" content= "Free Computer Science Content" /> <meta name="keywords" content="HTML" /> <meta name="author" content="GFG" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /></head> <body> <p>Meta Tags are used in this HTML Web page</p></body> </html>
Meta Tags are used
Uses of Meta Tags in HTML:
1. Specifying Important Keywords: The meta tag contains important keywords that are present on the web page and is utilized by the web browser to rank the page according to searches. Search Engine Optimization is another term for this optimizing the SEO rank of the content.Example:
HTML
<!DOCTYPE html><html> <head> <!-- meta tag starts --> <meta name="keywords" content= "Meta Tags HTML GFG Meta Data " /> <!-- meta tag ends --> </head> <body> <p>This is a MetaTags Web page</p></body> </html>
Output:
Specifying Keywords in the metatag
We can see that a few keywords have been provided in the example above, which will aid the web browser in ranking the web page.
2. Automatic Refresh: A specified time will be mentioned in the meta tag after which the webpage will be automatically refreshed.
Example:
HTML
<!DOCTYPE html><html> <head> <!-- meta tag starts --> <meta name="revised about" content="GeeksforGeeks" /> <meta http-equiv="refresh" content="8" /> <!-- meta tag ends --></head> <body> <p>We are using refresh meta tag</p></body> </html>
Output: As you can observe in the above example the web page will be reloaded after 8 seconds as mentioned in the <meta> tag.
The time after which the webpage has to be reloaded is mentioned in the metatag
3. Specifying Author of the Webpage: MetaTag allows us to mention the name of the author of the webpage as follows.
HTML
<!DOCTYPE html><html> <head> <!-- meta tag starts --> <meta name="author" content="U Phani Teja" /> <!-- meta tag ends --> </head> <body> <p> We are specifying name of the Author in the Meta Tag </p></body> </html>
Output: In this example, the name of the author is specified in the <meta> tag
Providing the Author’s name in the meta tag
4. Providing a Description of the web page: A brief description of the web page can be included in the Meta tag, which will help the web page rank on the internet.
HTML
<!DOCTYPE html><html> <head> <!-- meta tag starts --> <meta name="description" content="All About Meta tags" /> <!-- meta tag ends --> </head> <body> <p> A brief Description of the WebPage is present in the webapage </p></body> </html>
Output: In the this example, a small description of the web page is given in the <meta> tag.
Providing a brief description in the metatag
HTML-Questions
HTML-Tags
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Aug, 2021"
},
{
"code": null,
"e": 608,
"s": 28,
"text": "Meta Tag (<meta/>) is a HTML component that gives the metadata about a HTML document. MetaData can be characterized as data that gives the data of different information or basic information about information. It is an empty tag, for example, it just has an initial tag and no end tag. They are always present inside the <Head> tag and are utilized to portray Page portrayals, Certain Keywords, Author of the Document, viewport settings, determining character sets, and so on.They are used by Web Browsers, Search Engines, and other Web Services to rank the web pages accordingly."
},
{
"code": null,
"e": 618,
"s": 608,
"text": "Syntax : "
},
{
"code": null,
"e": 669,
"s": 618,
"text": "<head>\n <meta attribute-name = \"value\"/>\n</head>"
},
{
"code": null,
"e": 681,
"s": 669,
"text": "Attributes:"
},
{
"code": null,
"e": 771,
"s": 681,
"text": "name: This attribute is used for indicating the character encoding for the HTML Document."
},
{
"code": null,
"e": 847,
"s": 771,
"text": "http-equiv: This attribute is used to get the HTTP response message header."
},
{
"code": null,
"e": 908,
"s": 847,
"text": "content: This attribute is used to specify properties value."
},
{
"code": null,
"e": 991,
"s": 908,
"text": "charset: This is used for indicating the character encoding for the HTML Document."
},
{
"code": null,
"e": 1000,
"s": 991,
"text": "Example:"
},
{
"code": null,
"e": 1005,
"s": 1000,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\" /> <meta name=\"description\" content= \"Free Computer Science Content\" /> <meta name=\"keywords\" content=\"HTML\" /> <meta name=\"author\" content=\"GFG\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /></head> <body> <p>Meta Tags are used in this HTML Web page</p></body> </html>",
"e": 1391,
"s": 1005,
"text": null
},
{
"code": null,
"e": 1410,
"s": 1391,
"text": "Meta Tags are used"
},
{
"code": null,
"e": 1439,
"s": 1412,
"text": "Uses of Meta Tags in HTML:"
},
{
"code": null,
"e": 1722,
"s": 1439,
"text": "1. Specifying Important Keywords: The meta tag contains important keywords that are present on the web page and is utilized by the web browser to rank the page according to searches. Search Engine Optimization is another term for this optimizing the SEO rank of the content.Example:"
},
{
"code": null,
"e": 1727,
"s": 1722,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- meta tag starts --> <meta name=\"keywords\" content= \"Meta Tags HTML GFG Meta Data \" /> <!-- meta tag ends --> </head> <body> <p>This is a MetaTags Web page</p></body> </html>",
"e": 1958,
"s": 1727,
"text": null
},
{
"code": null,
"e": 1966,
"s": 1958,
"text": "Output:"
},
{
"code": null,
"e": 2001,
"s": 1966,
"text": "Specifying Keywords in the metatag"
},
{
"code": null,
"e": 2129,
"s": 2001,
"text": "We can see that a few keywords have been provided in the example above, which will aid the web browser in ranking the web page."
},
{
"code": null,
"e": 2259,
"s": 2129,
"text": "2. Automatic Refresh: A specified time will be mentioned in the meta tag after which the webpage will be automatically refreshed."
},
{
"code": null,
"e": 2268,
"s": 2259,
"text": "Example:"
},
{
"code": null,
"e": 2273,
"s": 2268,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- meta tag starts --> <meta name=\"revised about\" content=\"GeeksforGeeks\" /> <meta http-equiv=\"refresh\" content=\"8\" /> <!-- meta tag ends --></head> <body> <p>We are using refresh meta tag</p></body> </html>",
"e": 2540,
"s": 2273,
"text": null
},
{
"code": null,
"e": 2667,
"s": 2540,
"text": "Output: As you can observe in the above example the web page will be reloaded after 8 seconds as mentioned in the <meta> tag. "
},
{
"code": null,
"e": 2748,
"s": 2667,
"text": "The time after which the webpage has to be reloaded is mentioned in the metatag "
},
{
"code": null,
"e": 2864,
"s": 2748,
"text": "3. Specifying Author of the Webpage: MetaTag allows us to mention the name of the author of the webpage as follows."
},
{
"code": null,
"e": 2869,
"s": 2864,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- meta tag starts --> <meta name=\"author\" content=\"U Phani Teja\" /> <!-- meta tag ends --> </head> <body> <p> We are specifying name of the Author in the Meta Tag </p></body> </html>",
"e": 3124,
"s": 2869,
"text": null
},
{
"code": null,
"e": 3203,
"s": 3124,
"text": "Output: In this example, the name of the author is specified in the <meta> tag"
},
{
"code": null,
"e": 3248,
"s": 3203,
"text": "Providing the Author’s name in the meta tag "
},
{
"code": null,
"e": 3412,
"s": 3248,
"text": "4. Providing a Description of the web page: A brief description of the web page can be included in the Meta tag, which will help the web page rank on the internet."
},
{
"code": null,
"e": 3417,
"s": 3412,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- meta tag starts --> <meta name=\"description\" content=\"All About Meta tags\" /> <!-- meta tag ends --> </head> <body> <p> A brief Description of the WebPage is present in the webapage </p></body> </html>",
"e": 3697,
"s": 3417,
"text": null
},
{
"code": null,
"e": 3790,
"s": 3697,
"text": "Output: In the this example, a small description of the web page is given in the <meta> tag."
},
{
"code": null,
"e": 3835,
"s": 3790,
"text": "Providing a brief description in the metatag"
},
{
"code": null,
"e": 3850,
"s": 3835,
"text": "HTML-Questions"
},
{
"code": null,
"e": 3860,
"s": 3850,
"text": "HTML-Tags"
},
{
"code": null,
"e": 3867,
"s": 3860,
"text": "Picked"
},
{
"code": null,
"e": 3872,
"s": 3867,
"text": "HTML"
},
{
"code": null,
"e": 3889,
"s": 3872,
"text": "Web Technologies"
},
{
"code": null,
"e": 3894,
"s": 3889,
"text": "HTML"
},
{
"code": null,
"e": 3992,
"s": 3894,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4016,
"s": 3992,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 4055,
"s": 4016,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 4094,
"s": 4055,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 4114,
"s": 4094,
"text": "Angular File Upload"
},
{
"code": null,
"e": 4143,
"s": 4114,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 4176,
"s": 4143,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4237,
"s": 4176,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4280,
"s": 4237,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 4352,
"s": 4280,
"text": "Differences between Functional Components and Class Components in React"
}
]
|
Map Function in MATLAB | 22 Sep, 2021
A map function basically takes the elements of the array and applies a function to each element. The resultant output is of the same shape as the array, but the values are the result of the function. In MATLAB, there is a similar function called arrayfun(), which we can be used to achieve the same task. The output from this arrayfunc can have any data type.
Syntax:
X = arrayfun(func,A)
Parameters:
fun: It is a function that we are going to map on each element of the array A.
A: It is the array on which we are going to map the function.
X: In variable X the output is going to be stored from the map function.
Here, arrayfun(funct,A) applies the function funct to the elements of array A. arrayfun then concatenates the outputs from funct into the output array X, so that for the ith element of A, X(i) = funct(A(i)).
The input argument funct is a function handle to a function that takes one input argument and returns a scalar.
Let’s take an example for a better understanding:
Example 1:
Matlab
% MAP function in MatLab % creating a dummy array % on which we are going to map a functionA = [1,2,3,4,5,6,7,8,9,10]; % Applying arrayfun() output = arrayfun(@(x) x*2, A); % displaying outputfprintf("output is :");disp(output);
Output:
Applying arrayfun()
In the above function, firstly we have created an array to which we are going to map a custom function. The custom is x*2 i.e. multiply each element in the array by 2.
Then we are using arrayfun(@(x) x*2, A), lets break down this statement here arrayfun(fun,array) is the general syntax for mapping a function to the array. We are using @(x) and x*2 in the statement where x*2 is the custom function that we are applying and @(x) is acts as each element of that array A. After that, we’re storing the output to a variable and then using fprintf function we printed a string on display and using the disp function we display the output.
Example 2:
Matlab
% MAP function in MatLab % creating two dummy arrays % on which we are going to map a functionA = [1,2,3,4,5];B = [6,7,8,9,10]; % Applying arrayfun() output = arrayfun(@(x,y) x*y, A,B); % displaying outputfprintf("Product is :");disp(output);
Output:
Product to two arrays using arrayfun()
Blogathon-2021
MATLAB-Functions
Picked
Blogathon
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What’s a broadcast storm?
How to pass data into table from a form using React Components
How to Import JSON Data into SQL Server?
Consensus Problem of Distributed Systems
Difference between write() and writelines() function in Python
Installing MATLAB on Linux
How to Find Index of Element in Array in MATLAB?
Laplacian Filter using Matlab
Boundary Extraction of image using MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 389,
"s": 28,
"text": "A map function basically takes the elements of the array and applies a function to each element. The resultant output is of the same shape as the array, but the values are the result of the function. In MATLAB, there is a similar function called arrayfun(), which we can be used to achieve the same task. The output from this arrayfunc can have any data type."
},
{
"code": null,
"e": 397,
"s": 389,
"text": "Syntax:"
},
{
"code": null,
"e": 418,
"s": 397,
"text": "X = arrayfun(func,A)"
},
{
"code": null,
"e": 430,
"s": 418,
"text": "Parameters:"
},
{
"code": null,
"e": 509,
"s": 430,
"text": "fun: It is a function that we are going to map on each element of the array A."
},
{
"code": null,
"e": 572,
"s": 509,
"text": "A: It is the array on which we are going to map the function."
},
{
"code": null,
"e": 645,
"s": 572,
"text": "X: In variable X the output is going to be stored from the map function."
},
{
"code": null,
"e": 854,
"s": 645,
"text": "Here, arrayfun(funct,A) applies the function funct to the elements of array A. arrayfun then concatenates the outputs from funct into the output array X, so that for the ith element of A, X(i) = funct(A(i)). "
},
{
"code": null,
"e": 967,
"s": 854,
"text": "The input argument funct is a function handle to a function that takes one input argument and returns a scalar. "
},
{
"code": null,
"e": 1017,
"s": 967,
"text": "Let’s take an example for a better understanding:"
},
{
"code": null,
"e": 1028,
"s": 1017,
"text": "Example 1:"
},
{
"code": null,
"e": 1035,
"s": 1028,
"text": "Matlab"
},
{
"code": "% MAP function in MatLab % creating a dummy array % on which we are going to map a functionA = [1,2,3,4,5,6,7,8,9,10]; % Applying arrayfun() output = arrayfun(@(x) x*2, A); % displaying outputfprintf(\"output is :\");disp(output);",
"e": 1268,
"s": 1035,
"text": null
},
{
"code": null,
"e": 1276,
"s": 1268,
"text": "Output:"
},
{
"code": null,
"e": 1296,
"s": 1276,
"text": "Applying arrayfun()"
},
{
"code": null,
"e": 1464,
"s": 1296,
"text": "In the above function, firstly we have created an array to which we are going to map a custom function. The custom is x*2 i.e. multiply each element in the array by 2."
},
{
"code": null,
"e": 1933,
"s": 1464,
"text": " Then we are using arrayfun(@(x) x*2, A), lets break down this statement here arrayfun(fun,array) is the general syntax for mapping a function to the array. We are using @(x) and x*2 in the statement where x*2 is the custom function that we are applying and @(x) is acts as each element of that array A. After that, we’re storing the output to a variable and then using fprintf function we printed a string on display and using the disp function we display the output."
},
{
"code": null,
"e": 1944,
"s": 1933,
"text": "Example 2:"
},
{
"code": null,
"e": 1951,
"s": 1944,
"text": "Matlab"
},
{
"code": "% MAP function in MatLab % creating two dummy arrays % on which we are going to map a functionA = [1,2,3,4,5];B = [6,7,8,9,10]; % Applying arrayfun() output = arrayfun(@(x,y) x*y, A,B); % displaying outputfprintf(\"Product is :\");disp(output);",
"e": 2198,
"s": 1951,
"text": null
},
{
"code": null,
"e": 2206,
"s": 2198,
"text": "Output:"
},
{
"code": null,
"e": 2245,
"s": 2206,
"text": "Product to two arrays using arrayfun()"
},
{
"code": null,
"e": 2260,
"s": 2245,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 2277,
"s": 2260,
"text": "MATLAB-Functions"
},
{
"code": null,
"e": 2284,
"s": 2277,
"text": "Picked"
},
{
"code": null,
"e": 2294,
"s": 2284,
"text": "Blogathon"
},
{
"code": null,
"e": 2301,
"s": 2294,
"text": "MATLAB"
},
{
"code": null,
"e": 2399,
"s": 2301,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2425,
"s": 2399,
"text": "What’s a broadcast storm?"
},
{
"code": null,
"e": 2488,
"s": 2425,
"text": "How to pass data into table from a form using React Components"
},
{
"code": null,
"e": 2529,
"s": 2488,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 2570,
"s": 2529,
"text": "Consensus Problem of Distributed Systems"
},
{
"code": null,
"e": 2633,
"s": 2570,
"text": "Difference between write() and writelines() function in Python"
},
{
"code": null,
"e": 2660,
"s": 2633,
"text": "Installing MATLAB on Linux"
},
{
"code": null,
"e": 2709,
"s": 2660,
"text": "How to Find Index of Element in Array in MATLAB?"
},
{
"code": null,
"e": 2739,
"s": 2709,
"text": "Laplacian Filter using Matlab"
},
{
"code": null,
"e": 2781,
"s": 2739,
"text": "Boundary Extraction of image using MATLAB"
}
]
|
How to flatten a hierarchical index in Pandas DataFrame columns? | 15 Feb, 2022
In this article, we are going to see the flatten a hierarchical index in Pandas DataFrame columns. Hierarchical Index usually occurs as a result of groupby aggregation functions. The aggregated function used will appear in the hierarchical index of the resulting dataframe.
Pandas provide a function called reset_index() to flatten the hierarchical index created due to the groupby aggregation function.
Syntax: pandas.DataFrame.reset_index(level, drop, inplace)
Parameters:
level – removes only the specified levels from the index
drop – resets the index to the default integer index
inplace – modifies the dataframe object permanently without creating a copy.
Example:
In this example, We used the pandas groupby function to group car sales data by quarters and reset_index() pandas function to flatten the hierarchical indexed columns of the grouped dataframe.
Python3
# import the python pandas packageimport pandas as pd # create a sample dataframedata = pd.DataFrame({"cars": ["bmw", "bmw", "benz", "benz"], "sale_q1 in Cr": [20, 22, 24, 26], 'sale_q2 in Cr': [11, 13, 15, 17]}, columns=["cars", "sale_q1 in Cr", 'sale_q2 in Cr']) # group by cars based on the sum# of sales on quarter 1 and 2grouped_data = data.groupby(by="cars").agg("sum") print(grouped_data) # use reset_index to flattened# the hierarchical dataframe.flat_data = grouped_data.reset_index() print(flat_data)
Output:
Pandas provide a function called as_index() which is specified by a boolean value. The as_index() functions groups the dataframe by the specified aggregate function and if as_index() value is False, the resulting dataframe is flattened.
Syntax: pandas.DataFrame.groupby(by, level, axis, as_index)
Parameters:
by – specifies the columns on which the groupby operation has to be performed
level – specifies the index at which the columns has to be grouped
axis – specifies whether to split along rows (0) or columns (1)
as_index – Returns an object with group labels as the index, for aggregated output.
Example:
In this example, We are using the pandas groupby function to group car sales data by quarters and mention the as_index parameter as False and specify the as_index parameter as false ensures that the hierarchical index of the grouped dataframe is flattened.
Python3
# import the python pandas packageimport pandas as pd # create a sample dataframedata = pd.DataFrame({"cars": ["bmw", "bmw", "benz", "benz"], "sale_q1 in Cr": [20, 22, 24, 26], 'sale_q2 in Cr': [11, 13, 15, 17]}, columns=["cars", "sale_q1 in Cr", 'sale_q2 in Cr']) # group by cars based on the# sum of sales on quarter 1 and 2 # and mention as_index is Falsegrouped_data = data.groupby(by="cars", as_index=False).agg("sum") # displayprint(grouped_data)
Output:
Whenever we use the groupby function on a single column with multiple aggregation functions we get multiple hierarchical indexes based on the aggregation type. In such cases, the hierarchical index has to be flattened at both levels.
Syntax: pandas.DataFrame.groupby(by=None, axis=0, level=None)
Explanation:
by – mapping function that determines the groups in groupby function
axis – 0 – splits along rows and 1 – splits along columns.
level – if the axis is multi-indexed, groups at a specified level. (int)
Syntax: pandas.DataFrame.agg(func=None, axis=0)
Explanation:
func – specifies the function to be used as aggregation function. (min, max, sum etc)
axis – 0 – function applied to each column and 1- applied to each row.
Approach:
Import the python pandas package.
Create a sample dataframe showing the car sales in two-quarters q1 and q2 as shown.
Now use the pandas groupby function to group based on the sum and max of sales on quarter 1 and sum and min of sales 2.
The grouped dataframe has multi-indexed columns stored in a list of tuples. Use a for loop to iterate through the list of tuples and join them as a single string.
Append the joined strings in the flat_cols list. </li > <li > Now assign the flat_cols list to the column names of the multi-indexed grouped dataframe columns.
Python3
# import the python pandas packageimport pandas as pd # create a sample dataframedata = pd.DataFrame({"cars": ["bmw", "bmw", "benz", "benz"], "sale_q1 in Cr": [20, 22, 24, 26], 'sale_q2 in Cr': [11, 13, 15, 17]}, columns=["cars", "sale_q1 in Cr", 'sale_q2 in Cr']) # group by cars based on the sum and max of sales on quarter 1# and sum and min of sales 2 and mention as_index is Falsegrouped_data = data.groupby(by="cars").agg({"sale_q1 in Cr": [sum, max], 'sale_q2 in Cr': [sum, min]}) # create an empty list to save the# names of the flattened columnsflat_cols = [] # the multiindex columns of two# levels would be stored as tuples# iterate through this tuples and# join them as single stringfor i in grouped_data.columns: flat_cols.append(i[0]+'_'+i[1]) # now assign the list of flattened# columns to the grouped columns.grouped_data.columns = flat_cols # print the grouped dataprint(grouped_data)
Output:
In this example, we use the to_records() function of the pandas dataframe which converts all the rows in the dataframe as an array of tuples. This array of tuples is then passed to pandas.DataFrame function to convert the hierarchical index as flattened columns.
Syntax: pandas.DataFrame.to_records(index=True, column_dtypes=None)
Explanation:
index – creates an index in resulting array
column_dtypes – sets the columns to specified datatype.
Code:
Python3
# import the python pandas packageimport pandas as pd # create a sample dataframedata = pd.DataFrame({"cars": ["bmw", "bmw", "benz", "benz"], "sale_q1 in Cr": [20, 22, 24, 26], 'sale_q2 in Cr': [11, 13, 15, 17]}, columns=["cars", "sale_q1 in Cr", 'sale_q2 in Cr']) # group by cars based on the sum# and max of sales on quarter 1# and sum and min of sales 2 and mention # as_index is Falsegrouped_data = data.groupby(by="cars").agg({"sale_q1 in Cr": [sum, max], 'sale_q2 in Cr': [sum, min]})# use to_records function on grouped data# and pass this to the Dataframe functionflattened_data = pd.DataFrame(grouped_data.to_records()) print(flattened_data)
Output:
In this example, we use the join() and rstrip() functions to flatten the columns. Usually, when we group a dataframe as hierarchical indexed columns, the columns at multilevel are stored as an array of tuples elements. Here, we iterate through these tuples by joining the column name and index name of each tuple and storing the resulting flattened columns name in a list. Later, this stored list of flattened columns is assigned to the grouped dataframe.
Syntax: str.join(iterable)
Explanation: Returns a concatenated string, if iterable, else returns a type error.
Syntax: str.rstrip([chars])
Explanation: Returns a string by splitting the excess trailing spaces (rightmost) to the string.
Code:
Python3
# import the python pandas packageimport pandas as pd # create a sample dataframedata = pd.DataFrame({"cars": ["bmw", "bmw", "benz", "benz"], "sale_q1 in Cr": [20, 22, 24, 26], 'sale_q2 in Cr': [11, 13, 15, 17]}, columns=["cars", "sale_q1 in Cr", 'sale_q2 in Cr']) # group by cars based on the sum# and max of sales on quarter 1# and sum and min of sales 2 and# mention as_index is Falsegrouped_data = data.groupby(by="cars").agg({"sale_q1 in Cr": [sum, max], 'sale_q2 in Cr': [sum, min]}) # use join() and rstrip() function to # flatten the hierarchical columnsgrouped_data.columns = ['_'.join(i).rstrip('_') for i in grouped_data.columns.values] print(grouped_data)
Output:
sweetyty
Picked
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Feb, 2022"
},
{
"code": null,
"e": 327,
"s": 52,
"text": "In this article, we are going to see the flatten a hierarchical index in Pandas DataFrame columns. Hierarchical Index usually occurs as a result of groupby aggregation functions. The aggregated function used will appear in the hierarchical index of the resulting dataframe. "
},
{
"code": null,
"e": 458,
"s": 327,
"text": "Pandas provide a function called reset_index() to flatten the hierarchical index created due to the groupby aggregation function. "
},
{
"code": null,
"e": 517,
"s": 458,
"text": "Syntax: pandas.DataFrame.reset_index(level, drop, inplace)"
},
{
"code": null,
"e": 529,
"s": 517,
"text": "Parameters:"
},
{
"code": null,
"e": 586,
"s": 529,
"text": "level – removes only the specified levels from the index"
},
{
"code": null,
"e": 639,
"s": 586,
"text": "drop – resets the index to the default integer index"
},
{
"code": null,
"e": 716,
"s": 639,
"text": "inplace – modifies the dataframe object permanently without creating a copy."
},
{
"code": null,
"e": 725,
"s": 716,
"text": "Example:"
},
{
"code": null,
"e": 918,
"s": 725,
"text": "In this example, We used the pandas groupby function to group car sales data by quarters and reset_index() pandas function to flatten the hierarchical indexed columns of the grouped dataframe."
},
{
"code": null,
"e": 926,
"s": 918,
"text": "Python3"
},
{
"code": "# import the python pandas packageimport pandas as pd # create a sample dataframedata = pd.DataFrame({\"cars\": [\"bmw\", \"bmw\", \"benz\", \"benz\"], \"sale_q1 in Cr\": [20, 22, 24, 26], 'sale_q2 in Cr': [11, 13, 15, 17]}, columns=[\"cars\", \"sale_q1 in Cr\", 'sale_q2 in Cr']) # group by cars based on the sum# of sales on quarter 1 and 2grouped_data = data.groupby(by=\"cars\").agg(\"sum\") print(grouped_data) # use reset_index to flattened# the hierarchical dataframe.flat_data = grouped_data.reset_index() print(flat_data)",
"e": 1552,
"s": 926,
"text": null
},
{
"code": null,
"e": 1560,
"s": 1552,
"text": "Output:"
},
{
"code": null,
"e": 1798,
"s": 1560,
"text": "Pandas provide a function called as_index() which is specified by a boolean value. The as_index() functions groups the dataframe by the specified aggregate function and if as_index() value is False, the resulting dataframe is flattened."
},
{
"code": null,
"e": 1858,
"s": 1798,
"text": "Syntax: pandas.DataFrame.groupby(by, level, axis, as_index)"
},
{
"code": null,
"e": 1870,
"s": 1858,
"text": "Parameters:"
},
{
"code": null,
"e": 1948,
"s": 1870,
"text": "by – specifies the columns on which the groupby operation has to be performed"
},
{
"code": null,
"e": 2015,
"s": 1948,
"text": "level – specifies the index at which the columns has to be grouped"
},
{
"code": null,
"e": 2079,
"s": 2015,
"text": "axis – specifies whether to split along rows (0) or columns (1)"
},
{
"code": null,
"e": 2163,
"s": 2079,
"text": "as_index – Returns an object with group labels as the index, for aggregated output."
},
{
"code": null,
"e": 2172,
"s": 2163,
"text": "Example:"
},
{
"code": null,
"e": 2430,
"s": 2172,
"text": "In this example, We are using the pandas groupby function to group car sales data by quarters and mention the as_index parameter as False and specify the as_index parameter as false ensures that the hierarchical index of the grouped dataframe is flattened."
},
{
"code": null,
"e": 2438,
"s": 2430,
"text": "Python3"
},
{
"code": "# import the python pandas packageimport pandas as pd # create a sample dataframedata = pd.DataFrame({\"cars\": [\"bmw\", \"bmw\", \"benz\", \"benz\"], \"sale_q1 in Cr\": [20, 22, 24, 26], 'sale_q2 in Cr': [11, 13, 15, 17]}, columns=[\"cars\", \"sale_q1 in Cr\", 'sale_q2 in Cr']) # group by cars based on the# sum of sales on quarter 1 and 2 # and mention as_index is Falsegrouped_data = data.groupby(by=\"cars\", as_index=False).agg(\"sum\") # displayprint(grouped_data)",
"e": 2983,
"s": 2438,
"text": null
},
{
"code": null,
"e": 2991,
"s": 2983,
"text": "Output:"
},
{
"code": null,
"e": 3226,
"s": 2991,
"text": "Whenever we use the groupby function on a single column with multiple aggregation functions we get multiple hierarchical indexes based on the aggregation type. In such cases, the hierarchical index has to be flattened at both levels. "
},
{
"code": null,
"e": 3288,
"s": 3226,
"text": "Syntax: pandas.DataFrame.groupby(by=None, axis=0, level=None)"
},
{
"code": null,
"e": 3301,
"s": 3288,
"text": "Explanation:"
},
{
"code": null,
"e": 3370,
"s": 3301,
"text": "by – mapping function that determines the groups in groupby function"
},
{
"code": null,
"e": 3429,
"s": 3370,
"text": "axis – 0 – splits along rows and 1 – splits along columns."
},
{
"code": null,
"e": 3502,
"s": 3429,
"text": "level – if the axis is multi-indexed, groups at a specified level. (int)"
},
{
"code": null,
"e": 3550,
"s": 3502,
"text": "Syntax: pandas.DataFrame.agg(func=None, axis=0)"
},
{
"code": null,
"e": 3563,
"s": 3550,
"text": "Explanation:"
},
{
"code": null,
"e": 3649,
"s": 3563,
"text": "func – specifies the function to be used as aggregation function. (min, max, sum etc)"
},
{
"code": null,
"e": 3720,
"s": 3649,
"text": "axis – 0 – function applied to each column and 1- applied to each row."
},
{
"code": null,
"e": 3730,
"s": 3720,
"text": "Approach:"
},
{
"code": null,
"e": 3764,
"s": 3730,
"text": "Import the python pandas package."
},
{
"code": null,
"e": 3848,
"s": 3764,
"text": "Create a sample dataframe showing the car sales in two-quarters q1 and q2 as shown."
},
{
"code": null,
"e": 3968,
"s": 3848,
"text": "Now use the pandas groupby function to group based on the sum and max of sales on quarter 1 and sum and min of sales 2."
},
{
"code": null,
"e": 4131,
"s": 3968,
"text": "The grouped dataframe has multi-indexed columns stored in a list of tuples. Use a for loop to iterate through the list of tuples and join them as a single string."
},
{
"code": null,
"e": 4291,
"s": 4131,
"text": "Append the joined strings in the flat_cols list. </li > <li > Now assign the flat_cols list to the column names of the multi-indexed grouped dataframe columns."
},
{
"code": null,
"e": 4299,
"s": 4291,
"text": "Python3"
},
{
"code": "# import the python pandas packageimport pandas as pd # create a sample dataframedata = pd.DataFrame({\"cars\": [\"bmw\", \"bmw\", \"benz\", \"benz\"], \"sale_q1 in Cr\": [20, 22, 24, 26], 'sale_q2 in Cr': [11, 13, 15, 17]}, columns=[\"cars\", \"sale_q1 in Cr\", 'sale_q2 in Cr']) # group by cars based on the sum and max of sales on quarter 1# and sum and min of sales 2 and mention as_index is Falsegrouped_data = data.groupby(by=\"cars\").agg({\"sale_q1 in Cr\": [sum, max], 'sale_q2 in Cr': [sum, min]}) # create an empty list to save the# names of the flattened columnsflat_cols = [] # the multiindex columns of two# levels would be stored as tuples# iterate through this tuples and# join them as single stringfor i in grouped_data.columns: flat_cols.append(i[0]+'_'+i[1]) # now assign the list of flattened# columns to the grouped columns.grouped_data.columns = flat_cols # print the grouped dataprint(grouped_data)",
"e": 5347,
"s": 4299,
"text": null
},
{
"code": null,
"e": 5356,
"s": 5347,
"text": "Output: "
},
{
"code": null,
"e": 5619,
"s": 5356,
"text": "In this example, we use the to_records() function of the pandas dataframe which converts all the rows in the dataframe as an array of tuples. This array of tuples is then passed to pandas.DataFrame function to convert the hierarchical index as flattened columns."
},
{
"code": null,
"e": 5687,
"s": 5619,
"text": "Syntax: pandas.DataFrame.to_records(index=True, column_dtypes=None)"
},
{
"code": null,
"e": 5701,
"s": 5687,
"text": "Explanation: "
},
{
"code": null,
"e": 5745,
"s": 5701,
"text": "index – creates an index in resulting array"
},
{
"code": null,
"e": 5801,
"s": 5745,
"text": "column_dtypes – sets the columns to specified datatype."
},
{
"code": null,
"e": 5807,
"s": 5801,
"text": "Code:"
},
{
"code": null,
"e": 5815,
"s": 5807,
"text": "Python3"
},
{
"code": "# import the python pandas packageimport pandas as pd # create a sample dataframedata = pd.DataFrame({\"cars\": [\"bmw\", \"bmw\", \"benz\", \"benz\"], \"sale_q1 in Cr\": [20, 22, 24, 26], 'sale_q2 in Cr': [11, 13, 15, 17]}, columns=[\"cars\", \"sale_q1 in Cr\", 'sale_q2 in Cr']) # group by cars based on the sum# and max of sales on quarter 1# and sum and min of sales 2 and mention # as_index is Falsegrouped_data = data.groupby(by=\"cars\").agg({\"sale_q1 in Cr\": [sum, max], 'sale_q2 in Cr': [sum, min]})# use to_records function on grouped data# and pass this to the Dataframe functionflattened_data = pd.DataFrame(grouped_data.to_records()) print(flattened_data)",
"e": 6607,
"s": 5815,
"text": null
},
{
"code": null,
"e": 6615,
"s": 6607,
"text": "Output:"
},
{
"code": null,
"e": 7071,
"s": 6615,
"text": "In this example, we use the join() and rstrip() functions to flatten the columns. Usually, when we group a dataframe as hierarchical indexed columns, the columns at multilevel are stored as an array of tuples elements. Here, we iterate through these tuples by joining the column name and index name of each tuple and storing the resulting flattened columns name in a list. Later, this stored list of flattened columns is assigned to the grouped dataframe."
},
{
"code": null,
"e": 7098,
"s": 7071,
"text": "Syntax: str.join(iterable)"
},
{
"code": null,
"e": 7182,
"s": 7098,
"text": "Explanation: Returns a concatenated string, if iterable, else returns a type error."
},
{
"code": null,
"e": 7210,
"s": 7182,
"text": "Syntax: str.rstrip([chars])"
},
{
"code": null,
"e": 7307,
"s": 7210,
"text": "Explanation: Returns a string by splitting the excess trailing spaces (rightmost) to the string."
},
{
"code": null,
"e": 7313,
"s": 7307,
"text": "Code:"
},
{
"code": null,
"e": 7321,
"s": 7313,
"text": "Python3"
},
{
"code": "# import the python pandas packageimport pandas as pd # create a sample dataframedata = pd.DataFrame({\"cars\": [\"bmw\", \"bmw\", \"benz\", \"benz\"], \"sale_q1 in Cr\": [20, 22, 24, 26], 'sale_q2 in Cr': [11, 13, 15, 17]}, columns=[\"cars\", \"sale_q1 in Cr\", 'sale_q2 in Cr']) # group by cars based on the sum# and max of sales on quarter 1# and sum and min of sales 2 and# mention as_index is Falsegrouped_data = data.groupby(by=\"cars\").agg({\"sale_q1 in Cr\": [sum, max], 'sale_q2 in Cr': [sum, min]}) # use join() and rstrip() function to # flatten the hierarchical columnsgrouped_data.columns = ['_'.join(i).rstrip('_') for i in grouped_data.columns.values] print(grouped_data)",
"e": 8146,
"s": 7321,
"text": null
},
{
"code": null,
"e": 8154,
"s": 8146,
"text": "Output:"
},
{
"code": null,
"e": 8163,
"s": 8154,
"text": "sweetyty"
},
{
"code": null,
"e": 8170,
"s": 8163,
"text": "Picked"
},
{
"code": null,
"e": 8193,
"s": 8170,
"text": "Python pandas-indexing"
},
{
"code": null,
"e": 8207,
"s": 8193,
"text": "Python-pandas"
},
{
"code": null,
"e": 8214,
"s": 8207,
"text": "Python"
}
]
|
ReactJS - Pagination | Pagination is one of the distinct features requiring special logic and at the same time, the UI rendering may vary drastically. For example, the pagination can be done for a tabular content as well as a gallery content. Pagination component will do the pagination logic and delegates the rendering logic to other component. Let us try to create a pagination component (Pager) for our Expense manager application using Render props
Open expense-manager application in your favorite editor.
Next, create a file, Pager.css under src/components to add styles for pagination component.
a{
text-decoration: none;
}
p, li, a{
font-size: 12px;
}
.container{
width: 720px;
max-width: 340px;
margin: 0 auto;
position: relative;
text-align: center;
}
.pagination{
padding: 14px 0;
}
.pagination ul{
margin: 0 auto;
padding: 0;
list-style-type: none;
text-align: left;
}
.pagination a{
display: inline-block;
padding: 10px 18px;
color: #222;
}
.p1 a{
width: 30px;
height: 30px;
line-height: 30px;
padding: 0;
text-align: center;
}
.p1 a.is-active{
background-color: #887cb8;
border-radius: 25%;
color: #fff;
}
Next, create a file, Pager.js in src/components folder to create Pager component and start editing.
Next, import React library.
import React from 'react';
Next, import pagination stylesheet.
import './Pager.css'
Next, create a class, Pager and call constructor with props.
class Pager extends React.Component {
constructor(props) {
super(props);
}
}
Next, initialize the state of the component with expense items (items) and number of items to show in a page (pageCount).
this.state = {
items: this.props.items,
pageCount: this.props.pageCount
}
Write a function, calculate(), which accepts current state and the current page number. It calculates the total of available pages based on the page count and the items to show in current page (filteredItems). Finally, it returns the computed values.
calculate(state, pageNo) {
let currentPage = pageNo;
let totalPages = Math.ceil(state.items.length / state.pageCount);
if(currentPage > totalPages) currentPage = totalPages;
let hasPreviousPage = currentPage == 1 ? false : true;
let hasNextPage = currentPage == totalPages ? false : true;
let first = (currentPage - 1) * state.pageCount
let last = first + state.pageCount;
let filteredItems = state.items.slice(first, last)
let newState = {
items: state.items,
filteredItems: filteredItems,
currentPage: currentPage,
totalPages: totalPages,
pageCount: state.pageCount
}
return newState;
}
Next, call the calculate() method in the constructor to get the initial details about the pagination.
this.state = this.calculate(this.state, 1);
Next, write an event handler method, handleClick to handle the page navigation event of the pagination component.
handleClick(pageNo, e) {
e.preventDefault();
this.setState((state, props) => {
return this.calculate(state, pageNo);
})
}
Next, write an event handler to remove the expense item. Since, the pager component handles all the expense items, the remove feature should be moved here.
handleDelete = (id, e) => {
e.preventDefault();
console.log(id);
this.setState((state, props) => {
let items = [];
state.items.forEach((item, idx) => {
if (item.id != id)
items.push(item)
})
let newState = {
items: items
}
return newState;
})
this.setState((state, props) => {
return this.calculate(state, this.state.currentPage);
})
}
Next, create a render method to create the pagination user interface and then call the Render Props by passing the items needed to render for the current page.
render() {
let pageArray = new Array();
let i = 1;
for (i = 1; i <= this.state.totalPages; i++)
pageArray.push(i)
const pages = pageArray.map((idx) =>
<a href="#" key={idx} onClick={this.handleClick.bind(this, idx)} className={idx == this.state.currentPage ? "is-active" : ""}><li>{idx}</li></a>
);
let propsToPass = {
items: this.state.filteredItems,
deleteHandler: this.handleDelete
}
return (
<div>
{this.props.render(propsToPass)}
<div style={{ width: 720, margin: 0 }}>
<div className="container">
<div className="pagination p1">
<ul>
{this.state.currentPage != 1 ? <a href="#" onClick={this.handleClick.bind(this, this.state.currentPage - 1)}><li><</li></a> : <span> </span>}
{pages}
{this.state.currentPage != this.state.totalPages ?
<a href="#" onClick={this.handleClick.bind(this, this.state.currentPage + 1)}><li>></li></a> : <span> </span>}
</ul>
</div>
</div>
</div>
</div>
)
}
Here,
Used map to create the pagination buttons.
Used map to create the pagination buttons.
Used conditional rendering to show/hide first and last page.
Used conditional rendering to show/hide first and last page.
Used this.props.render to call and render the passed in component.
Used this.props.render to call and render the passed in component.
Finally, Export the component.
export default Pager
The complete code of the Pager component is as follows
import React from 'react';
import './Pager.css'
class Pager extends React.Component {
constructor(props) {
super(props);
this.state = {
items: this.props.items,
pageCount: this.props.pageCount,
}
this.state = this.calculate(this.state, 1);
}
calculate(state, pageNo) {
let currentPage = pageNo;
let totalPages = Math.ceil(state.items.length / state.pageCount);
if(currentPage > totalPages) currentPage = totalPages;
let hasPreviousPage = currentPage == 1 ? false : true;
let hasNextPage = currentPage == totalPages ? false : true;
let first = (currentPage - 1) * state.pageCount
let last = first + state.pageCount;
let filteredItems = state.items.slice(first, last)
let newState = {
items: state.items,
filteredItems: filteredItems,
currentPage: currentPage,
totalPages: totalPages,
pageCount: state.pageCount
}
return newState;
}
handleClick(pageNo, e) {
e.preventDefault();
this.setState((state, props) => {
return this.calculate(state, pageNo);
})
}
handleDelete = (id, e) => {
e.preventDefault();
console.log(id);
this.setState((state, props) => {
let items = [];
state.items.forEach((item, idx) => {
if (item.id != id)
items.push(item)
})
let newState = {
items: items
}
return newState;
})
this.setState((state, props) => {
return this.calculate(state, this.state.currentPage);
})
}
render() {
let pageArray = new Array();
let i = 1;
for (i = 1; i <= this.state.totalPages; i++)pageArray.push(i)
const pages = pageArray.map((idx) =>
<a href="#" key={idx} onClick={this.handleClick.bind(this, idx)} className={idx == this.state.currentPage ? "is-active" : ""}><li>{idx}</li></a>
);
let propsToPass = {
items: this.state.filteredItems,
deleteHandler: this.handleDelete
}
return (
<div>
{this.props.render(propsToPass)}
<div style={{ width: 720, margin: 0 }}>
<div className="container">
<div className="pagination p1">
<ul>
{this.state.currentPage != 1 ? <a href="#" onClick={this.handleClick.bind(this, this.state.currentPage - 1)}><li><</li></a> : <span> </span>}
{pages}
{this.state.currentPage != this.state.totalPages ?
<a href="#" onClick={this.handleClick.bind(this, this.state.currentPage + 1)}><li>></li></a> : <span> </span>}
</ul>
</div>
</div>
</div>
</div>
)
}
}
export default Pagerimport React from 'react';
import './Pager.css'
class Pager extends React.Component {
constructor(props) {
super(props);
this.state = {
items: this.props.items,
pageCount: this.props.pageCount,
}
this.state = this.calculate(this.state, 1);
}
calculate(state, pageNo) {
let currentPage = pageNo;
let totalPages = Math.ceil(state.items.length / state.pageCount);
if(currentPage > totalPages)currentPage = totalPages;
let hasPreviousPage = currentPage == 1 ? false : true;
let hasNextPage = currentPage == totalPages ? false : true;
let first = (currentPage - 1) * state.pageCount
let last = first + state.pageCount;
let filteredItems = state.items.slice(first, last)
let newState = {
items: state.items,
filteredItems: filteredItems,
currentPage: currentPage,
totalPages: totalPages,
pageCount: state.pageCount
}
return newState;
}
handleClick(pageNo, e) {
e.preventDefault();
this.setState((state, props) => {
return this.calculate(state, pageNo);
})
}
handleDelete = (id, e) => {
e.preventDefault();
console.log(id);
this.setState((state, props) => {
let items = [];
state.items.forEach((item, idx) => {
if (item.id != id)
items.push(item)
})
let newState = {
items: items
}
return newState;
})
this.setState((state, props) => {
return this.calculate(state, this.state.currentPage);
})
}
render() {
let pageArray = new Array();
let i = 1;
for (i = 1; i <= this.state.totalPages; i++)pageArray.push(i)
const pages = pageArray.map((idx) =>
<a href="#" key={idx} onClick={this.handleClick.bind(this, idx)} className={idx == this.state.currentPage ? "is-active" : ""}><li>{idx}</li></a>
);
let propsToPass = {
items: this.state.filteredItems,
deleteHandler: this.handleDelete
}
return (
<div>
{this.props.render(propsToPass)}
<div style={{ width: 720, margin: 0 }}>
<div className="container">
<div className="pagination p1">
<ul>
{this.state.currentPage != 1 ? <a href="#" onClick={this.handleClick.bind(this, this.state.currentPage - 1)}><li><</li></a> : <span> </span>}
{pages}
{this.state.currentPage != this.state.totalPages ?
<a href="#" onClick={this.handleClick.bind(this, this.state.currentPage + 1)}><li>></li></a> : <span> </span>}
</ul>
</div>
</div>
</div>
</div>
)
}
}
export default Pager
Next, open ExpenseEntryItemeList.js file and update the getDerivedStateFromProps function to get the current expense item list by copying the passed-in props into the new state.
static getDerivedStateFromProps(props, state) {
let newState = {
items: props.items
}
return newState;
}
Next, update the handleDelete method and call the event handler method passed into the component from from pager component through onDelete property.
handleDelete = (id, e) => {
e.preventDefault();
if(this.props.onDelete != null)this.props.onDelete(id, e);
}
Next, remove rendering of header and footer, if any available in the render method.
return (
<div>
<div>{this.props.header}</div>
... existing code ...
<div>{this.props.footer}</div>
</div>
);
The complete source code of the ExpenseEntryItemList component is given below −
import React from 'react';
import './ExpenseEntryItemList.css';
class ExpenseEntryItemList extends React.Component {
constructor(props) {
super(props);
this.state = {
items: this.props.items
}
this.handleMouseEnter = this.handleMouseEnter.bind();
this.handleMouseLeave = this.handleMouseLeave.bind();
this.handleMouseOver = this.handleMouseOver.bind();
}
handleMouseEnter(e) {
e.target.parentNode.classList.add("highlight");
}
handleMouseLeave(e) {
e.target.parentNode.classList.remove("highlight");
}
handleMouseOver(e) {
console.log("The mouse is at (" + e.clientX + ", " + e.clientY + ")");
}
handleDelete = (id, e) => {
e.preventDefault();
if(this.props.onDelete != null)this.props.onDelete(id, e);
/*console.log(id);
this.setState((state, props) => {
let items = [];
state.items.forEach((item, idx) => {
if (item.id != id)
items.push(item)
})
let newState = {
items: items
}
return newState;
})*/
}
getTotal() {
let total = 0;
for (var i = 0; i < this.state.items.length; i++) {
total += this.state.items[i].amount
}
return total;
}
static getDerivedStateFromProps(props, state) {
let newState = {
items: props.items
}
return newState;
}
render() {
const lists = this.state.items.map((item) =>
<tr key={item.id} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>
<td>{item.name}</td>
<td>{item.amount}</td>
<td>{new Date(item.spendDate).toDateString()}</td>
<td>{item.category}</td>
<td><a href="#"
onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td>
</tr>
);
return (
<div>
<table onMouseOver={this.handleMouseOver}>
<thead>
<tr>
<th>Item</th>
<th>Amount</th>
<th>Date</th>
<th>Category</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
{lists}
<tr>
<td colSpan="1" style={{ textAlign: "right" }}>Total Amount</td>
<td colSpan="4" style={{ textAlign: "left" }}>
{this.getTotal()}
</td>
</tr>
</tbody>
</table>
</div>
);
}
}
export default ExpenseEntryItemList;
Next, open index.js and call the Pager component and pass the ExpenseEntryItemList as render props.
import React from 'react';
import ReactDOM from 'react-dom';
import Pager from './components/Pager'
import ExpenseEntryItemList from './components/ExpenseEntryItemList'
const items = [
{ id: 1, name: "Pizza", amount: 80, spendDate: "2020-10-10", category: "Food" },
{ id: 2, name: "Grape Juice", amount: 30, spendDate: "2020-10-12", category: "Food" },
{ id: 3, name: "Cinema", amount: 210, spendDate: "2020-10-16", category: "Entertainment" },
{ id: 4, name: "Java Programming book", amount: 242, spendDate: "2020-10-15", category: "Academic" },
{ id: 5, name: "Mango Juice", amount: 35, spendDate: "2020-10-16", category: "Food" },
{ id: 6, name: "Dress", amount: 2000, spendDate: "2020-10-25", category: "Cloth" },
{ id: 7, name: "Tour", amount: 2555, spendDate: "2020-10-29", category: "Entertainment" },
{ id: 8, name: "Meals", amount: 300, spendDate: "2020-10-30", category: "Food" },
{ id: 9, name: "Mobile", amount: 3500, spendDate: "2020-11-02", category: "Gadgets" },
{ id: 10, name: "Exam Fees", amount: 1245, spendDate: "2020-11-04", category: "Academic" }
]
const pageCount = 3;
ReactDOM.render(
<React.StrictMode>
<Pager
items={items}
pageCount={pageCount}
render={
pagerState => (
<div>
<ExpenseEntryItemList items={pagerState.items}
onDelete={pagerState.deleteHandler} />
</div>
)
}
/>
</React.StrictMode>,
document.getElementById('root')
);
As we see, the Pager component accept any render props and only calculate the pagination logic.
Next, serve the application using npm command.
npm start
Next, open the browser and enter http://localhost:3000 in the address bar and press enter. | [
{
"code": null,
"e": 2598,
"s": 2167,
"text": "Pagination is one of the distinct features requiring special logic and at the same time, the UI rendering may vary drastically. For example, the pagination can be done for a tabular content as well as a gallery content. Pagination component will do the pagination logic and delegates the rendering logic to other component. Let us try to create a pagination component (Pager) for our Expense manager application using Render props"
},
{
"code": null,
"e": 2656,
"s": 2598,
"text": "Open expense-manager application in your favorite editor."
},
{
"code": null,
"e": 2748,
"s": 2656,
"text": "Next, create a file, Pager.css under src/components to add styles for pagination component."
},
{
"code": null,
"e": 3336,
"s": 2748,
"text": "a{\n text-decoration: none;\n}\np, li, a{\n font-size: 12px;\n} \n.container{\n width: 720px;\n max-width: 340px;\n margin: 0 auto;\n position: relative;\n text-align: center;\n}\n.pagination{\n padding: 14px 0;\n}\n.pagination ul{\n margin: 0 auto; \n padding: 0;\n list-style-type: none;\n text-align: left;\n}\n.pagination a{\n display: inline-block;\n padding: 10px 18px;\n color: #222;\n}\n.p1 a{\n width: 30px;\n height: 30px;\n line-height: 30px;\n padding: 0;\n text-align: center;\n}\n.p1 a.is-active{\n background-color: #887cb8;\n border-radius: 25%;\n color: #fff;\n}"
},
{
"code": null,
"e": 3436,
"s": 3336,
"text": "Next, create a file, Pager.js in src/components folder to create Pager component and start editing."
},
{
"code": null,
"e": 3464,
"s": 3436,
"text": "Next, import React library."
},
{
"code": null,
"e": 3492,
"s": 3464,
"text": "import React from 'react';\n"
},
{
"code": null,
"e": 3528,
"s": 3492,
"text": "Next, import pagination stylesheet."
},
{
"code": null,
"e": 3550,
"s": 3528,
"text": "import './Pager.css'\n"
},
{
"code": null,
"e": 3611,
"s": 3550,
"text": "Next, create a class, Pager and call constructor with props."
},
{
"code": null,
"e": 3705,
"s": 3611,
"text": "class Pager extends React.Component { \n constructor(props) { \n super(props); \n } \n}\n"
},
{
"code": null,
"e": 3827,
"s": 3705,
"text": "Next, initialize the state of the component with expense items (items) and number of items to show in a page (pageCount)."
},
{
"code": null,
"e": 3911,
"s": 3827,
"text": "this.state = { \n items: this.props.items, \n pageCount: this.props.pageCount \n}\n"
},
{
"code": null,
"e": 4162,
"s": 3911,
"text": "Write a function, calculate(), which accepts current state and the current page number. It calculates the total of available pages based on the page count and the items to show in current page (filteredItems). Finally, it returns the computed values."
},
{
"code": null,
"e": 4815,
"s": 4162,
"text": "calculate(state, pageNo) {\n let currentPage = pageNo;\n let totalPages = Math.ceil(state.items.length / state.pageCount);\n if(currentPage > totalPages) currentPage = totalPages;\n let hasPreviousPage = currentPage == 1 ? false : true;\n let hasNextPage = currentPage == totalPages ? false : true;\n let first = (currentPage - 1) * state.pageCount\n let last = first + state.pageCount;\n let filteredItems = state.items.slice(first, last)\n\n let newState = {\n items: state.items,\n filteredItems: filteredItems,\n currentPage: currentPage,\n totalPages: totalPages,\n pageCount: state.pageCount\n }\n return newState;\n}"
},
{
"code": null,
"e": 4917,
"s": 4815,
"text": "Next, call the calculate() method in the constructor to get the initial details about the pagination."
},
{
"code": null,
"e": 4962,
"s": 4917,
"text": "this.state = this.calculate(this.state, 1);\n"
},
{
"code": null,
"e": 5076,
"s": 4962,
"text": "Next, write an event handler method, handleClick to handle the page navigation event of the pagination component."
},
{
"code": null,
"e": 5219,
"s": 5076,
"text": "handleClick(pageNo, e) { \n e.preventDefault(); \n this.setState((state, props) => { \n return this.calculate(state, pageNo); \n }) \n}\n"
},
{
"code": null,
"e": 5375,
"s": 5219,
"text": "Next, write an event handler to remove the expense item. Since, the pager component handles all the expense items, the remove feature should be moved here."
},
{
"code": null,
"e": 5802,
"s": 5375,
"text": "handleDelete = (id, e) => {\n e.preventDefault();\n console.log(id);\n this.setState((state, props) => {\n let items = [];\n\n state.items.forEach((item, idx) => {\n if (item.id != id)\n items.push(item)\n })\n let newState = {\n items: items\n }\n return newState;\n })\n this.setState((state, props) => {\n return this.calculate(state, this.state.currentPage);\n })\n}"
},
{
"code": null,
"e": 5962,
"s": 5802,
"text": "Next, create a render method to create the pagination user interface and then call the Render Props by passing the items needed to render for the current page."
},
{
"code": null,
"e": 7117,
"s": 5962,
"text": "render() {\n let pageArray = new Array();\n let i = 1;\n for (i = 1; i <= this.state.totalPages; i++)\n pageArray.push(i)\n\n const pages = pageArray.map((idx) =>\n <a href=\"#\" key={idx} onClick={this.handleClick.bind(this, idx)} className={idx == this.state.currentPage ? \"is-active\" : \"\"}><li>{idx}</li></a>\n );\n let propsToPass = {\n items: this.state.filteredItems,\n deleteHandler: this.handleDelete\n }\n return (\n <div>\n {this.props.render(propsToPass)}\n <div style={{ width: 720, margin: 0 }}>\n <div className=\"container\">\n <div className=\"pagination p1\">\n <ul>\n {this.state.currentPage != 1 ? <a href=\"#\" onClick={this.handleClick.bind(this, this.state.currentPage - 1)}><li><</li></a> : <span> </span>}\n {pages}\n {this.state.currentPage != this.state.totalPages ?\n <a href=\"#\" onClick={this.handleClick.bind(this, this.state.currentPage + 1)}><li>></li></a> : <span> </span>}\n </ul>\n </div>\n </div>\n </div>\n </div>\n )\n}"
},
{
"code": null,
"e": 7123,
"s": 7117,
"text": "Here,"
},
{
"code": null,
"e": 7166,
"s": 7123,
"text": "Used map to create the pagination buttons."
},
{
"code": null,
"e": 7209,
"s": 7166,
"text": "Used map to create the pagination buttons."
},
{
"code": null,
"e": 7270,
"s": 7209,
"text": "Used conditional rendering to show/hide first and last page."
},
{
"code": null,
"e": 7331,
"s": 7270,
"text": "Used conditional rendering to show/hide first and last page."
},
{
"code": null,
"e": 7398,
"s": 7331,
"text": "Used this.props.render to call and render the passed in component."
},
{
"code": null,
"e": 7465,
"s": 7398,
"text": "Used this.props.render to call and render the passed in component."
},
{
"code": null,
"e": 7496,
"s": 7465,
"text": "Finally, Export the component."
},
{
"code": null,
"e": 7518,
"s": 7496,
"text": "export default Pager\n"
},
{
"code": null,
"e": 7573,
"s": 7518,
"text": "The complete code of the Pager component is as follows"
},
{
"code": null,
"e": 13391,
"s": 7573,
"text": "import React from 'react';\nimport './Pager.css'\n\nclass Pager extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n items: this.props.items,\n pageCount: this.props.pageCount,\n }\n this.state = this.calculate(this.state, 1);\n }\n calculate(state, pageNo) {\n let currentPage = pageNo;\n let totalPages = Math.ceil(state.items.length / state.pageCount);\n if(currentPage > totalPages) currentPage = totalPages;\n let hasPreviousPage = currentPage == 1 ? false : true;\n let hasNextPage = currentPage == totalPages ? false : true;\n let first = (currentPage - 1) * state.pageCount\n let last = first + state.pageCount;\n let filteredItems = state.items.slice(first, last)\n let newState = {\n items: state.items,\n filteredItems: filteredItems,\n currentPage: currentPage,\n totalPages: totalPages,\n pageCount: state.pageCount\n }\n return newState;\n }\n handleClick(pageNo, e) {\n e.preventDefault();\n this.setState((state, props) => {\n return this.calculate(state, pageNo);\n })\n }\n handleDelete = (id, e) => {\n e.preventDefault();\n console.log(id);\n\n this.setState((state, props) => {\n let items = [];\n state.items.forEach((item, idx) => {\n if (item.id != id)\n items.push(item)\n })\n let newState = {\n items: items\n }\n return newState;\n })\n this.setState((state, props) => {\n return this.calculate(state, this.state.currentPage);\n })\n }\n render() {\n let pageArray = new Array();\n let i = 1;\n for (i = 1; i <= this.state.totalPages; i++)pageArray.push(i)\n \n const pages = pageArray.map((idx) =>\n <a href=\"#\" key={idx} onClick={this.handleClick.bind(this, idx)} className={idx == this.state.currentPage ? \"is-active\" : \"\"}><li>{idx}</li></a>\n );\n let propsToPass = {\n items: this.state.filteredItems,\n deleteHandler: this.handleDelete\n }\n return (\n <div>\n {this.props.render(propsToPass)}\n \n <div style={{ width: 720, margin: 0 }}>\n <div className=\"container\">\n <div className=\"pagination p1\">\n <ul>\n {this.state.currentPage != 1 ? <a href=\"#\" onClick={this.handleClick.bind(this, this.state.currentPage - 1)}><li><</li></a> : <span> </span>}\n {pages}\n {this.state.currentPage != this.state.totalPages ?\n <a href=\"#\" onClick={this.handleClick.bind(this, this.state.currentPage + 1)}><li>></li></a> : <span> </span>}\n </ul>\n </div>\n </div>\n </div>\n </div>\n )\n }\n}\nexport default Pagerimport React from 'react';\nimport './Pager.css'\n\nclass Pager extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n items: this.props.items,\n pageCount: this.props.pageCount,\n }\n this.state = this.calculate(this.state, 1);\n }\n calculate(state, pageNo) {\n let currentPage = pageNo;\n let totalPages = Math.ceil(state.items.length / state.pageCount);\n\n if(currentPage > totalPages)currentPage = totalPages;\n \n let hasPreviousPage = currentPage == 1 ? false : true;\n let hasNextPage = currentPage == totalPages ? false : true;\n let first = (currentPage - 1) * state.pageCount\n let last = first + state.pageCount;\n let filteredItems = state.items.slice(first, last)\n \n let newState = {\n items: state.items,\n filteredItems: filteredItems,\n currentPage: currentPage,\n totalPages: totalPages,\n pageCount: state.pageCount\n }\n return newState;\n }\n handleClick(pageNo, e) {\n e.preventDefault();\n \n this.setState((state, props) => {\n return this.calculate(state, pageNo);\n })\n }\n handleDelete = (id, e) => {\n e.preventDefault();\n console.log(id);\n\n this.setState((state, props) => {\n let items = [];\n\n state.items.forEach((item, idx) => {\n if (item.id != id)\n items.push(item)\n })\n let newState = {\n items: items\n }\n return newState;\n })\n this.setState((state, props) => {\n return this.calculate(state, this.state.currentPage);\n })\n }\n render() {\n let pageArray = new Array();\n let i = 1;\n for (i = 1; i <= this.state.totalPages; i++)pageArray.push(i)\n \n const pages = pageArray.map((idx) =>\n <a href=\"#\" key={idx} onClick={this.handleClick.bind(this, idx)} className={idx == this.state.currentPage ? \"is-active\" : \"\"}><li>{idx}</li></a>\n );\n\n let propsToPass = {\n items: this.state.filteredItems,\n deleteHandler: this.handleDelete\n }\n return (\n <div>\n {this.props.render(propsToPass)}\n \n <div style={{ width: 720, margin: 0 }}>\n <div className=\"container\">\n <div className=\"pagination p1\">\n <ul>\n {this.state.currentPage != 1 ? <a href=\"#\" onClick={this.handleClick.bind(this, this.state.currentPage - 1)}><li><</li></a> : <span> </span>}\n {pages}\n {this.state.currentPage != this.state.totalPages ?\n <a href=\"#\" onClick={this.handleClick.bind(this, this.state.currentPage + 1)}><li>></li></a> : <span> </span>}\n </ul>\n </div>\n </div>\n </div>\n </div>\n )\n }\n}\nexport default Pager"
},
{
"code": null,
"e": 13569,
"s": 13391,
"text": "Next, open ExpenseEntryItemeList.js file and update the getDerivedStateFromProps function to get the current expense item list by copying the passed-in props into the new state."
},
{
"code": null,
"e": 13690,
"s": 13569,
"text": "static getDerivedStateFromProps(props, state) {\n let newState = {\n items: props.items\n }\n return newState;\n}\n"
},
{
"code": null,
"e": 13840,
"s": 13690,
"text": "Next, update the handleDelete method and call the event handler method passed into the component from from pager component through onDelete property."
},
{
"code": null,
"e": 13957,
"s": 13840,
"text": "handleDelete = (id, e) => {\n e.preventDefault();\n\n if(this.props.onDelete != null)this.props.onDelete(id, e);\n}\n"
},
{
"code": null,
"e": 14041,
"s": 13957,
"text": "Next, remove rendering of header and footer, if any available in the render method."
},
{
"code": null,
"e": 14178,
"s": 14041,
"text": "return (\n <div>\n <div>{this.props.header}</div>\n ... existing code ...\n <div>{this.props.footer}</div>\n </div>\n);\n"
},
{
"code": null,
"e": 14258,
"s": 14178,
"text": "The complete source code of the ExpenseEntryItemList component is given below −"
},
{
"code": null,
"e": 16965,
"s": 14258,
"text": "import React from 'react';\nimport './ExpenseEntryItemList.css';\n\nclass ExpenseEntryItemList extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n items: this.props.items\n }\n this.handleMouseEnter = this.handleMouseEnter.bind();\n this.handleMouseLeave = this.handleMouseLeave.bind();\n this.handleMouseOver = this.handleMouseOver.bind();\n }\n handleMouseEnter(e) {\n e.target.parentNode.classList.add(\"highlight\");\n }\n handleMouseLeave(e) {\n e.target.parentNode.classList.remove(\"highlight\");\n }\n handleMouseOver(e) {\n console.log(\"The mouse is at (\" + e.clientX + \", \" + e.clientY + \")\");\n }\n handleDelete = (id, e) => {\n e.preventDefault();\n\n if(this.props.onDelete != null)this.props.onDelete(id, e);\n \n /*console.log(id);\n\n this.setState((state, props) => {\n let items = [];\n state.items.forEach((item, idx) => {\n if (item.id != id)\n items.push(item)\n })\n let newState = {\n items: items\n }\n return newState;\n })*/\n }\n getTotal() {\n let total = 0;\n for (var i = 0; i < this.state.items.length; i++) {\n total += this.state.items[i].amount\n }\n return total;\n }\n static getDerivedStateFromProps(props, state) {\n let newState = {\n items: props.items\n }\n return newState;\n }\n render() {\n const lists = this.state.items.map((item) =>\n <tr key={item.id} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>\n <td>{item.name}</td>\n <td>{item.amount}</td>\n <td>{new Date(item.spendDate).toDateString()}</td>\n <td>{item.category}</td>\n <td><a href=\"#\"\n onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td>\n </tr>\n );\n return (\n <div>\n <table onMouseOver={this.handleMouseOver}>\n <thead>\n <tr>\n <th>Item</th>\n <th>Amount</th>\n <th>Date</th>\n <th>Category</th>\n <th>Remove</th>\n </tr>\n </thead>\n <tbody>\n {lists}\n <tr>\n <td colSpan=\"1\" style={{ textAlign: \"right\" }}>Total Amount</td>\n <td colSpan=\"4\" style={{ textAlign: \"left\" }}>\n {this.getTotal()}\n </td>\n </tr>\n </tbody>\n </table>\n </div>\n );\n }\n}\nexport default ExpenseEntryItemList;"
},
{
"code": null,
"e": 17065,
"s": 16965,
"text": "Next, open index.js and call the Pager component and pass the ExpenseEntryItemList as render props."
},
{
"code": null,
"e": 18609,
"s": 17065,
"text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport Pager from './components/Pager'\nimport ExpenseEntryItemList from './components/ExpenseEntryItemList'\n\nconst items = [\n { id: 1, name: \"Pizza\", amount: 80, spendDate: \"2020-10-10\", category: \"Food\" },\n { id: 2, name: \"Grape Juice\", amount: 30, spendDate: \"2020-10-12\", category: \"Food\" },\n { id: 3, name: \"Cinema\", amount: 210, spendDate: \"2020-10-16\", category: \"Entertainment\" },\n { id: 4, name: \"Java Programming book\", amount: 242, spendDate: \"2020-10-15\", category: \"Academic\" },\n { id: 5, name: \"Mango Juice\", amount: 35, spendDate: \"2020-10-16\", category: \"Food\" },\n { id: 6, name: \"Dress\", amount: 2000, spendDate: \"2020-10-25\", category: \"Cloth\" },\n { id: 7, name: \"Tour\", amount: 2555, spendDate: \"2020-10-29\", category: \"Entertainment\" },\n { id: 8, name: \"Meals\", amount: 300, spendDate: \"2020-10-30\", category: \"Food\" },\n { id: 9, name: \"Mobile\", amount: 3500, spendDate: \"2020-11-02\", category: \"Gadgets\" },\n { id: 10, name: \"Exam Fees\", amount: 1245, spendDate: \"2020-11-04\", category: \"Academic\" }\n]\nconst pageCount = 3;\nReactDOM.render(\n <React.StrictMode>\n <Pager\n items={items}\n pageCount={pageCount}\n render={\n pagerState => (\n <div>\n <ExpenseEntryItemList items={pagerState.items} \n onDelete={pagerState.deleteHandler} />\n </div>\n )\n }\n />\n </React.StrictMode>,\n document.getElementById('root')\n);\n"
},
{
"code": null,
"e": 18705,
"s": 18609,
"text": "As we see, the Pager component accept any render props and only calculate the pagination logic."
},
{
"code": null,
"e": 18752,
"s": 18705,
"text": "Next, serve the application using npm command."
},
{
"code": null,
"e": 18763,
"s": 18752,
"text": "npm start\n"
}
]
|
Charset name() method in Java with Examples - GeeksforGeeks | 28 Mar, 2019
The name() method is a built-in method of the java.nio.charset returns the charset’s canonical name.
Syntax:
public final String name()
Parameters: The function does not accepts any parameter.
Return Value: The function returns the charset’s canonical name.
Below is the implementation of the above function:
Program 1:
// Java program to demonstrate// the above function import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;import java.nio.charset.CharsetEncoder; public class GFG { public static void main(String[] args) { // Gets charset Charset Charset1 = Charset.forName("UTF8"); // Prints it System.out.println(Charset1.name()); }}
UTF-8
Program 2:
// Java program to demonstrate// the above function import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;import java.nio.charset.CharsetEncoder; public class GFG { public static void main(String[] args) { // Gets charset Charset Charset1 = Charset.forName("UTF16"); // Prints it System.out.println(Charset1.name()); }}
UTF-16
Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/charset/Charset.html#name–
Java-Charset
Java-Functions
Java-NIO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Stream In Java
Different ways of Reading a text file in Java
Internal Working of HashMap in Java
Iterators in Java
Java Programming Examples
Comparator Interface in Java with Examples
Strings in Java | [
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n28 Mar, 2019"
},
{
"code": null,
"e": 23658,
"s": 23557,
"text": "The name() method is a built-in method of the java.nio.charset returns the charset’s canonical name."
},
{
"code": null,
"e": 23666,
"s": 23658,
"text": "Syntax:"
},
{
"code": null,
"e": 23693,
"s": 23666,
"text": "public final String name()"
},
{
"code": null,
"e": 23750,
"s": 23693,
"text": "Parameters: The function does not accepts any parameter."
},
{
"code": null,
"e": 23815,
"s": 23750,
"text": "Return Value: The function returns the charset’s canonical name."
},
{
"code": null,
"e": 23866,
"s": 23815,
"text": "Below is the implementation of the above function:"
},
{
"code": null,
"e": 23877,
"s": 23866,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// the above function import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;import java.nio.charset.CharsetEncoder; public class GFG { public static void main(String[] args) { // Gets charset Charset Charset1 = Charset.forName(\"UTF8\"); // Prints it System.out.println(Charset1.name()); }}",
"e": 24258,
"s": 23877,
"text": null
},
{
"code": null,
"e": 24265,
"s": 24258,
"text": "UTF-8\n"
},
{
"code": null,
"e": 24276,
"s": 24265,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// the above function import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;import java.nio.charset.CharsetEncoder; public class GFG { public static void main(String[] args) { // Gets charset Charset Charset1 = Charset.forName(\"UTF16\"); // Prints it System.out.println(Charset1.name()); }}",
"e": 24658,
"s": 24276,
"text": null
},
{
"code": null,
"e": 24666,
"s": 24658,
"text": "UTF-16\n"
},
{
"code": null,
"e": 24755,
"s": 24666,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/charset/Charset.html#name–"
},
{
"code": null,
"e": 24768,
"s": 24755,
"text": "Java-Charset"
},
{
"code": null,
"e": 24783,
"s": 24768,
"text": "Java-Functions"
},
{
"code": null,
"e": 24800,
"s": 24783,
"text": "Java-NIO package"
},
{
"code": null,
"e": 24805,
"s": 24800,
"text": "Java"
},
{
"code": null,
"e": 24810,
"s": 24805,
"text": "Java"
},
{
"code": null,
"e": 24908,
"s": 24810,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24917,
"s": 24908,
"text": "Comments"
},
{
"code": null,
"e": 24930,
"s": 24917,
"text": "Old Comments"
},
{
"code": null,
"e": 24951,
"s": 24930,
"text": "Constructors in Java"
},
{
"code": null,
"e": 24970,
"s": 24951,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 25000,
"s": 24970,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 25015,
"s": 25000,
"text": "Stream In Java"
},
{
"code": null,
"e": 25061,
"s": 25015,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 25097,
"s": 25061,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 25115,
"s": 25097,
"text": "Iterators in Java"
},
{
"code": null,
"e": 25141,
"s": 25115,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 25184,
"s": 25141,
"text": "Comparator Interface in Java with Examples"
}
]
|
7 Best R Packages for Machine Learning - GeeksforGeeks | 21 Dec, 2021
Machine Learning is a subset of artificial intelligence that focuses on the development of computer software or programs that access data to learn themselves and make predictions i.e. without being explicitly programmed. Machine learning consists of different sub-parts i.e. unsupervised learning, supervised learning, and reinforcement learning. It defines numerical problems and categorical problems that help in building models.
R language is used for statistical analysis and computing used by the majority of researchers around the world. R is being used in building machine learning models due to its flexibility, efficient packages, and the ability to perform deep learning models with integration to the cloud. Being an open-source language, all the packages are published on R with contributions from programmers around the world to make it more user friendly. Following R packages are widely used in industry are:
data.table
dplyr
ggplot2
caret
e1071
xgboost
randomForest
data.table provides a high-performance version of R’s data.frame with feature enhancements and syntax for ease of use, memory efficient, and rich with features. It provides a fast and friendly delimited file reader and file writer. It is one of the top-rated packages on Github. It provides low-level parallelism, scalable aggregations with feature-rich joins, and feature-rich reshaping data.
R
# Installing the packageinstall.packages("data.table") # Loading packagelibrary(data.table) # Importing datasetGov_mortage <- fread("Government_Mortage.csv") # Record with loan amount 114# With country code 60Answer <- Gov_mortage[loan_amount == 114 & county_code == 60]Answer
Output:
row_id loan_type property_type loan_purpose occupancy loan_amount preapproval msa_md
1: 65 1 1 3 1 114 3 344
2: 1285 1 1 1 1 114 2 -1
3: 6748 1 1 3 1 114 3 309
4: 31396 1 1 1 1 114 1 333
5: 70311 1 1 1 1 114 3 309
6: 215535 1 1 3 1 114 3 365
7: 217264 1 1 1 2 114 3 333
8: 301947 1 1 3 1 114 3 48
state_code county_code applicant_ethnicity applicant_race applicant_sex
1: 9 60 2 5 1
2: 25 60 2 5 2
3: 47 60 2 5 2
4: 6 60 2 5 1
5: 47 60 2 5 2
6: 21 60 2 5 1
7: 6 60 2 5 1
8: 14 60 2 5 2
applicant_income population minority_population_pct ffiecmedian_family_income
1: 68 6355 14.844 61840
2: 57 1538 2.734 58558
3: 54 4084 5.329 76241
4: 116 5445 41.429 70519
5: 50 5214 3.141 74094
6: 57 6951 4.219 56341
7: 37 2416 18.382 70031
8: 35 3159 8.533 56335
tract_to_msa_md_income_pct number_of_owner-occupied_units
1: 100.000 1493
2: 100.000 561
3: 100.000 1359
4: 100.000 1522
5: 100.000 1694
6: 97.845 2134
7: 65.868 905
8: 100.000 1080
number_of_1_to_4_family_units lender co_applicant
1: 2202 3507 TRUE
2: 694 6325 FALSE
3: 1561 3549 FALSE
4: 1730 2111 TRUE
5: 2153 3229 FALSE
6: 2993 1574 TRUE
7: 3308 3110 FALSE
8: 1492 6314 FALSE
Dplyr is a data manipulation package widely used in the industry. It consists of five key data manipulation functions also known as verbs i.e Select, Filter, Arrange, Mutate, and Summarize.
R
# Installing the packageinstall.packages("dplyr") # Loading packagelibrary(dplyr) # Importing datasetGov_mortage <- fread("Government_Mortage.csv") # Selectselect(Gov_mortage, state_code) # Mutatem <- mutate(Gov_mortage, amount = loan_amount - applicant_income)m # Filterf = filter(Gov_mortage, county_code == 80)f # Arrangearrange(Gov_mortage, county_code == 80) # Summarizesummarise(f, max_loan = max(loan_amount))
Output:
# Filter
row_id loan_type property_type loan_purpose occupancy loan_amount preapproval msa_md
1 16 1 1 3 2 177 3 333
2 25 1 1 3 1 292 3 333
3 585 1 1 3 1 134 3 333
4 1033 1 1 1 1 349 2 333
5 1120 1 1 1 1 109 3 333
6 1303 1 1 3 2 166 3 333
7 1758 1 1 2 1 45 3 333
8 2053 3 1 1 1 267 3 333
9 3305 1 1 3 1 392 3 333
10 3555 1 1 3 1 98 3 333
11 3769 1 1 3 1 288 3 333
12 3807 1 1 1 1 185 3 333
13 3840 1 1 3 1 280 3 333
14 5356 1 1 3 1 123 3 333
15 5604 2 1 1 1 191 1 333
16 6294 1 1 2 1 102 3 333
17 7631 3 1 3 1 107 3 333
18 8222 2 1 3 1 62 3 333
19 9335 1 1 3 1 113 3 333
20 10137 1 1 1 1 204 3 333
21 10387 3 1 1 1 434 2 333
22 10601 2 1 1 1 299 2 333
23 13076 1 1 1 1 586 3 333
24 13763 1 1 3 1 29 3 333
25 13769 3 1 1 1 262 3 333
26 13818 2 1 1 1 233 3 333
27 14102 1 1 3 1 130 3 333
28 14196 1 1 2 1 3 3 333
29 15569 1 1 1 1 536 2 333
30 15863 1 1 1 1 20 3 333
31 16184 1 1 3 1 755 3 333
32 16296 1 1 1 2 123 2 333
33 16328 1 1 3 1 153 3 333
34 16486 3 1 3 1 95 3 333
35 16684 1 1 2 1 26 3 333
36 16922 1 1 1 1 160 2 333
37 17470 1 1 3 1 174 3 333
38 18336 1 2 1 1 37 3 333
39 18586 1 2 1 1 114 3 333
40 19249 1 1 3 1 422 3 333
41 19405 1 1 1 1 288 2 333
42 19421 1 1 2 1 301 3 333
43 20125 1 1 3 1 449 3 333
44 20388 1 1 1 1 494 3 333
45 21434 1 1 3 1 251 3 333
state_code county_code applicant_ethnicity applicant_race applicant_sex
1 6 80 1 5 2
2 6 80 2 3 2
3 6 80 2 5 2
4 6 80 3 6 1
5 6 80 2 5 2
6 6 80 1 5 1
7 6 80 2 5 1
8 6 80 1 5 2
9 6 80 2 5 1
10 6 80 2 5 1
11 6 80 2 5 1
12 6 80 1 5 1
13 6 80 1 5 1
14 6 80 1 5 1
15 6 80 2 5 1
16 6 80 2 5 1
17 6 80 3 6 3
18 6 80 2 5 1
19 6 80 2 5 2
20 6 80 2 5 1
21 6 80 2 5 1
22 6 80 2 5 1
23 6 80 3 6 3
24 6 80 2 5 2
25 6 80 2 5 1
26 6 80 2 5 1
27 6 80 2 5 2
28 6 80 1 6 1
29 6 80 2 5 1
30 6 80 2 5 1
31 6 80 2 5 1
32 6 80 2 5 2
33 6 80 1 5 1
34 6 80 2 5 1
35 6 80 2 5 1
36 6 80 2 5 2
37 6 80 2 5 1
38 6 80 1 5 1
39 6 80 1 5 1
40 6 80 1 5 1
41 6 80 2 2 1
42 6 80 2 5 1
43 6 80 2 5 1
44 6 80 2 5 1
45 6 80 2 5 1
applicant_income population minority_population_pct ffiecmedian_family_income
1 NA 6420 29.818 68065
2 99 4346 16.489 70745
3 46 6782 20.265 69818
4 236 9813 15.168 69691
5 49 5854 35.968 70555
6 148 4234 19.864 72156
7 231 5699 17.130 71892
8 48 6537 13.024 71562
9 219 18911 26.595 69795
10 71 8454 17.436 68727
11 94 6304 13.490 69181
12 78 9451 14.684 69337
13 74 15540 43.148 70000
14 54 16183 42.388 70862
15 73 11198 40.481 70039
16 199 12133 10.971 70023
17 43 10712 33.973 68117
18 115 8759 17.669 70526
19 59 24887 32.833 71510
20 135 25252 31.854 69602
21 108 6507 13.613 70267
22 191 9261 22.583 71505
23 430 7943 19.990 70801
24 206 7193 18.002 69973
25 150 7413 14.092 68202
26 94 7611 14.618 71260
27 81 10946 34.220 70386
28 64 10438 36.395 70141
29 387 8258 20.666 69409
30 80 7525 26.604 70104
31 NA 4525 20.299 71947
32 40 8397 32.542 68087
33 87 20083 19.750 69893
34 96 20539 19.673 72152
35 45 10497 12.920 70134
36 54 15686 26.071 70890
37 119 7558 14.710 69052
38 62 25960 32.858 68061
39 18 5790 39.450 68878
40 103 18086 26.099 69925
41 70 8689 31.467 70794
42 38 3923 30.206 68821
43 183 6522 13.795 69779
44 169 18459 26.874 69392
45 140 15954 25.330 71096
tract_to_msa_md_income_pct number_of_owner-occupied_units
1 100.000 1553
2 100.000 1198
3 100.000 1910
4 100.000 2351
5 100.000 1463
6 100.000 1276
7 100.000 1467
8 100.000 1766
9 100.000 4316
10 90.071 2324
11 100.000 1784
12 100.000 2357
13 100.000 3252
14 100.000 3319
15 79.049 2438
16 100.000 3639
17 100.000 2612
18 87.201 2345
19 100.000 6713
20 100.000 6987
21 100.000 1788
22 91.023 2349
23 100.000 1997
24 100.000 2012
25 100.000 2359
26 100.000 2304
27 100.000 2674
28 80.957 2023
29 100.000 2034
30 100.000 2343
31 77.707 1059
32 100.000 1546
33 100.000 5929
34 100.000 6017
35 100.000 3542
36 100.000 4277
37 100.000 2316
38 100.000 6989
39 56.933 1021
40 100.000 4183
41 100.000 1540
42 100.000 882
43 100.000 1774
44 100.000 4417
45 100.000 4169
number_of_1_to_4_family_units lender co_applicant
1 2001 3354 FALSE
2 1349 2458 FALSE
3 2326 4129 FALSE
4 2928 4701 TRUE
5 1914 2134 FALSE
6 1638 5710 FALSE
7 1670 3110 FALSE
8 1926 3080 TRUE
9 5241 5710 TRUE
10 3121 5710 FALSE
11 1953 933 FALSE
12 2989 186 TRUE
13 4482 2134 TRUE
14 4380 5339 TRUE
15 3495 5267 TRUE
16 4875 1831 TRUE
17 3220 5710 FALSE
18 3024 3885 TRUE
19 7980 2458 FALSE
20 7949 6240 TRUE
21 2015 542 TRUE
22 3215 2702 TRUE
23 2361 3216 FALSE
24 2482 6240 FALSE
25 2597 3970 TRUE
26 2503 3264 FALSE
27 3226 2570 TRUE
28 3044 6240 FALSE
29 2423 1928 TRUE
30 2659 5738 FALSE
31 1544 2458 FALSE
32 2316 3950 FALSE
33 7105 3143 FALSE
34 7191 4701 FALSE
35 4325 5339 FALSE
36 5188 2702 FALSE
37 2531 2458 TRUE
38 7976 2318 TRUE
39 1755 5026 FALSE
40 5159 4931 TRUE
41 2337 2352 FALSE
42 1317 2458 FALSE
43 1949 5726 FALSE
44 5055 5316 TRUE
45 5197 5726 FALSE
[ reached 'max' / getOption("max.print") -- omitted 1034 rows ]
#
ggplot2 also termed as Grammar of Graphics is a free, opensource, and easy to use visualization package widely used in R. It is the most powerful visualization package written by Hadley Wickham.
R
# Installing the packageinstall.packages("dplyr")install.packages("ggplot2") # Loading packageslibrary(dplyr)library(ggplot2) # Data Layerggplot(data = mtcars) # Aesthetic Layerggplot(data = mtcars, aes(x = hp, y = mpg, col = disp)) # Geometric layerggplot(data = mtcars, aes(x = hp, y = mpg, col = disp)) + geom_point()
Output:
Geometric layer:
Geometric layer – Adding Size:
caret termed as Classification and Regression Training uses many functions for training and plotting classification & regression models. It is one of the most widely used packages among R developers and in various machine learning competitions.
R
# Installing Packagesinstall.packages("e1071")install.packages("caTools")install.packages("caret") # Loading packagelibrary(e1071)library(caTools)library(caret) # Loading datadata(iris) # Splitting data into train# and test datasplit <- sample.split(iris, SplitRatio = 0.7)train_cl <- subset(iris, split == "TRUE")test_cl <- subset(iris, split == "FALSE") # Feature Scalingtrain_scale <- scale(train_cl[, 1:4])test_scale <- scale(test_cl[, 1:4]) # Fitting Naive Bayes Model # to training datasetset.seed(120) # Setting Seedclassifier_cl <- naiveBayes(Species ~ ., data = train_cl)classifier_cl # Predicting on test data'y_pred <- predict(classifier_cl, newdata = test_cl) # Confusion Matrixcm <- table(test_cl$Species, y_pred)cm
Output:
Model classifier_cl:
Confusion Matrix:
e1071 package is used for performing clustering algorithms, support vector machines(SVM), shortest path computations, bagged clustering algorithms, K-NN algorithm, etc. Mostly, it is used for performing a K-NN algorithm. which depends on its k value(Neighbors) and finds itĺs applications in many industries like the finance industry, healthcare industry, etc. K-Nearest Neighbor or K-NN is a Supervised Non-linear classification algorithm. K-NN is a Non-parametric algorithm i.e it doesn’t make any assumption about underlying data or its distribution.
R
# Installing Packagesinstall.packages("e1071")install.packages("caTools")install.packages("class") # Loading packagelibrary(e1071)library(caTools)library(class) # Loading datadata(iris) # Splitting data into train# and test datasplit <- sample.split(iris, SplitRatio = 0.7)train_cl <- subset(iris, split == "TRUE")test_cl <- subset(iris, split == "FALSE") # Feature Scalingtrain_scale <- scale(train_cl[, 1:4])test_scale <- scale(test_cl[, 1:4]) # Fitting KNN Model # to training datasetclassifier_knn <- knn(train = train_scale, test = test_scale, cl = train_cl$Species, k = 1)classifier_knn # Confusiin Matrixcm <- table(test_cl$Species, classifier_knn)cm # Model Evaluation - Choosing K# Calculate out of Sample errormisClassError <- mean(classifier_knn != test_cl$Species)print(paste('Accuracy =', 1 - misClassError))
Outputs:
Model classifier_knn(k=1):
Confusion Matrix:
Model Evaluation(k=1):
XGBoost works only with numeric variables. It is a part of the boosting technique in which the selection of the sample is done more intelligently to classify observations. There are interfaces of XGBoost in C++, R, Python, Julia, Java, and Scala. It consists of Bagging and Boosting techniques. The dataset used BigMart.
R
# Installing Packagesinstall.packages("data.table")install.packages("dplyr")install.packages("ggplot2")install.packages("caret")install.packages("xgboost")install.packages("e1071")install.packages("cowplot") # Loading packageslibrary(data.table) # for reading and manipulation of datalibrary(dplyr) # for data manipulation and joininglibrary(ggplot2) # for ploting library(caret) # for modelinglibrary(xgboost) # for building XGBoost modellibrary(e1071) # for skewnesslibrary(cowplot) # for combining multiple plots # Setting test dataset# Combining datasets# add Item_Outlet_Sales to test datatest[, Item_Outlet_Sales := NA] combi = rbind(train, test) # Missing Value Treatmentmissing_index = which(is.na(combi$Item_Weight))for(i in missing_index){ item = combi$Item_Identifier[i] combi$Item_Weight[i] = mean(combi$Item_Weight [combi$Item_Identifier == item], na.rm = T)} # Replacing 0 in Item_Visibility with meanzero_index = which(combi$Item_Visibility == 0)for(i in zero_index){ item = combi$Item_Identifier[i] combi$Item_Visibility[i] = mean( combi$Item_Visibility[combi$Item_Identifier == item], na.rm = T)} # Label Encoding# To convert categorical in numericalcombi[, Outlet_Size_num := ifelse(Outlet_Size == "Small", 0, ifelse(Outlet_Size == "Medium", 1, 2))] combi[, Outlet_Location_Type_num := ifelse(Outlet_Location_Type == "Tier 3", 0, ifelse(Outlet_Location_Type == "Tier 2", 1, 2))] combi[, c("Outlet_Size", "Outlet_Location_Type") := NULL] # One Hot Encoding# To convert categorical in numericalohe_1 = dummyVars("~.", data = combi[, -c("Item_Identifier", "Outlet_Establishment_Year", "Item_Type")], fullRank = T)ohe_df = data.table(predict(ohe_1, combi[, -c("Item_Identifier", "Outlet_Establishment_Year", "Item_Type")])) combi = cbind(combi[, "Item_Identifier"], ohe_df) # Remove skewnessskewness(combi$Item_Visibility) skewness(combi$price_per_unit_wt) # log + 1 to avoid division by zerocombi[, Item_Visibility := log(Item_Visibility + 1)] # Scaling and Centering data# index of numeric featuresnum_vars = which(sapply(combi, is.numeric)) num_vars_names = names(num_vars) combi_numeric = combi[, setdiff(num_vars_names, "Item_Outlet_Sales"), with = F] prep_num = preProcess(combi_numeric, method = c("center", "scale"))combi_numeric_norm = predict(prep_num, combi_numeric) # removing numeric independent variablescombi[, setdiff(num_vars_names, "Item_Outlet_Sales") := NULL] combi = cbind(combi, combi_numeric_norm) # Splitting data back to train and testtrain = combi[1:nrow(train)]test = combi[(nrow(train) + 1):nrow(combi)] # Removing Item_Outlet_Salestest[, Item_Outlet_Sales := NULL] # Model Building: XGBoostparam_list = list( objective = "reg:linear", eta = 0.01, gamma = 1, max_depth = 6, subsample = 0.8, colsample_bytree = 0.5) # Converting train and test into xgb.DMatrix formatDtrain = xgb.DMatrix( data = as.matrix(train[, -c("Item_Identifier", "Item_Outlet_Sales")]), label = train$Item_Outlet_Sales)Dtest = xgb.DMatrix( data = as.matrix(test[, -c("Item_Identifier")])) # 5-fold cross-validation to # find optimal value of nroundsset.seed(112) # Setting seedxgbcv = xgb.cv(params = param_list, data = Dtrain, nrounds = 1000, nfold = 5, print_every_n = 10, early_stopping_rounds = 30, maximize = F) # Training XGBoost model at nrounds = 428xgb_model = xgb.train(data = Dtrain, params = param_list, nrounds = 428)xgb_model
Output:
Training of Xgboost model:
Model xgb_model:
Random Forest in R Programming is an ensemble of decision trees. It builds and combines multiple decision trees to get more accurate predictions. It’s a non-linear classification algorithm. Each decision tree model is used when employed on its own. An error estimate of cases is made that is not used when constructing the tree. This is called an out-of-bag error estimate mentioned as a percentage.
R
# Installing package # For sampling the datasetinstall.packages("caTools") # For implementing random forest algorithminstall.packages("randomForest") # Loading packagelibrary(caTools)library(randomForest) # Loading datadata(iris) # Splitting data in train and test datasplit <- sample.split(iris, SplitRatio = 0.7)split train <- subset(iris, split == "TRUE")test <- subset(iris, split == "FALSE") # Fitting Random Forest to the train datasetset.seed(120) # Setting seedclassifier_RF = randomForest(x = train[-5], y = train$Species, ntree = 500) classifier_RF # Predicting the Test set resultsy_pred = predict(classifier_RF, newdata = test[-5]) # Confusion Matrixconfusion_mtx = table(test[, 5], y_pred)confusion_mtx
Outputs:
Model classifier_RF:
Confusion Matrix:
simmytarika5
R Machine-Learning
GBlog
Machine Learning
R Language
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Roadmap to Become a Web Developer in 2022
ML | Underfitting and Overfitting
Top 10 Angular Libraries For Web Developers
A Freshers Guide To Programming
Naive Bayes Classifiers
Linear Regression (Python Implementation)
Decision Tree
ML | Linear Regression
Python | Decision tree implementation | [
{
"code": null,
"e": 24904,
"s": 24876,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 25336,
"s": 24904,
"text": "Machine Learning is a subset of artificial intelligence that focuses on the development of computer software or programs that access data to learn themselves and make predictions i.e. without being explicitly programmed. Machine learning consists of different sub-parts i.e. unsupervised learning, supervised learning, and reinforcement learning. It defines numerical problems and categorical problems that help in building models."
},
{
"code": null,
"e": 25828,
"s": 25336,
"text": "R language is used for statistical analysis and computing used by the majority of researchers around the world. R is being used in building machine learning models due to its flexibility, efficient packages, and the ability to perform deep learning models with integration to the cloud. Being an open-source language, all the packages are published on R with contributions from programmers around the world to make it more user friendly. Following R packages are widely used in industry are:"
},
{
"code": null,
"e": 25839,
"s": 25828,
"text": "data.table"
},
{
"code": null,
"e": 25845,
"s": 25839,
"text": "dplyr"
},
{
"code": null,
"e": 25853,
"s": 25845,
"text": "ggplot2"
},
{
"code": null,
"e": 25859,
"s": 25853,
"text": "caret"
},
{
"code": null,
"e": 25865,
"s": 25859,
"text": "e1071"
},
{
"code": null,
"e": 25873,
"s": 25865,
"text": "xgboost"
},
{
"code": null,
"e": 25886,
"s": 25873,
"text": "randomForest"
},
{
"code": null,
"e": 26280,
"s": 25886,
"text": "data.table provides a high-performance version of R’s data.frame with feature enhancements and syntax for ease of use, memory efficient, and rich with features. It provides a fast and friendly delimited file reader and file writer. It is one of the top-rated packages on Github. It provides low-level parallelism, scalable aggregations with feature-rich joins, and feature-rich reshaping data."
},
{
"code": null,
"e": 26282,
"s": 26280,
"text": "R"
},
{
"code": "# Installing the packageinstall.packages(\"data.table\") # Loading packagelibrary(data.table) # Importing datasetGov_mortage <- fread(\"Government_Mortage.csv\") # Record with loan amount 114# With country code 60Answer <- Gov_mortage[loan_amount == 114 & county_code == 60]Answer",
"e": 26580,
"s": 26282,
"text": null
},
{
"code": null,
"e": 26588,
"s": 26580,
"text": "Output:"
},
{
"code": null,
"e": 29803,
"s": 26588,
"text": "row_id loan_type property_type loan_purpose occupancy loan_amount preapproval msa_md\n1: 65 1 1 3 1 114 3 344\n2: 1285 1 1 1 1 114 2 -1\n3: 6748 1 1 3 1 114 3 309\n4: 31396 1 1 1 1 114 1 333\n5: 70311 1 1 1 1 114 3 309\n6: 215535 1 1 3 1 114 3 365\n7: 217264 1 1 1 2 114 3 333\n8: 301947 1 1 3 1 114 3 48\n state_code county_code applicant_ethnicity applicant_race applicant_sex\n1: 9 60 2 5 1\n2: 25 60 2 5 2\n3: 47 60 2 5 2\n4: 6 60 2 5 1\n5: 47 60 2 5 2\n6: 21 60 2 5 1\n7: 6 60 2 5 1\n8: 14 60 2 5 2\n applicant_income population minority_population_pct ffiecmedian_family_income\n1: 68 6355 14.844 61840\n2: 57 1538 2.734 58558\n3: 54 4084 5.329 76241\n4: 116 5445 41.429 70519\n5: 50 5214 3.141 74094\n6: 57 6951 4.219 56341\n7: 37 2416 18.382 70031\n8: 35 3159 8.533 56335\n tract_to_msa_md_income_pct number_of_owner-occupied_units\n1: 100.000 1493\n2: 100.000 561\n3: 100.000 1359\n4: 100.000 1522\n5: 100.000 1694\n6: 97.845 2134\n7: 65.868 905\n8: 100.000 1080\n number_of_1_to_4_family_units lender co_applicant\n1: 2202 3507 TRUE\n2: 694 6325 FALSE\n3: 1561 3549 FALSE\n4: 1730 2111 TRUE\n5: 2153 3229 FALSE\n6: 2993 1574 TRUE\n7: 3308 3110 FALSE\n8: 1492 6314 FALSE"
},
{
"code": null,
"e": 29993,
"s": 29803,
"text": "Dplyr is a data manipulation package widely used in the industry. It consists of five key data manipulation functions also known as verbs i.e Select, Filter, Arrange, Mutate, and Summarize."
},
{
"code": null,
"e": 29995,
"s": 29993,
"text": "R"
},
{
"code": "# Installing the packageinstall.packages(\"dplyr\") # Loading packagelibrary(dplyr) # Importing datasetGov_mortage <- fread(\"Government_Mortage.csv\") # Selectselect(Gov_mortage, state_code) # Mutatem <- mutate(Gov_mortage, amount = loan_amount - applicant_income)m # Filterf = filter(Gov_mortage, county_code == 80)f # Arrangearrange(Gov_mortage, county_code == 80) # Summarizesummarise(f, max_loan = max(loan_amount))",
"e": 30423,
"s": 29995,
"text": null
},
{
"code": null,
"e": 30431,
"s": 30423,
"text": "Output:"
},
{
"code": null,
"e": 46968,
"s": 30431,
"text": "# Filter\nrow_id loan_type property_type loan_purpose occupancy loan_amount preapproval msa_md\n1 16 1 1 3 2 177 3 333\n2 25 1 1 3 1 292 3 333\n3 585 1 1 3 1 134 3 333\n4 1033 1 1 1 1 349 2 333\n5 1120 1 1 1 1 109 3 333\n6 1303 1 1 3 2 166 3 333\n7 1758 1 1 2 1 45 3 333\n8 2053 3 1 1 1 267 3 333\n9 3305 1 1 3 1 392 3 333\n10 3555 1 1 3 1 98 3 333\n11 3769 1 1 3 1 288 3 333\n12 3807 1 1 1 1 185 3 333\n13 3840 1 1 3 1 280 3 333\n14 5356 1 1 3 1 123 3 333\n15 5604 2 1 1 1 191 1 333\n16 6294 1 1 2 1 102 3 333\n17 7631 3 1 3 1 107 3 333\n18 8222 2 1 3 1 62 3 333\n19 9335 1 1 3 1 113 3 333\n20 10137 1 1 1 1 204 3 333\n21 10387 3 1 1 1 434 2 333\n22 10601 2 1 1 1 299 2 333\n23 13076 1 1 1 1 586 3 333\n24 13763 1 1 3 1 29 3 333\n25 13769 3 1 1 1 262 3 333\n26 13818 2 1 1 1 233 3 333\n27 14102 1 1 3 1 130 3 333\n28 14196 1 1 2 1 3 3 333\n29 15569 1 1 1 1 536 2 333\n30 15863 1 1 1 1 20 3 333\n31 16184 1 1 3 1 755 3 333\n32 16296 1 1 1 2 123 2 333\n33 16328 1 1 3 1 153 3 333\n34 16486 3 1 3 1 95 3 333\n35 16684 1 1 2 1 26 3 333\n36 16922 1 1 1 1 160 2 333\n37 17470 1 1 3 1 174 3 333\n38 18336 1 2 1 1 37 3 333\n39 18586 1 2 1 1 114 3 333\n40 19249 1 1 3 1 422 3 333\n41 19405 1 1 1 1 288 2 333\n42 19421 1 1 2 1 301 3 333\n43 20125 1 1 3 1 449 3 333\n44 20388 1 1 1 1 494 3 333\n45 21434 1 1 3 1 251 3 333\n state_code county_code applicant_ethnicity applicant_race applicant_sex\n1 6 80 1 5 2\n2 6 80 2 3 2\n3 6 80 2 5 2\n4 6 80 3 6 1\n5 6 80 2 5 2\n6 6 80 1 5 1\n7 6 80 2 5 1\n8 6 80 1 5 2\n9 6 80 2 5 1\n10 6 80 2 5 1\n11 6 80 2 5 1\n12 6 80 1 5 1\n13 6 80 1 5 1\n14 6 80 1 5 1\n15 6 80 2 5 1\n16 6 80 2 5 1\n17 6 80 3 6 3\n18 6 80 2 5 1\n19 6 80 2 5 2\n20 6 80 2 5 1\n21 6 80 2 5 1\n22 6 80 2 5 1\n23 6 80 3 6 3\n24 6 80 2 5 2\n25 6 80 2 5 1\n26 6 80 2 5 1\n27 6 80 2 5 2\n28 6 80 1 6 1\n29 6 80 2 5 1\n30 6 80 2 5 1\n31 6 80 2 5 1\n32 6 80 2 5 2\n33 6 80 1 5 1\n34 6 80 2 5 1\n35 6 80 2 5 1\n36 6 80 2 5 2\n37 6 80 2 5 1\n38 6 80 1 5 1\n39 6 80 1 5 1\n40 6 80 1 5 1\n41 6 80 2 2 1\n42 6 80 2 5 1\n43 6 80 2 5 1\n44 6 80 2 5 1\n45 6 80 2 5 1\n applicant_income population minority_population_pct ffiecmedian_family_income\n1 NA 6420 29.818 68065\n2 99 4346 16.489 70745\n3 46 6782 20.265 69818\n4 236 9813 15.168 69691\n5 49 5854 35.968 70555\n6 148 4234 19.864 72156\n7 231 5699 17.130 71892\n8 48 6537 13.024 71562\n9 219 18911 26.595 69795\n10 71 8454 17.436 68727\n11 94 6304 13.490 69181\n12 78 9451 14.684 69337\n13 74 15540 43.148 70000\n14 54 16183 42.388 70862\n15 73 11198 40.481 70039\n16 199 12133 10.971 70023\n17 43 10712 33.973 68117\n18 115 8759 17.669 70526\n19 59 24887 32.833 71510\n20 135 25252 31.854 69602\n21 108 6507 13.613 70267\n22 191 9261 22.583 71505\n23 430 7943 19.990 70801\n24 206 7193 18.002 69973\n25 150 7413 14.092 68202\n26 94 7611 14.618 71260\n27 81 10946 34.220 70386\n28 64 10438 36.395 70141\n29 387 8258 20.666 69409\n30 80 7525 26.604 70104\n31 NA 4525 20.299 71947\n32 40 8397 32.542 68087\n33 87 20083 19.750 69893\n34 96 20539 19.673 72152\n35 45 10497 12.920 70134\n36 54 15686 26.071 70890\n37 119 7558 14.710 69052\n38 62 25960 32.858 68061\n39 18 5790 39.450 68878\n40 103 18086 26.099 69925\n41 70 8689 31.467 70794\n42 38 3923 30.206 68821\n43 183 6522 13.795 69779\n44 169 18459 26.874 69392\n45 140 15954 25.330 71096\n tract_to_msa_md_income_pct number_of_owner-occupied_units\n1 100.000 1553\n2 100.000 1198\n3 100.000 1910\n4 100.000 2351\n5 100.000 1463\n6 100.000 1276\n7 100.000 1467\n8 100.000 1766\n9 100.000 4316\n10 90.071 2324\n11 100.000 1784\n12 100.000 2357\n13 100.000 3252\n14 100.000 3319\n15 79.049 2438\n16 100.000 3639\n17 100.000 2612\n18 87.201 2345\n19 100.000 6713\n20 100.000 6987\n21 100.000 1788\n22 91.023 2349\n23 100.000 1997\n24 100.000 2012\n25 100.000 2359\n26 100.000 2304\n27 100.000 2674\n28 80.957 2023\n29 100.000 2034\n30 100.000 2343\n31 77.707 1059\n32 100.000 1546\n33 100.000 5929\n34 100.000 6017\n35 100.000 3542\n36 100.000 4277\n37 100.000 2316\n38 100.000 6989\n39 56.933 1021\n40 100.000 4183\n41 100.000 1540\n42 100.000 882\n43 100.000 1774\n44 100.000 4417\n45 100.000 4169\n number_of_1_to_4_family_units lender co_applicant\n1 2001 3354 FALSE\n2 1349 2458 FALSE\n3 2326 4129 FALSE\n4 2928 4701 TRUE\n5 1914 2134 FALSE\n6 1638 5710 FALSE\n7 1670 3110 FALSE\n8 1926 3080 TRUE\n9 5241 5710 TRUE\n10 3121 5710 FALSE\n11 1953 933 FALSE\n12 2989 186 TRUE\n13 4482 2134 TRUE\n14 4380 5339 TRUE\n15 3495 5267 TRUE\n16 4875 1831 TRUE\n17 3220 5710 FALSE\n18 3024 3885 TRUE\n19 7980 2458 FALSE\n20 7949 6240 TRUE\n21 2015 542 TRUE\n22 3215 2702 TRUE\n23 2361 3216 FALSE\n24 2482 6240 FALSE\n25 2597 3970 TRUE\n26 2503 3264 FALSE\n27 3226 2570 TRUE\n28 3044 6240 FALSE\n29 2423 1928 TRUE\n30 2659 5738 FALSE\n31 1544 2458 FALSE\n32 2316 3950 FALSE\n33 7105 3143 FALSE\n34 7191 4701 FALSE\n35 4325 5339 FALSE\n36 5188 2702 FALSE\n37 2531 2458 TRUE\n38 7976 2318 TRUE\n39 1755 5026 FALSE\n40 5159 4931 TRUE\n41 2337 2352 FALSE\n42 1317 2458 FALSE\n43 1949 5726 FALSE\n44 5055 5316 TRUE\n45 5197 5726 FALSE\n[ reached 'max' / getOption(\"max.print\") -- omitted 1034 rows ]\n# "
},
{
"code": null,
"e": 47163,
"s": 46968,
"text": "ggplot2 also termed as Grammar of Graphics is a free, opensource, and easy to use visualization package widely used in R. It is the most powerful visualization package written by Hadley Wickham."
},
{
"code": null,
"e": 47165,
"s": 47163,
"text": "R"
},
{
"code": "# Installing the packageinstall.packages(\"dplyr\")install.packages(\"ggplot2\") # Loading packageslibrary(dplyr)library(ggplot2) # Data Layerggplot(data = mtcars) # Aesthetic Layerggplot(data = mtcars, aes(x = hp, y = mpg, col = disp)) # Geometric layerggplot(data = mtcars, aes(x = hp, y = mpg, col = disp)) + geom_point()",
"e": 47561,
"s": 47165,
"text": null
},
{
"code": null,
"e": 47569,
"s": 47561,
"text": "Output:"
},
{
"code": null,
"e": 47586,
"s": 47569,
"text": "Geometric layer:"
},
{
"code": null,
"e": 47617,
"s": 47586,
"text": "Geometric layer – Adding Size:"
},
{
"code": null,
"e": 47862,
"s": 47617,
"text": "caret termed as Classification and Regression Training uses many functions for training and plotting classification & regression models. It is one of the most widely used packages among R developers and in various machine learning competitions."
},
{
"code": null,
"e": 47864,
"s": 47862,
"text": "R"
},
{
"code": "# Installing Packagesinstall.packages(\"e1071\")install.packages(\"caTools\")install.packages(\"caret\") # Loading packagelibrary(e1071)library(caTools)library(caret) # Loading datadata(iris) # Splitting data into train# and test datasplit <- sample.split(iris, SplitRatio = 0.7)train_cl <- subset(iris, split == \"TRUE\")test_cl <- subset(iris, split == \"FALSE\") # Feature Scalingtrain_scale <- scale(train_cl[, 1:4])test_scale <- scale(test_cl[, 1:4]) # Fitting Naive Bayes Model # to training datasetset.seed(120) # Setting Seedclassifier_cl <- naiveBayes(Species ~ ., data = train_cl)classifier_cl # Predicting on test data'y_pred <- predict(classifier_cl, newdata = test_cl) # Confusion Matrixcm <- table(test_cl$Species, y_pred)cm",
"e": 48650,
"s": 47864,
"text": null
},
{
"code": null,
"e": 48658,
"s": 48650,
"text": "Output:"
},
{
"code": null,
"e": 48679,
"s": 48658,
"text": "Model classifier_cl:"
},
{
"code": null,
"e": 48697,
"s": 48679,
"text": "Confusion Matrix:"
},
{
"code": null,
"e": 49252,
"s": 48697,
"text": "e1071 package is used for performing clustering algorithms, support vector machines(SVM), shortest path computations, bagged clustering algorithms, K-NN algorithm, etc. Mostly, it is used for performing a K-NN algorithm. which depends on its k value(Neighbors) and finds itĺs applications in many industries like the finance industry, healthcare industry, etc. K-Nearest Neighbor or K-NN is a Supervised Non-linear classification algorithm. K-NN is a Non-parametric algorithm i.e it doesn’t make any assumption about underlying data or its distribution."
},
{
"code": null,
"e": 49254,
"s": 49252,
"text": "R"
},
{
"code": "# Installing Packagesinstall.packages(\"e1071\")install.packages(\"caTools\")install.packages(\"class\") # Loading packagelibrary(e1071)library(caTools)library(class) # Loading datadata(iris) # Splitting data into train# and test datasplit <- sample.split(iris, SplitRatio = 0.7)train_cl <- subset(iris, split == \"TRUE\")test_cl <- subset(iris, split == \"FALSE\") # Feature Scalingtrain_scale <- scale(train_cl[, 1:4])test_scale <- scale(test_cl[, 1:4]) # Fitting KNN Model # to training datasetclassifier_knn <- knn(train = train_scale, test = test_scale, cl = train_cl$Species, k = 1)classifier_knn # Confusiin Matrixcm <- table(test_cl$Species, classifier_knn)cm # Model Evaluation - Choosing K# Calculate out of Sample errormisClassError <- mean(classifier_knn != test_cl$Species)print(paste('Accuracy =', 1 - misClassError))",
"e": 50153,
"s": 49254,
"text": null
},
{
"code": null,
"e": 50163,
"s": 50153,
"text": "Outputs: "
},
{
"code": null,
"e": 50190,
"s": 50163,
"text": "Model classifier_knn(k=1):"
},
{
"code": null,
"e": 50208,
"s": 50190,
"text": "Confusion Matrix:"
},
{
"code": null,
"e": 50231,
"s": 50208,
"text": "Model Evaluation(k=1):"
},
{
"code": null,
"e": 50552,
"s": 50231,
"text": "XGBoost works only with numeric variables. It is a part of the boosting technique in which the selection of the sample is done more intelligently to classify observations. There are interfaces of XGBoost in C++, R, Python, Julia, Java, and Scala. It consists of Bagging and Boosting techniques. The dataset used BigMart."
},
{
"code": null,
"e": 50554,
"s": 50552,
"text": "R"
},
{
"code": "# Installing Packagesinstall.packages(\"data.table\")install.packages(\"dplyr\")install.packages(\"ggplot2\")install.packages(\"caret\")install.packages(\"xgboost\")install.packages(\"e1071\")install.packages(\"cowplot\") # Loading packageslibrary(data.table) # for reading and manipulation of datalibrary(dplyr) # for data manipulation and joininglibrary(ggplot2) # for ploting library(caret) # for modelinglibrary(xgboost) # for building XGBoost modellibrary(e1071) # for skewnesslibrary(cowplot) # for combining multiple plots # Setting test dataset# Combining datasets# add Item_Outlet_Sales to test datatest[, Item_Outlet_Sales := NA] combi = rbind(train, test) # Missing Value Treatmentmissing_index = which(is.na(combi$Item_Weight))for(i in missing_index){ item = combi$Item_Identifier[i] combi$Item_Weight[i] = mean(combi$Item_Weight [combi$Item_Identifier == item], na.rm = T)} # Replacing 0 in Item_Visibility with meanzero_index = which(combi$Item_Visibility == 0)for(i in zero_index){ item = combi$Item_Identifier[i] combi$Item_Visibility[i] = mean( combi$Item_Visibility[combi$Item_Identifier == item], na.rm = T)} # Label Encoding# To convert categorical in numericalcombi[, Outlet_Size_num := ifelse(Outlet_Size == \"Small\", 0, ifelse(Outlet_Size == \"Medium\", 1, 2))] combi[, Outlet_Location_Type_num := ifelse(Outlet_Location_Type == \"Tier 3\", 0, ifelse(Outlet_Location_Type == \"Tier 2\", 1, 2))] combi[, c(\"Outlet_Size\", \"Outlet_Location_Type\") := NULL] # One Hot Encoding# To convert categorical in numericalohe_1 = dummyVars(\"~.\", data = combi[, -c(\"Item_Identifier\", \"Outlet_Establishment_Year\", \"Item_Type\")], fullRank = T)ohe_df = data.table(predict(ohe_1, combi[, -c(\"Item_Identifier\", \"Outlet_Establishment_Year\", \"Item_Type\")])) combi = cbind(combi[, \"Item_Identifier\"], ohe_df) # Remove skewnessskewness(combi$Item_Visibility) skewness(combi$price_per_unit_wt) # log + 1 to avoid division by zerocombi[, Item_Visibility := log(Item_Visibility + 1)] # Scaling and Centering data# index of numeric featuresnum_vars = which(sapply(combi, is.numeric)) num_vars_names = names(num_vars) combi_numeric = combi[, setdiff(num_vars_names, \"Item_Outlet_Sales\"), with = F] prep_num = preProcess(combi_numeric, method = c(\"center\", \"scale\"))combi_numeric_norm = predict(prep_num, combi_numeric) # removing numeric independent variablescombi[, setdiff(num_vars_names, \"Item_Outlet_Sales\") := NULL] combi = cbind(combi, combi_numeric_norm) # Splitting data back to train and testtrain = combi[1:nrow(train)]test = combi[(nrow(train) + 1):nrow(combi)] # Removing Item_Outlet_Salestest[, Item_Outlet_Sales := NULL] # Model Building: XGBoostparam_list = list( objective = \"reg:linear\", eta = 0.01, gamma = 1, max_depth = 6, subsample = 0.8, colsample_bytree = 0.5) # Converting train and test into xgb.DMatrix formatDtrain = xgb.DMatrix( data = as.matrix(train[, -c(\"Item_Identifier\", \"Item_Outlet_Sales\")]), label = train$Item_Outlet_Sales)Dtest = xgb.DMatrix( data = as.matrix(test[, -c(\"Item_Identifier\")])) # 5-fold cross-validation to # find optimal value of nroundsset.seed(112) # Setting seedxgbcv = xgb.cv(params = param_list, data = Dtrain, nrounds = 1000, nfold = 5, print_every_n = 10, early_stopping_rounds = 30, maximize = F) # Training XGBoost model at nrounds = 428xgb_model = xgb.train(data = Dtrain, params = param_list, nrounds = 428)xgb_model",
"e": 54408,
"s": 50554,
"text": null
},
{
"code": null,
"e": 54416,
"s": 54408,
"text": "Output:"
},
{
"code": null,
"e": 54443,
"s": 54416,
"text": "Training of Xgboost model:"
},
{
"code": null,
"e": 54460,
"s": 54443,
"text": "Model xgb_model:"
},
{
"code": null,
"e": 54860,
"s": 54460,
"text": "Random Forest in R Programming is an ensemble of decision trees. It builds and combines multiple decision trees to get more accurate predictions. It’s a non-linear classification algorithm. Each decision tree model is used when employed on its own. An error estimate of cases is made that is not used when constructing the tree. This is called an out-of-bag error estimate mentioned as a percentage."
},
{
"code": null,
"e": 54862,
"s": 54860,
"text": "R"
},
{
"code": "# Installing package # For sampling the datasetinstall.packages(\"caTools\") # For implementing random forest algorithminstall.packages(\"randomForest\") # Loading packagelibrary(caTools)library(randomForest) # Loading datadata(iris) # Splitting data in train and test datasplit <- sample.split(iris, SplitRatio = 0.7)split train <- subset(iris, split == \"TRUE\")test <- subset(iris, split == \"FALSE\") # Fitting Random Forest to the train datasetset.seed(120) # Setting seedclassifier_RF = randomForest(x = train[-5], y = train$Species, ntree = 500) classifier_RF # Predicting the Test set resultsy_pred = predict(classifier_RF, newdata = test[-5]) # Confusion Matrixconfusion_mtx = table(test[, 5], y_pred)confusion_mtx",
"e": 55650,
"s": 54862,
"text": null
},
{
"code": null,
"e": 55659,
"s": 55650,
"text": "Outputs:"
},
{
"code": null,
"e": 55680,
"s": 55659,
"text": "Model classifier_RF:"
},
{
"code": null,
"e": 55698,
"s": 55680,
"text": "Confusion Matrix:"
},
{
"code": null,
"e": 55711,
"s": 55698,
"text": "simmytarika5"
},
{
"code": null,
"e": 55730,
"s": 55711,
"text": "R Machine-Learning"
},
{
"code": null,
"e": 55736,
"s": 55730,
"text": "GBlog"
},
{
"code": null,
"e": 55753,
"s": 55736,
"text": "Machine Learning"
},
{
"code": null,
"e": 55764,
"s": 55753,
"text": "R Language"
},
{
"code": null,
"e": 55781,
"s": 55764,
"text": "Machine Learning"
},
{
"code": null,
"e": 55879,
"s": 55781,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 55888,
"s": 55879,
"text": "Comments"
},
{
"code": null,
"e": 55901,
"s": 55888,
"text": "Old Comments"
},
{
"code": null,
"e": 55926,
"s": 55901,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 55968,
"s": 55926,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 56002,
"s": 55968,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 56046,
"s": 56002,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 56078,
"s": 56046,
"text": "A Freshers Guide To Programming"
},
{
"code": null,
"e": 56102,
"s": 56078,
"text": "Naive Bayes Classifiers"
},
{
"code": null,
"e": 56144,
"s": 56102,
"text": "Linear Regression (Python Implementation)"
},
{
"code": null,
"e": 56158,
"s": 56144,
"text": "Decision Tree"
},
{
"code": null,
"e": 56181,
"s": 56158,
"text": "ML | Linear Regression"
}
]
|
Program to find the kth factor of n using Python | Suppose we have two positive values n and k. Now consider we have a list of all factors of n sorted in ascending order, we have to find the kth factor in this list. If there are less than k factors, then return -1.
So, if the input is like n = 28 k = 4, then the output will be 7 because, the factors of 28 are [1,2,4,7,14,28], fourth one is 7.
To solve this, we will follow these steps −
if k is same as 1, thenreturn 1
if k is same as 1, then
return 1
return 1
cand := a list with one element [1]
cand := a list with one element [1]
for i in range 2 to 1 + floor of(square root of n), doif n mod i is same as 0, theninsert i at the end of candm := size of cand
for i in range 2 to 1 + floor of(square root of n), do
if n mod i is same as 0, theninsert i at the end of cand
if n mod i is same as 0, then
insert i at the end of cand
insert i at the end of cand
m := size of cand
m := size of cand
if k > 2*m or (k is same as 2*m and n = (last element of cand)^2)return -1
if k > 2*m or (k is same as 2*m and n = (last element of cand)^2)
return -1
return -1
if k <= m, thenreturn cand[k-1]
if k <= m, then
return cand[k-1]
return cand[k-1]
factor := cand[2*m - k]
factor := cand[2*m - k]
return quotient of n/factor
return quotient of n/factor
Let us see the following implementation to get better understanding −
from math import floor
def solve(n ,k):
if k == 1:
return 1
cand = [1]
for i in range(2, 1+floor(pow(n, 0.5))):
if n%i == 0:
cand.append(i)
m = len(cand)
if k > 2*m or (k == 2*m and n == cand[-1]**2):
return -1
if k <= m:
return cand[k-1]
factor = cand[2*m - k]
return n//factor
n = 28
k = 4
print(solve(n ,k))
28, 4
7 | [
{
"code": null,
"e": 1277,
"s": 1062,
"text": "Suppose we have two positive values n and k. Now consider we have a list of all factors of n sorted in ascending order, we have to find the kth factor in this list. If there are less than k factors, then return -1."
},
{
"code": null,
"e": 1407,
"s": 1277,
"text": "So, if the input is like n = 28 k = 4, then the output will be 7 because, the factors of 28 are [1,2,4,7,14,28], fourth one is 7."
},
{
"code": null,
"e": 1451,
"s": 1407,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1483,
"s": 1451,
"text": "if k is same as 1, thenreturn 1"
},
{
"code": null,
"e": 1507,
"s": 1483,
"text": "if k is same as 1, then"
},
{
"code": null,
"e": 1516,
"s": 1507,
"text": "return 1"
},
{
"code": null,
"e": 1525,
"s": 1516,
"text": "return 1"
},
{
"code": null,
"e": 1561,
"s": 1525,
"text": "cand := a list with one element [1]"
},
{
"code": null,
"e": 1597,
"s": 1561,
"text": "cand := a list with one element [1]"
},
{
"code": null,
"e": 1725,
"s": 1597,
"text": "for i in range 2 to 1 + floor of(square root of n), doif n mod i is same as 0, theninsert i at the end of candm := size of cand"
},
{
"code": null,
"e": 1780,
"s": 1725,
"text": "for i in range 2 to 1 + floor of(square root of n), do"
},
{
"code": null,
"e": 1837,
"s": 1780,
"text": "if n mod i is same as 0, theninsert i at the end of cand"
},
{
"code": null,
"e": 1867,
"s": 1837,
"text": "if n mod i is same as 0, then"
},
{
"code": null,
"e": 1895,
"s": 1867,
"text": "insert i at the end of cand"
},
{
"code": null,
"e": 1923,
"s": 1895,
"text": "insert i at the end of cand"
},
{
"code": null,
"e": 1941,
"s": 1923,
"text": "m := size of cand"
},
{
"code": null,
"e": 1959,
"s": 1941,
"text": "m := size of cand"
},
{
"code": null,
"e": 2034,
"s": 1959,
"text": "if k > 2*m or (k is same as 2*m and n = (last element of cand)^2)return -1"
},
{
"code": null,
"e": 2100,
"s": 2034,
"text": "if k > 2*m or (k is same as 2*m and n = (last element of cand)^2)"
},
{
"code": null,
"e": 2110,
"s": 2100,
"text": "return -1"
},
{
"code": null,
"e": 2120,
"s": 2110,
"text": "return -1"
},
{
"code": null,
"e": 2152,
"s": 2120,
"text": "if k <= m, thenreturn cand[k-1]"
},
{
"code": null,
"e": 2168,
"s": 2152,
"text": "if k <= m, then"
},
{
"code": null,
"e": 2185,
"s": 2168,
"text": "return cand[k-1]"
},
{
"code": null,
"e": 2202,
"s": 2185,
"text": "return cand[k-1]"
},
{
"code": null,
"e": 2226,
"s": 2202,
"text": "factor := cand[2*m - k]"
},
{
"code": null,
"e": 2250,
"s": 2226,
"text": "factor := cand[2*m - k]"
},
{
"code": null,
"e": 2278,
"s": 2250,
"text": "return quotient of n/factor"
},
{
"code": null,
"e": 2306,
"s": 2278,
"text": "return quotient of n/factor"
},
{
"code": null,
"e": 2376,
"s": 2306,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2765,
"s": 2376,
"text": "from math import floor\ndef solve(n ,k):\n if k == 1:\n return 1\n cand = [1]\n for i in range(2, 1+floor(pow(n, 0.5))):\n if n%i == 0:\n cand.append(i)\n m = len(cand)\n if k > 2*m or (k == 2*m and n == cand[-1]**2):\n return -1\n if k <= m:\n return cand[k-1]\n factor = cand[2*m - k]\n return n//factor\nn = 28\nk = 4\nprint(solve(n ,k))"
},
{
"code": null,
"e": 2771,
"s": 2765,
"text": "28, 4"
},
{
"code": null,
"e": 2773,
"s": 2771,
"text": "7"
}
]
|
SQL Query to Remove Primary Key - GeeksforGeeks | 08 Oct, 2021
The primary key is the key that may contain one or more columns that uniquely identify each row in a table. We can add a primary key constraint while creating the and we can add or remove after by using ALTER command on our table of the database.
In this article let us see how we can remove a primary key constraint in a table using MSSQL as the server.
Step 1: Creating a Database
We use the below command to create a database named GeeksforGeeks:
Query:
CREATE DATABASE GeeksforGeeks
Step 2: Using the Database
To use the GeeksforGeeks database use the below command:
Query:
USE GeeksforGeeks
Output:
Step 3: Creating the table
Create a table student_details with 3 columns using the following SQL query:
Query:
CREATE TABLE student_details(
stu_id VARCHAR(8) NOT NULL PRIMARY KEY,
stu_name VARCHAR(20),
stu_branch VARCHAR(20)
);
Output:
Step 4: Verifying the database
To view the description of the table using the following SQL query as follows.
Query:
EXEC sp_columns student_details
Output:
Step 5: Inserting data into the Table
Inserting rows into student_details using the following SQL query:
Query:
INSERT INTO student_details VALUES
('1940001','PRATHAM','E.C.E'),
('1940002','ASHOK','C.S.E'),
('1940003','PAVAN KUMAR','C.S.E'),
('1940004','SANTHOSH','E.C.E'),
('1940005','THAMAN','E.C.E'),
('1940006','HARSH','E.E.E')
Output:
Step 6: Verifying the inserted data
Viewing the tables student_details,student_branch_details,student_address after inserting rows by using the following SQL query:
Query:
SELECT* FROM student_details
Output:
Step 7: Knowing the constraints of the table using the following SQL query.
Query:
SELECT * FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
Output:
Here in output ‘PK’ means primary key. The constraint can be known from the object explorer as well.
Step 8: Here we use the Drop constraint to remove the primary key from the database. DROP is used to delete a whole database or just a table. The DROP statement destroys the objects like an existing database, table, index, or view. A DROP statement in SQL removes a component from a relational database management system (RDBMS).
Query:
Removing the primary key constraint using the following query:
Query:
ALTER TABLE student_details
DROP CONSTRAINT PK__student___E53CAB21F07312DD
The primary key constraint is now removed:
Output:
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Convert VARCHAR to INT
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates | [
{
"code": null,
"e": 25538,
"s": 25510,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 25785,
"s": 25538,
"text": "The primary key is the key that may contain one or more columns that uniquely identify each row in a table. We can add a primary key constraint while creating the and we can add or remove after by using ALTER command on our table of the database."
},
{
"code": null,
"e": 25894,
"s": 25785,
"text": "In this article let us see how we can remove a primary key constraint in a table using MSSQL as the server."
},
{
"code": null,
"e": 25922,
"s": 25894,
"text": "Step 1: Creating a Database"
},
{
"code": null,
"e": 25989,
"s": 25922,
"text": "We use the below command to create a database named GeeksforGeeks:"
},
{
"code": null,
"e": 25996,
"s": 25989,
"text": "Query:"
},
{
"code": null,
"e": 26026,
"s": 25996,
"text": "CREATE DATABASE GeeksforGeeks"
},
{
"code": null,
"e": 26053,
"s": 26026,
"text": "Step 2: Using the Database"
},
{
"code": null,
"e": 26110,
"s": 26053,
"text": "To use the GeeksforGeeks database use the below command:"
},
{
"code": null,
"e": 26117,
"s": 26110,
"text": "Query:"
},
{
"code": null,
"e": 26135,
"s": 26117,
"text": "USE GeeksforGeeks"
},
{
"code": null,
"e": 26143,
"s": 26135,
"text": "Output:"
},
{
"code": null,
"e": 26170,
"s": 26143,
"text": "Step 3: Creating the table"
},
{
"code": null,
"e": 26250,
"s": 26170,
"text": "Create a table student_details with 3 columns using the following SQL query: "
},
{
"code": null,
"e": 26257,
"s": 26250,
"text": "Query:"
},
{
"code": null,
"e": 26383,
"s": 26257,
"text": "CREATE TABLE student_details(\n stu_id VARCHAR(8) NOT NULL PRIMARY KEY,\n stu_name VARCHAR(20),\n stu_branch VARCHAR(20)\n );"
},
{
"code": null,
"e": 26391,
"s": 26383,
"text": "Output:"
},
{
"code": null,
"e": 26423,
"s": 26391,
"text": "Step 4: Verifying the database "
},
{
"code": null,
"e": 26502,
"s": 26423,
"text": "To view the description of the table using the following SQL query as follows."
},
{
"code": null,
"e": 26509,
"s": 26502,
"text": "Query:"
},
{
"code": null,
"e": 26541,
"s": 26509,
"text": "EXEC sp_columns student_details"
},
{
"code": null,
"e": 26549,
"s": 26541,
"text": "Output:"
},
{
"code": null,
"e": 26589,
"s": 26549,
"text": "Step 5: Inserting data into the Table "
},
{
"code": null,
"e": 26656,
"s": 26589,
"text": "Inserting rows into student_details using the following SQL query:"
},
{
"code": null,
"e": 26663,
"s": 26656,
"text": "Query:"
},
{
"code": null,
"e": 26883,
"s": 26663,
"text": "INSERT INTO student_details VALUES\n('1940001','PRATHAM','E.C.E'),\n('1940002','ASHOK','C.S.E'),\n('1940003','PAVAN KUMAR','C.S.E'),\n('1940004','SANTHOSH','E.C.E'),\n('1940005','THAMAN','E.C.E'),\n('1940006','HARSH','E.E.E')"
},
{
"code": null,
"e": 26891,
"s": 26883,
"text": "Output:"
},
{
"code": null,
"e": 26927,
"s": 26891,
"text": "Step 6: Verifying the inserted data"
},
{
"code": null,
"e": 27056,
"s": 26927,
"text": "Viewing the tables student_details,student_branch_details,student_address after inserting rows by using the following SQL query:"
},
{
"code": null,
"e": 27063,
"s": 27056,
"text": "Query:"
},
{
"code": null,
"e": 27093,
"s": 27063,
"text": "SELECT* FROM student_details "
},
{
"code": null,
"e": 27101,
"s": 27093,
"text": "Output:"
},
{
"code": null,
"e": 27177,
"s": 27101,
"text": "Step 7: Knowing the constraints of the table using the following SQL query."
},
{
"code": null,
"e": 27184,
"s": 27177,
"text": "Query:"
},
{
"code": null,
"e": 27243,
"s": 27184,
"text": "SELECT * FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE "
},
{
"code": null,
"e": 27251,
"s": 27243,
"text": "Output:"
},
{
"code": null,
"e": 27352,
"s": 27251,
"text": "Here in output ‘PK’ means primary key. The constraint can be known from the object explorer as well."
},
{
"code": null,
"e": 27682,
"s": 27352,
"text": "Step 8: Here we use the Drop constraint to remove the primary key from the database. DROP is used to delete a whole database or just a table. The DROP statement destroys the objects like an existing database, table, index, or view. A DROP statement in SQL removes a component from a relational database management system (RDBMS)."
},
{
"code": null,
"e": 27689,
"s": 27682,
"text": "Query:"
},
{
"code": null,
"e": 27752,
"s": 27689,
"text": "Removing the primary key constraint using the following query:"
},
{
"code": null,
"e": 27759,
"s": 27752,
"text": "Query:"
},
{
"code": null,
"e": 27834,
"s": 27759,
"text": "ALTER TABLE student_details\nDROP CONSTRAINT PK__student___E53CAB21F07312DD"
},
{
"code": null,
"e": 27877,
"s": 27834,
"text": "The primary key constraint is now removed:"
},
{
"code": null,
"e": 27885,
"s": 27877,
"text": "Output:"
},
{
"code": null,
"e": 27892,
"s": 27885,
"text": "Picked"
},
{
"code": null,
"e": 27902,
"s": 27892,
"text": "SQL-Query"
},
{
"code": null,
"e": 27913,
"s": 27902,
"text": "SQL-Server"
},
{
"code": null,
"e": 27917,
"s": 27913,
"text": "SQL"
},
{
"code": null,
"e": 27921,
"s": 27917,
"text": "SQL"
},
{
"code": null,
"e": 28019,
"s": 27921,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28085,
"s": 28019,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 28142,
"s": 28085,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 28174,
"s": 28142,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 28189,
"s": 28174,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 28225,
"s": 28189,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 28303,
"s": 28225,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 28320,
"s": 28303,
"text": "SQL using Python"
},
{
"code": null,
"e": 28386,
"s": 28320,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 28448,
"s": 28386,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
}
]
|
Pass data between components using Vue.js Event Bus - GeeksforGeeks | 26 Mar, 2021
Component communication in Vue.js can become complicated and messy at times using $emit and props. In real-world applications where the Component tree is nested and big, it is not convenient to pass data using this method as it will only increase the complexity of the application and make debugging very tedious. This is where an event bus comes into the picture.
An Event Bus is nothing but a global Vue instance that is imported by the components involved in communication and passing data. It makes use of the $on, $emit, and $off properties of the Vue object to emit out events and pass on data. An Event Bus provides a very simple and elegant solution to the complex $emit and prop chain which can be very hard to track down while testing and debugging. It acts as a global intermediate for all the components involved to emit out and listen to events and execute methods accordingly.
Syntax:
There is no special syntax for an Event Bus as it is just an instantiation of the Vue class.
const EventBus = new Vue();
Working:
Consider this simple component tree where we need to share data between the black and the green components. Using $emit and props, this will be a long process of first passing the data and event up through the tree using $emit and then down the tree using props.
However, using an event bus, this can be carried out in a very simple and easy manner.
Example: We will use the same example we have used to illustrate $emit and props here, however, this time using an Event Bus. It is a very basic webpage that displays how many times a button has been clicked. For this, we have 2 components:
Component1: Displays the number of times the button in component 2 has been clicked.
Component2: A button which when clicked upon increases a counter.
App.js
<template><div> <Component1></Component1> <Component2></Component2></div></template> <script> import Component1 from './components/Component1.vue' import Component2 from './components/Component2.vue' export default { name: 'App', components: { Component1,Component2 } }</script>
Component1.vue
<template> <div class="component1"> <h1>You have clicked {{ labeltext }} times</h1> </div></template> <script> import EventBus from '../event-bus'; export default { name: "Component1", data() { return { labeltext: 0, }; }, methods: { change_n(n) { this.labeltext = n; }, }, created() { // Sets up the Event Bus listener using // the custom event name and assosciates // it with a component method. EventBus.$on("change_n", this.change_n); }, destroyed() { // Removes Event Bus listener upon removal // of template from DOM. EventBus.$off("change_n", this.change_n); }, };</script> <style scoped> .component1 { display: block; background-color: green; height: 15em; text-align: center; color: white; padding-top: 5em; }</style>
Component2.vue
<template> <div class="component2"> <button @click="count">Click</button> </div></template> <script> import EventBus from '../event-bus'; export default { name: "Component2", data() { return { nclick : 0, }; }, methods: { count() { this.nclick += 1; // Emitting a custom-event via the Event Bus EventBus.$emit("change_n", this.nclick); }, }, };</script> <style scoped> .component2 { display: block; background-color: grey; height: 15em; text-align: center; padding-top: 5em; }</style>
event-bus.js
import Vue from 'vue'; // Create a new Vue instance and export itconst EventBus = new Vue(); export default EventBus;
Output:
Vue.JS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 26910,
"s": 26545,
"text": "Component communication in Vue.js can become complicated and messy at times using $emit and props. In real-world applications where the Component tree is nested and big, it is not convenient to pass data using this method as it will only increase the complexity of the application and make debugging very tedious. This is where an event bus comes into the picture."
},
{
"code": null,
"e": 27436,
"s": 26910,
"text": "An Event Bus is nothing but a global Vue instance that is imported by the components involved in communication and passing data. It makes use of the $on, $emit, and $off properties of the Vue object to emit out events and pass on data. An Event Bus provides a very simple and elegant solution to the complex $emit and prop chain which can be very hard to track down while testing and debugging. It acts as a global intermediate for all the components involved to emit out and listen to events and execute methods accordingly."
},
{
"code": null,
"e": 27444,
"s": 27436,
"text": "Syntax:"
},
{
"code": null,
"e": 27537,
"s": 27444,
"text": "There is no special syntax for an Event Bus as it is just an instantiation of the Vue class."
},
{
"code": null,
"e": 27565,
"s": 27537,
"text": "const EventBus = new Vue();"
},
{
"code": null,
"e": 27575,
"s": 27565,
"text": "Working: "
},
{
"code": null,
"e": 27838,
"s": 27575,
"text": "Consider this simple component tree where we need to share data between the black and the green components. Using $emit and props, this will be a long process of first passing the data and event up through the tree using $emit and then down the tree using props."
},
{
"code": null,
"e": 27925,
"s": 27838,
"text": "However, using an event bus, this can be carried out in a very simple and easy manner."
},
{
"code": null,
"e": 28166,
"s": 27925,
"text": "Example: We will use the same example we have used to illustrate $emit and props here, however, this time using an Event Bus. It is a very basic webpage that displays how many times a button has been clicked. For this, we have 2 components:"
},
{
"code": null,
"e": 28251,
"s": 28166,
"text": "Component1: Displays the number of times the button in component 2 has been clicked."
},
{
"code": null,
"e": 28317,
"s": 28251,
"text": "Component2: A button which when clicked upon increases a counter."
},
{
"code": null,
"e": 28324,
"s": 28317,
"text": "App.js"
},
{
"code": "<template><div> <Component1></Component1> <Component2></Component2></div></template> <script> import Component1 from './components/Component1.vue' import Component2 from './components/Component2.vue' export default { name: 'App', components: { Component1,Component2 } }</script>",
"e": 28626,
"s": 28324,
"text": null
},
{
"code": null,
"e": 28641,
"s": 28626,
"text": "Component1.vue"
},
{
"code": "<template> <div class=\"component1\"> <h1>You have clicked {{ labeltext }} times</h1> </div></template> <script> import EventBus from '../event-bus'; export default { name: \"Component1\", data() { return { labeltext: 0, }; }, methods: { change_n(n) { this.labeltext = n; }, }, created() { // Sets up the Event Bus listener using // the custom event name and assosciates // it with a component method. EventBus.$on(\"change_n\", this.change_n); }, destroyed() { // Removes Event Bus listener upon removal // of template from DOM. EventBus.$off(\"change_n\", this.change_n); }, };</script> <style scoped> .component1 { display: block; background-color: green; height: 15em; text-align: center; color: white; padding-top: 5em; }</style>",
"e": 29515,
"s": 28641,
"text": null
},
{
"code": null,
"e": 29530,
"s": 29515,
"text": "Component2.vue"
},
{
"code": "<template> <div class=\"component2\"> <button @click=\"count\">Click</button> </div></template> <script> import EventBus from '../event-bus'; export default { name: \"Component2\", data() { return { nclick : 0, }; }, methods: { count() { this.nclick += 1; // Emitting a custom-event via the Event Bus EventBus.$emit(\"change_n\", this.nclick); }, }, };</script> <style scoped> .component2 { display: block; background-color: grey; height: 15em; text-align: center; padding-top: 5em; }</style>",
"e": 30107,
"s": 29530,
"text": null
},
{
"code": null,
"e": 30120,
"s": 30107,
"text": "event-bus.js"
},
{
"code": "import Vue from 'vue'; // Create a new Vue instance and export itconst EventBus = new Vue(); export default EventBus;",
"e": 30240,
"s": 30120,
"text": null
},
{
"code": null,
"e": 30248,
"s": 30240,
"text": "Output:"
},
{
"code": null,
"e": 30255,
"s": 30248,
"text": "Vue.JS"
},
{
"code": null,
"e": 30266,
"s": 30255,
"text": "JavaScript"
},
{
"code": null,
"e": 30283,
"s": 30266,
"text": "Web Technologies"
},
{
"code": null,
"e": 30381,
"s": 30283,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30421,
"s": 30381,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30482,
"s": 30421,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30523,
"s": 30482,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30545,
"s": 30523,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 30599,
"s": 30545,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 30639,
"s": 30599,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30672,
"s": 30639,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30715,
"s": 30672,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30777,
"s": 30715,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
How to create a multiline input control text area in HTML5 ? - GeeksforGeeks | 06 Sep, 2021
The HTML <textarea> tag is used to specify a multiline input control text area in HTML5. The <cols> and <rows> attributes specify size of a textarea.
Syntax
<textarea rows="" cols=""> Contents... </textarea>
The <textarea> tag contains 5 attributes that are listed below:
cols: It specifies width of textarea.
rows: It specifies height of textarea.
name: It holds the name to input control.
maxlength or minlength: It specifies the maximum or minimum number of characters in textarea.
placeholder: It specifies the hint of the value of textarea.
Example 1:
In this example, we will set the rows, and cols attribute to create a multiline control input textarea.
HTML
<!DOCTYPE html><html> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <textarea rows="10" cols="20"> welcome to GeeksforGeeks Aman Rathod. A perfect Portal for Geeks </textarea></body> </html>
Output:
Example 2: In this example, we will set the number of characters allowed in the input textarea.
HTML
<!DOCTYPE html><html> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <textarea minlenght="100" maxlength="300" placeholder="Give Feedback here"> </textarea></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.
varshagumber28
CSS-Properties
HTML-Attributes
HTML-Questions
HTML-Tags
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 33003,
"s": 32975,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 33154,
"s": 33003,
"text": "The HTML <textarea> tag is used to specify a multiline input control text area in HTML5. The <cols> and <rows> attributes specify size of a textarea."
},
{
"code": null,
"e": 33161,
"s": 33154,
"text": "Syntax"
},
{
"code": null,
"e": 33212,
"s": 33161,
"text": "<textarea rows=\"\" cols=\"\"> Contents... </textarea>"
},
{
"code": null,
"e": 33276,
"s": 33212,
"text": "The <textarea> tag contains 5 attributes that are listed below:"
},
{
"code": null,
"e": 33314,
"s": 33276,
"text": "cols: It specifies width of textarea."
},
{
"code": null,
"e": 33353,
"s": 33314,
"text": "rows: It specifies height of textarea."
},
{
"code": null,
"e": 33395,
"s": 33353,
"text": "name: It holds the name to input control."
},
{
"code": null,
"e": 33489,
"s": 33395,
"text": "maxlength or minlength: It specifies the maximum or minimum number of characters in textarea."
},
{
"code": null,
"e": 33550,
"s": 33489,
"text": "placeholder: It specifies the hint of the value of textarea."
},
{
"code": null,
"e": 33561,
"s": 33550,
"text": "Example 1:"
},
{
"code": null,
"e": 33665,
"s": 33561,
"text": "In this example, we will set the rows, and cols attribute to create a multiline control input textarea."
},
{
"code": null,
"e": 33670,
"s": 33665,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <textarea rows=\"10\" cols=\"20\"> welcome to GeeksforGeeks Aman Rathod. A perfect Portal for Geeks </textarea></body> </html>",
"e": 33901,
"s": 33670,
"text": null
},
{
"code": null,
"e": 33909,
"s": 33901,
"text": "Output:"
},
{
"code": null,
"e": 34005,
"s": 33909,
"text": "Example 2: In this example, we will set the number of characters allowed in the input textarea."
},
{
"code": null,
"e": 34010,
"s": 34005,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <textarea minlenght=\"100\" maxlength=\"300\" placeholder=\"Give Feedback here\"> </textarea></body> </html>",
"e": 34212,
"s": 34010,
"text": null
},
{
"code": null,
"e": 34221,
"s": 34212,
"text": "Output: "
},
{
"code": null,
"e": 34360,
"s": 34223,
"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": 34375,
"s": 34360,
"text": "varshagumber28"
},
{
"code": null,
"e": 34390,
"s": 34375,
"text": "CSS-Properties"
},
{
"code": null,
"e": 34406,
"s": 34390,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 34421,
"s": 34406,
"text": "HTML-Questions"
},
{
"code": null,
"e": 34431,
"s": 34421,
"text": "HTML-Tags"
},
{
"code": null,
"e": 34438,
"s": 34431,
"text": "Picked"
},
{
"code": null,
"e": 34443,
"s": 34438,
"text": "HTML"
},
{
"code": null,
"e": 34460,
"s": 34443,
"text": "Web Technologies"
},
{
"code": null,
"e": 34465,
"s": 34460,
"text": "HTML"
},
{
"code": null,
"e": 34563,
"s": 34465,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34613,
"s": 34563,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 34675,
"s": 34613,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 34723,
"s": 34675,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 34783,
"s": 34723,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 34836,
"s": 34783,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 34876,
"s": 34836,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 34909,
"s": 34876,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 34954,
"s": 34909,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 34997,
"s": 34954,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
How to Extract and Copy Files from ISO Image in Linux? - GeeksforGeeks | 20 Apr, 2021
The term ISO was derived from the ISO 9660 file system, which is commonly used by optical media. An ISO image is a full copy of everything contained on a physical optical disc, such as a CD, DVD, or Blu-ray disc, including the file system. There is no compression and they are a sector-by-sector copy of the disc. ISO images are designed to allow you to save an exact digital copy of a disc and then use that image to burn a new disc that is an exact copy of the original. Most operating systems (and many utilities) allow you to install an ISO image as a virtual disc, which means that all of your apps can treat it as if it were a real optical disc.
In certain cases, you can need to extract a single file or multiple files from an ISO image. Here we are going to see how to extract and Copy Files from ISO Image in Linux
The loop system can be used to mount ISO files. The mount command is needed. First, make a directory using the mkdir command:
$ mkdir /mnt/iso
Making directory
Now mount the iso image in a newly created directory using the below command:
$ mount -o loop isofilename.iso /mnt/iso
Mount iso to the directory
Change the directory to /mnt/iso:
Change directory
You can verify the content of iso using the ls command:
$ ls
Verifying content
You can now copy files to the /tmp directory easily:
Copying files
7-Zip is a free and open-source file archive, a program that compresses files and stores them in compact containers called “archives.”
First, install 7zip using the below command:
$ sudo apt-get install p7zip-full
Installing 7zip
Now you can extract the iso file using the below command:
$ sudo 7z x ubuntu-20.04.2.0-desktop-amd64.iso
Extracting iso file
Now you can copy files from extracted iso using the above steps.
You can also extract the archive using inbuilt GNOME manager just follow the below steps:
First, find your iso file where it is located:
Locate your file
Then right-click on it, and you will see the options menu:
Right-click on it
Now click on the extract here option in the options menu:
Extract file
Now you should see extracting pop-up wait till it finishes:
Wait till it finishes
After successful extract you can see your file by clicking show files:
You can view your files by clicking show files
Now you can copy any file you want by clicking right-click:
Copy files
In this article, we show you how to extract ISO files using 3 different easiest methods. That said, we appreciate your sticking with us to the end, and we hope the guide was as useful as we hoped.
Picked
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Install Jupyter Notebook on MacOS?
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
cp command in Linux with examples | [
{
"code": null,
"e": 26223,
"s": 26195,
"text": "\n20 Apr, 2021"
},
{
"code": null,
"e": 26875,
"s": 26223,
"text": "The term ISO was derived from the ISO 9660 file system, which is commonly used by optical media. An ISO image is a full copy of everything contained on a physical optical disc, such as a CD, DVD, or Blu-ray disc, including the file system. There is no compression and they are a sector-by-sector copy of the disc. ISO images are designed to allow you to save an exact digital copy of a disc and then use that image to burn a new disc that is an exact copy of the original. Most operating systems (and many utilities) allow you to install an ISO image as a virtual disc, which means that all of your apps can treat it as if it were a real optical disc."
},
{
"code": null,
"e": 27047,
"s": 26875,
"text": "In certain cases, you can need to extract a single file or multiple files from an ISO image. Here we are going to see how to extract and Copy Files from ISO Image in Linux"
},
{
"code": null,
"e": 27173,
"s": 27047,
"text": "The loop system can be used to mount ISO files. The mount command is needed. First, make a directory using the mkdir command:"
},
{
"code": null,
"e": 27190,
"s": 27173,
"text": "$ mkdir /mnt/iso"
},
{
"code": null,
"e": 27207,
"s": 27190,
"text": "Making directory"
},
{
"code": null,
"e": 27285,
"s": 27207,
"text": "Now mount the iso image in a newly created directory using the below command:"
},
{
"code": null,
"e": 27326,
"s": 27285,
"text": "$ mount -o loop isofilename.iso /mnt/iso"
},
{
"code": null,
"e": 27353,
"s": 27326,
"text": "Mount iso to the directory"
},
{
"code": null,
"e": 27387,
"s": 27353,
"text": "Change the directory to /mnt/iso:"
},
{
"code": null,
"e": 27404,
"s": 27387,
"text": "Change directory"
},
{
"code": null,
"e": 27460,
"s": 27404,
"text": "You can verify the content of iso using the ls command:"
},
{
"code": null,
"e": 27465,
"s": 27460,
"text": "$ ls"
},
{
"code": null,
"e": 27483,
"s": 27465,
"text": "Verifying content"
},
{
"code": null,
"e": 27536,
"s": 27483,
"text": "You can now copy files to the /tmp directory easily:"
},
{
"code": null,
"e": 27550,
"s": 27536,
"text": "Copying files"
},
{
"code": null,
"e": 27685,
"s": 27550,
"text": "7-Zip is a free and open-source file archive, a program that compresses files and stores them in compact containers called “archives.”"
},
{
"code": null,
"e": 27730,
"s": 27685,
"text": "First, install 7zip using the below command:"
},
{
"code": null,
"e": 27764,
"s": 27730,
"text": "$ sudo apt-get install p7zip-full"
},
{
"code": null,
"e": 27780,
"s": 27764,
"text": "Installing 7zip"
},
{
"code": null,
"e": 27838,
"s": 27780,
"text": "Now you can extract the iso file using the below command:"
},
{
"code": null,
"e": 27885,
"s": 27838,
"text": "$ sudo 7z x ubuntu-20.04.2.0-desktop-amd64.iso"
},
{
"code": null,
"e": 27905,
"s": 27885,
"text": "Extracting iso file"
},
{
"code": null,
"e": 27970,
"s": 27905,
"text": "Now you can copy files from extracted iso using the above steps."
},
{
"code": null,
"e": 28060,
"s": 27970,
"text": "You can also extract the archive using inbuilt GNOME manager just follow the below steps:"
},
{
"code": null,
"e": 28107,
"s": 28060,
"text": "First, find your iso file where it is located:"
},
{
"code": null,
"e": 28124,
"s": 28107,
"text": "Locate your file"
},
{
"code": null,
"e": 28183,
"s": 28124,
"text": "Then right-click on it, and you will see the options menu:"
},
{
"code": null,
"e": 28201,
"s": 28183,
"text": "Right-click on it"
},
{
"code": null,
"e": 28259,
"s": 28201,
"text": "Now click on the extract here option in the options menu:"
},
{
"code": null,
"e": 28272,
"s": 28259,
"text": "Extract file"
},
{
"code": null,
"e": 28332,
"s": 28272,
"text": "Now you should see extracting pop-up wait till it finishes:"
},
{
"code": null,
"e": 28354,
"s": 28332,
"text": "Wait till it finishes"
},
{
"code": null,
"e": 28425,
"s": 28354,
"text": "After successful extract you can see your file by clicking show files:"
},
{
"code": null,
"e": 28472,
"s": 28425,
"text": "You can view your files by clicking show files"
},
{
"code": null,
"e": 28532,
"s": 28472,
"text": "Now you can copy any file you want by clicking right-click:"
},
{
"code": null,
"e": 28543,
"s": 28532,
"text": "Copy files"
},
{
"code": null,
"e": 28740,
"s": 28543,
"text": "In this article, we show you how to extract ISO files using 3 different easiest methods. That said, we appreciate your sticking with us to the end, and we hope the guide was as useful as we hoped."
},
{
"code": null,
"e": 28747,
"s": 28740,
"text": "Picked"
},
{
"code": null,
"e": 28754,
"s": 28747,
"text": "How To"
},
{
"code": null,
"e": 28765,
"s": 28754,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28863,
"s": 28765,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28897,
"s": 28863,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28955,
"s": 28897,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 29004,
"s": 28955,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 29051,
"s": 29004,
"text": "How to create a nested RecyclerView in Android"
},
{
"code": null,
"e": 29093,
"s": 29051,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 29133,
"s": 29093,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 29173,
"s": 29133,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 29200,
"s": 29173,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 29235,
"s": 29200,
"text": "cut command in Linux with examples"
}
]
|
Quadruplet pair with XOR zero in the given Array - GeeksforGeeks | 18 Nov, 2021
Given an array arr[] of N integers such that any two adjacent elements in the array differ at only one position in their binary representation. The task is to find whether there exists a quadruple (arr[i], arr[j], arr[k], arr[l]) such that arr[i] ^ arr[j] ^ arr[k] ^ arr[l] = 0. Here ^ denotes the bitwise xor operation and 1 ≤ i < j < k < l ≤ N.Examples:
Input: arr[] = {1, 3, 7, 3} Output: No 1 ^ 3 ^ 7 ^ 3 = 6Input: arr[] = {1, 0, 2, 3, 7} Output: Yes 1 ^ 0 ^ 2 ^ 3 = 0
Naive approach: Check for all possible quadruples whether their xor is zero or not. But the time complexity of such a solution would be N4, for all N. Time Complexity:
Efficient Approach (O(N4), for N ≤ 130): We can Say that for array length more than or equal to 130 we can have at least 65 adjacent pairs each denoting xor of two elements. Here it is given that all adjacent elements differ at only one position in their binary form thus there would result in only one set bit. Since we have only 64 possible positions, we can say that at least two pairs will have the same xor. Thus, xor of these 4 integers will be 0. For N < 130 we can use the naive approach.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; const int MAX = 130; // Function that returns true if the array// contains a valid quadruplet pairbool validQuadruple(int arr[], int n){ // We can always find a valid quadruplet pair // for array size greater than MAX if (n >= MAX) return true; // For smaller size arrays, perform brute force for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) for (int l = k + 1; l < n; l++) { if ((arr[i] ^ arr[j] ^ arr[k] ^ arr[l]) == 0) { return true; } } return false;} // Driver codeint main(){ int arr[] = { 1, 0, 2, 3, 7 }; int n = sizeof(arr) / sizeof(arr[0]); if (validQuadruple(arr, n)) cout << "Yes"; else cout << "No"; return 0;}
// Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ static int MAX = 130; // Function that returns true if the array// contains a valid quadruplet pairstatic boolean validQuadruple(int arr[], int n){ // We can always find a valid quadruplet pair // for array size greater than MAX if (n >= MAX) return true; // For smaller size arrays, perform brute force for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) for (int l = k + 1; l < n; l++) { if ((arr[i] ^ arr[j] ^ arr[k] ^ arr[l]) == 0) { return true; } } return false;} // Driver codepublic static void main (String[] args) throws java.lang.Exception{ int arr[] = { 1, 0, 2, 3, 7 }; int n = arr.length; if (validQuadruple(arr, n)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by nidhiva
# Python3 implementation of the approachMAX = 130 # Function that returns true if the array# contains a valid quadruplet pairdef validQuadruple(arr, n): # We can always find a valid quadruplet pair # for array size greater than MAX if (n >= MAX): return True # For smaller size arrays, # perform brute force for i in range(n): for j in range(i + 1, n): for k in range(j + 1, n): for l in range(k + 1, n): if ((arr[i] ^ arr[j] ^ arr[k] ^ arr[l]) == 0): return True return False # Driver codearr = [1, 0, 2, 3, 7]n = len(arr) if (validQuadruple(arr, n)): print("Yes")else: print("No") # This code is contributed# by Mohit Kumar
// C# implementation of the approachusing System; class GFG{ static int MAX = 130; // Function that returns true if the array// contains a valid quadruplet pairstatic Boolean validQuadruple(int []arr, int n){ // We can always find a valid quadruplet pair // for array size greater than MAX if (n >= MAX) return true; // For smaller size arrays, perform brute force for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) for (int l = k + 1; l < n; l++) { if ((arr[i] ^ arr[j] ^ arr[k] ^ arr[l]) == 0) { return true; } } return false;} // Driver codepublic static void Main (String[] args){ int []arr = { 1, 0, 2, 3, 7 }; int n = arr.Length; if (validQuadruple(arr, n)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by 29AjayKumar
<?php// PHP implementation of the approachconst MAX = 130; // Function that returns true if the array// contains a valid quadruplet pairfunction validQuadruple($arr, $n){ // We can always find a valid quadruplet pair // for array size greater than MAX if ($n >= MAX) return true; // For smaller size arrays, // perform brute force for ($i = 0; $i < $n; $i++) for ($j = $i + 1; $j < $n; $j++) for ($k = $j + 1; $k < $n; $k++) for ($l = $k + 1; $l < $n; $l++) { if (($arr[$i] ^ $arr[$j] ^ $arr[$k] ^ $arr[$l]) == 0) { return true; } } return false;} // Driver code$arr = array(1, 0, 2, 3, 7);$n = count($arr); if (validQuadruple($arr, $n)) echo ("Yes");else echo ("No"); // This code is contributed by Naman_Garg?>
<script> // Javascript implementation// of the approach const MAX = 130; // Function that returns true if the array// contains a valid quadruplet pairfunction validQuadruple(arr, n){ // We can always find a valid quadruplet pair // for array size greater than MAX if (n >= MAX) return true; // For smaller size arrays, perform brute force for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) for (let k = j + 1; k < n; k++) for (let l = k + 1; l < n; l++) { if ((arr[i] ^ arr[j] ^ arr[k] ^ arr[l]) == 0) { return true; } } return false;} // Driver code let arr = [ 1, 0, 2, 3, 7 ]; let n = arr.length; if (validQuadruple(arr, n)) document.write("Yes"); else document.write("No"); </script>
Yes
Time Complexity:
Auxiliary Space: O(1)
Another Efficient Approach (O(N2log N), for N ≤ 130): Compute Xor of all pairs and hash it. ie, store indexes i and j in a list and Hash it in form <xor, list>. If the same xor is found again for different i and j, then we have a Quadruplet pair. Below is the implementation of the above approach :
Java
Javascript
// Java implementation of the approachimport java.util.HashMap;import java.util.LinkedList;import java.util.List;import java.util.Map; public class QuadrapuleXor { static boolean check(int arr[]) { int n = arr.length; if(n < 4) return false; if(n >=130) return true; Map<Integer,List<Integer>> map = new HashMap<>(); for(int i=0;i<n-1;i++) { for(int j=i+1;j<n;j++) { int k = arr[i] ^ arr[j]; if(!map.containsKey(k)) map.put(k,new LinkedList<>()); List<Integer> data = map.get(k); if(!data.contains(i) && !data.contains(j)) { data.add(i); data.add(j); if(data.size()>=4) return true; map.put(k, data); } } } return false; } // Driver code public static void main (String[] args) throws java.lang.Exception { int arr[] = { 1, 0, 2, 3, 7 }; if (check(arr)) System.out.println("Yes"); else System.out.println("No"); }} //This code contributed by Pramod Hosahalli
<script>// Javascript implementation of the approach function check(arr){ let n = arr.length; if(n < 4) return false; if(n >=130) return true; let map = new Map(); for(let i=0;i<n-1;i++) { for(let j=i+1;j<n;j++) { let k = arr[i] ^ arr[j]; if(!map.has(k)) map.set(k,[]); let data = map.get(k); if(!data.includes(i) && !data.includes(j)) { data.push(i); data.push(j); if(data.length>=4) return true; map.set(k, data); } } } return false;} // Driver codelet arr=[ 1, 0, 2, 3, 7 ];if (check(arr)) document.write("Yes<br>");else document.write("No<br>"); // This code is contributed by rag2127</script>
Yes
Time Complexity:
Auxiliary Space: O(N2)
mohit kumar 29
nidhiva
29AjayKumar
PramodHosahalli
Naman_Garg
subham348
rag2127
subhammahato348
Bitwise-XOR
Arrays
Bit Magic
Mathematical
Arrays
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Count pairs with given sum
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
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
How to swap two numbers without using a temporary variable? | [
{
"code": null,
"e": 26041,
"s": 26013,
"text": "\n18 Nov, 2021"
},
{
"code": null,
"e": 26399,
"s": 26041,
"text": "Given an array arr[] of N integers such that any two adjacent elements in the array differ at only one position in their binary representation. The task is to find whether there exists a quadruple (arr[i], arr[j], arr[k], arr[l]) such that arr[i] ^ arr[j] ^ arr[k] ^ arr[l] = 0. Here ^ denotes the bitwise xor operation and 1 ≤ i < j < k < l ≤ N.Examples: "
},
{
"code": null,
"e": 26518,
"s": 26399,
"text": "Input: arr[] = {1, 3, 7, 3} Output: No 1 ^ 3 ^ 7 ^ 3 = 6Input: arr[] = {1, 0, 2, 3, 7} Output: Yes 1 ^ 0 ^ 2 ^ 3 = 0 "
},
{
"code": null,
"e": 26692,
"s": 26522,
"text": "Naive approach: Check for all possible quadruples whether their xor is zero or not. But the time complexity of such a solution would be N4, for all N. Time Complexity: "
},
{
"code": null,
"e": 27245,
"s": 26692,
"text": "Efficient Approach (O(N4), for N ≤ 130): We can Say that for array length more than or equal to 130 we can have at least 65 adjacent pairs each denoting xor of two elements. Here it is given that all adjacent elements differ at only one position in their binary form thus there would result in only one set bit. Since we have only 64 possible positions, we can say that at least two pairs will have the same xor. Thus, xor of these 4 integers will be 0. For N < 130 we can use the naive approach.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27249,
"s": 27245,
"text": "C++"
},
{
"code": null,
"e": 27254,
"s": 27249,
"text": "Java"
},
{
"code": null,
"e": 27262,
"s": 27254,
"text": "Python3"
},
{
"code": null,
"e": 27265,
"s": 27262,
"text": "C#"
},
{
"code": null,
"e": 27269,
"s": 27265,
"text": "PHP"
},
{
"code": null,
"e": 27280,
"s": 27269,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int MAX = 130; // Function that returns true if the array// contains a valid quadruplet pairbool validQuadruple(int arr[], int n){ // We can always find a valid quadruplet pair // for array size greater than MAX if (n >= MAX) return true; // For smaller size arrays, perform brute force for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) for (int l = k + 1; l < n; l++) { if ((arr[i] ^ arr[j] ^ arr[k] ^ arr[l]) == 0) { return true; } } return false;} // Driver codeint main(){ int arr[] = { 1, 0, 2, 3, 7 }; int n = sizeof(arr) / sizeof(arr[0]); if (validQuadruple(arr, n)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 28196,
"s": 27280,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ static int MAX = 130; // Function that returns true if the array// contains a valid quadruplet pairstatic boolean validQuadruple(int arr[], int n){ // We can always find a valid quadruplet pair // for array size greater than MAX if (n >= MAX) return true; // For smaller size arrays, perform brute force for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) for (int l = k + 1; l < n; l++) { if ((arr[i] ^ arr[j] ^ arr[k] ^ arr[l]) == 0) { return true; } } return false;} // Driver codepublic static void main (String[] args) throws java.lang.Exception{ int arr[] = { 1, 0, 2, 3, 7 }; int n = arr.length; if (validQuadruple(arr, n)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by nidhiva",
"e": 29305,
"s": 28196,
"text": null
},
{
"code": "# Python3 implementation of the approachMAX = 130 # Function that returns true if the array# contains a valid quadruplet pairdef validQuadruple(arr, n): # We can always find a valid quadruplet pair # for array size greater than MAX if (n >= MAX): return True # For smaller size arrays, # perform brute force for i in range(n): for j in range(i + 1, n): for k in range(j + 1, n): for l in range(k + 1, n): if ((arr[i] ^ arr[j] ^ arr[k] ^ arr[l]) == 0): return True return False # Driver codearr = [1, 0, 2, 3, 7]n = len(arr) if (validQuadruple(arr, n)): print(\"Yes\")else: print(\"No\") # This code is contributed# by Mohit Kumar",
"e": 30068,
"s": 29305,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ static int MAX = 130; // Function that returns true if the array// contains a valid quadruplet pairstatic Boolean validQuadruple(int []arr, int n){ // We can always find a valid quadruplet pair // for array size greater than MAX if (n >= MAX) return true; // For smaller size arrays, perform brute force for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) for (int l = k + 1; l < n; l++) { if ((arr[i] ^ arr[j] ^ arr[k] ^ arr[l]) == 0) { return true; } } return false;} // Driver codepublic static void Main (String[] args){ int []arr = { 1, 0, 2, 3, 7 }; int n = arr.Length; if (validQuadruple(arr, n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by 29AjayKumar",
"e": 31099,
"s": 30068,
"text": null
},
{
"code": "<?php// PHP implementation of the approachconst MAX = 130; // Function that returns true if the array// contains a valid quadruplet pairfunction validQuadruple($arr, $n){ // We can always find a valid quadruplet pair // for array size greater than MAX if ($n >= MAX) return true; // For smaller size arrays, // perform brute force for ($i = 0; $i < $n; $i++) for ($j = $i + 1; $j < $n; $j++) for ($k = $j + 1; $k < $n; $k++) for ($l = $k + 1; $l < $n; $l++) { if (($arr[$i] ^ $arr[$j] ^ $arr[$k] ^ $arr[$l]) == 0) { return true; } } return false;} // Driver code$arr = array(1, 0, 2, 3, 7);$n = count($arr); if (validQuadruple($arr, $n)) echo (\"Yes\");else echo (\"No\"); // This code is contributed by Naman_Garg?>",
"e": 32015,
"s": 31099,
"text": null
},
{
"code": "<script> // Javascript implementation// of the approach const MAX = 130; // Function that returns true if the array// contains a valid quadruplet pairfunction validQuadruple(arr, n){ // We can always find a valid quadruplet pair // for array size greater than MAX if (n >= MAX) return true; // For smaller size arrays, perform brute force for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) for (let k = j + 1; k < n; k++) for (let l = k + 1; l < n; l++) { if ((arr[i] ^ arr[j] ^ arr[k] ^ arr[l]) == 0) { return true; } } return false;} // Driver code let arr = [ 1, 0, 2, 3, 7 ]; let n = arr.length; if (validQuadruple(arr, n)) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 32899,
"s": 32015,
"text": null
},
{
"code": null,
"e": 32903,
"s": 32899,
"text": "Yes"
},
{
"code": null,
"e": 32924,
"s": 32905,
"text": "Time Complexity: "
},
{
"code": null,
"e": 32946,
"s": 32924,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 33250,
"s": 32946,
"text": "Another Efficient Approach (O(N2log N), for N ≤ 130): Compute Xor of all pairs and hash it. ie, store indexes i and j in a list and Hash it in form <xor, list>. If the same xor is found again for different i and j, then we have a Quadruplet pair. Below is the implementation of the above approach : "
},
{
"code": null,
"e": 33255,
"s": 33250,
"text": "Java"
},
{
"code": null,
"e": 33266,
"s": 33255,
"text": "Javascript"
},
{
"code": "// Java implementation of the approachimport java.util.HashMap;import java.util.LinkedList;import java.util.List;import java.util.Map; public class QuadrapuleXor { static boolean check(int arr[]) { int n = arr.length; if(n < 4) return false; if(n >=130) return true; Map<Integer,List<Integer>> map = new HashMap<>(); for(int i=0;i<n-1;i++) { for(int j=i+1;j<n;j++) { int k = arr[i] ^ arr[j]; if(!map.containsKey(k)) map.put(k,new LinkedList<>()); List<Integer> data = map.get(k); if(!data.contains(i) && !data.contains(j)) { data.add(i); data.add(j); if(data.size()>=4) return true; map.put(k, data); } } } return false; } // Driver code public static void main (String[] args) throws java.lang.Exception { int arr[] = { 1, 0, 2, 3, 7 }; if (check(arr)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} //This code contributed by Pramod Hosahalli",
"e": 34591,
"s": 33266,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach function check(arr){ let n = arr.length; if(n < 4) return false; if(n >=130) return true; let map = new Map(); for(let i=0;i<n-1;i++) { for(let j=i+1;j<n;j++) { let k = arr[i] ^ arr[j]; if(!map.has(k)) map.set(k,[]); let data = map.get(k); if(!data.includes(i) && !data.includes(j)) { data.push(i); data.push(j); if(data.length>=4) return true; map.set(k, data); } } } return false;} // Driver codelet arr=[ 1, 0, 2, 3, 7 ];if (check(arr)) document.write(\"Yes<br>\");else document.write(\"No<br>\"); // This code is contributed by rag2127</script>",
"e": 35567,
"s": 34591,
"text": null
},
{
"code": null,
"e": 35571,
"s": 35567,
"text": "Yes"
},
{
"code": null,
"e": 35590,
"s": 35573,
"text": "Time Complexity:"
},
{
"code": null,
"e": 35613,
"s": 35590,
"text": "Auxiliary Space: O(N2)"
},
{
"code": null,
"e": 35630,
"s": 35615,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 35638,
"s": 35630,
"text": "nidhiva"
},
{
"code": null,
"e": 35650,
"s": 35638,
"text": "29AjayKumar"
},
{
"code": null,
"e": 35666,
"s": 35650,
"text": "PramodHosahalli"
},
{
"code": null,
"e": 35677,
"s": 35666,
"text": "Naman_Garg"
},
{
"code": null,
"e": 35687,
"s": 35677,
"text": "subham348"
},
{
"code": null,
"e": 35695,
"s": 35687,
"text": "rag2127"
},
{
"code": null,
"e": 35711,
"s": 35695,
"text": "subhammahato348"
},
{
"code": null,
"e": 35723,
"s": 35711,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 35730,
"s": 35723,
"text": "Arrays"
},
{
"code": null,
"e": 35740,
"s": 35730,
"text": "Bit Magic"
},
{
"code": null,
"e": 35753,
"s": 35740,
"text": "Mathematical"
},
{
"code": null,
"e": 35760,
"s": 35753,
"text": "Arrays"
},
{
"code": null,
"e": 35773,
"s": 35760,
"text": "Mathematical"
},
{
"code": null,
"e": 35783,
"s": 35773,
"text": "Bit Magic"
},
{
"code": null,
"e": 35881,
"s": 35783,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35912,
"s": 35881,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 35939,
"s": 35912,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 35964,
"s": 35939,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 36002,
"s": 35964,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 36023,
"s": 36002,
"text": "Next Greater Element"
},
{
"code": null,
"e": 36050,
"s": 36023,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 36096,
"s": 36050,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 36164,
"s": 36096,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 36193,
"s": 36164,
"text": "Count set bits in an integer"
}
]
|
All ways to add parenthesis for evaluation - GeeksforGeeks | 21 Mar, 2017
Given a string that represents an expression constituting numbers and binary operator +, – and * only. We need to parenthesize the expression in all possible way and return all evaluated values.
Input : expr = “3-2-1”
Output : {0, 2}
((3-2)-1) = 0
(3-(2-1)) = 2
Input : expr = "5*4-3*2"
Output : {-10, 10, 14, 10, 34}
(5*(4-(3*2))) = -10
(5*((4-3)*2)) = 10
((5*4)-(3*2)) = 14
((5*(4-3))*2) = 10
(((5*4)-3)*2) = 34
We can solve this problem by parenthesizing all possible valid substring of the expression and then evaluating them, but as we can see that it will involve solving lots of repeating subproblem, to save ourselves we can follow a dynamic programming approach.We store the result for each substring in a map and if string in recursion is already solved, we return result from map instead of solving that again.Below code runs a loop in the string and if at any instant, character is operator then we divide the input from there, recursively solve each part and then combine the result in all possible ways.See the use of c_str() function, this function converts the C++ string into C char array, this function is used in below code because atoi() function expects a character array as an argument not the string. It converts character array to number.
// C++ program to output all possible values of// an expression by parenthesizing it.#include <bits/stdc++.h>using namespace std; // method checks, character is operator or notbool isOperator(char op){ return (op == '+' || op == '-' || op == '*');} // Utility recursive method to get all possible// result of input stringvector<int> possibleResultUtil(string input, map< string, vector<int> > memo){ // If already calculated, then return from memo if (memo.find(input) != memo.end()) return memo[input]; vector<int> res; for (int i = 0; i < input.size(); i++) { if (isOperator(input[i])) { // If character is operator then split and // calculate recursively vector<int> resPre = possibleResultUtil(input.substr(0, i), memo); vector<int> resSuf = possibleResultUtil(input.substr(i + 1), memo); // Combine all possible combination for (int j = 0; j < resPre.size(); j++) { for (int k = 0; k < resSuf.size(); k++) { if (input[i] == '+') res.push_back(resPre[j] + resSuf[k]); else if (input[i] == '-') res.push_back(resPre[j] - resSuf[k]); else if (input[i] == '*') res.push_back(resPre[j] * resSuf[k]); } } } } // if input contains only number then save that // into res vector if (res.size() == 0) res.push_back(atoi(input.c_str())); // Store in memo so that input string is not // processed repeatedly memo[input] = res; return res;} // method to return all possible output // from input expressionvector<int> possibleResult(string input){ map< string, vector<int> > memo; return possibleResultUtil(input, memo);} // Driver code to test above methodsint main(){ string input = "5*4-3*2"; vector<int> res = possibleResult(input); for (int i = 0; i < res.size(); i++) cout << res[i] << " "; return 0;}
Output:
-10 10 14 10 34
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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.
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum size square sub-matrix with all 1s
Optimal Substructure Property in Dynamic Programming | DP-2
Optimal Binary Search Tree | DP-24
Min Cost Path | DP-6
Maximum Subarray Sum using Divide and Conquer algorithm
Greedy approach vs Dynamic programming
Maximum sum such that no two elements are adjacent
Word Break Problem | DP-32
3 Different ways to print Fibonacci series in Java
Top 50 Dynamic Programming Coding Problems for Interviews | [
{
"code": null,
"e": 25941,
"s": 25913,
"text": "\n21 Mar, 2017"
},
{
"code": null,
"e": 26136,
"s": 25941,
"text": "Given a string that represents an expression constituting numbers and binary operator +, – and * only. We need to parenthesize the expression in all possible way and return all evaluated values."
},
{
"code": null,
"e": 26358,
"s": 26136,
"text": "Input : expr = “3-2-1”\nOutput : {0, 2}\n((3-2)-1) = 0 \n(3-(2-1)) = 2\n\nInput : expr = \"5*4-3*2\"\nOutput : {-10, 10, 14, 10, 34}\n(5*(4-(3*2))) = -10\n(5*((4-3)*2)) = 10\n((5*4)-(3*2)) = 14\n((5*(4-3))*2) = 10\n(((5*4)-3)*2) = 34\n"
},
{
"code": null,
"e": 27207,
"s": 26358,
"text": "We can solve this problem by parenthesizing all possible valid substring of the expression and then evaluating them, but as we can see that it will involve solving lots of repeating subproblem, to save ourselves we can follow a dynamic programming approach.We store the result for each substring in a map and if string in recursion is already solved, we return result from map instead of solving that again.Below code runs a loop in the string and if at any instant, character is operator then we divide the input from there, recursively solve each part and then combine the result in all possible ways.See the use of c_str() function, this function converts the C++ string into C char array, this function is used in below code because atoi() function expects a character array as an argument not the string. It converts character array to number."
},
{
"code": "// C++ program to output all possible values of// an expression by parenthesizing it.#include <bits/stdc++.h>using namespace std; // method checks, character is operator or notbool isOperator(char op){ return (op == '+' || op == '-' || op == '*');} // Utility recursive method to get all possible// result of input stringvector<int> possibleResultUtil(string input, map< string, vector<int> > memo){ // If already calculated, then return from memo if (memo.find(input) != memo.end()) return memo[input]; vector<int> res; for (int i = 0; i < input.size(); i++) { if (isOperator(input[i])) { // If character is operator then split and // calculate recursively vector<int> resPre = possibleResultUtil(input.substr(0, i), memo); vector<int> resSuf = possibleResultUtil(input.substr(i + 1), memo); // Combine all possible combination for (int j = 0; j < resPre.size(); j++) { for (int k = 0; k < resSuf.size(); k++) { if (input[i] == '+') res.push_back(resPre[j] + resSuf[k]); else if (input[i] == '-') res.push_back(resPre[j] - resSuf[k]); else if (input[i] == '*') res.push_back(resPre[j] * resSuf[k]); } } } } // if input contains only number then save that // into res vector if (res.size() == 0) res.push_back(atoi(input.c_str())); // Store in memo so that input string is not // processed repeatedly memo[input] = res; return res;} // method to return all possible output // from input expressionvector<int> possibleResult(string input){ map< string, vector<int> > memo; return possibleResultUtil(input, memo);} // Driver code to test above methodsint main(){ string input = \"5*4-3*2\"; vector<int> res = possibleResult(input); for (int i = 0; i < res.size(); i++) cout << res[i] << \" \"; return 0;}",
"e": 29327,
"s": 27207,
"text": null
},
{
"code": null,
"e": 29335,
"s": 29327,
"text": "Output:"
},
{
"code": null,
"e": 29353,
"s": 29335,
"text": "-10 10 14 10 34 \n"
},
{
"code": null,
"e": 29656,
"s": 29353,
"text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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": 29781,
"s": 29656,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29801,
"s": 29781,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 29821,
"s": 29801,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 29919,
"s": 29821,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29962,
"s": 29919,
"text": "Maximum size square sub-matrix with all 1s"
},
{
"code": null,
"e": 30022,
"s": 29962,
"text": "Optimal Substructure Property in Dynamic Programming | DP-2"
},
{
"code": null,
"e": 30057,
"s": 30022,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 30078,
"s": 30057,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 30134,
"s": 30078,
"text": "Maximum Subarray Sum using Divide and Conquer algorithm"
},
{
"code": null,
"e": 30173,
"s": 30134,
"text": "Greedy approach vs Dynamic programming"
},
{
"code": null,
"e": 30224,
"s": 30173,
"text": "Maximum sum such that no two elements are adjacent"
},
{
"code": null,
"e": 30251,
"s": 30224,
"text": "Word Break Problem | DP-32"
},
{
"code": null,
"e": 30302,
"s": 30251,
"text": "3 Different ways to print Fibonacci series in Java"
}
]
|
MoviePy – Adding Mask to Video File Clip | 30 Aug, 2020
In this article we will see how we can add mask to the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. IsMask property tells that if the given video clip is mask or not, mask is basically that video which is used as mask for the another video. We can make a video clip as mask with the help of set_ismask method. Adding mask gives copy of the clip with a completely opaque mask (made of ones). This makes computations slower compared to having a None mask but can be useful in many cases.
In order to do this we will use add_mask method with the VideoFileClip object
Syntax : clip.add_mask()
Argument : It takes no argument
Return : It returns VideoFileClip object
Below is the implementation
# Import everything needed to edit video clips from moviepy.editor import * # loading video dsa gfg intro video clip = VideoFileClip("dsa_geek.mp4") # getting only first 5 secondsclip = clip.subclip(0, 5) # add mask to the clipclip = clip.add_mask() # displaying new clipclip.ipython_display(width = 420)
Output :
Clip is Mask : False
Moviepy - Building video __temp__.mp4.
Moviepy - Writing video __temp__.mp4
Moviepy - Done !
Moviepy - video ready __temp__.mp4
Another example
# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip("geeks.mp4") # getting only first 5 secondsclip = clip.subclip(0, 5) # add mask to the clipclip = clip.add_mask() # displaying new clipclip.ipython_display(width = 420)
Output :
Clip is Mask : True
Moviepy - Building video __temp__.mp4.
MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3
MoviePy - Done.
Moviepy - Writing video __temp__.mp4
Moviepy - Done !
Moviepy - video ready __temp__.mp4
Python-MoviePy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Aug, 2020"
},
{
"code": null,
"e": 603,
"s": 28,
"text": "In this article we will see how we can add mask to the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. IsMask property tells that if the given video clip is mask or not, mask is basically that video which is used as mask for the another video. We can make a video clip as mask with the help of set_ismask method. Adding mask gives copy of the clip with a completely opaque mask (made of ones). This makes computations slower compared to having a None mask but can be useful in many cases."
},
{
"code": null,
"e": 681,
"s": 603,
"text": "In order to do this we will use add_mask method with the VideoFileClip object"
},
{
"code": null,
"e": 706,
"s": 681,
"text": "Syntax : clip.add_mask()"
},
{
"code": null,
"e": 738,
"s": 706,
"text": "Argument : It takes no argument"
},
{
"code": null,
"e": 779,
"s": 738,
"text": "Return : It returns VideoFileClip object"
},
{
"code": null,
"e": 807,
"s": 779,
"text": "Below is the implementation"
},
{
"code": "# Import everything needed to edit video clips from moviepy.editor import * # loading video dsa gfg intro video clip = VideoFileClip(\"dsa_geek.mp4\") # getting only first 5 secondsclip = clip.subclip(0, 5) # add mask to the clipclip = clip.add_mask() # displaying new clipclip.ipython_display(width = 420)",
"e": 1124,
"s": 807,
"text": null
},
{
"code": null,
"e": 1133,
"s": 1124,
"text": "Output :"
},
{
"code": null,
"e": 1405,
"s": 1133,
"text": "Clip is Mask : False\nMoviepy - Building video __temp__.mp4.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4\n"
},
{
"code": null,
"e": 1421,
"s": 1405,
"text": "Another example"
},
{
"code": "# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video gfgclip = VideoFileClip(\"geeks.mp4\") # getting only first 5 secondsclip = clip.subclip(0, 5) # add mask to the clipclip = clip.add_mask() # displaying new clipclip.ipython_display(width = 420)",
"e": 1713,
"s": 1421,
"text": null
},
{
"code": null,
"e": 1722,
"s": 1713,
"text": "Output :"
},
{
"code": null,
"e": 2185,
"s": 1722,
"text": "Clip is Mask : True\nMoviepy - Building video __temp__.mp4.\nMoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3\n \nMoviePy - Done.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4\n"
},
{
"code": null,
"e": 2200,
"s": 2185,
"text": "Python-MoviePy"
},
{
"code": null,
"e": 2207,
"s": 2200,
"text": "Python"
},
{
"code": null,
"e": 2305,
"s": 2207,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2323,
"s": 2305,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2365,
"s": 2323,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2387,
"s": 2365,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2422,
"s": 2387,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2448,
"s": 2422,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2480,
"s": 2448,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2509,
"s": 2480,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2536,
"s": 2509,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2566,
"s": 2536,
"text": "Iterate over a list in Python"
}
]
|
Insertion Sort | 11 May, 2022
Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.
This algorithm is one of the simplest algorithm with simple implementation
Basically, Insertion sort is efficient for small data values
Insertion sort is adaptive in nature, i.e. it is appropriate for data sets which are already partially sorted.
Consider an example: arr[]: {12, 11, 13, 5, 6}
First Pass:
Initially, the first two elements of the array are compared in insertion sort.
Here, 12 is greater than 11 hence they are not in the ascending order and 12 is not at its correct position. Thus, swap 11 and 12.
So, for now 11 is stored in a sorted sub-array.
Second Pass:
Now, move to the next two elements and compare them
Here, 13 is greater than 12, thus both elements seems to be in ascending order, hence, no swapping will occur. 12 also stored in a sorted sub-array along with 11
Third Pass:
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.
Now, two elements are present in the sorted sub-array which are 11 and 12
Moving forward to the next two elements which are 13 and 5
Both 5 and 13 are not present at their correct place so swap them
After swapping, elements 12 and 5 are not sorted, thus swap again
Here, again 11 and 5 are not sorted, hence swap again
here, it is at its correct position
Fourth Pass:
Now, the elements which are present in the sorted sub-array are 5, 11 and 12
Moving to the next two elements 13 and 6
Clearly, they are not sorted, thus perform swap between both
Now, 6 is smaller than 12, hence, swap again
Here, also swapping makes 11 and 6 unsorted hence, swap again
Finally, the array is completely sorted.
Illustrations:
To sort an array of size N in ascending order:
Iterate from arr[1] to arr[N] over the array.
Compare the current element (key) to its predecessor.
If the key element is smaller than its predecessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element.
Below is the implementation:
C++
C
Java
Python
C#
PHP
Javascript
// C++ program for insertion sort #include <bits/stdc++.h>using namespace std; // Function to sort an array using// insertion sortvoid insertionSort(int arr[], int n){ int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; // Move elements of arr[0..i-1], // that are greater than key, to one // position ahead of their // current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }} // A utility function to print an array// of size nvoid printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) cout << arr[i] << " "; cout << endl;} // Driver codeint main(){ int arr[] = { 12, 11, 13, 5, 6 }; int N = sizeof(arr) / sizeof(arr[0]); insertionSort(arr, N); printArray(arr, N); return 0;}// This is code is contributed by rathbhupendra
// C program for insertion sort#include <math.h>#include <stdio.h> /* Function to sort an array using insertion sort*/void insertionSort(int arr[], int n){ int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }} // A utility function to print an array of size nvoid printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n");} /* Driver program to test insertion sort */int main(){ int arr[] = { 12, 11, 13, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); insertionSort(arr, n); printArray(arr, n); return 0;}
// Java program for implementation of Insertion Sortclass InsertionSort { /*Function to sort array using insertion sort*/ void sort(int arr[]) { int n = arr.length; for (int i = 1; i < n; ++i) { int key = arr[i]; int j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } /* A utility function to print array of size n*/ static void printArray(int arr[]) { int n = arr.length; for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); System.out.println(); } // Driver method public static void main(String args[]) { int arr[] = { 12, 11, 13, 5, 6 }; InsertionSort ob = new InsertionSort(); ob.sort(arr); printArray(arr); }} /* This code is contributed by Rajat Mishra. */
# Python program for implementation of Insertion Sort # Function to do insertion sortdef insertionSort(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position j = i-1 while j >= 0 and key < arr[j] : arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key # Driver code to test abovearr = [12, 11, 13, 5, 6]insertionSort(arr)for i in range(len(arr)): print ("% d" % arr[i]) # This code is contributed by Mohit Kumra
// C# program for implementation of Insertion Sortusing System; class InsertionSort { // Function to sort array // using insertion sort void sort(int[] arr) { int n = arr.Length; for (int i = 1; i < n; ++i) { int key = arr[i]; int j = i - 1; // Move elements of arr[0..i-1], // that are greater than key, // to one position ahead of // their current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } // A utility function to print // array of size n static void printArray(int[] arr) { int n = arr.Length; for (int i = 0; i < n; ++i) Console.Write(arr[i] + " "); Console.Write("\n"); } // Driver Code public static void Main() { int[] arr = { 12, 11, 13, 5, 6 }; InsertionSort ob = new InsertionSort(); ob.sort(arr); printArray(arr); }} // This code is contributed by ChitraNayal.
<?php// PHP program for insertion sort // Function to sort an array// using insertion sortfunction insertionSort(&$arr, $n){ for ($i = 1; $i < $n; $i++) { $key = $arr[$i]; $j = $i-1; // Move elements of arr[0..i-1], // that are greater than key, to // one position ahead of their // current position while ($j >= 0 && $arr[$j] > $key) { $arr[$j + 1] = $arr[$j]; $j = $j - 1; } $arr[$j + 1] = $key; }} // A utility function to// print an array of size nfunction printArray(&$arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i]." "; echo "\n";} // Driver Code$arr = array(12, 11, 13, 5, 6);$n = sizeof($arr);insertionSort($arr, $n);printArray($arr, $n); // This code is contributed by ChitraNayal.?>
<script>// Javascript program for insertion sort // Function to sort an array using insertion sortfunction insertionSort(arr, n) { let i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } // A utility function to print an array of size n function printArray(arr, n) { let i; for (i = 0; i < n; i++) document.write(arr[i] + " "); document.write("<br>");} // Driver code let arr = [12, 11, 13, 5, 6 ]; let n = arr.length; insertionSort(arr, n); printArray(arr, n); // This code is contributed by Mayank Tyagi </script>
5 6 11 12 13
Time Complexity: O(N^2) Auxiliary Space: O(1)
Insertion sort takes maximum time to sort if elements are sorted in reverse order. And it takes minimum time (Order of n) when elements are already sorted.
Insertion Sort algorithm follows incremental approach.
Yes, insertion sort is an in-place sorting algorithm.
Yes, insertion sort is a stable sorting algorithm.
Insertion sort is used when number of elements is small. It can also be useful when input array is almost sorted, only few elements are misplaced in complete big array.
We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort uses binary search to find the proper location to insert the selected item at each iteration. In normal insertion, sorting takes O(i) (at ith iteration) in worst case. We can reduce it to O(logi) by using binary search. The algorithm, as a whole, still has a running worst case running time of O(n^2) because of the series of swaps required for each insertion. Refer this for implementation.
Below is simple insertion sort algorithm for linked list.
Create an empty sorted (or result) list
Traverse the given list, do following for every node.Insert current node in sorted way in sorted or result list.
Insert current node in sorted way in sorted or result list.
Change head of given linked list to head of sorted (or result) list.
Refer this for implementation.
Insertion Sort | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersInsertion Sort | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:42•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=OGzPmgsI-pQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Snapshots: Quiz on Insertion Sort
Other Sorting Algorithms on GeeksforGeeks/GeeksQuiz Selection Sort, Bubble Sort, Insertion Sort, Merge Sort, Heap Sort, QuickSort, Radix Sort, Counting Sort, Bucket Sort, ShellSort, Comb Sort Coding practice for sorting. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ukasp
PIYUSHKUMAR19
PuneetChaurasia
rathbhupendra
theohollweg
mayanktyagi1709
parth_07
debugagrawal
kashishkumar2
Accenture
Cisco
Dell
Grofers
Juniper Networks
MAQ Software
Veritas
Sorting
MAQ Software
Juniper Networks
Cisco
Accenture
Dell
Veritas
Grofers
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 326,
"s": 52,
"text": "Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part."
},
{
"code": null,
"e": 401,
"s": 326,
"text": "This algorithm is one of the simplest algorithm with simple implementation"
},
{
"code": null,
"e": 462,
"s": 401,
"text": "Basically, Insertion sort is efficient for small data values"
},
{
"code": null,
"e": 573,
"s": 462,
"text": "Insertion sort is adaptive in nature, i.e. it is appropriate for data sets which are already partially sorted."
},
{
"code": null,
"e": 620,
"s": 573,
"text": "Consider an example: arr[]: {12, 11, 13, 5, 6}"
},
{
"code": null,
"e": 632,
"s": 620,
"text": "First Pass:"
},
{
"code": null,
"e": 711,
"s": 632,
"text": "Initially, the first two elements of the array are compared in insertion sort."
},
{
"code": null,
"e": 842,
"s": 711,
"text": "Here, 12 is greater than 11 hence they are not in the ascending order and 12 is not at its correct position. Thus, swap 11 and 12."
},
{
"code": null,
"e": 890,
"s": 842,
"text": "So, for now 11 is stored in a sorted sub-array."
},
{
"code": null,
"e": 903,
"s": 890,
"text": "Second Pass:"
},
{
"code": null,
"e": 956,
"s": 903,
"text": " Now, move to the next two elements and compare them"
},
{
"code": null,
"e": 1118,
"s": 956,
"text": "Here, 13 is greater than 12, thus both elements seems to be in ascending order, hence, no swapping will occur. 12 also stored in a sorted sub-array along with 11"
},
{
"code": null,
"e": 1130,
"s": 1118,
"text": "Third Pass:"
},
{
"code": null,
"e": 1139,
"s": 1130,
"text": "Chapters"
},
{
"code": null,
"e": 1166,
"s": 1139,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1216,
"s": 1166,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1239,
"s": 1216,
"text": "captions off, selected"
},
{
"code": null,
"e": 1247,
"s": 1239,
"text": "English"
},
{
"code": null,
"e": 1271,
"s": 1247,
"text": "This is a modal window."
},
{
"code": null,
"e": 1340,
"s": 1271,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1362,
"s": 1340,
"text": "End of dialog window."
},
{
"code": null,
"e": 1436,
"s": 1362,
"text": "Now, two elements are present in the sorted sub-array which are 11 and 12"
},
{
"code": null,
"e": 1495,
"s": 1436,
"text": "Moving forward to the next two elements which are 13 and 5"
},
{
"code": null,
"e": 1561,
"s": 1495,
"text": "Both 5 and 13 are not present at their correct place so swap them"
},
{
"code": null,
"e": 1627,
"s": 1561,
"text": "After swapping, elements 12 and 5 are not sorted, thus swap again"
},
{
"code": null,
"e": 1681,
"s": 1627,
"text": "Here, again 11 and 5 are not sorted, hence swap again"
},
{
"code": null,
"e": 1717,
"s": 1681,
"text": "here, it is at its correct position"
},
{
"code": null,
"e": 1730,
"s": 1717,
"text": "Fourth Pass:"
},
{
"code": null,
"e": 1807,
"s": 1730,
"text": "Now, the elements which are present in the sorted sub-array are 5, 11 and 12"
},
{
"code": null,
"e": 1848,
"s": 1807,
"text": "Moving to the next two elements 13 and 6"
},
{
"code": null,
"e": 1909,
"s": 1848,
"text": "Clearly, they are not sorted, thus perform swap between both"
},
{
"code": null,
"e": 1954,
"s": 1909,
"text": "Now, 6 is smaller than 12, hence, swap again"
},
{
"code": null,
"e": 2016,
"s": 1954,
"text": "Here, also swapping makes 11 and 6 unsorted hence, swap again"
},
{
"code": null,
"e": 2057,
"s": 2016,
"text": "Finally, the array is completely sorted."
},
{
"code": null,
"e": 2072,
"s": 2057,
"text": "Illustrations:"
},
{
"code": null,
"e": 2122,
"s": 2074,
"text": "To sort an array of size N in ascending order: "
},
{
"code": null,
"e": 2169,
"s": 2122,
"text": "Iterate from arr[1] to arr[N] over the array. "
},
{
"code": null,
"e": 2224,
"s": 2169,
"text": "Compare the current element (key) to its predecessor. "
},
{
"code": null,
"e": 2392,
"s": 2224,
"text": "If the key element is smaller than its predecessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element."
},
{
"code": null,
"e": 2421,
"s": 2392,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 2425,
"s": 2421,
"text": "C++"
},
{
"code": null,
"e": 2427,
"s": 2425,
"text": "C"
},
{
"code": null,
"e": 2432,
"s": 2427,
"text": "Java"
},
{
"code": null,
"e": 2439,
"s": 2432,
"text": "Python"
},
{
"code": null,
"e": 2442,
"s": 2439,
"text": "C#"
},
{
"code": null,
"e": 2446,
"s": 2442,
"text": "PHP"
},
{
"code": null,
"e": 2457,
"s": 2446,
"text": "Javascript"
},
{
"code": "// C++ program for insertion sort #include <bits/stdc++.h>using namespace std; // Function to sort an array using// insertion sortvoid insertionSort(int arr[], int n){ int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; // Move elements of arr[0..i-1], // that are greater than key, to one // position ahead of their // current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }} // A utility function to print an array// of size nvoid printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) cout << arr[i] << \" \"; cout << endl;} // Driver codeint main(){ int arr[] = { 12, 11, 13, 5, 6 }; int N = sizeof(arr) / sizeof(arr[0]); insertionSort(arr, N); printArray(arr, N); return 0;}// This is code is contributed by rathbhupendra",
"e": 3389,
"s": 2457,
"text": null
},
{
"code": "// C program for insertion sort#include <math.h>#include <stdio.h> /* Function to sort an array using insertion sort*/void insertionSort(int arr[], int n){ int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }} // A utility function to print an array of size nvoid printArray(int arr[], int n){ int i; for (i = 0; i < n; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} /* Driver program to test insertion sort */int main(){ int arr[] = { 12, 11, 13, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); insertionSort(arr, n); printArray(arr, n); return 0;}",
"e": 4269,
"s": 3389,
"text": null
},
{
"code": "// Java program for implementation of Insertion Sortclass InsertionSort { /*Function to sort array using insertion sort*/ void sort(int arr[]) { int n = arr.length; for (int i = 1; i < n; ++i) { int key = arr[i]; int j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } /* A utility function to print array of size n*/ static void printArray(int arr[]) { int n = arr.length; for (int i = 0; i < n; ++i) System.out.print(arr[i] + \" \"); System.out.println(); } // Driver method public static void main(String args[]) { int arr[] = { 12, 11, 13, 5, 6 }; InsertionSort ob = new InsertionSort(); ob.sort(arr); printArray(arr); }} /* This code is contributed by Rajat Mishra. */",
"e": 5347,
"s": 4269,
"text": null
},
{
"code": "# Python program for implementation of Insertion Sort # Function to do insertion sortdef insertionSort(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position j = i-1 while j >= 0 and key < arr[j] : arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key # Driver code to test abovearr = [12, 11, 13, 5, 6]insertionSort(arr)for i in range(len(arr)): print (\"% d\" % arr[i]) # This code is contributed by Mohit Kumra",
"e": 5978,
"s": 5347,
"text": null
},
{
"code": "// C# program for implementation of Insertion Sortusing System; class InsertionSort { // Function to sort array // using insertion sort void sort(int[] arr) { int n = arr.Length; for (int i = 1; i < n; ++i) { int key = arr[i]; int j = i - 1; // Move elements of arr[0..i-1], // that are greater than key, // to one position ahead of // their current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } // A utility function to print // array of size n static void printArray(int[] arr) { int n = arr.Length; for (int i = 0; i < n; ++i) Console.Write(arr[i] + \" \"); Console.Write(\"\\n\"); } // Driver Code public static void Main() { int[] arr = { 12, 11, 13, 5, 6 }; InsertionSort ob = new InsertionSort(); ob.sort(arr); printArray(arr); }} // This code is contributed by ChitraNayal.",
"e": 7064,
"s": 5978,
"text": null
},
{
"code": "<?php// PHP program for insertion sort // Function to sort an array// using insertion sortfunction insertionSort(&$arr, $n){ for ($i = 1; $i < $n; $i++) { $key = $arr[$i]; $j = $i-1; // Move elements of arr[0..i-1], // that are greater than key, to // one position ahead of their // current position while ($j >= 0 && $arr[$j] > $key) { $arr[$j + 1] = $arr[$j]; $j = $j - 1; } $arr[$j + 1] = $key; }} // A utility function to// print an array of size nfunction printArray(&$arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i].\" \"; echo \"\\n\";} // Driver Code$arr = array(12, 11, 13, 5, 6);$n = sizeof($arr);insertionSort($arr, $n);printArray($arr, $n); // This code is contributed by ChitraNayal.?>",
"e": 7893,
"s": 7064,
"text": null
},
{
"code": "<script>// Javascript program for insertion sort // Function to sort an array using insertion sortfunction insertionSort(arr, n) { let i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } // A utility function to print an array of size n function printArray(arr, n) { let i; for (i = 0; i < n; i++) document.write(arr[i] + \" \"); document.write(\"<br>\");} // Driver code let arr = [12, 11, 13, 5, 6 ]; let n = arr.length; insertionSort(arr, n); printArray(arr, n); // This code is contributed by Mayank Tyagi </script>",
"e": 8785,
"s": 7893,
"text": null
},
{
"code": null,
"e": 8799,
"s": 8785,
"text": "5 6 11 12 13 "
},
{
"code": null,
"e": 8845,
"s": 8799,
"text": "Time Complexity: O(N^2) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9002,
"s": 8845,
"text": "Insertion sort takes maximum time to sort if elements are sorted in reverse order. And it takes minimum time (Order of n) when elements are already sorted. "
},
{
"code": null,
"e": 9057,
"s": 9002,
"text": "Insertion Sort algorithm follows incremental approach."
},
{
"code": null,
"e": 9111,
"s": 9057,
"text": "Yes, insertion sort is an in-place sorting algorithm."
},
{
"code": null,
"e": 9162,
"s": 9111,
"text": "Yes, insertion sort is a stable sorting algorithm."
},
{
"code": null,
"e": 9331,
"s": 9162,
"text": "Insertion sort is used when number of elements is small. It can also be useful when input array is almost sorted, only few elements are misplaced in complete big array."
},
{
"code": null,
"e": 9832,
"s": 9331,
"text": "We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort uses binary search to find the proper location to insert the selected item at each iteration. In normal insertion, sorting takes O(i) (at ith iteration) in worst case. We can reduce it to O(logi) by using binary search. The algorithm, as a whole, still has a running worst case running time of O(n^2) because of the series of swaps required for each insertion. Refer this for implementation."
},
{
"code": null,
"e": 9891,
"s": 9832,
"text": "Below is simple insertion sort algorithm for linked list. "
},
{
"code": null,
"e": 9931,
"s": 9891,
"text": "Create an empty sorted (or result) list"
},
{
"code": null,
"e": 10044,
"s": 9931,
"text": "Traverse the given list, do following for every node.Insert current node in sorted way in sorted or result list."
},
{
"code": null,
"e": 10104,
"s": 10044,
"text": "Insert current node in sorted way in sorted or result list."
},
{
"code": null,
"e": 10174,
"s": 10104,
"text": "Change head of given linked list to head of sorted (or result) list. "
},
{
"code": null,
"e": 10208,
"s": 10174,
"text": "Refer this for implementation. "
},
{
"code": null,
"e": 11054,
"s": 10208,
"text": "Insertion Sort | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersInsertion Sort | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:42•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=OGzPmgsI-pQ\" 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": 11088,
"s": 11054,
"text": "Snapshots: Quiz on Insertion Sort"
},
{
"code": null,
"e": 11434,
"s": 11088,
"text": "Other Sorting Algorithms on GeeksforGeeks/GeeksQuiz Selection Sort, Bubble Sort, Insertion Sort, Merge Sort, Heap Sort, QuickSort, Radix Sort, Counting Sort, Bucket Sort, ShellSort, Comb Sort Coding practice for sorting. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 11440,
"s": 11434,
"text": "ukasp"
},
{
"code": null,
"e": 11454,
"s": 11440,
"text": "PIYUSHKUMAR19"
},
{
"code": null,
"e": 11470,
"s": 11454,
"text": "PuneetChaurasia"
},
{
"code": null,
"e": 11484,
"s": 11470,
"text": "rathbhupendra"
},
{
"code": null,
"e": 11496,
"s": 11484,
"text": "theohollweg"
},
{
"code": null,
"e": 11512,
"s": 11496,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 11521,
"s": 11512,
"text": "parth_07"
},
{
"code": null,
"e": 11534,
"s": 11521,
"text": "debugagrawal"
},
{
"code": null,
"e": 11548,
"s": 11534,
"text": "kashishkumar2"
},
{
"code": null,
"e": 11558,
"s": 11548,
"text": "Accenture"
},
{
"code": null,
"e": 11564,
"s": 11558,
"text": "Cisco"
},
{
"code": null,
"e": 11569,
"s": 11564,
"text": "Dell"
},
{
"code": null,
"e": 11577,
"s": 11569,
"text": "Grofers"
},
{
"code": null,
"e": 11594,
"s": 11577,
"text": "Juniper Networks"
},
{
"code": null,
"e": 11607,
"s": 11594,
"text": "MAQ Software"
},
{
"code": null,
"e": 11615,
"s": 11607,
"text": "Veritas"
},
{
"code": null,
"e": 11623,
"s": 11615,
"text": "Sorting"
},
{
"code": null,
"e": 11636,
"s": 11623,
"text": "MAQ Software"
},
{
"code": null,
"e": 11653,
"s": 11636,
"text": "Juniper Networks"
},
{
"code": null,
"e": 11659,
"s": 11653,
"text": "Cisco"
},
{
"code": null,
"e": 11669,
"s": 11659,
"text": "Accenture"
},
{
"code": null,
"e": 11674,
"s": 11669,
"text": "Dell"
},
{
"code": null,
"e": 11682,
"s": 11674,
"text": "Veritas"
},
{
"code": null,
"e": 11690,
"s": 11682,
"text": "Grofers"
},
{
"code": null,
"e": 11698,
"s": 11690,
"text": "Sorting"
}
]
|
Python – Add prefix to each key name in dictionary | 01 Aug, 2020
Given a dictionary, update its each key by adding prefix to each key.
Input : test_dict = {‘Gfg’ : 6, ‘is’ : 7, ‘best’ : 9}, temp = “Pro”Output : {‘ProGfg’ : 6, ‘Prois’ : 7, ‘Probest’ : 9}Explanation : “Pro” prefix added to each key.
Input : test_dict = {‘Gfg’ : 6, ‘is’ : 7, ‘best’ : 9}, temp = “a”Output : {‘aGfg’ : 6, ‘ais’ : 7, ‘abest’ : 9}Explanation : “a” prefix added to each key.
Method #1 : Using dictionary comprehension
This is one of the methods in which this task can be performed. In this we construct new dictionary by performing concatenation of prefix with all keys.
Python3
# Python3 code to demonstrate working of # Add prefix to each key name in dictionary# Using loop # initializing dictionarytest_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing prefix temp = "Pro" # + operator is used to perform task of concatenationres = {temp + str(key): val for key, val in test_dict.items()} # printing result print("The extracted dictionary : " + str(res))
The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}
The extracted dictionary : {'ProGfg': 6, 'Prois': 7, 'Probest': 9, 'Profor': 8, 'Progeeks': 11}
Method #2 : Using f strings + dictionary comprehension
The combination of above functionalities can be used to solve this problem. In this, we perform the task of concatenation using f strings. Works only in >=3.6 versions of Python.
Python3
# Python3 code to demonstrate working of # Add prefix to each key name in dictionary# Using f strings + dictionary comprehension # initializing dictionarytest_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing prefix temp = "Pro" # dictionary comprehension is used to bind result # f strings are used to bind prefix with keyres = {f"Pro{key}": val for key, val in test_dict.items()} # printing result print("The extracted dictionary : " + str(res))
The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}
The extracted dictionary : {'ProGfg': 6, 'Prois': 7, 'Probest': 9, 'Profor': 8, 'Progeeks': 11}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 98,
"s": 28,
"text": "Given a dictionary, update its each key by adding prefix to each key."
},
{
"code": null,
"e": 262,
"s": 98,
"text": "Input : test_dict = {‘Gfg’ : 6, ‘is’ : 7, ‘best’ : 9}, temp = “Pro”Output : {‘ProGfg’ : 6, ‘Prois’ : 7, ‘Probest’ : 9}Explanation : “Pro” prefix added to each key."
},
{
"code": null,
"e": 416,
"s": 262,
"text": "Input : test_dict = {‘Gfg’ : 6, ‘is’ : 7, ‘best’ : 9}, temp = “a”Output : {‘aGfg’ : 6, ‘ais’ : 7, ‘abest’ : 9}Explanation : “a” prefix added to each key."
},
{
"code": null,
"e": 459,
"s": 416,
"text": "Method #1 : Using dictionary comprehension"
},
{
"code": null,
"e": 612,
"s": 459,
"text": "This is one of the methods in which this task can be performed. In this we construct new dictionary by performing concatenation of prefix with all keys."
},
{
"code": null,
"e": 620,
"s": 612,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Add prefix to each key name in dictionary# Using loop # initializing dictionarytest_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing prefix temp = \"Pro\" # + operator is used to perform task of concatenationres = {temp + str(key): val for key, val in test_dict.items()} # printing result print(\"The extracted dictionary : \" + str(res)) ",
"e": 1123,
"s": 620,
"text": null
},
{
"code": null,
"e": 1303,
"s": 1123,
"text": "The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}\nThe extracted dictionary : {'ProGfg': 6, 'Prois': 7, 'Probest': 9, 'Profor': 8, 'Progeeks': 11}\n"
},
{
"code": null,
"e": 1358,
"s": 1303,
"text": "Method #2 : Using f strings + dictionary comprehension"
},
{
"code": null,
"e": 1537,
"s": 1358,
"text": "The combination of above functionalities can be used to solve this problem. In this, we perform the task of concatenation using f strings. Works only in >=3.6 versions of Python."
},
{
"code": null,
"e": 1545,
"s": 1537,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Add prefix to each key name in dictionary# Using f strings + dictionary comprehension # initializing dictionarytest_dict = {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing prefix temp = \"Pro\" # dictionary comprehension is used to bind result # f strings are used to bind prefix with keyres = {f\"Pro{key}\": val for key, val in test_dict.items()} # printing result print(\"The extracted dictionary : \" + str(res)) ",
"e": 2117,
"s": 1545,
"text": null
},
{
"code": null,
"e": 2297,
"s": 2117,
"text": "The original dictionary is : {'Gfg': 6, 'is': 7, 'best': 9, 'for': 8, 'geeks': 11}\nThe extracted dictionary : {'ProGfg': 6, 'Prois': 7, 'Probest': 9, 'Profor': 8, 'Progeeks': 11}\n"
},
{
"code": null,
"e": 2324,
"s": 2297,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2331,
"s": 2324,
"text": "Python"
},
{
"code": null,
"e": 2347,
"s": 2331,
"text": "Python Programs"
},
{
"code": null,
"e": 2445,
"s": 2347,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2477,
"s": 2445,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2504,
"s": 2477,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2535,
"s": 2504,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2558,
"s": 2535,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2579,
"s": 2558,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2601,
"s": 2579,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2640,
"s": 2601,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2678,
"s": 2640,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2727,
"s": 2678,
"text": "Python | Convert string dictionary to dictionary"
}
]
|
Python | Intersection in Tuple Records Data | 29 Oct, 2019
Sometimes, while working with data, we may have a problem in which we require to find the matching records between two lists that we receive. This is a very common problem and records usually occur as a tuple. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehensionList comprehension can opt as method to perform this task in one line rather than running a loop to find the common element. In this, we just iterate for single list and check if any element occurs in other one.
# Python3 code to demonstrate working of# Intersection in Tuple Records Data# Using list comprehension # Initializing liststest_list1 = [('gfg', 1), ('is', 2), ('best', 3)]test_list2 = [('i', 3), ('love', 4), ('gfg', 1)] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # Intersection in Tuple Records Data# Using list comprehensionres = [ele1 for ele1 in test_list1 for ele2 in test_list2 if ele1 == ele2] # printing resultprint("The Intersection of data records is : " + str(res))
The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)]
The original list 2 is : [('i', 3), ('love', 4), ('gfg', 1)]
The Intersection of data records is : [('gfg', 1)]
Method #2 : Using set.intersection()This task can also be performed in smaller way using the generic set intersection. In this, we first convert the list of records to a set and then perform its intersection using intersection().
# Python3 code to demonstrate working of# Intersection in Tuple Records Data# Using set.intersection() # Initializing liststest_list1 = [('gfg', 1), ('is', 2), ('best', 3)]test_list2 = [('i', 3), ('love', 4), ('gfg', 1)] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # Intersection in Tuple Records Data# set.intersection()res = list(set(test_list1).intersection(set(test_list2))) # printing resultprint("The Intersection of data records is : " + str(res))
The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)]
The original list 2 is : [('i', 3), ('love', 4), ('gfg', 1)]
The Intersection of data records is : [('gfg', 1)]
Python list-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Oct, 2019"
},
{
"code": null,
"e": 302,
"s": 28,
"text": "Sometimes, while working with data, we may have a problem in which we require to find the matching records between two lists that we receive. This is a very common problem and records usually occur as a tuple. Let’s discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 550,
"s": 302,
"text": "Method #1 : Using list comprehensionList comprehension can opt as method to perform this task in one line rather than running a loop to find the common element. In this, we just iterate for single list and check if any element occurs in other one."
},
{
"code": "# Python3 code to demonstrate working of# Intersection in Tuple Records Data# Using list comprehension # Initializing liststest_list1 = [('gfg', 1), ('is', 2), ('best', 3)]test_list2 = [('i', 3), ('love', 4), ('gfg', 1)] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # Intersection in Tuple Records Data# Using list comprehensionres = [ele1 for ele1 in test_list1 for ele2 in test_list2 if ele1 == ele2] # printing resultprint(\"The Intersection of data records is : \" + str(res))",
"e": 1125,
"s": 550,
"text": null
},
{
"code": null,
"e": 1300,
"s": 1125,
"text": "The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)]\nThe original list 2 is : [('i', 3), ('love', 4), ('gfg', 1)]\nThe Intersection of data records is : [('gfg', 1)]\n"
},
{
"code": null,
"e": 1532,
"s": 1302,
"text": "Method #2 : Using set.intersection()This task can also be performed in smaller way using the generic set intersection. In this, we first convert the list of records to a set and then perform its intersection using intersection()."
},
{
"code": "# Python3 code to demonstrate working of# Intersection in Tuple Records Data# Using set.intersection() # Initializing liststest_list1 = [('gfg', 1), ('is', 2), ('best', 3)]test_list2 = [('i', 3), ('love', 4), ('gfg', 1)] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # Intersection in Tuple Records Data# set.intersection()res = list(set(test_list1).intersection(set(test_list2))) # printing resultprint(\"The Intersection of data records is : \" + str(res))",
"e": 2077,
"s": 1532,
"text": null
},
{
"code": null,
"e": 2252,
"s": 2077,
"text": "The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)]\nThe original list 2 is : [('i', 3), ('love', 4), ('gfg', 1)]\nThe Intersection of data records is : [('gfg', 1)]\n"
},
{
"code": null,
"e": 2273,
"s": 2252,
"text": "Python list-programs"
},
{
"code": null,
"e": 2295,
"s": 2273,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 2302,
"s": 2295,
"text": "Python"
},
{
"code": null,
"e": 2318,
"s": 2302,
"text": "Python Programs"
},
{
"code": null,
"e": 2416,
"s": 2318,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2434,
"s": 2416,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2476,
"s": 2434,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2498,
"s": 2476,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2533,
"s": 2498,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2559,
"s": 2533,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2602,
"s": 2559,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2624,
"s": 2602,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2663,
"s": 2624,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2701,
"s": 2663,
"text": "Python | Convert a list to dictionary"
}
]
|
Python – Counter.items(), Counter.keys() and Counter.values() | 27 Oct, 2021
Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python’s general-purpose built-ins like dictionaries, lists and tuples. Counter is a sub-class that is used to count hashable objects. It implicitly creates a hash table of an iterable when invoked.
The Counter.items() method helps to see the elements of the list along with their respective frequencies in a tuple.
Syntax : Counter.items()Parameters : NoneReturns : object of class dict_items
Example :
Python3
# importing the modulefrom collections import Counter # making a listlist = [1, 1, 2, 3, 4, 5, 6, 7, 9, 2, 3, 4, 8] # instantiating a Counter objectob = Counter(list) # Counter.items()items = ob.items() print("The datatype is " + str(type(items))) # displaying the dict_itemsprint(items) # iterating over the dict_itemsfor i in items: print(i)
Output :
The datatype is dict_items([(1, 2), (2, 2), (3, 2), (4, 2), (5, 1), (6, 1), (7, 1), (9, 1), (8, 1)]) (1, 2) (2, 2) (3, 2) (4, 2) (5, 1) (6, 1) (7, 1) (9, 1) (8, 1)
The Counter.keys() method helps to see the unique elements in the list.
Syntax : Counter.keys()Parameters : NoneReturns : object of class dict_items
Example :
Python3
# importing the modulefrom collections import Counter # making a listlist = [1, 1, 2, 3, 4, 5, 6, 7, 9, 2, 3, 4, 8] # instantiating a Counter objectob = Counter(list) # Counter.keys()keys = ob.keys() print("The datatype is " + str(type(keys))) # displaying the dict_itemsprint(keys) # iterating over the dict_itemsfor i in keys: print(i)
Output :
The datatype is dict_keys([1, 2, 3, 4, 5, 6, 7, 9, 8]) 1 2 3 4 5 6 7 9 8
The Counter.values() method helps to see the frequencies of each unique element.
Syntax : Counter.values()Parameters : NoneReturns : object of class dict_items
Example :
Python3
# importing the modulefrom collections import Counter # making a listlist = [1, 1, 2, 3, 4, 5, 6, 7, 9, 2, 3, 4, 8] # instantiating a Counter objectob = Counter(list) # Counter.values()values = ob.values() print("The datatype is " + str(type(values))) # displaying the dict_itemsprint(values) # iterating over the dict_itemsfor i in values: print(i)
Output :
The datatype is dict_values([2, 2, 2, 2, 1, 1, 1, 1, 1]) 2 2 2 2 1 1 1 1 1
anikaseth98
Python collections-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 Oct, 2021"
},
{
"code": null,
"e": 437,
"s": 28,
"text": "Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python’s general-purpose built-ins like dictionaries, lists and tuples. Counter is a sub-class that is used to count hashable objects. It implicitly creates a hash table of an iterable when invoked. "
},
{
"code": null,
"e": 556,
"s": 437,
"text": "The Counter.items() method helps to see the elements of the list along with their respective frequencies in a tuple. "
},
{
"code": null,
"e": 636,
"s": 556,
"text": "Syntax : Counter.items()Parameters : NoneReturns : object of class dict_items "
},
{
"code": null,
"e": 648,
"s": 636,
"text": "Example : "
},
{
"code": null,
"e": 656,
"s": 648,
"text": "Python3"
},
{
"code": "# importing the modulefrom collections import Counter # making a listlist = [1, 1, 2, 3, 4, 5, 6, 7, 9, 2, 3, 4, 8] # instantiating a Counter objectob = Counter(list) # Counter.items()items = ob.items() print(\"The datatype is \" + str(type(items))) # displaying the dict_itemsprint(items) # iterating over the dict_itemsfor i in items: print(i)",
"e": 1015,
"s": 656,
"text": null
},
{
"code": null,
"e": 1026,
"s": 1015,
"text": "Output : "
},
{
"code": null,
"e": 1192,
"s": 1026,
"text": "The datatype is dict_items([(1, 2), (2, 2), (3, 2), (4, 2), (5, 1), (6, 1), (7, 1), (9, 1), (8, 1)]) (1, 2) (2, 2) (3, 2) (4, 2) (5, 1) (6, 1) (7, 1) (9, 1) (8, 1) "
},
{
"code": null,
"e": 1267,
"s": 1194,
"text": "The Counter.keys() method helps to see the unique elements in the list. "
},
{
"code": null,
"e": 1346,
"s": 1267,
"text": "Syntax : Counter.keys()Parameters : NoneReturns : object of class dict_items "
},
{
"code": null,
"e": 1358,
"s": 1346,
"text": "Example : "
},
{
"code": null,
"e": 1366,
"s": 1358,
"text": "Python3"
},
{
"code": "# importing the modulefrom collections import Counter # making a listlist = [1, 1, 2, 3, 4, 5, 6, 7, 9, 2, 3, 4, 8] # instantiating a Counter objectob = Counter(list) # Counter.keys()keys = ob.keys() print(\"The datatype is \" + str(type(keys))) # displaying the dict_itemsprint(keys) # iterating over the dict_itemsfor i in keys: print(i)",
"e": 1719,
"s": 1366,
"text": null
},
{
"code": null,
"e": 1730,
"s": 1719,
"text": "Output : "
},
{
"code": null,
"e": 1805,
"s": 1730,
"text": "The datatype is dict_keys([1, 2, 3, 4, 5, 6, 7, 9, 8]) 1 2 3 4 5 6 7 9 8 "
},
{
"code": null,
"e": 1890,
"s": 1807,
"text": "The Counter.values() method helps to see the frequencies of each unique element. "
},
{
"code": null,
"e": 1971,
"s": 1890,
"text": "Syntax : Counter.values()Parameters : NoneReturns : object of class dict_items "
},
{
"code": null,
"e": 1983,
"s": 1971,
"text": "Example : "
},
{
"code": null,
"e": 1991,
"s": 1983,
"text": "Python3"
},
{
"code": "# importing the modulefrom collections import Counter # making a listlist = [1, 1, 2, 3, 4, 5, 6, 7, 9, 2, 3, 4, 8] # instantiating a Counter objectob = Counter(list) # Counter.values()values = ob.values() print(\"The datatype is \" + str(type(values))) # displaying the dict_itemsprint(values) # iterating over the dict_itemsfor i in values: print(i)",
"e": 2356,
"s": 1991,
"text": null
},
{
"code": null,
"e": 2367,
"s": 2356,
"text": "Output : "
},
{
"code": null,
"e": 2444,
"s": 2367,
"text": "The datatype is dict_values([2, 2, 2, 2, 1, 1, 1, 1, 1]) 2 2 2 2 1 1 1 1 1 "
},
{
"code": null,
"e": 2458,
"s": 2446,
"text": "anikaseth98"
},
{
"code": null,
"e": 2484,
"s": 2458,
"text": "Python collections-module"
},
{
"code": null,
"e": 2491,
"s": 2484,
"text": "Python"
}
]
|
Matplotlib.pyplot.xkcd() in Python | 24 Feb, 2022
One of the main process in Data Science is Data Visualization. Data Visualization refers to present a dataset in the form of graphs and pictures. We can identify upcoming trend by observing these Graphs.
Python provides us with an amazing Data Visualization library in it which is Matplotlib which was developed by John Hunter (1968-2012). Matplotlib is built on numpy and sideby framework that’s why it is fast and efficient. It is open-source and has huge community support.It possesses the ability to work well with many operating systems and graphic backends.
Generally, plots generated by matplotlib are very perfect as well as monotonous. Observing these graphs are not that much fun. Matplotlib provides a library that can make these graphs a bit interesting and draws graphs in comic style. These graphs are interesting and everyone would love to study through these graphs.
For Example :
Parameters :All three parameters in xkcd() are optional.
Example 1:
Lets generate a sine wave in xkcd() style
Python3
import numpy as npimport matplotlib.pyplot as plt time = np.arange(0, 10, 0.1);amplitude = np.sin(time) with plt.xkcd(): plt.plot(time, amplitude) plt.title('Sine wave') plt.xlabel('Time') plt.ylabel('Amplitude = sin(time)') plt.axhline(y = 0, color ='k') plt.show()
Output :
Example 2:
Python3
import numpy as npimport matplotlib.pyplot as plt with plt.xkcd(): plt.plot([1, 2, 3, 4], [5, 4, 9, 2]) plt.title('matplotlib.pyplot.xkcd()') plt.axhline(y = 0, color ='k') plt.show()
Output:
surinderdawra388
kapoorsagar226
varshagumber28
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": 28,
"s": 0,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 232,
"s": 28,
"text": "One of the main process in Data Science is Data Visualization. Data Visualization refers to present a dataset in the form of graphs and pictures. We can identify upcoming trend by observing these Graphs."
},
{
"code": null,
"e": 593,
"s": 232,
"text": "Python provides us with an amazing Data Visualization library in it which is Matplotlib which was developed by John Hunter (1968-2012). Matplotlib is built on numpy and sideby framework that’s why it is fast and efficient. It is open-source and has huge community support.It possesses the ability to work well with many operating systems and graphic backends. "
},
{
"code": null,
"e": 913,
"s": 593,
"text": "Generally, plots generated by matplotlib are very perfect as well as monotonous. Observing these graphs are not that much fun. Matplotlib provides a library that can make these graphs a bit interesting and draws graphs in comic style. These graphs are interesting and everyone would love to study through these graphs. "
},
{
"code": null,
"e": 929,
"s": 913,
"text": "For Example : "
},
{
"code": null,
"e": 987,
"s": 929,
"text": "Parameters :All three parameters in xkcd() are optional. "
},
{
"code": null,
"e": 999,
"s": 987,
"text": "Example 1: "
},
{
"code": null,
"e": 1043,
"s": 999,
"text": "Lets generate a sine wave in xkcd() style "
},
{
"code": null,
"e": 1051,
"s": 1043,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt time = np.arange(0, 10, 0.1);amplitude = np.sin(time) with plt.xkcd(): plt.plot(time, amplitude) plt.title('Sine wave') plt.xlabel('Time') plt.ylabel('Amplitude = sin(time)') plt.axhline(y = 0, color ='k') plt.show()",
"e": 1341,
"s": 1051,
"text": null
},
{
"code": null,
"e": 1351,
"s": 1341,
"text": "Output : "
},
{
"code": null,
"e": 1362,
"s": 1351,
"text": "Example 2:"
},
{
"code": null,
"e": 1370,
"s": 1362,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt with plt.xkcd(): plt.plot([1, 2, 3, 4], [5, 4, 9, 2]) plt.title('matplotlib.pyplot.xkcd()') plt.axhline(y = 0, color ='k') plt.show()",
"e": 1572,
"s": 1370,
"text": null
},
{
"code": null,
"e": 1580,
"s": 1572,
"text": "Output:"
},
{
"code": null,
"e": 1599,
"s": 1582,
"text": "surinderdawra388"
},
{
"code": null,
"e": 1614,
"s": 1599,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 1629,
"s": 1614,
"text": "varshagumber28"
},
{
"code": null,
"e": 1647,
"s": 1629,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 1654,
"s": 1647,
"text": "Python"
},
{
"code": null,
"e": 1752,
"s": 1654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1784,
"s": 1752,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1811,
"s": 1784,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1842,
"s": 1811,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1865,
"s": 1842,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1886,
"s": 1865,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1942,
"s": 1886,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1984,
"s": 1942,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2026,
"s": 1984,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2065,
"s": 2026,
"text": "Python | Get unique values from a list"
}
]
|
Remove elements from array using JavaScript filter - JavaScript | Suppose, we have two arrays of literals like these −
const arr1 = [4, 23, 7, 6, 3, 6, 4, 3, 56, 4];
const arr2 = [4, 56, 23];
We are required to write a JavaScript function that takes in these two arrays and filters the first to contain only those elements that are not present in the second array.
And then return the filtered array to get the below output −
const output = [7, 6, 3, 6, 3];
Following is the code −
const arr1 = [4, 23, 7, 6, 3, 6, 4, 3, 56, 4];
const arr2 = [4, 56, 23];
const filterArray = (arr1, arr2) => {
const filtered = arr1.filter(el => {
return arr2.indexOf(el) === -1;
});
return filtered;
};
console.log(filterArray(arr1, arr2));
This will produce the following output in console −
[ 7, 6, 3, 6, 3 ] | [
{
"code": null,
"e": 1240,
"s": 1187,
"text": "Suppose, we have two arrays of literals like these −"
},
{
"code": null,
"e": 1313,
"s": 1240,
"text": "const arr1 = [4, 23, 7, 6, 3, 6, 4, 3, 56, 4];\nconst arr2 = [4, 56, 23];"
},
{
"code": null,
"e": 1486,
"s": 1313,
"text": "We are required to write a JavaScript function that takes in these two arrays and filters the first to contain only those elements that are not present in the second array."
},
{
"code": null,
"e": 1547,
"s": 1486,
"text": "And then return the filtered array to get the below output −"
},
{
"code": null,
"e": 1579,
"s": 1547,
"text": "const output = [7, 6, 3, 6, 3];"
},
{
"code": null,
"e": 1603,
"s": 1579,
"text": "Following is the code −"
},
{
"code": null,
"e": 1860,
"s": 1603,
"text": "const arr1 = [4, 23, 7, 6, 3, 6, 4, 3, 56, 4];\nconst arr2 = [4, 56, 23];\nconst filterArray = (arr1, arr2) => {\n const filtered = arr1.filter(el => {\n return arr2.indexOf(el) === -1;\n });\n return filtered;\n};\nconsole.log(filterArray(arr1, arr2));"
},
{
"code": null,
"e": 1912,
"s": 1860,
"text": "This will produce the following output in console −"
},
{
"code": null,
"e": 1930,
"s": 1912,
"text": "[ 7, 6, 3, 6, 3 ]"
}
]
|
Maximum value of short int in C++ | 21 Jun, 2022
In this article, we will discuss the short int data type in C++. This data type in C++ is used to store 16-bit integers.
Some properties of the short int data type are:
Being a signed data type, it can store positive values as well as negative values.Takes a size of 16 bits, where 1 bit is used to store the sign of the integer.A maximum integer value that can be stored in a short int data type is typically 32767, around 215-1(but is compiler dependent).The maximum value that can be stored in short int is stored as a constant in <climits> header file. Whose value can be used as SHRT_MAX.The minimum value that can be stored in short int is stored as a constant in <climits> header file. Whose value can be used as SHRT_MIN.A minimum integer value that can be stored in a short int data type is typically -32768 around (-215+1) (but is compiler dependent).In case of overflow or underflow of data type, the value is wrapped around. For example, if -32768 is stored in a short int data type and 1 is subtracted from it, the value in that variable will become equal to 32767. Similarly, in the case of overflow, the value will round back to -32768.
Being a signed data type, it can store positive values as well as negative values.
Takes a size of 16 bits, where 1 bit is used to store the sign of the integer.
A maximum integer value that can be stored in a short int data type is typically 32767, around 215-1(but is compiler dependent).
The maximum value that can be stored in short int is stored as a constant in <climits> header file. Whose value can be used as SHRT_MAX.
The minimum value that can be stored in short int is stored as a constant in <climits> header file. Whose value can be used as SHRT_MIN.
A minimum integer value that can be stored in a short int data type is typically -32768 around (-215+1) (but is compiler dependent).
In case of overflow or underflow of data type, the value is wrapped around. For example, if -32768 is stored in a short int data type and 1 is subtracted from it, the value in that variable will become equal to 32767. Similarly, in the case of overflow, the value will round back to -32768.
Below is the program to get the highest value that can be stored in unsigned long long int in C++:
C++
// C++ program to obtain themaximum// value that can be store in short int#include <climits>#include <iostream>using namespace std; // Driver Codeint main(){ // From the constant of climits // header file short int valueFromLimits = SHRT_MAX; cout << "Value from climits " << "constant (maximum): " << valueFromLimits << "\n"; valueFromLimits = SHRT_MIN; cout << "Value from climits " << "constant (minimum): " << valueFromLimits << "\n"; // Using the wrap around property // of data types // Initialize two variables with // -1 as previous and 0 as present short int previous = -1; short int present = 0; // Increment both values until the // present increases to the max limit // and wraps around to the negative // value i.e., present becomes less // than the previous value while (present > previous) { previous++; present++; } cout << "Value using the wrap " << "around property :\n"; cout << "Maximum: " << previous << "\n"; cout << "Minimum: " << present << "\n"; return 0;}
Value from climits constant (maximum): 32767
Value from climits constant (minimum): -32768
Value using the wrap around property :
Maximum: 32767
Minimum: -32768
Time Complexity: O(N)Auxiliary Space: O(1)
jayanth_mkv
Data Type
Data Types
C++
C++ Programs
Data Type
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++ | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 174,
"s": 53,
"text": "In this article, we will discuss the short int data type in C++. This data type in C++ is used to store 16-bit integers."
},
{
"code": null,
"e": 222,
"s": 174,
"text": "Some properties of the short int data type are:"
},
{
"code": null,
"e": 1205,
"s": 222,
"text": "Being a signed data type, it can store positive values as well as negative values.Takes a size of 16 bits, where 1 bit is used to store the sign of the integer.A maximum integer value that can be stored in a short int data type is typically 32767, around 215-1(but is compiler dependent).The maximum value that can be stored in short int is stored as a constant in <climits> header file. Whose value can be used as SHRT_MAX.The minimum value that can be stored in short int is stored as a constant in <climits> header file. Whose value can be used as SHRT_MIN.A minimum integer value that can be stored in a short int data type is typically -32768 around (-215+1) (but is compiler dependent).In case of overflow or underflow of data type, the value is wrapped around. For example, if -32768 is stored in a short int data type and 1 is subtracted from it, the value in that variable will become equal to 32767. Similarly, in the case of overflow, the value will round back to -32768."
},
{
"code": null,
"e": 1288,
"s": 1205,
"text": "Being a signed data type, it can store positive values as well as negative values."
},
{
"code": null,
"e": 1367,
"s": 1288,
"text": "Takes a size of 16 bits, where 1 bit is used to store the sign of the integer."
},
{
"code": null,
"e": 1496,
"s": 1367,
"text": "A maximum integer value that can be stored in a short int data type is typically 32767, around 215-1(but is compiler dependent)."
},
{
"code": null,
"e": 1633,
"s": 1496,
"text": "The maximum value that can be stored in short int is stored as a constant in <climits> header file. Whose value can be used as SHRT_MAX."
},
{
"code": null,
"e": 1770,
"s": 1633,
"text": "The minimum value that can be stored in short int is stored as a constant in <climits> header file. Whose value can be used as SHRT_MIN."
},
{
"code": null,
"e": 1903,
"s": 1770,
"text": "A minimum integer value that can be stored in a short int data type is typically -32768 around (-215+1) (but is compiler dependent)."
},
{
"code": null,
"e": 2194,
"s": 1903,
"text": "In case of overflow or underflow of data type, the value is wrapped around. For example, if -32768 is stored in a short int data type and 1 is subtracted from it, the value in that variable will become equal to 32767. Similarly, in the case of overflow, the value will round back to -32768."
},
{
"code": null,
"e": 2294,
"s": 2194,
"text": "Below is the program to get the highest value that can be stored in unsigned long long int in C++: "
},
{
"code": null,
"e": 2298,
"s": 2294,
"text": "C++"
},
{
"code": "// C++ program to obtain themaximum// value that can be store in short int#include <climits>#include <iostream>using namespace std; // Driver Codeint main(){ // From the constant of climits // header file short int valueFromLimits = SHRT_MAX; cout << \"Value from climits \" << \"constant (maximum): \" << valueFromLimits << \"\\n\"; valueFromLimits = SHRT_MIN; cout << \"Value from climits \" << \"constant (minimum): \" << valueFromLimits << \"\\n\"; // Using the wrap around property // of data types // Initialize two variables with // -1 as previous and 0 as present short int previous = -1; short int present = 0; // Increment both values until the // present increases to the max limit // and wraps around to the negative // value i.e., present becomes less // than the previous value while (present > previous) { previous++; present++; } cout << \"Value using the wrap \" << \"around property :\\n\"; cout << \"Maximum: \" << previous << \"\\n\"; cout << \"Minimum: \" << present << \"\\n\"; return 0;}",
"e": 3410,
"s": 2298,
"text": null
},
{
"code": null,
"e": 3571,
"s": 3410,
"text": "Value from climits constant (maximum): 32767\nValue from climits constant (minimum): -32768\nValue using the wrap around property :\nMaximum: 32767\nMinimum: -32768"
},
{
"code": null,
"e": 3614,
"s": 3571,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3626,
"s": 3614,
"text": "jayanth_mkv"
},
{
"code": null,
"e": 3636,
"s": 3626,
"text": "Data Type"
},
{
"code": null,
"e": 3647,
"s": 3636,
"text": "Data Types"
},
{
"code": null,
"e": 3651,
"s": 3647,
"text": "C++"
},
{
"code": null,
"e": 3664,
"s": 3651,
"text": "C++ Programs"
},
{
"code": null,
"e": 3674,
"s": 3664,
"text": "Data Type"
},
{
"code": null,
"e": 3678,
"s": 3674,
"text": "CPP"
},
{
"code": null,
"e": 3776,
"s": 3678,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3800,
"s": 3776,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 3820,
"s": 3800,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 3853,
"s": 3820,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 3897,
"s": 3853,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3922,
"s": 3897,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3957,
"s": 3922,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 3991,
"s": 3957,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 4035,
"s": 3991,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 4094,
"s": 4035,
"text": "How to return multiple values from a function in C or C++?"
}
]
|
Efficient Huffman Coding for Sorted Input | Greedy Algo-4 | 08 Jul, 2021
We recommend to read following post as a prerequisite for this.Greedy Algorithms | Set 3 (Huffman Coding)
Time complexity of the algorithm discussed in above post is O(nLogn). If we know that the given array is sorted (by non-decreasing order of frequency), we can generate Huffman codes in O(n) time. Following is a O(n) algorithm for sorted input.1. Create two empty queues.2. Create a leaf node for each unique character and Enqueue it to the first queue in non-decreasing order of frequency. Initially second queue is empty.3. Dequeue two nodes with the minimum frequency by examining the front of both queues. Repeat following steps two times 1. If second queue is empty, dequeue from first queue. 2. If first queue is empty, dequeue from second queue. 3. Else, compare the front of two queues and dequeue the minimum. 4. Create a new internal node with frequency equal to the sum of the two nodes frequencies. Make the first Dequeued node as its left child and the second Dequeued node as right child. Enqueue this node to second queue.5. Repeat steps#3 and #4 while there is more than one node in the queues. The remaining node is the root node and the tree is complete.
C++
C
Python3
// C++ Program for Efficient Huffman Coding for Sorted input#include <bits/stdc++.h>using namespace std; // This constant can be avoided by explicitly// calculating height of Huffman Tree#define MAX_TREE_HT 100 // A node of huffman treeclass QueueNode {public: char data; unsigned freq; QueueNode *left, *right;}; // Structure for Queue: collection// of Huffman Tree nodes (or QueueNodes)class Queue {public: int front, rear; int capacity; QueueNode** array;}; // A utility function to create a new QueuenodeQueueNode* newNode(char data, unsigned freq){ QueueNode* temp = new QueueNode[(sizeof(QueueNode))]; temp->left = temp->right = NULL; temp->data = data; temp->freq = freq; return temp;} // A utility function to create a Queue of given capacityQueue* createQueue(int capacity){ Queue* queue = new Queue[(sizeof(Queue))]; queue->front = queue->rear = -1; queue->capacity = capacity; queue->array = new QueueNode*[(queue->capacity * sizeof(QueueNode*))]; return queue;} // A utility function to check if size of given queue is 1int isSizeOne(Queue* queue){ return queue->front == queue->rear && queue->front != -1;} // A utility function to check if given queue is emptyint isEmpty(Queue* queue) { return queue->front == -1; } // A utility function to check if given queue is fullint isFull(Queue* queue){ return queue->rear == queue->capacity - 1;} // A utility function to add an item to queuevoid enQueue(Queue* queue, QueueNode* item){ if (isFull(queue)) return; queue->array[++queue->rear] = item; if (queue->front == -1) ++queue->front;} // A utility function to remove an item from queueQueueNode* deQueue(Queue* queue){ if (isEmpty(queue)) return NULL; QueueNode* temp = queue->array[queue->front]; if (queue->front == queue ->rear) // If there is only one item in queue queue->front = queue->rear = -1; else ++queue->front; return temp;} // A utility function to get from of queueQueueNode* getFront(Queue* queue){ if (isEmpty(queue)) return NULL; return queue->array[queue->front];} /* A function to get minimum item from two queues */QueueNode* findMin(Queue* firstQueue, Queue* secondQueue){ // Step 3.a: If first queue is empty, dequeue from // second queue if (isEmpty(firstQueue)) return deQueue(secondQueue); // Step 3.b: If second queue is empty, dequeue from // first queue if (isEmpty(secondQueue)) return deQueue(firstQueue); // Step 3.c: Else, compare the front of two queues and // dequeue minimum if (getFront(firstQueue)->freq < getFront(secondQueue)->freq) return deQueue(firstQueue); return deQueue(secondQueue);} // Utility function to check if this node is leafint isLeaf(QueueNode* root){ return !(root->left) && !(root->right);} // A utility function to print an array of size nvoid printArr(int arr[], int n){ int i; for (i = 0; i < n; ++i) cout << arr[i]; cout << endl;} // The main function that builds Huffman treeQueueNode* buildHuffmanTree(char data[], int freq[], int size){ QueueNode *left, *right, *top; // Step 1: Create two empty queues Queue* firstQueue = createQueue(size); Queue* secondQueue = createQueue(size); // Step 2:Create a leaf node for each unique character // and Enqueue it to the first queue in non-decreasing // order of frequency. Initially second queue is empty for (int i = 0; i < size; ++i) enQueue(firstQueue, newNode(data[i], freq[i])); // Run while Queues contain more than one node. Finally, // first queue will be empty and second queue will // contain only one node while ( !(isEmpty(firstQueue) && isSizeOne(secondQueue))) { // Step 3: Dequeue two nodes with the minimum // frequency by examining the front of both queues left = findMin(firstQueue, secondQueue); right = findMin(firstQueue, secondQueue); // Step 4: Create a new internal node with frequency // equal to the sum of the two nodes frequencies. // Enqueue this node to second queue. top = newNode('$', left->freq + right->freq); top->left = left; top->right = right; enQueue(secondQueue, top); } return deQueue(secondQueue);} // Prints huffman codes from the root of Huffman Tree. It// uses arr[] to store codesvoid printCodes(QueueNode* root, int arr[], int top){ // Assign 0 to left edge and recur if (root->left) { arr[top] = 0; printCodes(root->left, arr, top + 1); } // Assign 1 to right edge and recur if (root->right) { arr[top] = 1; printCodes(root->right, arr, top + 1); } // If this is a leaf node, then it contains one of the // input characters, print the character and its code // from arr[] if (isLeaf(root)) { cout << root->data << ": "; printArr(arr, top); }} // The main function that builds a Huffman Tree and print// codes by traversing the built Huffman Treevoid HuffmanCodes(char data[], int freq[], int size){ // Construct Huffman Tree QueueNode* root = buildHuffmanTree(data, freq, size); // Print Huffman codes using the Huffman tree built // above int arr[MAX_TREE_HT], top = 0; printCodes(root, arr, top);} // Driver codeint main(){ char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; int freq[] = { 5, 9, 12, 13, 16, 45 }; int size = sizeof(arr) / sizeof(arr[0]); HuffmanCodes(arr, freq, size); return 0;} // This code is contributed by rathbhupendra
// C Program for Efficient Huffman Coding for Sorted input#include <stdio.h>#include <stdlib.h> // This constant can be avoided by explicitly calculating// height of Huffman Tree#define MAX_TREE_HT 100 // A node of huffman treestruct QueueNode { char data; unsigned freq; struct QueueNode *left, *right;}; // Structure for Queue: collection of Huffman Tree nodes (or// QueueNodes)struct Queue { int front, rear; int capacity; struct QueueNode** array;}; // A utility function to create a new Queuenodestruct QueueNode* newNode(char data, unsigned freq){ struct QueueNode* temp = (struct QueueNode*)malloc( sizeof(struct QueueNode)); temp->left = temp->right = NULL; temp->data = data; temp->freq = freq; return temp;} // A utility function to create a Queue of given capacitystruct Queue* createQueue(int capacity){ struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue)); queue->front = queue->rear = -1; queue->capacity = capacity; queue->array = (struct QueueNode**)malloc( queue->capacity * sizeof(struct QueueNode*)); return queue;} // A utility function to check if size of given queue is 1int isSizeOne(struct Queue* queue){ return queue->front == queue->rear && queue->front != -1;} // A utility function to check if given queue is emptyint isEmpty(struct Queue* queue){ return queue->front == -1;} // A utility function to check if given queue is fullint isFull(struct Queue* queue){ return queue->rear == queue->capacity - 1;} // A utility function to add an item to queuevoid enQueue(struct Queue* queue, struct QueueNode* item){ if (isFull(queue)) return; queue->array[++queue->rear] = item; if (queue->front == -1) ++queue->front;} // A utility function to remove an item from queuestruct QueueNode* deQueue(struct Queue* queue){ if (isEmpty(queue)) return NULL; struct QueueNode* temp = queue->array[queue->front]; if (queue->front == queue ->rear) // If there is only one item in queue queue->front = queue->rear = -1; else ++queue->front; return temp;} // A utility function to get from of queuestruct QueueNode* getFront(struct Queue* queue){ if (isEmpty(queue)) return NULL; return queue->array[queue->front];} /* A function to get minimum item from two queues */struct QueueNode* findMin(struct Queue* firstQueue, struct Queue* secondQueue){ // Step 3.a: If first queue is empty, dequeue from // second queue if (isEmpty(firstQueue)) return deQueue(secondQueue); // Step 3.b: If second queue is empty, dequeue from // first queue if (isEmpty(secondQueue)) return deQueue(firstQueue); // Step 3.c: Else, compare the front of two queues and // dequeue minimum if (getFront(firstQueue)->freq < getFront(secondQueue)->freq) return deQueue(firstQueue); return deQueue(secondQueue);} // Utility function to check if this node is leafint isLeaf(struct QueueNode* root){ return !(root->left) && !(root->right);} // A utility function to print an array of size nvoid printArr(int arr[], int n){ int i; for (i = 0; i < n; ++i) printf("%d", arr[i]); printf("\n");} // The main function that builds Huffman treestruct QueueNode* buildHuffmanTree(char data[], int freq[], int size){ struct QueueNode *left, *right, *top; // Step 1: Create two empty queues struct Queue* firstQueue = createQueue(size); struct Queue* secondQueue = createQueue(size); // Step 2:Create a leaf node for each unique character // and Enqueue it to the first queue in non-decreasing // order of frequency. Initially second queue is empty for (int i = 0; i < size; ++i) enQueue(firstQueue, newNode(data[i], freq[i])); // Run while Queues contain more than one node. Finally, // first queue will be empty and second queue will // contain only one node while ( !(isEmpty(firstQueue) && isSizeOne(secondQueue))) { // Step 3: Dequeue two nodes with the minimum // frequency by examining the front of both queues left = findMin(firstQueue, secondQueue); right = findMin(firstQueue, secondQueue); // Step 4: Create a new internal node with frequency // equal to the sum of the two nodes frequencies. // Enqueue this node to second queue. top = newNode('$', left->freq + right->freq); top->left = left; top->right = right; enQueue(secondQueue, top); } return deQueue(secondQueue);} // Prints huffman codes from the root of Huffman Tree. It// uses arr[] to store codesvoid printCodes(struct QueueNode* root, int arr[], int top){ // Assign 0 to left edge and recur if (root->left) { arr[top] = 0; printCodes(root->left, arr, top + 1); } // Assign 1 to right edge and recur if (root->right) { arr[top] = 1; printCodes(root->right, arr, top + 1); } // If this is a leaf node, then it contains one of the // input characters, print the character and its code // from arr[] if (isLeaf(root)) { printf("%c: ", root->data); printArr(arr, top); }} // The main function that builds a Huffman Tree and print// codes by traversing the built Huffman Treevoid HuffmanCodes(char data[], int freq[], int size){ // Construct Huffman Tree struct QueueNode* root = buildHuffmanTree(data, freq, size); // Print Huffman codes using the Huffman tree built // above int arr[MAX_TREE_HT], top = 0; printCodes(root, arr, top);} // Driver program to test above functionsint main(){ char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; int freq[] = { 5, 9, 12, 13, 16, 45 }; int size = sizeof(arr) / sizeof(arr[0]); HuffmanCodes(arr, freq, size); return 0;}
# Python3 program for Efficient Huffman Coding# for Sorted input # Class for the nodes of the Huffman treeclass QueueNode: def __init__(self, data = None, freq = None, left = None, right = None): self.data = data self.freq = freq self.left = left self.right = right # Function to check if the following # node is a leaf node def isLeaf(self): return (self.left == None and self.right == None) # Class for the two Queuesclass Queue: def __init__(self): self.queue = [] # Function for checking if the # queue has only 1 node def isSizeOne(self): return len(self.queue) == 1 # Function for checking if # the queue is empty def isEmpty(self): return self.queue == [] # Function to add item to the queue def enqueue(self, x): self.queue.append(x) # Function to remove item from the queue def dequeue(self): return self.queue.pop(0) # Function to get minimum item from two queuesdef findMin(firstQueue, secondQueue): # Step 3.1: If second queue is empty, # dequeue from first queue if secondQueue.isEmpty(): return firstQueue.dequeue() # Step 3.2: If first queue is empty, # dequeue from second queue if firstQueue.isEmpty(): return secondQueue.dequeue() # Step 3.3: Else, compare the front of # two queues and dequeue minimum if (firstQueue.queue[0].freq < secondQueue.queue[0].freq): return firstQueue.dequeue() return secondQueue.dequeue() # The main function that builds Huffman treedef buildHuffmanTree(data, freq, size): # Step 1: Create two empty queues firstQueue = Queue() secondQueue = Queue() # Step 2: Create a leaf node for each unique # character and Enqueue it to the first queue # in non-decreasing order of frequency. # Initially second queue is empty. for i in range(size): firstQueue.enqueue(QueueNode(data[i], freq[i])) # Run while Queues contain more than one node. # Finally, first queue will be empty and # second queue will contain only one node while not (firstQueue.isEmpty() and secondQueue.isSizeOne()): # Step 3: Dequeue two nodes with the minimum # frequency by examining the front of both queues left = findMin(firstQueue, secondQueue) right = findMin(firstQueue, secondQueue) # Step 4: Create a new internal node with # frequency equal to the sum of the two # nodes frequencies. Enqueue this node # to second queue. top = QueueNode("$", left.freq + right.freq, left, right) secondQueue.enqueue(top) return secondQueue.dequeue() # Prints huffman codes from the root of# Huffman tree. It uses arr[] to store codesdef printCodes(root, arr): # Assign 0 to left edge and recur if root.left: arr.append(0) printCodes(root.left, arr) arr.pop(-1) # Assign 1 to right edge and recur if root.right: arr.append(1) printCodes(root.right, arr) arr.pop(-1) # If this is a leaf node, then it contains # one of the input characters, print the # character and its code from arr[] if root.isLeaf(): print(f"{root.data}: ", end = "") for i in arr: print(i, end = "") print() # The main function that builds a Huffman# tree and print codes by traversing the# built Huffman treedef HuffmanCodes(data, freq, size): # Construct Huffman Tree root = buildHuffmanTree(data, freq, size) # Print Huffman codes using the Huffman # tree built above arr = [] printCodes(root, arr) # Driver codearr = ["a", "b", "c", "d", "e", "f"]freq = [5, 9, 12, 13, 16, 45]size = len(arr) HuffmanCodes(arr, freq, size) # This code is contributed by Kevin Joshi
Output:
f: 0
c: 100
d: 101
a: 1100
b: 1101
e: 111
Time complexity: O(n)If the input is not sorted, it need to be sorted first before it can be processed by the above algorithm. Sorting can be done using heap-sort or merge-sort both of which run in Theta(nlogn). So, the overall time complexity becomes O(nlogn) for unsorted input.
Efficient Huffman Coding for Sorted Input | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersEfficient Huffman Coding for Sorted Input | 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 / 10:30•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=IX810fNtTzU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Reference: http://en.wikipedia.org/wiki/Huffman_codingThis article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
harrypotter0
rathbhupendra
mnadeembscs18seecs
kevinjoshi46b
encoding-decoding
Huffman Coding
Greedy
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Coin Change | DP-7
Activity Selection Problem | Greedy Algo-1
Fractional Knapsack Problem
Job Sequencing Problem
Policemen catch thieves
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Minimum Number of Platforms Required for a Railway/Bus Station
Difference between Prim's and Kruskal's algorithm for MST
3 Different ways to print Fibonacci series in Java
K Centers Problem | Set 1 (Greedy Approximate Algorithm) | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Jul, 2021"
},
{
"code": null,
"e": 160,
"s": 54,
"text": "We recommend to read following post as a prerequisite for this.Greedy Algorithms | Set 3 (Huffman Coding)"
},
{
"code": null,
"e": 1257,
"s": 160,
"text": "Time complexity of the algorithm discussed in above post is O(nLogn). If we know that the given array is sorted (by non-decreasing order of frequency), we can generate Huffman codes in O(n) time. Following is a O(n) algorithm for sorted input.1. Create two empty queues.2. Create a leaf node for each unique character and Enqueue it to the first queue in non-decreasing order of frequency. Initially second queue is empty.3. Dequeue two nodes with the minimum frequency by examining the front of both queues. Repeat following steps two times 1. If second queue is empty, dequeue from first queue. 2. If first queue is empty, dequeue from second queue. 3. Else, compare the front of two queues and dequeue the minimum. 4. Create a new internal node with frequency equal to the sum of the two nodes frequencies. Make the first Dequeued node as its left child and the second Dequeued node as right child. Enqueue this node to second queue.5. Repeat steps#3 and #4 while there is more than one node in the queues. The remaining node is the root node and the tree is complete. "
},
{
"code": null,
"e": 1261,
"s": 1257,
"text": "C++"
},
{
"code": null,
"e": 1263,
"s": 1261,
"text": "C"
},
{
"code": null,
"e": 1271,
"s": 1263,
"text": "Python3"
},
{
"code": "// C++ Program for Efficient Huffman Coding for Sorted input#include <bits/stdc++.h>using namespace std; // This constant can be avoided by explicitly// calculating height of Huffman Tree#define MAX_TREE_HT 100 // A node of huffman treeclass QueueNode {public: char data; unsigned freq; QueueNode *left, *right;}; // Structure for Queue: collection// of Huffman Tree nodes (or QueueNodes)class Queue {public: int front, rear; int capacity; QueueNode** array;}; // A utility function to create a new QueuenodeQueueNode* newNode(char data, unsigned freq){ QueueNode* temp = new QueueNode[(sizeof(QueueNode))]; temp->left = temp->right = NULL; temp->data = data; temp->freq = freq; return temp;} // A utility function to create a Queue of given capacityQueue* createQueue(int capacity){ Queue* queue = new Queue[(sizeof(Queue))]; queue->front = queue->rear = -1; queue->capacity = capacity; queue->array = new QueueNode*[(queue->capacity * sizeof(QueueNode*))]; return queue;} // A utility function to check if size of given queue is 1int isSizeOne(Queue* queue){ return queue->front == queue->rear && queue->front != -1;} // A utility function to check if given queue is emptyint isEmpty(Queue* queue) { return queue->front == -1; } // A utility function to check if given queue is fullint isFull(Queue* queue){ return queue->rear == queue->capacity - 1;} // A utility function to add an item to queuevoid enQueue(Queue* queue, QueueNode* item){ if (isFull(queue)) return; queue->array[++queue->rear] = item; if (queue->front == -1) ++queue->front;} // A utility function to remove an item from queueQueueNode* deQueue(Queue* queue){ if (isEmpty(queue)) return NULL; QueueNode* temp = queue->array[queue->front]; if (queue->front == queue ->rear) // If there is only one item in queue queue->front = queue->rear = -1; else ++queue->front; return temp;} // A utility function to get from of queueQueueNode* getFront(Queue* queue){ if (isEmpty(queue)) return NULL; return queue->array[queue->front];} /* A function to get minimum item from two queues */QueueNode* findMin(Queue* firstQueue, Queue* secondQueue){ // Step 3.a: If first queue is empty, dequeue from // second queue if (isEmpty(firstQueue)) return deQueue(secondQueue); // Step 3.b: If second queue is empty, dequeue from // first queue if (isEmpty(secondQueue)) return deQueue(firstQueue); // Step 3.c: Else, compare the front of two queues and // dequeue minimum if (getFront(firstQueue)->freq < getFront(secondQueue)->freq) return deQueue(firstQueue); return deQueue(secondQueue);} // Utility function to check if this node is leafint isLeaf(QueueNode* root){ return !(root->left) && !(root->right);} // A utility function to print an array of size nvoid printArr(int arr[], int n){ int i; for (i = 0; i < n; ++i) cout << arr[i]; cout << endl;} // The main function that builds Huffman treeQueueNode* buildHuffmanTree(char data[], int freq[], int size){ QueueNode *left, *right, *top; // Step 1: Create two empty queues Queue* firstQueue = createQueue(size); Queue* secondQueue = createQueue(size); // Step 2:Create a leaf node for each unique character // and Enqueue it to the first queue in non-decreasing // order of frequency. Initially second queue is empty for (int i = 0; i < size; ++i) enQueue(firstQueue, newNode(data[i], freq[i])); // Run while Queues contain more than one node. Finally, // first queue will be empty and second queue will // contain only one node while ( !(isEmpty(firstQueue) && isSizeOne(secondQueue))) { // Step 3: Dequeue two nodes with the minimum // frequency by examining the front of both queues left = findMin(firstQueue, secondQueue); right = findMin(firstQueue, secondQueue); // Step 4: Create a new internal node with frequency // equal to the sum of the two nodes frequencies. // Enqueue this node to second queue. top = newNode('$', left->freq + right->freq); top->left = left; top->right = right; enQueue(secondQueue, top); } return deQueue(secondQueue);} // Prints huffman codes from the root of Huffman Tree. It// uses arr[] to store codesvoid printCodes(QueueNode* root, int arr[], int top){ // Assign 0 to left edge and recur if (root->left) { arr[top] = 0; printCodes(root->left, arr, top + 1); } // Assign 1 to right edge and recur if (root->right) { arr[top] = 1; printCodes(root->right, arr, top + 1); } // If this is a leaf node, then it contains one of the // input characters, print the character and its code // from arr[] if (isLeaf(root)) { cout << root->data << \": \"; printArr(arr, top); }} // The main function that builds a Huffman Tree and print// codes by traversing the built Huffman Treevoid HuffmanCodes(char data[], int freq[], int size){ // Construct Huffman Tree QueueNode* root = buildHuffmanTree(data, freq, size); // Print Huffman codes using the Huffman tree built // above int arr[MAX_TREE_HT], top = 0; printCodes(root, arr, top);} // Driver codeint main(){ char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; int freq[] = { 5, 9, 12, 13, 16, 45 }; int size = sizeof(arr) / sizeof(arr[0]); HuffmanCodes(arr, freq, size); return 0;} // This code is contributed by rathbhupendra",
"e": 6927,
"s": 1271,
"text": null
},
{
"code": "// C Program for Efficient Huffman Coding for Sorted input#include <stdio.h>#include <stdlib.h> // This constant can be avoided by explicitly calculating// height of Huffman Tree#define MAX_TREE_HT 100 // A node of huffman treestruct QueueNode { char data; unsigned freq; struct QueueNode *left, *right;}; // Structure for Queue: collection of Huffman Tree nodes (or// QueueNodes)struct Queue { int front, rear; int capacity; struct QueueNode** array;}; // A utility function to create a new Queuenodestruct QueueNode* newNode(char data, unsigned freq){ struct QueueNode* temp = (struct QueueNode*)malloc( sizeof(struct QueueNode)); temp->left = temp->right = NULL; temp->data = data; temp->freq = freq; return temp;} // A utility function to create a Queue of given capacitystruct Queue* createQueue(int capacity){ struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue)); queue->front = queue->rear = -1; queue->capacity = capacity; queue->array = (struct QueueNode**)malloc( queue->capacity * sizeof(struct QueueNode*)); return queue;} // A utility function to check if size of given queue is 1int isSizeOne(struct Queue* queue){ return queue->front == queue->rear && queue->front != -1;} // A utility function to check if given queue is emptyint isEmpty(struct Queue* queue){ return queue->front == -1;} // A utility function to check if given queue is fullint isFull(struct Queue* queue){ return queue->rear == queue->capacity - 1;} // A utility function to add an item to queuevoid enQueue(struct Queue* queue, struct QueueNode* item){ if (isFull(queue)) return; queue->array[++queue->rear] = item; if (queue->front == -1) ++queue->front;} // A utility function to remove an item from queuestruct QueueNode* deQueue(struct Queue* queue){ if (isEmpty(queue)) return NULL; struct QueueNode* temp = queue->array[queue->front]; if (queue->front == queue ->rear) // If there is only one item in queue queue->front = queue->rear = -1; else ++queue->front; return temp;} // A utility function to get from of queuestruct QueueNode* getFront(struct Queue* queue){ if (isEmpty(queue)) return NULL; return queue->array[queue->front];} /* A function to get minimum item from two queues */struct QueueNode* findMin(struct Queue* firstQueue, struct Queue* secondQueue){ // Step 3.a: If first queue is empty, dequeue from // second queue if (isEmpty(firstQueue)) return deQueue(secondQueue); // Step 3.b: If second queue is empty, dequeue from // first queue if (isEmpty(secondQueue)) return deQueue(firstQueue); // Step 3.c: Else, compare the front of two queues and // dequeue minimum if (getFront(firstQueue)->freq < getFront(secondQueue)->freq) return deQueue(firstQueue); return deQueue(secondQueue);} // Utility function to check if this node is leafint isLeaf(struct QueueNode* root){ return !(root->left) && !(root->right);} // A utility function to print an array of size nvoid printArr(int arr[], int n){ int i; for (i = 0; i < n; ++i) printf(\"%d\", arr[i]); printf(\"\\n\");} // The main function that builds Huffman treestruct QueueNode* buildHuffmanTree(char data[], int freq[], int size){ struct QueueNode *left, *right, *top; // Step 1: Create two empty queues struct Queue* firstQueue = createQueue(size); struct Queue* secondQueue = createQueue(size); // Step 2:Create a leaf node for each unique character // and Enqueue it to the first queue in non-decreasing // order of frequency. Initially second queue is empty for (int i = 0; i < size; ++i) enQueue(firstQueue, newNode(data[i], freq[i])); // Run while Queues contain more than one node. Finally, // first queue will be empty and second queue will // contain only one node while ( !(isEmpty(firstQueue) && isSizeOne(secondQueue))) { // Step 3: Dequeue two nodes with the minimum // frequency by examining the front of both queues left = findMin(firstQueue, secondQueue); right = findMin(firstQueue, secondQueue); // Step 4: Create a new internal node with frequency // equal to the sum of the two nodes frequencies. // Enqueue this node to second queue. top = newNode('$', left->freq + right->freq); top->left = left; top->right = right; enQueue(secondQueue, top); } return deQueue(secondQueue);} // Prints huffman codes from the root of Huffman Tree. It// uses arr[] to store codesvoid printCodes(struct QueueNode* root, int arr[], int top){ // Assign 0 to left edge and recur if (root->left) { arr[top] = 0; printCodes(root->left, arr, top + 1); } // Assign 1 to right edge and recur if (root->right) { arr[top] = 1; printCodes(root->right, arr, top + 1); } // If this is a leaf node, then it contains one of the // input characters, print the character and its code // from arr[] if (isLeaf(root)) { printf(\"%c: \", root->data); printArr(arr, top); }} // The main function that builds a Huffman Tree and print// codes by traversing the built Huffman Treevoid HuffmanCodes(char data[], int freq[], int size){ // Construct Huffman Tree struct QueueNode* root = buildHuffmanTree(data, freq, size); // Print Huffman codes using the Huffman tree built // above int arr[MAX_TREE_HT], top = 0; printCodes(root, arr, top);} // Driver program to test above functionsint main(){ char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; int freq[] = { 5, 9, 12, 13, 16, 45 }; int size = sizeof(arr) / sizeof(arr[0]); HuffmanCodes(arr, freq, size); return 0;}",
"e": 12815,
"s": 6927,
"text": null
},
{
"code": "# Python3 program for Efficient Huffman Coding# for Sorted input # Class for the nodes of the Huffman treeclass QueueNode: def __init__(self, data = None, freq = None, left = None, right = None): self.data = data self.freq = freq self.left = left self.right = right # Function to check if the following # node is a leaf node def isLeaf(self): return (self.left == None and self.right == None) # Class for the two Queuesclass Queue: def __init__(self): self.queue = [] # Function for checking if the # queue has only 1 node def isSizeOne(self): return len(self.queue) == 1 # Function for checking if # the queue is empty def isEmpty(self): return self.queue == [] # Function to add item to the queue def enqueue(self, x): self.queue.append(x) # Function to remove item from the queue def dequeue(self): return self.queue.pop(0) # Function to get minimum item from two queuesdef findMin(firstQueue, secondQueue): # Step 3.1: If second queue is empty, # dequeue from first queue if secondQueue.isEmpty(): return firstQueue.dequeue() # Step 3.2: If first queue is empty, # dequeue from second queue if firstQueue.isEmpty(): return secondQueue.dequeue() # Step 3.3: Else, compare the front of # two queues and dequeue minimum if (firstQueue.queue[0].freq < secondQueue.queue[0].freq): return firstQueue.dequeue() return secondQueue.dequeue() # The main function that builds Huffman treedef buildHuffmanTree(data, freq, size): # Step 1: Create two empty queues firstQueue = Queue() secondQueue = Queue() # Step 2: Create a leaf node for each unique # character and Enqueue it to the first queue # in non-decreasing order of frequency. # Initially second queue is empty. for i in range(size): firstQueue.enqueue(QueueNode(data[i], freq[i])) # Run while Queues contain more than one node. # Finally, first queue will be empty and # second queue will contain only one node while not (firstQueue.isEmpty() and secondQueue.isSizeOne()): # Step 3: Dequeue two nodes with the minimum # frequency by examining the front of both queues left = findMin(firstQueue, secondQueue) right = findMin(firstQueue, secondQueue) # Step 4: Create a new internal node with # frequency equal to the sum of the two # nodes frequencies. Enqueue this node # to second queue. top = QueueNode(\"$\", left.freq + right.freq, left, right) secondQueue.enqueue(top) return secondQueue.dequeue() # Prints huffman codes from the root of# Huffman tree. It uses arr[] to store codesdef printCodes(root, arr): # Assign 0 to left edge and recur if root.left: arr.append(0) printCodes(root.left, arr) arr.pop(-1) # Assign 1 to right edge and recur if root.right: arr.append(1) printCodes(root.right, arr) arr.pop(-1) # If this is a leaf node, then it contains # one of the input characters, print the # character and its code from arr[] if root.isLeaf(): print(f\"{root.data}: \", end = \"\") for i in arr: print(i, end = \"\") print() # The main function that builds a Huffman# tree and print codes by traversing the# built Huffman treedef HuffmanCodes(data, freq, size): # Construct Huffman Tree root = buildHuffmanTree(data, freq, size) # Print Huffman codes using the Huffman # tree built above arr = [] printCodes(root, arr) # Driver codearr = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]freq = [5, 9, 12, 13, 16, 45]size = len(arr) HuffmanCodes(arr, freq, size) # This code is contributed by Kevin Joshi",
"e": 16709,
"s": 12815,
"text": null
},
{
"code": null,
"e": 16718,
"s": 16709,
"text": "Output: "
},
{
"code": null,
"e": 16760,
"s": 16718,
"text": "f: 0\nc: 100\nd: 101\na: 1100\nb: 1101\ne: 111"
},
{
"code": null,
"e": 17042,
"s": 16760,
"text": "Time complexity: O(n)If the input is not sorted, it need to be sorted first before it can be processed by the above algorithm. Sorting can be done using heap-sort or merge-sort both of which run in Theta(nlogn). So, the overall time complexity becomes O(nlogn) for unsorted input. "
},
{
"code": null,
"e": 17943,
"s": 17042,
"text": "Efficient Huffman Coding for Sorted Input | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersEfficient Huffman Coding for Sorted Input | 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 / 10:30•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=IX810fNtTzU\" 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": 18203,
"s": 17943,
"text": "Reference: http://en.wikipedia.org/wiki/Huffman_codingThis article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 18216,
"s": 18203,
"text": "harrypotter0"
},
{
"code": null,
"e": 18230,
"s": 18216,
"text": "rathbhupendra"
},
{
"code": null,
"e": 18249,
"s": 18230,
"text": "mnadeembscs18seecs"
},
{
"code": null,
"e": 18263,
"s": 18249,
"text": "kevinjoshi46b"
},
{
"code": null,
"e": 18281,
"s": 18263,
"text": "encoding-decoding"
},
{
"code": null,
"e": 18296,
"s": 18281,
"text": "Huffman Coding"
},
{
"code": null,
"e": 18303,
"s": 18296,
"text": "Greedy"
},
{
"code": null,
"e": 18310,
"s": 18303,
"text": "Greedy"
},
{
"code": null,
"e": 18408,
"s": 18310,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 18427,
"s": 18408,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 18470,
"s": 18427,
"text": "Activity Selection Problem | Greedy Algo-1"
},
{
"code": null,
"e": 18498,
"s": 18470,
"text": "Fractional Knapsack Problem"
},
{
"code": null,
"e": 18521,
"s": 18498,
"text": "Job Sequencing Problem"
},
{
"code": null,
"e": 18545,
"s": 18521,
"text": "Policemen catch thieves"
},
{
"code": null,
"e": 18626,
"s": 18545,
"text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)"
},
{
"code": null,
"e": 18689,
"s": 18626,
"text": "Minimum Number of Platforms Required for a Railway/Bus Station"
},
{
"code": null,
"e": 18747,
"s": 18689,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 18798,
"s": 18747,
"text": "3 Different ways to print Fibonacci series in Java"
}
]
|
Introduction to Dask in Python | 10 Jul, 2020
Dask is a library that supports parallel computing in python. It provides features like-
Dynamic task scheduling which is optimized for interactive computational workloadsBig data collections of dask extends the common interfaces like NumPy, Pandas etc.
Dynamic task scheduling which is optimized for interactive computational workloads
Big data collections of dask extends the common interfaces like NumPy, Pandas etc.
Most of the BigData analytics will be using Pandas, NumPy for analyzing big data. All the mentioned packages support a wide variety of computations. But when the dataset doesn’t fit in the memory these packages will not scale. Here comes dask. When the dataset doesn’t “fit in memory” dask extends the dataset to “fit into disk”. Dask allows us to easily scale out to clusters or scale down to single machine based on the size of the dataset.
To install this module type the below command in the terminal –
python -m pip install "dask[complete]"
Let’s see an example comparing dask and pandas. To download the dataset used in the below examples, click here.
1. Pandas Performance: Read the dataset using pd.read_csv()
Python3
import pandas as pd %time temp = pd.read_csv('dataset.csv', encoding = 'ISO-8859-1')
Output:
CPU times: user 619 ms, sys: 73.6 ms, total: 692 ms
Wall time: 705 ms
2. Dask Performance: Read the dataset using dask.dataframe.read_csv
Python3
import dask.dataframe as dd %time df = dd.read_csv("dataset.csv", encoding = 'ISO-8859-1')
Output:
CPU times: user 21.7 ms, sys: 938 μs, total: 22.7 ms
Wall time: 23.2 ms
Now a question might arise that how large datasets were handled using pandas before dask? There are few tricks handled to manage large datasets in pandas.
Using chunksize parameter of read_csv in pandasUse only needed columns while reading the csv files
Using chunksize parameter of read_csv in pandas
Use only needed columns while reading the csv files
The above techniques will be followed in most cases while reading large datasets using pandas. But in some cases, the above might not be useful at that time dask comes into play a major role.
There are certain limitations in dask.
Dask cannot parallelize within individual tasks.As a distributed-computing framework, dask enables remote execution of arbitrary code. So dask workers should be hosted within trusted network only.
Dask cannot parallelize within individual tasks.
As a distributed-computing framework, dask enables remote execution of arbitrary code. So dask workers should be hosted within trusted network only.
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python OOPs Concepts | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 142,
"s": 53,
"text": "Dask is a library that supports parallel computing in python. It provides features like-"
},
{
"code": null,
"e": 307,
"s": 142,
"text": "Dynamic task scheduling which is optimized for interactive computational workloadsBig data collections of dask extends the common interfaces like NumPy, Pandas etc."
},
{
"code": null,
"e": 390,
"s": 307,
"text": "Dynamic task scheduling which is optimized for interactive computational workloads"
},
{
"code": null,
"e": 473,
"s": 390,
"text": "Big data collections of dask extends the common interfaces like NumPy, Pandas etc."
},
{
"code": null,
"e": 917,
"s": 473,
"text": "Most of the BigData analytics will be using Pandas, NumPy for analyzing big data. All the mentioned packages support a wide variety of computations. But when the dataset doesn’t fit in the memory these packages will not scale. Here comes dask. When the dataset doesn’t “fit in memory” dask extends the dataset to “fit into disk”. Dask allows us to easily scale out to clusters or scale down to single machine based on the size of the dataset. "
},
{
"code": null,
"e": 982,
"s": 917,
"text": "To install this module type the below command in the terminal – "
},
{
"code": null,
"e": 1022,
"s": 982,
"text": "python -m pip install \"dask[complete]\" "
},
{
"code": null,
"e": 1134,
"s": 1022,
"text": "Let’s see an example comparing dask and pandas. To download the dataset used in the below examples, click here."
},
{
"code": null,
"e": 1194,
"s": 1134,
"text": "1. Pandas Performance: Read the dataset using pd.read_csv()"
},
{
"code": null,
"e": 1202,
"s": 1194,
"text": "Python3"
},
{
"code": "import pandas as pd %time temp = pd.read_csv('dataset.csv', encoding = 'ISO-8859-1')",
"e": 1313,
"s": 1202,
"text": null
},
{
"code": null,
"e": 1321,
"s": 1313,
"text": "Output:"
},
{
"code": null,
"e": 1373,
"s": 1321,
"text": "CPU times: user 619 ms, sys: 73.6 ms, total: 692 ms"
},
{
"code": null,
"e": 1391,
"s": 1373,
"text": "Wall time: 705 ms"
},
{
"code": null,
"e": 1459,
"s": 1391,
"text": "2. Dask Performance: Read the dataset using dask.dataframe.read_csv"
},
{
"code": null,
"e": 1467,
"s": 1459,
"text": "Python3"
},
{
"code": "import dask.dataframe as dd %time df = dd.read_csv(\"dataset.csv\", encoding = 'ISO-8859-1')",
"e": 1583,
"s": 1467,
"text": null
},
{
"code": null,
"e": 1591,
"s": 1583,
"text": "Output:"
},
{
"code": null,
"e": 1644,
"s": 1591,
"text": "CPU times: user 21.7 ms, sys: 938 μs, total: 22.7 ms"
},
{
"code": null,
"e": 1663,
"s": 1644,
"text": "Wall time: 23.2 ms"
},
{
"code": null,
"e": 1818,
"s": 1663,
"text": "Now a question might arise that how large datasets were handled using pandas before dask? There are few tricks handled to manage large datasets in pandas."
},
{
"code": null,
"e": 1917,
"s": 1818,
"text": "Using chunksize parameter of read_csv in pandasUse only needed columns while reading the csv files"
},
{
"code": null,
"e": 1965,
"s": 1917,
"text": "Using chunksize parameter of read_csv in pandas"
},
{
"code": null,
"e": 2017,
"s": 1965,
"text": "Use only needed columns while reading the csv files"
},
{
"code": null,
"e": 2209,
"s": 2017,
"text": "The above techniques will be followed in most cases while reading large datasets using pandas. But in some cases, the above might not be useful at that time dask comes into play a major role."
},
{
"code": null,
"e": 2248,
"s": 2209,
"text": "There are certain limitations in dask."
},
{
"code": null,
"e": 2445,
"s": 2248,
"text": "Dask cannot parallelize within individual tasks.As a distributed-computing framework, dask enables remote execution of arbitrary code. So dask workers should be hosted within trusted network only."
},
{
"code": null,
"e": 2494,
"s": 2445,
"text": "Dask cannot parallelize within individual tasks."
},
{
"code": null,
"e": 2643,
"s": 2494,
"text": "As a distributed-computing framework, dask enables remote execution of arbitrary code. So dask workers should be hosted within trusted network only."
},
{
"code": null,
"e": 2658,
"s": 2643,
"text": "python-modules"
},
{
"code": null,
"e": 2665,
"s": 2658,
"text": "Python"
},
{
"code": null,
"e": 2763,
"s": 2665,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2781,
"s": 2763,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2823,
"s": 2781,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2845,
"s": 2823,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2871,
"s": 2845,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2903,
"s": 2871,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2932,
"s": 2903,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2959,
"s": 2932,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2989,
"s": 2959,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3025,
"s": 2989,
"text": "Convert integer to string in Python"
}
]
|
Download Instagram profile pic using Python | 16 Jun, 2022
Instagram is a photo and video-sharing social networking service owned by Facebook, Python provides powerful tools for web scraping of Instagram.
requests:
pip install requests
concept – For a given user profile, open view-source and find “profile_pic_url_hd” . To find press ctrl+f and type “profile_pic_url_hd” the link with it is our data or profile pic. The link will look like :
https://scontent-bom1-1.cdninstagram.com/vp/d2df9b2d162969e87200984ee763cc27/5DC590F2/t51.2885-19/s320x320/61851740_845288152518430_7068999703693623296_n.jpg?_nc_ht=scontent-bom1-1.cdninstagram.com
Below is the stepwise implementation of the project:
Step 1: import all dependence
Python3
import requestsfrom bs4 import BeautifulSoup as bsimport jsonimport randomimport os.path
Step 2: Ask for username and send a response to Instagram.
Python3
insta_url='https://www.instagram.com'inta_username= input('enter username of instagram : ') response = requests.get(f"{insta_url}/{inta_username}/")
Step 3: if the response is ok, find profile photo link
(Note: replace ‘\\u0026’ with ‘&’ in the string_url to remove bad URL timestamp or bad URL hash error)
Python3
if response.ok: html=response.text bs_html=bs(html, features="lxml") bs_html=bs_html.text index=bs_html.find('profile_pic_url_hd')+21 remaining_text=bs_html[index:] remaining_text_index=remaining_text.find('requested_by_viewer')-3 string_url=remaining_text[:remaining_text_index].replace("\\u0026","&") print(string_url, "\n \n downloading..........")
Step 4: Now, create a loop and download photo.
Python3
while True: filename='pic'+str(random.randint(1, 100000))+'.jpg' file_exists = os.path.isfile(filename) if not file_exists: with open(filename, 'wb+') as handle: response = requests.get(string_url, stream=True) if not response.ok: print(response) for block in response.iter_content(1024): if not block: break handle.write(block) else: continue breakprint("\n downloading completed ..............")
Output:
Other Method : We can download profile pic of any Instagram account using instaloader module by just giving Instagram handle of the user.
First we need to install instaloader module :
pip install instaloader
Example:
Python3
import instaloader ig = instaloader.Instaloader()dp = input("Enter Insta username : ") ig.download_profile(dp , profile_pic_only=True)
Output : Profile pic will be downloaded in the same directory when we enter the input user id.
hammadbasithb
imsushant12
surinderdawra388
Project
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Implementing Web Scraping in Python with BeautifulSoup
10 Best Web Development Projects For Your Resume
OpenCV C++ Program for Face Detection
Simple Chat Room using Python
Twitter Sentiment Analysis using Python
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": 52,
"s": 24,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 199,
"s": 52,
"text": "Instagram is a photo and video-sharing social networking service owned by Facebook, Python provides powerful tools for web scraping of Instagram. "
},
{
"code": null,
"e": 209,
"s": 199,
"text": "requests:"
},
{
"code": null,
"e": 230,
"s": 209,
"text": "pip install requests"
},
{
"code": null,
"e": 439,
"s": 230,
"text": "concept – For a given user profile, open view-source and find “profile_pic_url_hd” . To find press ctrl+f and type “profile_pic_url_hd” the link with it is our data or profile pic. The link will look like : "
},
{
"code": null,
"e": 637,
"s": 439,
"text": "https://scontent-bom1-1.cdninstagram.com/vp/d2df9b2d162969e87200984ee763cc27/5DC590F2/t51.2885-19/s320x320/61851740_845288152518430_7068999703693623296_n.jpg?_nc_ht=scontent-bom1-1.cdninstagram.com"
},
{
"code": null,
"e": 692,
"s": 639,
"text": "Below is the stepwise implementation of the project:"
},
{
"code": null,
"e": 724,
"s": 692,
"text": "Step 1: import all dependence "
},
{
"code": null,
"e": 732,
"s": 724,
"text": "Python3"
},
{
"code": "import requestsfrom bs4 import BeautifulSoup as bsimport jsonimport randomimport os.path",
"e": 821,
"s": 732,
"text": null
},
{
"code": null,
"e": 882,
"s": 821,
"text": "Step 2: Ask for username and send a response to Instagram. "
},
{
"code": null,
"e": 890,
"s": 882,
"text": "Python3"
},
{
"code": "insta_url='https://www.instagram.com'inta_username= input('enter username of instagram : ') response = requests.get(f\"{insta_url}/{inta_username}/\")",
"e": 1039,
"s": 890,
"text": null
},
{
"code": null,
"e": 1096,
"s": 1039,
"text": "Step 3: if the response is ok, find profile photo link "
},
{
"code": null,
"e": 1200,
"s": 1096,
"text": "(Note: replace ‘\\\\u0026’ with ‘&’ in the string_url to remove bad URL timestamp or bad URL hash error) "
},
{
"code": null,
"e": 1208,
"s": 1200,
"text": "Python3"
},
{
"code": "if response.ok: html=response.text bs_html=bs(html, features=\"lxml\") bs_html=bs_html.text index=bs_html.find('profile_pic_url_hd')+21 remaining_text=bs_html[index:] remaining_text_index=remaining_text.find('requested_by_viewer')-3 string_url=remaining_text[:remaining_text_index].replace(\"\\\\u0026\",\"&\") print(string_url, \"\\n \\n downloading..........\")",
"e": 1587,
"s": 1208,
"text": null
},
{
"code": null,
"e": 1636,
"s": 1587,
"text": "Step 4: Now, create a loop and download photo. "
},
{
"code": null,
"e": 1644,
"s": 1636,
"text": "Python3"
},
{
"code": "while True: filename='pic'+str(random.randint(1, 100000))+'.jpg' file_exists = os.path.isfile(filename) if not file_exists: with open(filename, 'wb+') as handle: response = requests.get(string_url, stream=True) if not response.ok: print(response) for block in response.iter_content(1024): if not block: break handle.write(block) else: continue breakprint(\"\\n downloading completed ..............\")",
"e": 2184,
"s": 1644,
"text": null
},
{
"code": null,
"e": 2194,
"s": 2184,
"text": "Output: "
},
{
"code": null,
"e": 2332,
"s": 2194,
"text": "Other Method : We can download profile pic of any Instagram account using instaloader module by just giving Instagram handle of the user."
},
{
"code": null,
"e": 2378,
"s": 2332,
"text": "First we need to install instaloader module :"
},
{
"code": null,
"e": 2403,
"s": 2378,
"text": "pip install instaloader "
},
{
"code": null,
"e": 2412,
"s": 2403,
"text": "Example:"
},
{
"code": null,
"e": 2420,
"s": 2412,
"text": "Python3"
},
{
"code": "import instaloader ig = instaloader.Instaloader()dp = input(\"Enter Insta username : \") ig.download_profile(dp , profile_pic_only=True)",
"e": 2555,
"s": 2420,
"text": null
},
{
"code": null,
"e": 2652,
"s": 2555,
"text": "Output : Profile pic will be downloaded in the same directory when we enter the input user id."
},
{
"code": null,
"e": 2666,
"s": 2652,
"text": "hammadbasithb"
},
{
"code": null,
"e": 2678,
"s": 2666,
"text": "imsushant12"
},
{
"code": null,
"e": 2695,
"s": 2678,
"text": "surinderdawra388"
},
{
"code": null,
"e": 2703,
"s": 2695,
"text": "Project"
},
{
"code": null,
"e": 2710,
"s": 2703,
"text": "Python"
},
{
"code": null,
"e": 2729,
"s": 2710,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2827,
"s": 2729,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2882,
"s": 2827,
"text": "Implementing Web Scraping in Python with BeautifulSoup"
},
{
"code": null,
"e": 2931,
"s": 2882,
"text": "10 Best Web Development Projects For Your Resume"
},
{
"code": null,
"e": 2969,
"s": 2931,
"text": "OpenCV C++ Program for Face Detection"
},
{
"code": null,
"e": 2999,
"s": 2969,
"text": "Simple Chat Room using Python"
},
{
"code": null,
"e": 3039,
"s": 2999,
"text": "Twitter Sentiment Analysis using Python"
},
{
"code": null,
"e": 3067,
"s": 3039,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3117,
"s": 3067,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3139,
"s": 3117,
"text": "Python map() function"
},
{
"code": null,
"e": 3157,
"s": 3139,
"text": "Python Dictionary"
}
]
|
Iterate over words of a String in Python | 23 Jan, 2020
Given a String comprising of many words separated by space, write a Python program to iterate over these words of the string.
Examples:
Input: str = “GeeksforGeeks is a computer science portal for Geeks”Output:GeeksforGeeksisacomputerscienceportalforGeeks
Input: str = “Geeks for Geeks”Output:GeeksforGeeks
Method 1: Using split()
Using split() function, we can split the string into a list of words and is the most generic and recommended method if one wished to accomplish this particular task. But the drawback is that it fails in the cases in string contains punctuation marks.
# Python3 code to demonstrate # to extract words from string # using split() # initializing string test_string = "GeeksforGeeks is a computer science portal for Geeks" # printing original string print ("The original string is : " + test_string) # using split() # to extract words from string res = test_string.split() # printing result print ("\nThe words of string are")for i in res: print(i)
Output:
The original string is : GeeksforGeeks is a computer science portal for Geeks
The words of string are
GeeksforGeeks
is
a
computer
science
portal
for
Geeks
Method 2: Using re.findall()
In the cases which contain all the special characters and punctuation marks, as discussed above, the conventional method of finding words in a string using split can fail and hence requires regular expressions to perform this task. findall() function returns the list after filtering the string and extracting words ignoring punctuation marks.
# Python3 code to demonstrate # to extract words from string # using regex( findall() ) import re # initializing string test_string = "GeeksforGeeks is a computer science portal for Geeks !!!" # printing original string print ("The original string is : " + test_string) # using regex( findall() ) # to extract words from string res = re.findall(r'\w+', test_string) # printing result print ("\nThe words of string are")for i in res: print(i)
Output:
The original string is : GeeksforGeeks is a computer science portal for Geeks!!!
The words of string are
GeeksforGeeks
is
a
computer
science
portal
for
Geeks
Python string-programs
python-string
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Jan, 2020"
},
{
"code": null,
"e": 154,
"s": 28,
"text": "Given a String comprising of many words separated by space, write a Python program to iterate over these words of the string."
},
{
"code": null,
"e": 164,
"s": 154,
"text": "Examples:"
},
{
"code": null,
"e": 284,
"s": 164,
"text": "Input: str = “GeeksforGeeks is a computer science portal for Geeks”Output:GeeksforGeeksisacomputerscienceportalforGeeks"
},
{
"code": null,
"e": 335,
"s": 284,
"text": "Input: str = “Geeks for Geeks”Output:GeeksforGeeks"
},
{
"code": null,
"e": 359,
"s": 335,
"text": "Method 1: Using split()"
},
{
"code": null,
"e": 610,
"s": 359,
"text": "Using split() function, we can split the string into a list of words and is the most generic and recommended method if one wished to accomplish this particular task. But the drawback is that it fails in the cases in string contains punctuation marks."
},
{
"code": "# Python3 code to demonstrate # to extract words from string # using split() # initializing string test_string = \"GeeksforGeeks is a computer science portal for Geeks\" # printing original string print (\"The original string is : \" + test_string) # using split() # to extract words from string res = test_string.split() # printing result print (\"\\nThe words of string are\")for i in res: print(i)",
"e": 1027,
"s": 610,
"text": null
},
{
"code": null,
"e": 1035,
"s": 1027,
"text": "Output:"
},
{
"code": null,
"e": 1192,
"s": 1035,
"text": "The original string is : GeeksforGeeks is a computer science portal for Geeks\n\nThe words of string are\nGeeksforGeeks\nis\na\ncomputer\nscience\nportal\nfor\nGeeks\n"
},
{
"code": null,
"e": 1221,
"s": 1192,
"text": "Method 2: Using re.findall()"
},
{
"code": null,
"e": 1565,
"s": 1221,
"text": "In the cases which contain all the special characters and punctuation marks, as discussed above, the conventional method of finding words in a string using split can fail and hence requires regular expressions to perform this task. findall() function returns the list after filtering the string and extracting words ignoring punctuation marks."
},
{
"code": "# Python3 code to demonstrate # to extract words from string # using regex( findall() ) import re # initializing string test_string = \"GeeksforGeeks is a computer science portal for Geeks !!!\" # printing original string print (\"The original string is : \" + test_string) # using regex( findall() ) # to extract words from string res = re.findall(r'\\w+', test_string) # printing result print (\"\\nThe words of string are\")for i in res: print(i)",
"e": 2030,
"s": 1565,
"text": null
},
{
"code": null,
"e": 2038,
"s": 2030,
"text": "Output:"
},
{
"code": null,
"e": 2198,
"s": 2038,
"text": "The original string is : GeeksforGeeks is a computer science portal for Geeks!!!\n\nThe words of string are\nGeeksforGeeks\nis\na\ncomputer\nscience\nportal\nfor\nGeeks\n"
},
{
"code": null,
"e": 2221,
"s": 2198,
"text": "Python string-programs"
},
{
"code": null,
"e": 2235,
"s": 2221,
"text": "python-string"
},
{
"code": null,
"e": 2242,
"s": 2235,
"text": "Python"
},
{
"code": null,
"e": 2258,
"s": 2242,
"text": "Python Programs"
},
{
"code": null,
"e": 2356,
"s": 2258,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2388,
"s": 2356,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2415,
"s": 2388,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2436,
"s": 2415,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2459,
"s": 2436,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2515,
"s": 2459,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2537,
"s": 2515,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2576,
"s": 2537,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2614,
"s": 2576,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2651,
"s": 2614,
"text": "Python Program for Fibonacci numbers"
}
]
|
How to change browser theme-color using HTML ? | 16 Dec, 2021
In this article, we will know how to change the browser theme-color in HTML. Suppose that if we want our website to appear in green color along with changing the browser theme color which will be the same as our website, then we can use a meta tag with name and content attribute.
Meta Tag: The <meta> tag is used in the <head> element of HTML Document. It defines meta-data about the HTML document.
theme-color: The theme-color is the value used in the name attribute of the meta tag. The theme-color provides color to the browser to display as a theme, that color is provided by color code or color name in the content attribute of the meta tag.
Syntax:
<meta name="theme-color" content="#1bb566">
Approach: We will declare the name attribute that has value as theme-color and, the content attribute will have any color Hex-code or a color name that we want.
Example 1: Using Color hex-code:
HTML
<!DOCTYPE html><html> <head> <title>Change Browser theme-color</title> <meta name="theme-color" content="#1bb566"> </head> <body> <h1>Welcome To GFG</h1></body> </html>
Output:
CHROME ANDROID
Example 2: Using Color Name:
HTML
<!DOCTYPE html><html> <head> <title>Change Browser theme-color</title> <meta name="theme-color" content="blue" /></head> <body> <h1>Welcome To GFG</h1></body> </html>
Output:
CHROME ANDROID
Note: The theme-color value will not work in Android Chrome with dark mode. In order to see the result, disable the dark mode of the browser.
HTML-Questions
HTML-Tags
HTML5
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 334,
"s": 53,
"text": "In this article, we will know how to change the browser theme-color in HTML. Suppose that if we want our website to appear in green color along with changing the browser theme color which will be the same as our website, then we can use a meta tag with name and content attribute."
},
{
"code": null,
"e": 453,
"s": 334,
"text": "Meta Tag: The <meta> tag is used in the <head> element of HTML Document. It defines meta-data about the HTML document."
},
{
"code": null,
"e": 701,
"s": 453,
"text": "theme-color: The theme-color is the value used in the name attribute of the meta tag. The theme-color provides color to the browser to display as a theme, that color is provided by color code or color name in the content attribute of the meta tag."
},
{
"code": null,
"e": 711,
"s": 703,
"text": "Syntax:"
},
{
"code": null,
"e": 755,
"s": 711,
"text": "<meta name=\"theme-color\" content=\"#1bb566\">"
},
{
"code": null,
"e": 916,
"s": 755,
"text": "Approach: We will declare the name attribute that has value as theme-color and, the content attribute will have any color Hex-code or a color name that we want."
},
{
"code": null,
"e": 949,
"s": 916,
"text": "Example 1: Using Color hex-code:"
},
{
"code": null,
"e": 954,
"s": 949,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Change Browser theme-color</title> <meta name=\"theme-color\" content=\"#1bb566\"> </head> <body> <h1>Welcome To GFG</h1></body> </html>",
"e": 1135,
"s": 954,
"text": null
},
{
"code": null,
"e": 1143,
"s": 1135,
"text": "Output:"
},
{
"code": null,
"e": 1158,
"s": 1143,
"text": "CHROME ANDROID"
},
{
"code": null,
"e": 1187,
"s": 1158,
"text": "Example 2: Using Color Name:"
},
{
"code": null,
"e": 1192,
"s": 1187,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Change Browser theme-color</title> <meta name=\"theme-color\" content=\"blue\" /></head> <body> <h1>Welcome To GFG</h1></body> </html>",
"e": 1371,
"s": 1192,
"text": null
},
{
"code": null,
"e": 1379,
"s": 1371,
"text": "Output:"
},
{
"code": null,
"e": 1394,
"s": 1379,
"text": "CHROME ANDROID"
},
{
"code": null,
"e": 1536,
"s": 1394,
"text": "Note: The theme-color value will not work in Android Chrome with dark mode. In order to see the result, disable the dark mode of the browser."
},
{
"code": null,
"e": 1551,
"s": 1536,
"text": "HTML-Questions"
},
{
"code": null,
"e": 1561,
"s": 1551,
"text": "HTML-Tags"
},
{
"code": null,
"e": 1567,
"s": 1561,
"text": "HTML5"
},
{
"code": null,
"e": 1572,
"s": 1567,
"text": "HTML"
},
{
"code": null,
"e": 1589,
"s": 1572,
"text": "Web Technologies"
},
{
"code": null,
"e": 1594,
"s": 1589,
"text": "HTML"
}
]
|
What is float property in CSS ? | 21 May, 2021
In this article, we will learn about CSS float property with suitable examples of all available attributes.
The float property is used to change the normal flow of an element. It defines how an element should float and place an element on its container’s right or left side.
float: none|inherit|left|right|initial;
Note – The default value of the float property is none and it won’t work with the absolutely positioned element.
In the below example, we use the float value left. After using this value the element must be left on its container as shown in the below image.
float:left
HTML
<!DOCTYPE html><html><head> <title>Float Left</title> <style> img { float:left; /* element must be left on its container */ height: 100px; } div{ width:300px; height: 220px; box-shadow: 0px 2px 2px 2px; } </style></head><body> <div> <h1> float left...</h1> <p>The below picture must be left on its container.</p> <img src="https://img.icons8.com/color/452/GeeksforGeeks.png"> <p>The GeeksforGeeks is the portal for geeks that contain computer science and programming articles. </p> </div></body></html>
In the below example, we use the float value right. After using this value the element must be right on its container as shown in the below image.
float:right
HTML
<!DOCTYPE html><html><head> <title>Float Right</title> <style> img { float:right; /* element must be right on its container */ height: 100px; } div{ width:300px; height: 220px; box-shadow: 0px 2px 2px 2px; } </style></head><body> <div> <h1> float right...</h1> <p>The below picture must be right on its container.</p> <img src="https://img.icons8.com/color/452/GeeksforGeeks.png"> <p>The GeeksforGeeks is the portal for geeks that contain computer science and programming articles. </p> </div></body></html>
In the below example, we will see that the float property won’t work with an absolutely positioned element.
position:absolute;
HTML
<!DOCTYPE html><html><head> <title>Float</title> <style> img { float:right; /* It won't work because element is absolutely positioned */ height: 100px; position: absolute; } div{ width:300px; height: 230px; box-shadow: 0px 2px 2px 2px; } </style></head><body> <div> <h1> float with absolutely positioned element.</h1> <p>floating won't work</p> <img src="https://img.icons8.com/color/452/GeeksforGeeks.png"> <p>The GeeksforGeeks is the portal for geeks that contain computer science and programming articles. </p> </div></body></html>
The CSS float property is used before flexbox and grid. Today we want a website which is mobile friendly. The flexbox is more efficient rather than float.
Positioning child elements becomes easier with flexbox.flexbox is responsive and mobile-friendly.flex container’s margins do not collapse with the margins of its content.we can easily change the order of elements on our webpage without even making changes in HTML.
Positioning child elements becomes easier with flexbox.
flexbox is responsive and mobile-friendly.
flex container’s margins do not collapse with the margins of its content.
we can easily change the order of elements on our webpage without even making changes in HTML.
Conclusion – In this article, we learned CSS float property with available values and suitable examples.
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 163,
"s": 54,
"text": "In this article, we will learn about CSS float property with suitable examples of all available attributes. "
},
{
"code": null,
"e": 331,
"s": 163,
"text": "The float property is used to change the normal flow of an element. It defines how an element should float and place an element on its container’s right or left side. "
},
{
"code": null,
"e": 371,
"s": 331,
"text": "float: none|inherit|left|right|initial;"
},
{
"code": null,
"e": 485,
"s": 371,
"text": "Note – The default value of the float property is none and it won’t work with the absolutely positioned element. "
},
{
"code": null,
"e": 631,
"s": 485,
"text": "In the below example, we use the float value left. After using this value the element must be left on its container as shown in the below image. "
},
{
"code": null,
"e": 642,
"s": 631,
"text": "float:left"
},
{
"code": null,
"e": 647,
"s": 642,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Float Left</title> <style> img { float:left; /* element must be left on its container */ height: 100px; } div{ width:300px; height: 220px; box-shadow: 0px 2px 2px 2px; } </style></head><body> <div> <h1> float left...</h1> <p>The below picture must be left on its container.</p> <img src=\"https://img.icons8.com/color/452/GeeksforGeeks.png\"> <p>The GeeksforGeeks is the portal for geeks that contain computer science and programming articles. </p> </div></body></html> ",
"e": 1302,
"s": 647,
"text": null
},
{
"code": null,
"e": 1450,
"s": 1302,
"text": "In the below example, we use the float value right. After using this value the element must be right on its container as shown in the below image. "
},
{
"code": null,
"e": 1462,
"s": 1450,
"text": "float:right"
},
{
"code": null,
"e": 1467,
"s": 1462,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Float Right</title> <style> img { float:right; /* element must be right on its container */ height: 100px; } div{ width:300px; height: 220px; box-shadow: 0px 2px 2px 2px; } </style></head><body> <div> <h1> float right...</h1> <p>The below picture must be right on its container.</p> <img src=\"https://img.icons8.com/color/452/GeeksforGeeks.png\"> <p>The GeeksforGeeks is the portal for geeks that contain computer science and programming articles. </p> </div></body></html> ",
"e": 2128,
"s": 1467,
"text": null
},
{
"code": null,
"e": 2237,
"s": 2128,
"text": "In the below example, we will see that the float property won’t work with an absolutely positioned element. "
},
{
"code": null,
"e": 2256,
"s": 2237,
"text": "position:absolute;"
},
{
"code": null,
"e": 2261,
"s": 2256,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Float</title> <style> img { float:right; /* It won't work because element is absolutely positioned */ height: 100px; position: absolute; } div{ width:300px; height: 230px; box-shadow: 0px 2px 2px 2px; } </style></head><body> <div> <h1> float with absolutely positioned element.</h1> <p>floating won't work</p> <img src=\"https://img.icons8.com/color/452/GeeksforGeeks.png\"> <p>The GeeksforGeeks is the portal for geeks that contain computer science and programming articles. </p> </div></body></html> ",
"e": 2969,
"s": 2261,
"text": null
},
{
"code": null,
"e": 3124,
"s": 2969,
"text": "The CSS float property is used before flexbox and grid. Today we want a website which is mobile friendly. The flexbox is more efficient rather than float."
},
{
"code": null,
"e": 3389,
"s": 3124,
"text": "Positioning child elements becomes easier with flexbox.flexbox is responsive and mobile-friendly.flex container’s margins do not collapse with the margins of its content.we can easily change the order of elements on our webpage without even making changes in HTML."
},
{
"code": null,
"e": 3445,
"s": 3389,
"text": "Positioning child elements becomes easier with flexbox."
},
{
"code": null,
"e": 3488,
"s": 3445,
"text": "flexbox is responsive and mobile-friendly."
},
{
"code": null,
"e": 3562,
"s": 3488,
"text": "flex container’s margins do not collapse with the margins of its content."
},
{
"code": null,
"e": 3657,
"s": 3562,
"text": "we can easily change the order of elements on our webpage without even making changes in HTML."
},
{
"code": null,
"e": 3763,
"s": 3657,
"text": "Conclusion – In this article, we learned CSS float property with available values and suitable examples. "
},
{
"code": null,
"e": 3778,
"s": 3763,
"text": "CSS-Properties"
},
{
"code": null,
"e": 3792,
"s": 3778,
"text": "CSS-Questions"
},
{
"code": null,
"e": 3799,
"s": 3792,
"text": "Picked"
},
{
"code": null,
"e": 3803,
"s": 3799,
"text": "CSS"
},
{
"code": null,
"e": 3820,
"s": 3803,
"text": "Web Technologies"
},
{
"code": null,
"e": 3918,
"s": 3820,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3957,
"s": 3918,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3996,
"s": 3957,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 4035,
"s": 3996,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 4072,
"s": 4035,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 4101,
"s": 4072,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 4134,
"s": 4101,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4195,
"s": 4134,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4238,
"s": 4195,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 4310,
"s": 4238,
"text": "Differences between Functional Components and Class Components in React"
}
]
|
SQL Query to Find All Employees Who Are Also Managers | 13 Apr, 2021
Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, etc.
Here, we are going to see how to find the details of all the employees who are also managers in SQL. We will first create a database named “geeks” then we will create a table “employees” in that database. After that, we will execute our query on that table.
Use the below SQL statement to create a database called geeks:
CREATE DATABASE geeks;
USE geeks;
We have the following Employee table in our geeks database :
CREATE TABLE employees(
EMPLOYEE_ID int,
NAME Varchar(20),
PHONE_NUMBER int,
HIRE_DATE date,
MANAGER_ID int);
You can use the below statement to query the description of the created table:
EXEC SP_COLUMNS employees;
Use the below statement to add data to the Employee table:
INSERT INTO EMPLOYEES VALUES (100, "ANURAG", 9889269997, "1987-06-17", 100);
INSERT INTO EMPLOYEES VALUES (101, "harsh", 8789269986, "1987-06-20", 100);
INSERT INTO EMPLOYEES VALUES (102, "SUMIT", 7689269975, "1987-07-07", 103);
INSERT INTO EMPLOYEES VALUES (103, "RUHI", 9589269964, "1987-07-12", 102);
INSERT INTO EMPLOYEES VALUES (104, "KAE", 8489269953, "1987-07-23", 103);
To verify the contents of the table use the below statement:
SELECT * FROM EMPLOYEES;
Now to get the details of all the employees who are also managers, we make use of the EMPLOYEE_ID field and the MANAGER_ID, and we will find out the details of employees who are also managers. The query would have the following syntax:
Syntax:
SELECT *
FROM table_name
WHERE (column_name IN (SELECT column_name FROM table_name));
Now run the same query with on the table we created as shown below:
SELECT * FROM EMPLOYEES WHERE (EMPLOYEE_ID IN (SELECT MANAGER_ID FROM EMPLOYEES));
Output:
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 224,
"s": 52,
"text": "Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, etc. "
},
{
"code": null,
"e": 482,
"s": 224,
"text": "Here, we are going to see how to find the details of all the employees who are also managers in SQL. We will first create a database named “geeks” then we will create a table “employees” in that database. After that, we will execute our query on that table."
},
{
"code": null,
"e": 545,
"s": 482,
"text": "Use the below SQL statement to create a database called geeks:"
},
{
"code": null,
"e": 568,
"s": 545,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 579,
"s": 568,
"text": "USE geeks;"
},
{
"code": null,
"e": 640,
"s": 579,
"text": "We have the following Employee table in our geeks database :"
},
{
"code": null,
"e": 770,
"s": 640,
"text": "CREATE TABLE employees(\n EMPLOYEE_ID int,\n NAME Varchar(20),\n PHONE_NUMBER int,\n HIRE_DATE date,\n MANAGER_ID int);"
},
{
"code": null,
"e": 849,
"s": 770,
"text": "You can use the below statement to query the description of the created table:"
},
{
"code": null,
"e": 876,
"s": 849,
"text": "EXEC SP_COLUMNS employees;"
},
{
"code": null,
"e": 935,
"s": 876,
"text": "Use the below statement to add data to the Employee table:"
},
{
"code": null,
"e": 1313,
"s": 935,
"text": "INSERT INTO EMPLOYEES VALUES (100, \"ANURAG\", 9889269997, \"1987-06-17\", 100);\nINSERT INTO EMPLOYEES VALUES (101, \"harsh\", 8789269986, \"1987-06-20\", 100);\nINSERT INTO EMPLOYEES VALUES (102, \"SUMIT\", 7689269975, \"1987-07-07\", 103);\nINSERT INTO EMPLOYEES VALUES (103, \"RUHI\", 9589269964, \"1987-07-12\", 102);\nINSERT INTO EMPLOYEES VALUES (104, \"KAE\", 8489269953, \"1987-07-23\", 103);"
},
{
"code": null,
"e": 1374,
"s": 1313,
"text": "To verify the contents of the table use the below statement:"
},
{
"code": null,
"e": 1399,
"s": 1374,
"text": "SELECT * FROM EMPLOYEES;"
},
{
"code": null,
"e": 1636,
"s": 1399,
"text": "Now to get the details of all the employees who are also managers, we make use of the EMPLOYEE_ID field and the MANAGER_ID, and we will find out the details of employees who are also managers. The query would have the following syntax:"
},
{
"code": null,
"e": 1732,
"s": 1636,
"text": "Syntax:\nSELECT *\nFROM table_name \nWHERE (column_name IN (SELECT column_name FROM table_name));"
},
{
"code": null,
"e": 1800,
"s": 1732,
"text": "Now run the same query with on the table we created as shown below:"
},
{
"code": null,
"e": 1883,
"s": 1800,
"text": "SELECT * FROM EMPLOYEES WHERE (EMPLOYEE_ID IN (SELECT MANAGER_ID FROM EMPLOYEES));"
},
{
"code": null,
"e": 1891,
"s": 1883,
"text": "Output:"
},
{
"code": null,
"e": 1898,
"s": 1891,
"text": "Picked"
},
{
"code": null,
"e": 1908,
"s": 1898,
"text": "SQL-Query"
},
{
"code": null,
"e": 1912,
"s": 1908,
"text": "SQL"
},
{
"code": null,
"e": 1916,
"s": 1912,
"text": "SQL"
}
]
|
How to Install ImageMagick on Ubuntu | Use ImageMagick to create, edit, compose or convert bitmap pix. It could actually read and write snapshots in a type of codecs (over 200) including PNG, JPEG, JPEG-2000, GIF, TIFF, DPX, EXR, WebP, Postscript, PDF, and SVG. Use ImageMagick to resize, flip, mirror, rotate, distort, shear and develop into snapshots, alter image colors, follow various certain effects, or draw text, lines, polygons, ellipses and Bézier curves.This article explains about -“How to Install ImageMagick on Ubuntu”
Before installing ImageMagick, It should be required, to build essentials as shown below –
$sudo apt-get install build-essential checkinstall && apt-get build-dep imagemagick -y
The sample output should be like this –
Reading package lists... Done
Building dependency tree
Reading state information... Done
build-essential is already the newest version (12.1ubuntu2).
The following NEW packages will be installed:
checkinstall
0 upgraded, 1 newly installed, 0 to remove and 204 not upgraded.
Need to get 121 kB of archives.
After this operation, 516 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://in.archive.ubuntu.com/ubuntu xenial/universe amd64 checkinstall amd64 1.6.2-4ubuntu1 [121 kB]
Fetched 121 kB in 0s (162 kB/s)
..................................................................................
Now download The ImageMagick, as shown below –
$sudo wget http://www.imagemagick.org/download/ImageMagick.tar.gz
The sample output should be like this –
--2017-01-27 11:49:08-- http://www.imagemagick.org/download/ImageMagick.tar.gz
Resolving www.imagemagick.org (www.imagemagick.org)... 198.72.81.86
Connecting to www.imagemagick.org (www.imagemagick.org)|198.72.81.86|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 12746042 (12M) [application/x-gzip]
Saving to: ‘ImageMagick.tar.gz’
ImageMagick.tar.gz 100%[===================>] 12.16M 1.28MB/s in 14s
2017-01-27 11:49:22 (907 KB/s) - ‘ImageMagick.tar.gz’ saved [12746042/12746042]
Unzip the downloaded file as shown below –
$sudo tar xzvf ImageMagick.tar.gz
The sample output should be like this –
ImageMagick-7.0.4-5/PerlMagick/t/ttf/
ImageMagick-7.0.4-5/PerlMagick/t/ttf/read.t
ImageMagick-7.0.4-5/PerlMagick/t/ttf/input.ttf
ImageMagick-7.0.4-5/PerlMagick/t/composite.t
ImageMagick-7.0.4-5/PerlMagick/t/input.dib
ImageMagick-7.0.4-5/PerlMagick/t/input_p5.pgm
ImageMagick-7.0.4-5/PerlMagick/t/input_70x46.uyvy
ImageMagick-7.0.4-5/PerlMagick/t/input.im8
ImageMagick-7.0.4-5/PerlMagick/t/input.sgi
ImageMagick-7.0.4-5/PerlMagick/t/png/
ImageMagick-7.0.4-5/PerlMagick/t/png/input.mng
ImageMagick-7.0.4-5/PerlMagick/t/png/write.t
ImageMagick-7.0.4-5/PerlMagick/t/png/read-16.t
ImageMagick-7.0.4-5/PerlMagick/t/png/input_256.png
ImageMagick-7.0.4-5/PerlMagick/t/png/input_bw.png
ImageMagick-7.0.4-5/PerlMagick/t/png/input_truecolor.png
ImageMagick-7.0.4-5/PerlMagick/t/png/write-16.t
ImageMagick-7.0.4-5/PerlMagick/t/png/input_mono.png
..........................................................................
To verify the above command, use the following command –
$ ls
The sample output should be like this –
ImageMagick-7.0.4-5 ImageMagick.tar.gz
Now enter into extracted directory as shown below –
$cd ImageMagick-7.0.4-5
To check configuration, use the following command –
~/ImageMagick-7.0.4-5# ./configure
To build the source code, use the following commands as shown below –
~/ImageMagick-7.0.4-5# make clean
~/ImageMagick-7.0.4-5# make
~/ImageMagick-7.0.4-5# checkinstall
~/ImageMagick-7.0.4-5# ldconfig /usr/local/lib
To get more infomation about magick, use the following command –
$ magick -help
The sample output should be like this –
Usage: magick [ {option} | {image} ... ] {output_image}
magick [ {option} | {image} ... ] -script {filename} [ {script_args} ...]
magick -help | -version | -usage | -list {option}
To get the version of magick, use the following command –
$ magick -version
The sample output should be like this –
Version: ImageMagick 7.0.4-5 Q16 x86_64 2017-01-27 http://www.imagemagick.org
Copyright: © 1999-2017 ImageMagick Studio LLC
License: http://www.imagemagick.org/script/license.php
Features: Cipher DPC HDRI OpenMP
Delegates (built-in): x zlib
In this article, we have learnt about – How to Install ImageMagick on Ubuntu, we will come up with more Linux based tricks and tips. Keep reading!. | [
{
"code": null,
"e": 1681,
"s": 1187,
"text": "Use ImageMagick to create, edit, compose or convert bitmap pix. It could actually read and write snapshots in a type of codecs (over 200) including PNG, JPEG, JPEG-2000, GIF, TIFF, DPX, EXR, WebP, Postscript, PDF, and SVG. Use ImageMagick to resize, flip, mirror, rotate, distort, shear and develop into snapshots, alter image colors, follow various certain effects, or draw text, lines, polygons, ellipses and Bézier curves.This article explains about -“How to Install ImageMagick on Ubuntu”"
},
{
"code": null,
"e": 1772,
"s": 1681,
"text": "Before installing ImageMagick, It should be required, to build essentials as shown below –"
},
{
"code": null,
"e": 1859,
"s": 1772,
"text": "$sudo apt-get install build-essential checkinstall && apt-get build-dep imagemagick -y"
},
{
"code": null,
"e": 1899,
"s": 1859,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 2531,
"s": 1899,
"text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nbuild-essential is already the newest version (12.1ubuntu2).\nThe following NEW packages will be installed:\n checkinstall\n0 upgraded, 1 newly installed, 0 to remove and 204 not upgraded.\nNeed to get 121 kB of archives.\nAfter this operation, 516 kB of additional disk space will be used.\nDo you want to continue? [Y/n] y\nGet:1 http://in.archive.ubuntu.com/ubuntu xenial/universe amd64 checkinstall amd64 1.6.2-4ubuntu1 [121 kB]\nFetched 121 kB in 0s (162 kB/s)\n.................................................................................."
},
{
"code": null,
"e": 2578,
"s": 2531,
"text": "Now download The ImageMagick, as shown below –"
},
{
"code": null,
"e": 2644,
"s": 2578,
"text": "$sudo wget http://www.imagemagick.org/download/ImageMagick.tar.gz"
},
{
"code": null,
"e": 2684,
"s": 2644,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 3192,
"s": 2684,
"text": "--2017-01-27 11:49:08-- http://www.imagemagick.org/download/ImageMagick.tar.gz\nResolving www.imagemagick.org (www.imagemagick.org)... 198.72.81.86\nConnecting to www.imagemagick.org (www.imagemagick.org)|198.72.81.86|:80... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 12746042 (12M) [application/x-gzip]\nSaving to: ‘ImageMagick.tar.gz’\n\nImageMagick.tar.gz 100%[===================>] 12.16M 1.28MB/s in 14s\n\n2017-01-27 11:49:22 (907 KB/s) - ‘ImageMagick.tar.gz’ saved [12746042/12746042]"
},
{
"code": null,
"e": 3235,
"s": 3192,
"text": "Unzip the downloaded file as shown below –"
},
{
"code": null,
"e": 3269,
"s": 3235,
"text": "$sudo tar xzvf ImageMagick.tar.gz"
},
{
"code": null,
"e": 3309,
"s": 3269,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 4218,
"s": 3309,
"text": "ImageMagick-7.0.4-5/PerlMagick/t/ttf/\nImageMagick-7.0.4-5/PerlMagick/t/ttf/read.t\nImageMagick-7.0.4-5/PerlMagick/t/ttf/input.ttf\nImageMagick-7.0.4-5/PerlMagick/t/composite.t\nImageMagick-7.0.4-5/PerlMagick/t/input.dib\nImageMagick-7.0.4-5/PerlMagick/t/input_p5.pgm\nImageMagick-7.0.4-5/PerlMagick/t/input_70x46.uyvy\nImageMagick-7.0.4-5/PerlMagick/t/input.im8\nImageMagick-7.0.4-5/PerlMagick/t/input.sgi\nImageMagick-7.0.4-5/PerlMagick/t/png/\nImageMagick-7.0.4-5/PerlMagick/t/png/input.mng\nImageMagick-7.0.4-5/PerlMagick/t/png/write.t\nImageMagick-7.0.4-5/PerlMagick/t/png/read-16.t\nImageMagick-7.0.4-5/PerlMagick/t/png/input_256.png\nImageMagick-7.0.4-5/PerlMagick/t/png/input_bw.png\nImageMagick-7.0.4-5/PerlMagick/t/png/input_truecolor.png\nImageMagick-7.0.4-5/PerlMagick/t/png/write-16.t\nImageMagick-7.0.4-5/PerlMagick/t/png/input_mono.png\n.........................................................................."
},
{
"code": null,
"e": 4275,
"s": 4218,
"text": "To verify the above command, use the following command –"
},
{
"code": null,
"e": 4280,
"s": 4275,
"text": "$ ls"
},
{
"code": null,
"e": 4320,
"s": 4280,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 4359,
"s": 4320,
"text": "ImageMagick-7.0.4-5 ImageMagick.tar.gz"
},
{
"code": null,
"e": 4411,
"s": 4359,
"text": "Now enter into extracted directory as shown below –"
},
{
"code": null,
"e": 4435,
"s": 4411,
"text": "$cd ImageMagick-7.0.4-5"
},
{
"code": null,
"e": 4487,
"s": 4435,
"text": "To check configuration, use the following command –"
},
{
"code": null,
"e": 4522,
"s": 4487,
"text": "~/ImageMagick-7.0.4-5# ./configure"
},
{
"code": null,
"e": 4592,
"s": 4522,
"text": "To build the source code, use the following commands as shown below –"
},
{
"code": null,
"e": 4737,
"s": 4592,
"text": "~/ImageMagick-7.0.4-5# make clean\n~/ImageMagick-7.0.4-5# make\n~/ImageMagick-7.0.4-5# checkinstall\n~/ImageMagick-7.0.4-5# ldconfig /usr/local/lib"
},
{
"code": null,
"e": 4802,
"s": 4737,
"text": "To get more infomation about magick, use the following command –"
},
{
"code": null,
"e": 4817,
"s": 4802,
"text": "$ magick -help"
},
{
"code": null,
"e": 4857,
"s": 4817,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 5053,
"s": 4857,
"text": "Usage: magick [ {option} | {image} ... ] {output_image}\n magick [ {option} | {image} ... ] -script {filename} [ {script_args} ...]\n magick -help | -version | -usage | -list {option}\n\n"
},
{
"code": null,
"e": 5111,
"s": 5053,
"text": "To get the version of magick, use the following command –"
},
{
"code": null,
"e": 5129,
"s": 5111,
"text": "$ magick -version"
},
{
"code": null,
"e": 5169,
"s": 5129,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 5410,
"s": 5169,
"text": "Version: ImageMagick 7.0.4-5 Q16 x86_64 2017-01-27 http://www.imagemagick.org\nCopyright: © 1999-2017 ImageMagick Studio LLC\nLicense: http://www.imagemagick.org/script/license.php\nFeatures: Cipher DPC HDRI OpenMP\nDelegates (built-in): x zlib"
},
{
"code": null,
"e": 5558,
"s": 5410,
"text": "In this article, we have learnt about – How to Install ImageMagick on Ubuntu, we will come up with more Linux based tricks and tips. Keep reading!."
}
]
|
Ruby | Array transpose() function | 06 Dec, 2019
Array#transpose() : transpose() is a Array class method which returns the length of elements in the array transposes the rows and columns.
Syntax: Array.transpose()
Parameter: Array
Return: transposes the rows and columns.
Example #1 :
# Ruby code for transpose() method # declaring arraya = [[18, 22], [33, 3, ], [5, 6]] # declaring arrayb = [[1, 4, 1, 1, 88, 9]] # transpose method exampleputs "transpose() method form : #{a.transpose()}\n\n" puts "transpose() method form : #{b.transpose()}\n\n"
Output :
transpose() method form : [[18, 33, 5], [22, 3, 6]]
transpose() method form : [[1], [4], [1], [1], [88], [9]]
Example #2 :
# Ruby code for transpose() method # declaring arraya = [["abc", "nil", "dog"]] # declaring arrayb = [["cow", "go", "dog"]] # transpose method exampleputs "transpose() method form : #{a.transpose()}\n\n" puts "transpose() method form : #{b.transpose()}\n\n"
Output :
transpose() method form : [["abc"], ["nil"], ["dog"]]
transpose() method form : [["cow"], ["go"], ["dog"]]
Ruby Array-class
Ruby-Methods
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 | push() function
Ruby | Array slice() function
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Array select() function
Ruby | Data Types
Ruby | Case Statement
Ruby | Enumerator each_with_index function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Dec, 2019"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "Array#transpose() : transpose() is a Array class method which returns the length of elements in the array transposes the rows and columns."
},
{
"code": null,
"e": 193,
"s": 167,
"text": "Syntax: Array.transpose()"
},
{
"code": null,
"e": 210,
"s": 193,
"text": "Parameter: Array"
},
{
"code": null,
"e": 251,
"s": 210,
"text": "Return: transposes the rows and columns."
},
{
"code": null,
"e": 264,
"s": 251,
"text": "Example #1 :"
},
{
"code": "# Ruby code for transpose() method # declaring arraya = [[18, 22], [33, 3, ], [5, 6]] # declaring arrayb = [[1, 4, 1, 1, 88, 9]] # transpose method exampleputs \"transpose() method form : #{a.transpose()}\\n\\n\" puts \"transpose() method form : #{b.transpose()}\\n\\n\"",
"e": 531,
"s": 264,
"text": null
},
{
"code": null,
"e": 540,
"s": 531,
"text": "Output :"
},
{
"code": null,
"e": 653,
"s": 540,
"text": "transpose() method form : [[18, 33, 5], [22, 3, 6]]\n\ntranspose() method form : [[1], [4], [1], [1], [88], [9]]\n\n"
},
{
"code": null,
"e": 666,
"s": 653,
"text": "Example #2 :"
},
{
"code": "# Ruby code for transpose() method # declaring arraya = [[\"abc\", \"nil\", \"dog\"]] # declaring arrayb = [[\"cow\", \"go\", \"dog\"]] # transpose method exampleputs \"transpose() method form : #{a.transpose()}\\n\\n\" puts \"transpose() method form : #{b.transpose()}\\n\\n\"",
"e": 930,
"s": 666,
"text": null
},
{
"code": null,
"e": 939,
"s": 930,
"text": "Output :"
},
{
"code": null,
"e": 1049,
"s": 939,
"text": "transpose() method form : [[\"abc\"], [\"nil\"], [\"dog\"]]\n\ntranspose() method form : [[\"cow\"], [\"go\"], [\"dog\"]]\n\n"
},
{
"code": null,
"e": 1066,
"s": 1049,
"text": "Ruby Array-class"
},
{
"code": null,
"e": 1079,
"s": 1066,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 1084,
"s": 1079,
"text": "Ruby"
},
{
"code": null,
"e": 1182,
"s": 1084,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1228,
"s": 1182,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 1259,
"s": 1228,
"text": "Ruby | Array count() operation"
},
{
"code": null,
"e": 1282,
"s": 1259,
"text": "Ruby | push() function"
},
{
"code": null,
"e": 1312,
"s": 1282,
"text": "Ruby | Array slice() function"
},
{
"code": null,
"e": 1339,
"s": 1312,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 1363,
"s": 1339,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 1394,
"s": 1363,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 1412,
"s": 1394,
"text": "Ruby | Data Types"
},
{
"code": null,
"e": 1434,
"s": 1412,
"text": "Ruby | Case Statement"
}
]
|
JSF - h:inputText | The h:inputText tag renders an HTML input element of the type "text".
<h:inputText value = "Hello World!" />
<input type = "text" name = "j_idt6:j_idt8" value = "Hello World!" />
id
Identifier for a component
binding
Reference to the component that can be used in a backing bean
rendered
A boolean; false suppresses rendering
styleClass
Cascading stylesheet (CSS) class name
value
A component’s value, typically a value binding
valueChangeListener
A method binding to a method that responds to value changes
converter
Converter class name
validator
Class name of a validator that’s created and attached to a component
required
A boolean; if true, requires a value to be entered in the associated field
accesskey
A key, typically combined with a system-defined metakey, that gives focus to an element
accept
Comma-separated list of content types for a form
accept-charset
Comma- or space-separated list of character encodings for a form. The accept-charset attribute is specified with the JSF HTML attribute named acceptcharset.
alt
Alternative text for nontextual elements such as images or applets
border
Pixel value for an element’s border width
charset
Character encoding for a linked resource
coords
Coordinates for an element whose shape is a rectangle, circle, or polygon
dir
Direction for text. Valid values are ltr (left to right) and rtl (right to left).
disabled
Disabled state of an input element or button
hreflang
Base language of a resource specified with the href attribute; hreflang may only be used with href
lang
Base language of an element’s attributes and text
maxlength
Maximum number of characters for text fields
readonly
Read-only state of an input field; the text can be selected in a readonly field but not edited
style
Inline style information
tabindex
Numerical value specifying a tab index
target
The name of a frame in which a document is opened
title
A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value
type
Type of a link; for example, stylesheet
width
Width of an element
onblur
Element loses focus
onchange
Element’s value changes
onclick
Mouse button is clicked over the element
ondblclick
Mouse button is double-clicked over the element
onfocus
Element receives focus
onkeydown
Key is pressed
onkeypress
Key is pressed and subsequently released
onkeyup
Key is released
onmousedown
Mouse button is pressed over the element
onmousemove
Mouse moves over the element
onmouseout
Mouse leaves the element’s area
onmouseover
Mouse moves onto an element
onmouseup
Mouse button is released
onreset
Form is reset
onselect
Text is selected in an input field
immediate
Process validation early in the life cycle
Let us create a test JSF application to test the above tag.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>JSF Tutorial!</title>
</head>
<body>
<h2>h:inputText example</h2>
<hr />
<h:form>
<h3>Read-Only input text box</h3>
<h:inputText value = "Hello World!" readonly = "true"/>
<h3>Read-Only input text box</h3>
<h:inputText value = "Hello World"/>
</h:form>
</body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result. | [
{
"code": null,
"e": 2156,
"s": 2086,
"text": "The h:inputText tag renders an HTML input element of the type \"text\"."
},
{
"code": null,
"e": 2197,
"s": 2156,
"text": "<h:inputText value = \"Hello World!\" /> \n"
},
{
"code": null,
"e": 2268,
"s": 2197,
"text": "<input type = \"text\" name = \"j_idt6:j_idt8\" value = \"Hello World!\" />\n"
},
{
"code": null,
"e": 2271,
"s": 2268,
"text": "id"
},
{
"code": null,
"e": 2298,
"s": 2271,
"text": "Identifier for a component"
},
{
"code": null,
"e": 2306,
"s": 2298,
"text": "binding"
},
{
"code": null,
"e": 2368,
"s": 2306,
"text": "Reference to the component that can be used in a backing bean"
},
{
"code": null,
"e": 2377,
"s": 2368,
"text": "rendered"
},
{
"code": null,
"e": 2415,
"s": 2377,
"text": "A boolean; false suppresses rendering"
},
{
"code": null,
"e": 2426,
"s": 2415,
"text": "styleClass"
},
{
"code": null,
"e": 2464,
"s": 2426,
"text": "Cascading stylesheet (CSS) class name"
},
{
"code": null,
"e": 2470,
"s": 2464,
"text": "value"
},
{
"code": null,
"e": 2517,
"s": 2470,
"text": "A component’s value, typically a value binding"
},
{
"code": null,
"e": 2537,
"s": 2517,
"text": "valueChangeListener"
},
{
"code": null,
"e": 2597,
"s": 2537,
"text": "A method binding to a method that responds to value changes"
},
{
"code": null,
"e": 2607,
"s": 2597,
"text": "converter"
},
{
"code": null,
"e": 2628,
"s": 2607,
"text": "Converter class name"
},
{
"code": null,
"e": 2638,
"s": 2628,
"text": "validator"
},
{
"code": null,
"e": 2707,
"s": 2638,
"text": "Class name of a validator that’s created and attached to a component"
},
{
"code": null,
"e": 2716,
"s": 2707,
"text": "required"
},
{
"code": null,
"e": 2791,
"s": 2716,
"text": "A boolean; if true, requires a value to be entered in the associated field"
},
{
"code": null,
"e": 2801,
"s": 2791,
"text": "accesskey"
},
{
"code": null,
"e": 2889,
"s": 2801,
"text": "A key, typically combined with a system-defined metakey, that gives focus to an element"
},
{
"code": null,
"e": 2896,
"s": 2889,
"text": "accept"
},
{
"code": null,
"e": 2945,
"s": 2896,
"text": "Comma-separated list of content types for a form"
},
{
"code": null,
"e": 2960,
"s": 2945,
"text": "accept-charset"
},
{
"code": null,
"e": 3117,
"s": 2960,
"text": "Comma- or space-separated list of character encodings for a form. The accept-charset attribute is specified with the JSF HTML attribute named acceptcharset."
},
{
"code": null,
"e": 3121,
"s": 3117,
"text": "alt"
},
{
"code": null,
"e": 3188,
"s": 3121,
"text": "Alternative text for nontextual elements such as images or applets"
},
{
"code": null,
"e": 3195,
"s": 3188,
"text": "border"
},
{
"code": null,
"e": 3237,
"s": 3195,
"text": "Pixel value for an element’s border width"
},
{
"code": null,
"e": 3245,
"s": 3237,
"text": "charset"
},
{
"code": null,
"e": 3286,
"s": 3245,
"text": "Character encoding for a linked resource"
},
{
"code": null,
"e": 3293,
"s": 3286,
"text": "coords"
},
{
"code": null,
"e": 3367,
"s": 3293,
"text": "Coordinates for an element whose shape is a rectangle, circle, or polygon"
},
{
"code": null,
"e": 3371,
"s": 3367,
"text": "dir"
},
{
"code": null,
"e": 3453,
"s": 3371,
"text": "Direction for text. Valid values are ltr (left to right) and rtl (right to left)."
},
{
"code": null,
"e": 3462,
"s": 3453,
"text": "disabled"
},
{
"code": null,
"e": 3507,
"s": 3462,
"text": "Disabled state of an input element or button"
},
{
"code": null,
"e": 3516,
"s": 3507,
"text": "hreflang"
},
{
"code": null,
"e": 3615,
"s": 3516,
"text": "Base language of a resource specified with the href attribute; hreflang may only be used with href"
},
{
"code": null,
"e": 3620,
"s": 3615,
"text": "lang"
},
{
"code": null,
"e": 3670,
"s": 3620,
"text": "Base language of an element’s attributes and text"
},
{
"code": null,
"e": 3680,
"s": 3670,
"text": "maxlength"
},
{
"code": null,
"e": 3725,
"s": 3680,
"text": "Maximum number of characters for text fields"
},
{
"code": null,
"e": 3734,
"s": 3725,
"text": "readonly"
},
{
"code": null,
"e": 3829,
"s": 3734,
"text": "Read-only state of an input field; the text can be selected in a readonly field but not edited"
},
{
"code": null,
"e": 3835,
"s": 3829,
"text": "style"
},
{
"code": null,
"e": 3860,
"s": 3835,
"text": "Inline style information"
},
{
"code": null,
"e": 3869,
"s": 3860,
"text": "tabindex"
},
{
"code": null,
"e": 3908,
"s": 3869,
"text": "Numerical value specifying a tab index"
},
{
"code": null,
"e": 3915,
"s": 3908,
"text": "target"
},
{
"code": null,
"e": 3965,
"s": 3915,
"text": "The name of a frame in which a document is opened"
},
{
"code": null,
"e": 3971,
"s": 3965,
"text": "title"
},
{
"code": null,
"e": 4095,
"s": 3971,
"text": "A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value"
},
{
"code": null,
"e": 4100,
"s": 4095,
"text": "type"
},
{
"code": null,
"e": 4140,
"s": 4100,
"text": "Type of a link; for example, stylesheet"
},
{
"code": null,
"e": 4146,
"s": 4140,
"text": "width"
},
{
"code": null,
"e": 4166,
"s": 4146,
"text": "Width of an element"
},
{
"code": null,
"e": 4173,
"s": 4166,
"text": "onblur"
},
{
"code": null,
"e": 4193,
"s": 4173,
"text": "Element loses focus"
},
{
"code": null,
"e": 4202,
"s": 4193,
"text": "onchange"
},
{
"code": null,
"e": 4226,
"s": 4202,
"text": "Element’s value changes"
},
{
"code": null,
"e": 4234,
"s": 4226,
"text": "onclick"
},
{
"code": null,
"e": 4275,
"s": 4234,
"text": "Mouse button is clicked over the element"
},
{
"code": null,
"e": 4286,
"s": 4275,
"text": "ondblclick"
},
{
"code": null,
"e": 4334,
"s": 4286,
"text": "Mouse button is double-clicked over the element"
},
{
"code": null,
"e": 4342,
"s": 4334,
"text": "onfocus"
},
{
"code": null,
"e": 4365,
"s": 4342,
"text": "Element receives focus"
},
{
"code": null,
"e": 4375,
"s": 4365,
"text": "onkeydown"
},
{
"code": null,
"e": 4390,
"s": 4375,
"text": "Key is pressed"
},
{
"code": null,
"e": 4401,
"s": 4390,
"text": "onkeypress"
},
{
"code": null,
"e": 4442,
"s": 4401,
"text": "Key is pressed and subsequently released"
},
{
"code": null,
"e": 4450,
"s": 4442,
"text": "onkeyup"
},
{
"code": null,
"e": 4466,
"s": 4450,
"text": "Key is released"
},
{
"code": null,
"e": 4478,
"s": 4466,
"text": "onmousedown"
},
{
"code": null,
"e": 4519,
"s": 4478,
"text": "Mouse button is pressed over the element"
},
{
"code": null,
"e": 4531,
"s": 4519,
"text": "onmousemove"
},
{
"code": null,
"e": 4560,
"s": 4531,
"text": "Mouse moves over the element"
},
{
"code": null,
"e": 4571,
"s": 4560,
"text": "onmouseout"
},
{
"code": null,
"e": 4603,
"s": 4571,
"text": "Mouse leaves the element’s area"
},
{
"code": null,
"e": 4615,
"s": 4603,
"text": "onmouseover"
},
{
"code": null,
"e": 4643,
"s": 4615,
"text": "Mouse moves onto an element"
},
{
"code": null,
"e": 4653,
"s": 4643,
"text": "onmouseup"
},
{
"code": null,
"e": 4678,
"s": 4653,
"text": "Mouse button is released"
},
{
"code": null,
"e": 4686,
"s": 4678,
"text": "onreset"
},
{
"code": null,
"e": 4700,
"s": 4686,
"text": "Form is reset"
},
{
"code": null,
"e": 4709,
"s": 4700,
"text": "onselect"
},
{
"code": null,
"e": 4744,
"s": 4709,
"text": "Text is selected in an input field"
},
{
"code": null,
"e": 4754,
"s": 4744,
"text": "immediate"
},
{
"code": null,
"e": 4797,
"s": 4754,
"text": "Process validation early in the life cycle"
},
{
"code": null,
"e": 4857,
"s": 4797,
"text": "Let us create a test JSF application to test the above tag."
},
{
"code": null,
"e": 5405,
"s": 4857,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\">\n <head>\n <title>JSF Tutorial!</title>\n </head>\n \n <body>\n <h2>h:inputText example</h2>\n <hr />\n \n <h:form>\n <h3>Read-Only input text box</h3>\n <h:inputText value = \"Hello World!\" readonly = \"true\"/>\n <h3>Read-Only input text box</h3>\n <h:inputText value = \"Hello World\"/>\n </h:form>\n \n </body>\n</html>"
}
]
|
JavaScript string.normalize() Method | 06 Oct, 2021
Below is the example of the string.normalize() method.
Example:
javascript
<script>var a = "Geeks For Geeks"; b = a.normalize('NFC')c = a.normalize('NFD')d = a.normalize('NFKC')e = a.normalize('NFKD') document.write(b,c,d,e);</script>
Output:
Geeks For GeeksGeeks For GeeksGeeks For GeeksGeeks For Geeks
The string.normalize() is an inbuilt method in javascript which is used to return a Unicode normalisation form of a given input string. If the given input is not a string, then at first it will be converted into a string then this method will work.Syntax:
string.normalize([form])
Parameters: Here the parameter is form which is of many types-
NFC: Normalization Form Canonical Composition.
NFD: Normalization Form Canonical Decomposition.
NFKC: Normalization Form Compatibility Composition.
NFKD: Normalization Form Compatibility Decomposition.
These all say the Unicode Normalization Form. Return value: It returns a new string containing the Unicode Normalization Form of the given input string.JavaScript code to show the working of string.normalize() method:
javascript
<script> // Taking a string as input. var a = "GeeksForGeeks"; // calling normalize method. b = a.normalize('NFC') c = a.normalize('NFD') d = a.normalize('NFKC') e = a.normalize('NFKD') // Printing normalised form. document.write(b +"<br>"); document.write(c +"<br>"); document.write(d +"<br>"); document.write(e); </script>
Output:
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
Supported Browsers:
Google Chrome 34 and above
Edge 12 and above
Firefox 31 and above
Opera 21 and above
Safari 10 and above
ysachin2314
JavaScript-Methods
javascript-string
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
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": "\n06 Oct, 2021"
},
{
"code": null,
"e": 85,
"s": 28,
"text": "Below is the example of the string.normalize() method. "
},
{
"code": null,
"e": 96,
"s": 85,
"text": "Example: "
},
{
"code": null,
"e": 107,
"s": 96,
"text": "javascript"
},
{
"code": "<script>var a = \"Geeks For Geeks\"; b = a.normalize('NFC')c = a.normalize('NFD')d = a.normalize('NFKC')e = a.normalize('NFKD') document.write(b,c,d,e);</script>",
"e": 271,
"s": 107,
"text": null
},
{
"code": null,
"e": 281,
"s": 271,
"text": "Output: "
},
{
"code": null,
"e": 342,
"s": 281,
"text": "Geeks For GeeksGeeks For GeeksGeeks For GeeksGeeks For Geeks"
},
{
"code": null,
"e": 600,
"s": 342,
"text": "The string.normalize() is an inbuilt method in javascript which is used to return a Unicode normalisation form of a given input string. If the given input is not a string, then at first it will be converted into a string then this method will work.Syntax: "
},
{
"code": null,
"e": 625,
"s": 600,
"text": "string.normalize([form])"
},
{
"code": null,
"e": 690,
"s": 625,
"text": "Parameters: Here the parameter is form which is of many types- "
},
{
"code": null,
"e": 737,
"s": 690,
"text": "NFC: Normalization Form Canonical Composition."
},
{
"code": null,
"e": 786,
"s": 737,
"text": "NFD: Normalization Form Canonical Decomposition."
},
{
"code": null,
"e": 838,
"s": 786,
"text": "NFKC: Normalization Form Compatibility Composition."
},
{
"code": null,
"e": 892,
"s": 838,
"text": "NFKD: Normalization Form Compatibility Decomposition."
},
{
"code": null,
"e": 1112,
"s": 892,
"text": "These all say the Unicode Normalization Form. Return value: It returns a new string containing the Unicode Normalization Form of the given input string.JavaScript code to show the working of string.normalize() method: "
},
{
"code": null,
"e": 1123,
"s": 1112,
"text": "javascript"
},
{
"code": "<script> // Taking a string as input. var a = \"GeeksForGeeks\"; // calling normalize method. b = a.normalize('NFC') c = a.normalize('NFD') d = a.normalize('NFKC') e = a.normalize('NFKD') // Printing normalised form. document.write(b +\"<br>\"); document.write(c +\"<br>\"); document.write(d +\"<br>\"); document.write(e); </script>",
"e": 1469,
"s": 1123,
"text": null
},
{
"code": null,
"e": 1479,
"s": 1469,
"text": "Output: "
},
{
"code": null,
"e": 1535,
"s": 1479,
"text": "GeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks"
},
{
"code": null,
"e": 1557,
"s": 1535,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 1584,
"s": 1557,
"text": "Google Chrome 34 and above"
},
{
"code": null,
"e": 1602,
"s": 1584,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 1623,
"s": 1602,
"text": "Firefox 31 and above"
},
{
"code": null,
"e": 1642,
"s": 1623,
"text": "Opera 21 and above"
},
{
"code": null,
"e": 1662,
"s": 1642,
"text": "Safari 10 and above"
},
{
"code": null,
"e": 1676,
"s": 1664,
"text": "ysachin2314"
},
{
"code": null,
"e": 1695,
"s": 1676,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 1713,
"s": 1695,
"text": "javascript-string"
},
{
"code": null,
"e": 1724,
"s": 1713,
"text": "JavaScript"
},
{
"code": null,
"e": 1741,
"s": 1724,
"text": "Web Technologies"
},
{
"code": null,
"e": 1839,
"s": 1741,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1900,
"s": 1839,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1972,
"s": 1900,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2012,
"s": 1972,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2053,
"s": 2012,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2105,
"s": 2053,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2167,
"s": 2105,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2200,
"s": 2167,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2261,
"s": 2200,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2311,
"s": 2261,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Lodash _.property() Method | 09 Sep, 2020
The Lodash _.property() method is used to return a function that will return the specified property of any passed-in object.
Syntax:
_.property(path)
Parameters: This method accepts one parameter as mentioned above and described below:
path: This parameter holds the path of the property to get.
Return Value: This method returns a new accessor function.
Example 1 :
Javascript
// Requiring the lodash library const _ = require("lodash"); var info = { Company: 'GeeksforGeeks', Address: 'Noida' }; // Use of _.property() method let gfg = _.property('Company') (info) === 'GeeksforGeeks' // Printing the output console.log(gfg);
Output:
true
Example 2 :
Javascript
// Requiring the lodash library const _ = require("lodash"); var info = { Company: { name: 'GeeksforGeeks' }, Contact: { Address: { AddressInfo: 'Noida' } } }; // Use of _.property() method var propInfo = _.property(['Contact', 'Address', 'AddressInfo', ]); // Printing the output console.log(propInfo(info));
Output:
Noida
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
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": "\n09 Sep, 2020"
},
{
"code": null,
"e": 153,
"s": 28,
"text": "The Lodash _.property() method is used to return a function that will return the specified property of any passed-in object."
},
{
"code": null,
"e": 162,
"s": 153,
"text": "Syntax: "
},
{
"code": null,
"e": 180,
"s": 162,
"text": "_.property(path)\n"
},
{
"code": null,
"e": 266,
"s": 180,
"text": "Parameters: This method accepts one parameter as mentioned above and described below:"
},
{
"code": null,
"e": 326,
"s": 266,
"text": "path: This parameter holds the path of the property to get."
},
{
"code": null,
"e": 385,
"s": 326,
"text": "Return Value: This method returns a new accessor function."
},
{
"code": null,
"e": 397,
"s": 385,
"text": "Example 1 :"
},
{
"code": null,
"e": 408,
"s": 397,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); var info = { Company: 'GeeksforGeeks', Address: 'Noida' }; // Use of _.property() method let gfg = _.property('Company') (info) === 'GeeksforGeeks' // Printing the output console.log(gfg);",
"e": 733,
"s": 408,
"text": null
},
{
"code": null,
"e": 741,
"s": 733,
"text": "Output:"
},
{
"code": null,
"e": 747,
"s": 741,
"text": "true\n"
},
{
"code": null,
"e": 759,
"s": 747,
"text": "Example 2 :"
},
{
"code": null,
"e": 770,
"s": 759,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); var info = { Company: { name: 'GeeksforGeeks' }, Contact: { Address: { AddressInfo: 'Noida' } } }; // Use of _.property() method var propInfo = _.property(['Contact', 'Address', 'AddressInfo', ]); // Printing the output console.log(propInfo(info));",
"e": 1218,
"s": 770,
"text": null
},
{
"code": null,
"e": 1226,
"s": 1218,
"text": "Output:"
},
{
"code": null,
"e": 1233,
"s": 1226,
"text": "Noida\n"
},
{
"code": null,
"e": 1251,
"s": 1233,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1262,
"s": 1251,
"text": "JavaScript"
},
{
"code": null,
"e": 1279,
"s": 1262,
"text": "Web Technologies"
},
{
"code": null,
"e": 1377,
"s": 1279,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1438,
"s": 1377,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1478,
"s": 1438,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1519,
"s": 1478,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1561,
"s": 1519,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 1583,
"s": 1561,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 1616,
"s": 1583,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1678,
"s": 1616,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1739,
"s": 1678,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1789,
"s": 1739,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
C# Program For Listing the Files in a Directory | 15 Nov, 2021
Given files, now our task is to list all these files in the directory using C#. So to do this task we use the following function and class:
DirectoryInfo: It is a class that provides different types of methods for moving, creating, and enumerating through directories and their subdirectories. You cannot inherit it.
Syntax:
DirectoryInfo object = new DirectoryInfo(path);
Where path is the file destination for example – @”C:\MyFolder\file_name”.
GetFiles: This method is used to get the list of files that are present in the current directory. The filenames are returned in this method in an unsorted way. If you want sorted file names then use the Sort method.
Syntax:
DirectoryInfo_object.GetFiles()
This method returns an array of type FileInfo. And throws DirectoryNotFoundException when the specified path is not found or is invalid. This method can be overloaded in the following ways:
GetFiles(String): This method is used to get the files’ names including their paths in the given directory.
GetFiles(String, String, EnumerationOptions): This method is used to get files names along with their paths that match the given search pattern and enumeration options in the given directory.
GetFiles(String, String, SearchOption): This method is used to get the file’s names along with their paths that match the given search pattern in the given directory. Also using a value to check whether to search subdirectories.
Approach
1. Create and read the directory using DirectoryInfo class
DirectoryInfo place = new DirectoryInfo(@"C:\Train");
2. Create an Array to get all list of files using GetFiles() Method
FileInfo[] Files = place.GetFiles();
3. Display file names with Name attribute through foreach loop
foreach(FileInfo i in Files)
{
Console.WriteLine("File Name - {0}",
i.Name);
}
Example:
In this example, we are taking C drive one folder(directory) named Train – It includes all csv files. Now we will display the list of files present in this directory.
C#
// C# program to listing the files in a directoryusing System;using System.IO; class GFG{ static void Main(string[] args){ // Get the directory DirectoryInfo place = new DirectoryInfo(@"C:\Train"); // Using GetFiles() method to get list of all // the files present in the Train directory FileInfo[] Files = place.GetFiles(); Console.WriteLine("Files are:"); Console.WriteLine(); // Display the file names foreach(FileInfo i in Files) { Console.WriteLine("File Name - {0}", i.Name); }}}
Output:
Files are:
File Name - crop_yielding.csv
File Name - cropdamage.csv
File Name - crops_data.csv
File Name - doses.csv
File Name - pesticides.csv
File Name - soiltype.csv
sooda367
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Partial Classes in C#
Lambda Expressions in C#
Hello World in C# | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "Given files, now our task is to list all these files in the directory using C#. So to do this task we use the following function and class:"
},
{
"code": null,
"e": 345,
"s": 168,
"text": "DirectoryInfo: It is a class that provides different types of methods for moving, creating, and enumerating through directories and their subdirectories. You cannot inherit it."
},
{
"code": null,
"e": 353,
"s": 345,
"text": "Syntax:"
},
{
"code": null,
"e": 401,
"s": 353,
"text": "DirectoryInfo object = new DirectoryInfo(path);"
},
{
"code": null,
"e": 476,
"s": 401,
"text": "Where path is the file destination for example – @”C:\\MyFolder\\file_name”."
},
{
"code": null,
"e": 692,
"s": 476,
"text": "GetFiles: This method is used to get the list of files that are present in the current directory. The filenames are returned in this method in an unsorted way. If you want sorted file names then use the Sort method."
},
{
"code": null,
"e": 700,
"s": 692,
"text": "Syntax:"
},
{
"code": null,
"e": 732,
"s": 700,
"text": "DirectoryInfo_object.GetFiles()"
},
{
"code": null,
"e": 922,
"s": 732,
"text": "This method returns an array of type FileInfo. And throws DirectoryNotFoundException when the specified path is not found or is invalid. This method can be overloaded in the following ways:"
},
{
"code": null,
"e": 1030,
"s": 922,
"text": "GetFiles(String): This method is used to get the files’ names including their paths in the given directory."
},
{
"code": null,
"e": 1222,
"s": 1030,
"text": "GetFiles(String, String, EnumerationOptions): This method is used to get files names along with their paths that match the given search pattern and enumeration options in the given directory."
},
{
"code": null,
"e": 1451,
"s": 1222,
"text": "GetFiles(String, String, SearchOption): This method is used to get the file’s names along with their paths that match the given search pattern in the given directory. Also using a value to check whether to search subdirectories."
},
{
"code": null,
"e": 1460,
"s": 1451,
"text": "Approach"
},
{
"code": null,
"e": 1519,
"s": 1460,
"text": "1. Create and read the directory using DirectoryInfo class"
},
{
"code": null,
"e": 1574,
"s": 1519,
"text": "DirectoryInfo place = new DirectoryInfo(@\"C:\\Train\");"
},
{
"code": null,
"e": 1642,
"s": 1574,
"text": "2. Create an Array to get all list of files using GetFiles() Method"
},
{
"code": null,
"e": 1691,
"s": 1642,
"text": " FileInfo[] Files = place.GetFiles();"
},
{
"code": null,
"e": 1754,
"s": 1691,
"text": "3. Display file names with Name attribute through foreach loop"
},
{
"code": null,
"e": 1871,
"s": 1754,
"text": "foreach(FileInfo i in Files)\n{ \n Console.WriteLine(\"File Name - {0}\",\n i.Name);\n}"
},
{
"code": null,
"e": 1881,
"s": 1871,
"text": "Example: "
},
{
"code": null,
"e": 2048,
"s": 1881,
"text": "In this example, we are taking C drive one folder(directory) named Train – It includes all csv files. Now we will display the list of files present in this directory."
},
{
"code": null,
"e": 2051,
"s": 2048,
"text": "C#"
},
{
"code": "// C# program to listing the files in a directoryusing System;using System.IO; class GFG{ static void Main(string[] args){ // Get the directory DirectoryInfo place = new DirectoryInfo(@\"C:\\Train\"); // Using GetFiles() method to get list of all // the files present in the Train directory FileInfo[] Files = place.GetFiles(); Console.WriteLine(\"Files are:\"); Console.WriteLine(); // Display the file names foreach(FileInfo i in Files) { Console.WriteLine(\"File Name - {0}\", i.Name); }}}",
"e": 2596,
"s": 2051,
"text": null
},
{
"code": null,
"e": 2604,
"s": 2596,
"text": "Output:"
},
{
"code": null,
"e": 2773,
"s": 2604,
"text": "Files are:\nFile Name - crop_yielding.csv\nFile Name - cropdamage.csv\nFile Name - crops_data.csv\nFile Name - doses.csv\nFile Name - pesticides.csv\nFile Name - soiltype.csv"
},
{
"code": null,
"e": 2782,
"s": 2773,
"text": "sooda367"
},
{
"code": null,
"e": 2798,
"s": 2782,
"text": "CSharp-programs"
},
{
"code": null,
"e": 2805,
"s": 2798,
"text": "Picked"
},
{
"code": null,
"e": 2808,
"s": 2805,
"text": "C#"
},
{
"code": null,
"e": 2906,
"s": 2808,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2949,
"s": 2906,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 2998,
"s": 2949,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 3021,
"s": 2998,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 3037,
"s": 3021,
"text": "C# | List Class"
},
{
"code": null,
"e": 3065,
"s": 3037,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 3126,
"s": 3065,
"text": "C# | .NET Framework (Basic Architecture and Component Stack)"
},
{
"code": null,
"e": 3149,
"s": 3126,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 3171,
"s": 3149,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 3196,
"s": 3171,
"text": "Lambda Expressions in C#"
}
]
|
Ruby | Control Flow Alteration | 12 Jun, 2019
Prerequisite : Decision Making , Loops
Ruby programming language provides some statements in addition to loops, conditionals, and iterators, which are used to change the flow of control in a program.In other words, these statements are a piece of code that executes one after another until the condition is true and when the condition becomes false then code terminated. The following are the statements which can alter the control flow in a Ruby program:
break statementnext statementredo statementretry statementreturn statementthrow/catch statement
break statement
next statement
redo statement
retry statement
return statement
throw/catch statement
break StatementIn Ruby, Break statement is used to exit a loop when the condition is true. Break statement is basically used in while loop because in while loop the output is printed till the condition is true, when the condition is false the loop exited. The break statement is used inside the loop. The break statement are executed by break keyword. Break statement can also be used in for, while, and case control statements.Syntax:breakExample:# Ruby program to illustrate break statement #!/usr/bin/ruby i = 1 # using while loopwhile true if i * 6 >= 30 # using break statement break # ending of if statement end puts i * 6 i += 1 # ending of while loopend Output:6
12
18
24
Explanation: In above example, break statement is used to stop the execution of while loop when the condition if i * 6 >= 30 becomes true. Otherwise loop goes to infinite.next StatementIn Ruby, next statement is used to jump to the next iterator of given loop. The next statement is identical to continue statement in C and Java language. When the next statement is used no other iteration will be performed. Generally, the next statement is used in for and while loop.Syntax:nextExample:# Ruby program to illustrate next statement #!/usr/bin/ruby # using for loopfor t in 0...10 # using if statement if t == 5 then # using next statement next # ending of if end # displaying values puts t # end of for loop end Output:0
1
2
3
4
6
7
8
9
Explanation: In the above program, 5 will not be printed in the output due to next statement. So here at 5 next statement will cause to skip it and continue from next statement in program.redo StatementThe redo statement is used to restart the current iteration of a loop or the iterator. There is a difference between the redo and next statement. next statement always transfers the control to the end of the loop where the statement after the loop can start to execute, but redo statement transfer the control back to the top of block or loop so that iteration can start over.Syntax:redoExample:# Ruby program to demonstrate the redo statement # defining a variableval = 0 # using while loop which should give# output as 0,1,2,3 but here it will # output as 0,1,2,3,4while(val < 4) # Control returns here when # redo will executeputs valval += 1 # using redo statementredo if val == 4 # ending of while loopendOutput:0
1
2
3
4
Explanation: In the above program, redo statement will transfer the control to puts val which is the first expression of while loop. It is neither going to retest the loop condition nor going to fetch the next element from the iterator. So, here while loop will print 0,1,2,3,4 instead of 0,1,2,3.retry Statement(deprecated in recent versions)retry statement is used to restart an iterator based on a certain condition or any method invocation from the starting. In simple words, retry statement transfers the control at the beginning. Generally, a retry statement is used rarely. It will only work till Ruby version 1.8.Note: retry statement has been removed from the Ruby version 1.9 onwards because it is considered deprecated language feature. So it will hardly run on online IDE’s because mostly using version above 1.8.Syntax:retryExample:# Ruby program to demonstrate the retry statement # variablevar = 7 # Iterate 7 times from 0 to 7-1var.times do |val| # display iteration numberputs val # If we've reached 6if val == 6 # Decrement val and user won't# reach 6 next timevar = var - 1 # Restart the iteration# using retry statementretry # end of if end # end of do..endendOutput:0
1
2
3
4
5
6
0
1
2
3
4
5
Explanation: In above program, when the control goes to retry statement then it transfers that control to var.times do |val| . Now here the value of var variable is updated i.e. 5. So user won’t reach 6 to next time and retry statement will not execute again.return statementThis is used to exit from a method, with or without a value. It always returns a value to its caller. There are many options with the return statement. If there is no expression used with return statement then it always returns the value of method as nil. A list of expression after the return statement is always separated by the comma(,) In this case, the value of the method will be an array containing the values of those specified expressions.Example:# Ruby program to demonstrate the return statement #!/usr/bin/ruby # defining a method 'geeks'def geeks # variables of method val1 = 61 val2 = 55 # returning multiple values return val1, val2 # this statement will not executeputs "Hello Geeks" # end of the methodend # variable outside the method to # store the return value of the methodvalue = geeks # displaying the returned valuesputs valueOutput:55
61
Explanation: In above example, method geeks has a return statement which return the two values i.e. val1 and val2 to its caller. Here value is the variable which stored the returned values. The important point is that the statement puts “Hello Geeks” after return statement doesn’t execute because statements after the return statement will not execute inside a method.throw/catch Statementthrow and catch are used to define a control structure which can be considered as a multilevel break. throw is used to break the current loop and transfer the control outside of the catch block. The best thing about throw is that it can break out of the current loop or methods or we can say it can cross any number of levels. Here, catch defines a “labeled block” of code which causes to exit by the throw block. More details will be discussed In Ruby Exception Handling section.Example:# Ruby program to illustrate the throw/catch statement# for altering the control flow # defining a methoddef lessNumber(num) # using throw statement # here 'numberError' is its label throw :numberError if num < 10 # displaying result puts "Number is Greater than 10!"end # catch blockcatch :numberError do # calling method lessNumber(11) lessNumber(78) # exits catch block here lessNumber(7) lessNumber(4)end puts "Outside Catch Block"Output:Number is Greater than 10!
Number is Greater than 10!
Outside Catch Block
Explanation: In above program, 11 is passed to method lessNumber to check whether it is greater than 10 or not. 11 is greater than 10 so statement will print out on display and next statement of catch block will execute. Now 78 is passed to the method call, which is checked and it is greater than 10 so statement will print out on screen. But as soon as 7 is passed which is less than 10 throw: numberError cause the catch block to exits and all the statements skip out and last statement “Outside Catch Block” will print. So here as soon as the condition becomes false throw causes the catch block to exit the catch block from execution.My Personal Notes
arrow_drop_upSave
In Ruby, Break statement is used to exit a loop when the condition is true. Break statement is basically used in while loop because in while loop the output is printed till the condition is true, when the condition is false the loop exited. The break statement is used inside the loop. The break statement are executed by break keyword. Break statement can also be used in for, while, and case control statements.
Syntax:
break
Example:
# Ruby program to illustrate break statement #!/usr/bin/ruby i = 1 # using while loopwhile true if i * 6 >= 30 # using break statement break # ending of if statement end puts i * 6 i += 1 # ending of while loopend
Output:
6
12
18
24
Explanation: In above example, break statement is used to stop the execution of while loop when the condition if i * 6 >= 30 becomes true. Otherwise loop goes to infinite.
In Ruby, next statement is used to jump to the next iterator of given loop. The next statement is identical to continue statement in C and Java language. When the next statement is used no other iteration will be performed. Generally, the next statement is used in for and while loop.
Syntax:
next
Example:
# Ruby program to illustrate next statement #!/usr/bin/ruby # using for loopfor t in 0...10 # using if statement if t == 5 then # using next statement next # ending of if end # displaying values puts t # end of for loop end
Output:
0
1
2
3
4
6
7
8
9
Explanation: In the above program, 5 will not be printed in the output due to next statement. So here at 5 next statement will cause to skip it and continue from next statement in program.
The redo statement is used to restart the current iteration of a loop or the iterator. There is a difference between the redo and next statement. next statement always transfers the control to the end of the loop where the statement after the loop can start to execute, but redo statement transfer the control back to the top of block or loop so that iteration can start over.
Syntax:
redo
Example:
# Ruby program to demonstrate the redo statement # defining a variableval = 0 # using while loop which should give# output as 0,1,2,3 but here it will # output as 0,1,2,3,4while(val < 4) # Control returns here when # redo will executeputs valval += 1 # using redo statementredo if val == 4 # ending of while loopend
Output:
0
1
2
3
4
Explanation: In the above program, redo statement will transfer the control to puts val which is the first expression of while loop. It is neither going to retest the loop condition nor going to fetch the next element from the iterator. So, here while loop will print 0,1,2,3,4 instead of 0,1,2,3.
retry statement is used to restart an iterator based on a certain condition or any method invocation from the starting. In simple words, retry statement transfers the control at the beginning. Generally, a retry statement is used rarely. It will only work till Ruby version 1.8.
Note: retry statement has been removed from the Ruby version 1.9 onwards because it is considered deprecated language feature. So it will hardly run on online IDE’s because mostly using version above 1.8.
Syntax:
retry
Example:
# Ruby program to demonstrate the retry statement # variablevar = 7 # Iterate 7 times from 0 to 7-1var.times do |val| # display iteration numberputs val # If we've reached 6if val == 6 # Decrement val and user won't# reach 6 next timevar = var - 1 # Restart the iteration# using retry statementretry # end of if end # end of do..endend
Output:
0
1
2
3
4
5
6
0
1
2
3
4
5
Explanation: In above program, when the control goes to retry statement then it transfers that control to var.times do |val| . Now here the value of var variable is updated i.e. 5. So user won’t reach 6 to next time and retry statement will not execute again.
This is used to exit from a method, with or without a value. It always returns a value to its caller. There are many options with the return statement. If there is no expression used with return statement then it always returns the value of method as nil. A list of expression after the return statement is always separated by the comma(,) In this case, the value of the method will be an array containing the values of those specified expressions.
Example:
# Ruby program to demonstrate the return statement #!/usr/bin/ruby # defining a method 'geeks'def geeks # variables of method val1 = 61 val2 = 55 # returning multiple values return val1, val2 # this statement will not executeputs "Hello Geeks" # end of the methodend # variable outside the method to # store the return value of the methodvalue = geeks # displaying the returned valuesputs value
Output:
55
61
Explanation: In above example, method geeks has a return statement which return the two values i.e. val1 and val2 to its caller. Here value is the variable which stored the returned values. The important point is that the statement puts “Hello Geeks” after return statement doesn’t execute because statements after the return statement will not execute inside a method.
throw and catch are used to define a control structure which can be considered as a multilevel break. throw is used to break the current loop and transfer the control outside of the catch block. The best thing about throw is that it can break out of the current loop or methods or we can say it can cross any number of levels. Here, catch defines a “labeled block” of code which causes to exit by the throw block. More details will be discussed In Ruby Exception Handling section.
Example:
# Ruby program to illustrate the throw/catch statement# for altering the control flow # defining a methoddef lessNumber(num) # using throw statement # here 'numberError' is its label throw :numberError if num < 10 # displaying result puts "Number is Greater than 10!"end # catch blockcatch :numberError do # calling method lessNumber(11) lessNumber(78) # exits catch block here lessNumber(7) lessNumber(4)end puts "Outside Catch Block"
Output:
Number is Greater than 10!
Number is Greater than 10!
Outside Catch Block
Explanation: In above program, 11 is passed to method lessNumber to check whether it is greater than 10 or not. 11 is greater than 10 so statement will print out on display and next statement of catch block will execute. Now 78 is passed to the method call, which is checked and it is greater than 10 so statement will print out on screen. But as soon as 7 is passed which is less than 10 throw: numberError cause the catch block to exits and all the statements skip out and last statement “Outside Catch Block” will print. So here as soon as the condition becomes false throw causes the catch block to exit the catch block from execution.
nidhi_biet
Ruby-Basics
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 | Enumerator each_with_index function
Ruby | unless Statement and unless Modifier
Ruby on Rails Introduction
Ruby | String concat Method
Ruby | Array class find_index() operation
Ruby For Beginners
Ruby | Array shift() function
Ruby | Types of Variables | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n12 Jun, 2019"
},
{
"code": null,
"e": 92,
"s": 53,
"text": "Prerequisite : Decision Making , Loops"
},
{
"code": null,
"e": 509,
"s": 92,
"text": "Ruby programming language provides some statements in addition to loops, conditionals, and iterators, which are used to change the flow of control in a program.In other words, these statements are a piece of code that executes one after another until the condition is true and when the condition becomes false then code terminated. The following are the statements which can alter the control flow in a Ruby program:"
},
{
"code": null,
"e": 605,
"s": 509,
"text": "break statementnext statementredo statementretry statementreturn statementthrow/catch statement"
},
{
"code": null,
"e": 621,
"s": 605,
"text": "break statement"
},
{
"code": null,
"e": 636,
"s": 621,
"text": "next statement"
},
{
"code": null,
"e": 651,
"s": 636,
"text": "redo statement"
},
{
"code": null,
"e": 667,
"s": 651,
"text": "retry statement"
},
{
"code": null,
"e": 684,
"s": 667,
"text": "return statement"
},
{
"code": null,
"e": 706,
"s": 684,
"text": "throw/catch statement"
},
{
"code": null,
"e": 7710,
"s": 706,
"text": "break StatementIn Ruby, Break statement is used to exit a loop when the condition is true. Break statement is basically used in while loop because in while loop the output is printed till the condition is true, when the condition is false the loop exited. The break statement is used inside the loop. The break statement are executed by break keyword. Break statement can also be used in for, while, and case control statements.Syntax:breakExample:# Ruby program to illustrate break statement #!/usr/bin/ruby i = 1 # using while loopwhile true if i * 6 >= 30 # using break statement break # ending of if statement end puts i * 6 i += 1 # ending of while loopend Output:6\n12\n18\n24\nExplanation: In above example, break statement is used to stop the execution of while loop when the condition if i * 6 >= 30 becomes true. Otherwise loop goes to infinite.next StatementIn Ruby, next statement is used to jump to the next iterator of given loop. The next statement is identical to continue statement in C and Java language. When the next statement is used no other iteration will be performed. Generally, the next statement is used in for and while loop.Syntax:nextExample:# Ruby program to illustrate next statement #!/usr/bin/ruby # using for loopfor t in 0...10 # using if statement if t == 5 then # using next statement next # ending of if end # displaying values puts t # end of for loop end Output:0\n1\n2\n3\n4\n6\n7\n8\n9\nExplanation: In the above program, 5 will not be printed in the output due to next statement. So here at 5 next statement will cause to skip it and continue from next statement in program.redo StatementThe redo statement is used to restart the current iteration of a loop or the iterator. There is a difference between the redo and next statement. next statement always transfers the control to the end of the loop where the statement after the loop can start to execute, but redo statement transfer the control back to the top of block or loop so that iteration can start over.Syntax:redoExample:# Ruby program to demonstrate the redo statement # defining a variableval = 0 # using while loop which should give# output as 0,1,2,3 but here it will # output as 0,1,2,3,4while(val < 4) # Control returns here when # redo will executeputs valval += 1 # using redo statementredo if val == 4 # ending of while loopendOutput:0\n1\n2\n3\n4\nExplanation: In the above program, redo statement will transfer the control to puts val which is the first expression of while loop. It is neither going to retest the loop condition nor going to fetch the next element from the iterator. So, here while loop will print 0,1,2,3,4 instead of 0,1,2,3.retry Statement(deprecated in recent versions)retry statement is used to restart an iterator based on a certain condition or any method invocation from the starting. In simple words, retry statement transfers the control at the beginning. Generally, a retry statement is used rarely. It will only work till Ruby version 1.8.Note: retry statement has been removed from the Ruby version 1.9 onwards because it is considered deprecated language feature. So it will hardly run on online IDE’s because mostly using version above 1.8.Syntax:retryExample:# Ruby program to demonstrate the retry statement # variablevar = 7 # Iterate 7 times from 0 to 7-1var.times do |val| # display iteration numberputs val # If we've reached 6if val == 6 # Decrement val and user won't# reach 6 next timevar = var - 1 # Restart the iteration# using retry statementretry # end of if end # end of do..endendOutput:0\n1\n2\n3\n4\n5\n6\n0\n1\n2\n3\n4\n5\nExplanation: In above program, when the control goes to retry statement then it transfers that control to var.times do |val| . Now here the value of var variable is updated i.e. 5. So user won’t reach 6 to next time and retry statement will not execute again.return statementThis is used to exit from a method, with or without a value. It always returns a value to its caller. There are many options with the return statement. If there is no expression used with return statement then it always returns the value of method as nil. A list of expression after the return statement is always separated by the comma(,) In this case, the value of the method will be an array containing the values of those specified expressions.Example:# Ruby program to demonstrate the return statement #!/usr/bin/ruby # defining a method 'geeks'def geeks # variables of method val1 = 61 val2 = 55 # returning multiple values return val1, val2 # this statement will not executeputs \"Hello Geeks\" # end of the methodend # variable outside the method to # store the return value of the methodvalue = geeks # displaying the returned valuesputs valueOutput:55\n61\nExplanation: In above example, method geeks has a return statement which return the two values i.e. val1 and val2 to its caller. Here value is the variable which stored the returned values. The important point is that the statement puts “Hello Geeks” after return statement doesn’t execute because statements after the return statement will not execute inside a method.throw/catch Statementthrow and catch are used to define a control structure which can be considered as a multilevel break. throw is used to break the current loop and transfer the control outside of the catch block. The best thing about throw is that it can break out of the current loop or methods or we can say it can cross any number of levels. Here, catch defines a “labeled block” of code which causes to exit by the throw block. More details will be discussed In Ruby Exception Handling section.Example:# Ruby program to illustrate the throw/catch statement# for altering the control flow # defining a methoddef lessNumber(num) # using throw statement # here 'numberError' is its label throw :numberError if num < 10 # displaying result puts \"Number is Greater than 10!\"end # catch blockcatch :numberError do # calling method lessNumber(11) lessNumber(78) # exits catch block here lessNumber(7) lessNumber(4)end puts \"Outside Catch Block\"Output:Number is Greater than 10!\nNumber is Greater than 10!\nOutside Catch Block\nExplanation: In above program, 11 is passed to method lessNumber to check whether it is greater than 10 or not. 11 is greater than 10 so statement will print out on display and next statement of catch block will execute. Now 78 is passed to the method call, which is checked and it is greater than 10 so statement will print out on screen. But as soon as 7 is passed which is less than 10 throw: numberError cause the catch block to exits and all the statements skip out and last statement “Outside Catch Block” will print. So here as soon as the condition becomes false throw causes the catch block to exit the catch block from execution.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 8124,
"s": 7710,
"text": "In Ruby, Break statement is used to exit a loop when the condition is true. Break statement is basically used in while loop because in while loop the output is printed till the condition is true, when the condition is false the loop exited. The break statement is used inside the loop. The break statement are executed by break keyword. Break statement can also be used in for, while, and case control statements."
},
{
"code": null,
"e": 8132,
"s": 8124,
"text": "Syntax:"
},
{
"code": null,
"e": 8138,
"s": 8132,
"text": "break"
},
{
"code": null,
"e": 8147,
"s": 8138,
"text": "Example:"
},
{
"code": "# Ruby program to illustrate break statement #!/usr/bin/ruby i = 1 # using while loopwhile true if i * 6 >= 30 # using break statement break # ending of if statement end puts i * 6 i += 1 # ending of while loopend ",
"e": 8446,
"s": 8147,
"text": null
},
{
"code": null,
"e": 8454,
"s": 8446,
"text": "Output:"
},
{
"code": null,
"e": 8466,
"s": 8454,
"text": "6\n12\n18\n24\n"
},
{
"code": null,
"e": 8638,
"s": 8466,
"text": "Explanation: In above example, break statement is used to stop the execution of while loop when the condition if i * 6 >= 30 becomes true. Otherwise loop goes to infinite."
},
{
"code": null,
"e": 8923,
"s": 8638,
"text": "In Ruby, next statement is used to jump to the next iterator of given loop. The next statement is identical to continue statement in C and Java language. When the next statement is used no other iteration will be performed. Generally, the next statement is used in for and while loop."
},
{
"code": null,
"e": 8931,
"s": 8923,
"text": "Syntax:"
},
{
"code": null,
"e": 8936,
"s": 8931,
"text": "next"
},
{
"code": null,
"e": 8945,
"s": 8936,
"text": "Example:"
},
{
"code": "# Ruby program to illustrate next statement #!/usr/bin/ruby # using for loopfor t in 0...10 # using if statement if t == 5 then # using next statement next # ending of if end # displaying values puts t # end of for loop end ",
"e": 9219,
"s": 8945,
"text": null
},
{
"code": null,
"e": 9227,
"s": 9219,
"text": "Output:"
},
{
"code": null,
"e": 9246,
"s": 9227,
"text": "0\n1\n2\n3\n4\n6\n7\n8\n9\n"
},
{
"code": null,
"e": 9435,
"s": 9246,
"text": "Explanation: In the above program, 5 will not be printed in the output due to next statement. So here at 5 next statement will cause to skip it and continue from next statement in program."
},
{
"code": null,
"e": 9812,
"s": 9435,
"text": "The redo statement is used to restart the current iteration of a loop or the iterator. There is a difference between the redo and next statement. next statement always transfers the control to the end of the loop where the statement after the loop can start to execute, but redo statement transfer the control back to the top of block or loop so that iteration can start over."
},
{
"code": null,
"e": 9820,
"s": 9812,
"text": "Syntax:"
},
{
"code": null,
"e": 9825,
"s": 9820,
"text": "redo"
},
{
"code": null,
"e": 9834,
"s": 9825,
"text": "Example:"
},
{
"code": "# Ruby program to demonstrate the redo statement # defining a variableval = 0 # using while loop which should give# output as 0,1,2,3 but here it will # output as 0,1,2,3,4while(val < 4) # Control returns here when # redo will executeputs valval += 1 # using redo statementredo if val == 4 # ending of while loopend",
"e": 10156,
"s": 9834,
"text": null
},
{
"code": null,
"e": 10164,
"s": 10156,
"text": "Output:"
},
{
"code": null,
"e": 10175,
"s": 10164,
"text": "0\n1\n2\n3\n4\n"
},
{
"code": null,
"e": 10473,
"s": 10175,
"text": "Explanation: In the above program, redo statement will transfer the control to puts val which is the first expression of while loop. It is neither going to retest the loop condition nor going to fetch the next element from the iterator. So, here while loop will print 0,1,2,3,4 instead of 0,1,2,3."
},
{
"code": null,
"e": 10752,
"s": 10473,
"text": "retry statement is used to restart an iterator based on a certain condition or any method invocation from the starting. In simple words, retry statement transfers the control at the beginning. Generally, a retry statement is used rarely. It will only work till Ruby version 1.8."
},
{
"code": null,
"e": 10957,
"s": 10752,
"text": "Note: retry statement has been removed from the Ruby version 1.9 onwards because it is considered deprecated language feature. So it will hardly run on online IDE’s because mostly using version above 1.8."
},
{
"code": null,
"e": 10965,
"s": 10957,
"text": "Syntax:"
},
{
"code": null,
"e": 10971,
"s": 10965,
"text": "retry"
},
{
"code": null,
"e": 10980,
"s": 10971,
"text": "Example:"
},
{
"code": "# Ruby program to demonstrate the retry statement # variablevar = 7 # Iterate 7 times from 0 to 7-1var.times do |val| # display iteration numberputs val # If we've reached 6if val == 6 # Decrement val and user won't# reach 6 next timevar = var - 1 # Restart the iteration# using retry statementretry # end of if end # end of do..endend",
"e": 11329,
"s": 10980,
"text": null
},
{
"code": null,
"e": 11337,
"s": 11329,
"text": "Output:"
},
{
"code": null,
"e": 11364,
"s": 11337,
"text": "0\n1\n2\n3\n4\n5\n6\n0\n1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 11624,
"s": 11364,
"text": "Explanation: In above program, when the control goes to retry statement then it transfers that control to var.times do |val| . Now here the value of var variable is updated i.e. 5. So user won’t reach 6 to next time and retry statement will not execute again."
},
{
"code": null,
"e": 12073,
"s": 11624,
"text": "This is used to exit from a method, with or without a value. It always returns a value to its caller. There are many options with the return statement. If there is no expression used with return statement then it always returns the value of method as nil. A list of expression after the return statement is always separated by the comma(,) In this case, the value of the method will be an array containing the values of those specified expressions."
},
{
"code": null,
"e": 12082,
"s": 12073,
"text": "Example:"
},
{
"code": "# Ruby program to demonstrate the return statement #!/usr/bin/ruby # defining a method 'geeks'def geeks # variables of method val1 = 61 val2 = 55 # returning multiple values return val1, val2 # this statement will not executeputs \"Hello Geeks\" # end of the methodend # variable outside the method to # store the return value of the methodvalue = geeks # displaying the returned valuesputs value",
"e": 12499,
"s": 12082,
"text": null
},
{
"code": null,
"e": 12507,
"s": 12499,
"text": "Output:"
},
{
"code": null,
"e": 12514,
"s": 12507,
"text": "55\n61\n"
},
{
"code": null,
"e": 12884,
"s": 12514,
"text": "Explanation: In above example, method geeks has a return statement which return the two values i.e. val1 and val2 to its caller. Here value is the variable which stored the returned values. The important point is that the statement puts “Hello Geeks” after return statement doesn’t execute because statements after the return statement will not execute inside a method."
},
{
"code": null,
"e": 13365,
"s": 12884,
"text": "throw and catch are used to define a control structure which can be considered as a multilevel break. throw is used to break the current loop and transfer the control outside of the catch block. The best thing about throw is that it can break out of the current loop or methods or we can say it can cross any number of levels. Here, catch defines a “labeled block” of code which causes to exit by the throw block. More details will be discussed In Ruby Exception Handling section."
},
{
"code": null,
"e": 13374,
"s": 13365,
"text": "Example:"
},
{
"code": "# Ruby program to illustrate the throw/catch statement# for altering the control flow # defining a methoddef lessNumber(num) # using throw statement # here 'numberError' is its label throw :numberError if num < 10 # displaying result puts \"Number is Greater than 10!\"end # catch blockcatch :numberError do # calling method lessNumber(11) lessNumber(78) # exits catch block here lessNumber(7) lessNumber(4)end puts \"Outside Catch Block\"",
"e": 13874,
"s": 13374,
"text": null
},
{
"code": null,
"e": 13882,
"s": 13874,
"text": "Output:"
},
{
"code": null,
"e": 13957,
"s": 13882,
"text": "Number is Greater than 10!\nNumber is Greater than 10!\nOutside Catch Block\n"
},
{
"code": null,
"e": 14597,
"s": 13957,
"text": "Explanation: In above program, 11 is passed to method lessNumber to check whether it is greater than 10 or not. 11 is greater than 10 so statement will print out on display and next statement of catch block will execute. Now 78 is passed to the method call, which is checked and it is greater than 10 so statement will print out on screen. But as soon as 7 is passed which is less than 10 throw: numberError cause the catch block to exits and all the statements skip out and last statement “Outside Catch Block” will print. So here as soon as the condition becomes false throw causes the catch block to exit the catch block from execution."
},
{
"code": null,
"e": 14608,
"s": 14597,
"text": "nidhi_biet"
},
{
"code": null,
"e": 14620,
"s": 14608,
"text": "Ruby-Basics"
},
{
"code": null,
"e": 14625,
"s": 14620,
"text": "Ruby"
},
{
"code": null,
"e": 14723,
"s": 14625,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14769,
"s": 14723,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 14812,
"s": 14769,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 14856,
"s": 14812,
"text": "Ruby | unless Statement and unless Modifier"
},
{
"code": null,
"e": 14883,
"s": 14856,
"text": "Ruby on Rails Introduction"
},
{
"code": null,
"e": 14911,
"s": 14883,
"text": "Ruby | String concat Method"
},
{
"code": null,
"e": 14953,
"s": 14911,
"text": "Ruby | Array class find_index() operation"
},
{
"code": null,
"e": 14972,
"s": 14953,
"text": "Ruby For Beginners"
},
{
"code": null,
"e": 15002,
"s": 14972,
"text": "Ruby | Array shift() function"
}
]
|
Search Algorithms in AI | 07 Jun, 2022
Artificial Intelligence is the study of building agents that act rationally. Most of the time, these agents perform some kind of search algorithm in the background in order to achieve their tasks.
A search problem consists of: A State Space. Set of all possible states where you can be.A Start State. The state from where the search begins.A Goal Test. A function that looks at the current state returns whether or not it is the goal state.
A State Space. Set of all possible states where you can be.
A Start State. The state from where the search begins.
A Goal Test. A function that looks at the current state returns whether or not it is the goal state.
The Solution to a search problem is a sequence of actions, called the plan that transforms the start state to the goal state.
This plan is achieved through search algorithms.
There are far too many powerful search algorithms out there to fit in a single article. Instead, this article will discuss six of the fundamental search algorithms, divided into two categories, as shown below.
Note that there is much more to search algorithms than the chart I have provided above. However, this article will mostly stick to the above chart, exploring the algorithms given there.
The search algorithms in this section have no additional information on the goal node other than the one provided in the problem definition. The plans to reach the goal state from the start state differ only by the order and/or length of actions. Uninformed search is also called Blind search. These algorithms can only generate the successors and differentiate between the goal state and non goal state.
The following uninformed search algorithms are discussed in this section.
Depth First SearchBreadth First SearchUniform Cost Search
Depth First Search
Breadth First Search
Uniform Cost Search
Each of these algorithms will have:
A problem graph, containing the start node S and the goal node G.
A strategy, describing the manner in which the graph will be traversed to get to G.
A fringe, which is a data structure used to store all the possible states (nodes) that you can go from the current states.
A tree, that results while traversing to the goal node.
A solution plan, which the sequence of nodes from S to G.
Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking. It uses last in- first-out strategy and hence it is implemented using a stack.
Example:
Question. Which solution would DFS find to move from node S to node G if run on the graph below?
Solution. The equivalent search tree for the above graph is as follows. As DFS traverses the tree “deepest node first”, it would always pick the deeper branch until it reaches the solution (or it runs out of nodes, and goes to the next branch). The traversal is shown in blue arrows.
Path: S -> A -> B -> C -> G
= the depth of the search tree = the number of levels of the search tree. = number of nodes in level .
Time complexity: Equivalent to the number of nodes traversed in DFS. Space complexity: Equivalent to how large can the fringe get. Completeness: DFS is complete if the search tree is finite, meaning for a given finite search tree, DFS will come up with a solution if it exists. Optimality: DFS is not optimal, meaning the number of steps in reaching the solution, or the cost spent in reaching it is high.
Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root (or some arbitrary node of a graph, sometimes referred to as a ‘search key’), and explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level. It is implemented using a queue.
Example: Question. Which solution would BFS find to move from node S to node G if run on the graph below?
Solution. The equivalent search tree for the above graph is as follows. As BFS traverses the tree “shallowest node first”, it would always pick the shallower branch until it reaches the solution (or it runs out of nodes, and goes to the next branch). The traversal is shown in blue arrows.
Path: S -> D -> G
= the depth of the shallowest solution. = number of nodes in level . Time complexity: Equivalent to the number of nodes traversed in BFS until the shallowest solution. Space complexity: Equivalent to how large can the fringe get. Completeness: BFS is complete, meaning for a given search tree, BFS will come up with a solution if it exists.
Optimality: BFS is optimal as long as the costs of all edges are equal.
UCS is different from BFS and DFS because here the costs come into play. In other words, traversing via different edges might not have the same cost. The goal is to find a path where the cumulative sum of costs is the least.
Cost of a node is defined as:
cost(node) = cumulative cost of all nodes from root
cost(root) = 0
Example: Question. Which solution would UCS find to move from node S to node G if run on the graph below?
Solution. The equivalent search tree for the above graph is as follows. The cost of each node is the cumulative cost of reaching that node from the root. Based on the UCS strategy, the path with the least cumulative cost is chosen. Note that due to the many options in the fringe, the algorithm explores most of them so long as their cost is low, and discards them when a lower-cost path is found; these discarded traversals are not shown below. The actual traversal is shown in blue.
Path: S -> A -> B -> G Cost: 5
Let = cost of solution. = arcs cost.
Then effective depth
Time complexity: , Space complexity:
Advantages:
UCS is complete only if states are finite and there should be no loop with zero weight.
UCS is optimal only if there is no negative cost.
Disadvantages:
Explores options in every “direction”.
No information on goal location.
Here, the algorithms have information on the goal state, which helps in more efficient searching. This information is obtained by something called a heuristic. In this section, we will discuss the following search algorithms.
Greedy SearchA* Tree SearchA* Graph Search
Greedy Search
A* Tree Search
A* Graph Search
Search Heuristics: In an informed search, a heuristic is a function that estimates how close a state is to the goal state. For example – Manhattan distance, Euclidean distance, etc. (Lesser the distance, closer the goal.) Different heuristics are used in different informed algorithms discussed below.
In greedy search, we expand the node closest to the goal node. The “closeness” is estimated by a heuristic h(x).
Heuristic: A heuristic h is defined as- h(x) = Estimate of distance of node x from the goal node. Lower the value of h(x), closer is the node from the goal.
Strategy: Expand the node closest to the goal state, i.e. expand the node with a lower h value.
Example:
Question. Find the path from S to G using greedy search. The heuristic values h of each node below the name of the node.
Solution. Starting from S, we can traverse to A(h=9) or D(h=5). We choose D, as it has the lower heuristic cost. Now from D, we can move to B(h=4) or E(h=3). We choose E with a lower heuristic cost. Finally, from E, we go to G(h=0). This entire traversal is shown in the search tree below, in blue.
Path: S -> D -> E -> G
Advantage: Works well with informed search problems, with fewer steps to reach a goal. Disadvantage: Can turn into unguided DFS in the worst case.
A* Tree Search, or simply known as A* Search, combines the strengths of uniform-cost search and greedy search. In this search, the heuristic is the summation of the cost in UCS, denoted by g(x), and the cost in the greedy search, denoted by h(x). The summed cost is denoted by f(x).
Heuristic: The following points should be noted wrt heuristics in A* search.
Here, h(x) is called the forward cost and is an estimate of the distance of the current node from the goal node.
And, g(x) is called the backward cost and is the cumulative cost of a node from the root node.
A* search is optimal only when for all nodes, the forward cost for a node h(x) underestimates the actual cost h*(x) to reach the goal. This property of A* heuristic is called admissibility.
Strategy: Choose the node with the lowest f(x) value.
Example:
Question. Find the path to reach from S to G using A* search.
Solution. Starting from S, the algorithm computes g(x) + h(x) for all nodes in the fringe at each step, choosing the node with the lowest sum. The entire work is shown in the table below.
Note that in the fourth set of iterations, we get two paths with equal summed cost f(x), so we expand them both in the next set. The path with a lower cost on further expansion is the chosen path.
A* tree search works well, except that it takes time re-exploring the branches it has already explored. In other words, if the same node has expanded twice in different branches of the search tree, A* search might explore both of those branches, thus wasting time
A* Graph Search, or simply Graph Search, removes this limitation by adding this rule: do not expand the same node more than once.
Heuristic. Graph search is optimal only when the forward cost between two successive nodes A and B, given by h(A) – h (B), is less than or equal to the backward cost between those two nodes g(A -> B). This property of the graph search heuristic is called consistency.
Example:
Question. Use graph searches to find paths from S to G in the following graph.
the Solution. We solve this question pretty much the same way we solved last question, but in this case, we keep a track of nodes explored so that we don’t re-explore them.
Path: S -> D -> B -> C -> E -> G Cost: 7
MayankAggarwal2
siddhibhanushali1234
Artificial Intelligence
Technical Scripter 2018
Machine Learning
Technical Scripter
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Jun, 2022"
},
{
"code": null,
"e": 252,
"s": 54,
"text": "Artificial Intelligence is the study of building agents that act rationally. Most of the time, these agents perform some kind of search algorithm in the background in order to achieve their tasks. "
},
{
"code": null,
"e": 496,
"s": 252,
"text": "A search problem consists of: A State Space. Set of all possible states where you can be.A Start State. The state from where the search begins.A Goal Test. A function that looks at the current state returns whether or not it is the goal state."
},
{
"code": null,
"e": 556,
"s": 496,
"text": "A State Space. Set of all possible states where you can be."
},
{
"code": null,
"e": 611,
"s": 556,
"text": "A Start State. The state from where the search begins."
},
{
"code": null,
"e": 712,
"s": 611,
"text": "A Goal Test. A function that looks at the current state returns whether or not it is the goal state."
},
{
"code": null,
"e": 838,
"s": 712,
"text": "The Solution to a search problem is a sequence of actions, called the plan that transforms the start state to the goal state."
},
{
"code": null,
"e": 887,
"s": 838,
"text": "This plan is achieved through search algorithms."
},
{
"code": null,
"e": 1098,
"s": 887,
"text": "There are far too many powerful search algorithms out there to fit in a single article. Instead, this article will discuss six of the fundamental search algorithms, divided into two categories, as shown below. "
},
{
"code": null,
"e": 1285,
"s": 1098,
"text": "Note that there is much more to search algorithms than the chart I have provided above. However, this article will mostly stick to the above chart, exploring the algorithms given there. "
},
{
"code": null,
"e": 1691,
"s": 1285,
"text": "The search algorithms in this section have no additional information on the goal node other than the one provided in the problem definition. The plans to reach the goal state from the start state differ only by the order and/or length of actions. Uninformed search is also called Blind search. These algorithms can only generate the successors and differentiate between the goal state and non goal state. "
},
{
"code": null,
"e": 1765,
"s": 1691,
"text": "The following uninformed search algorithms are discussed in this section."
},
{
"code": null,
"e": 1823,
"s": 1765,
"text": "Depth First SearchBreadth First SearchUniform Cost Search"
},
{
"code": null,
"e": 1842,
"s": 1823,
"text": "Depth First Search"
},
{
"code": null,
"e": 1863,
"s": 1842,
"text": "Breadth First Search"
},
{
"code": null,
"e": 1883,
"s": 1863,
"text": "Uniform Cost Search"
},
{
"code": null,
"e": 1920,
"s": 1883,
"text": "Each of these algorithms will have: "
},
{
"code": null,
"e": 1986,
"s": 1920,
"text": "A problem graph, containing the start node S and the goal node G."
},
{
"code": null,
"e": 2070,
"s": 1986,
"text": "A strategy, describing the manner in which the graph will be traversed to get to G."
},
{
"code": null,
"e": 2193,
"s": 2070,
"text": "A fringe, which is a data structure used to store all the possible states (nodes) that you can go from the current states."
},
{
"code": null,
"e": 2249,
"s": 2193,
"text": "A tree, that results while traversing to the goal node."
},
{
"code": null,
"e": 2307,
"s": 2249,
"text": "A solution plan, which the sequence of nodes from S to G."
},
{
"code": null,
"e": 2667,
"s": 2307,
"text": "Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking. It uses last in- first-out strategy and hence it is implemented using a stack."
},
{
"code": null,
"e": 2677,
"s": 2667,
"text": "Example: "
},
{
"code": null,
"e": 2776,
"s": 2677,
"text": "Question. Which solution would DFS find to move from node S to node G if run on the graph below? "
},
{
"code": null,
"e": 3061,
"s": 2776,
"text": "Solution. The equivalent search tree for the above graph is as follows. As DFS traverses the tree “deepest node first”, it would always pick the deeper branch until it reaches the solution (or it runs out of nodes, and goes to the next branch). The traversal is shown in blue arrows. "
},
{
"code": null,
"e": 3092,
"s": 3061,
"text": "Path: S -> A -> B -> C -> G "
},
{
"code": null,
"e": 3196,
"s": 3092,
"text": "= the depth of the search tree = the number of levels of the search tree. = number of nodes in level . "
},
{
"code": null,
"e": 3603,
"s": 3196,
"text": "Time complexity: Equivalent to the number of nodes traversed in DFS. Space complexity: Equivalent to how large can the fringe get. Completeness: DFS is complete if the search tree is finite, meaning for a given finite search tree, DFS will come up with a solution if it exists. Optimality: DFS is not optimal, meaning the number of steps in reaching the solution, or the cost spent in reaching it is high. "
},
{
"code": null,
"e": 3960,
"s": 3603,
"text": "Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root (or some arbitrary node of a graph, sometimes referred to as a ‘search key’), and explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level. It is implemented using a queue."
},
{
"code": null,
"e": 4067,
"s": 3960,
"text": "Example: Question. Which solution would BFS find to move from node S to node G if run on the graph below? "
},
{
"code": null,
"e": 4358,
"s": 4067,
"text": "Solution. The equivalent search tree for the above graph is as follows. As BFS traverses the tree “shallowest node first”, it would always pick the shallower branch until it reaches the solution (or it runs out of nodes, and goes to the next branch). The traversal is shown in blue arrows. "
},
{
"code": null,
"e": 4377,
"s": 4358,
"text": "Path: S -> D -> G "
},
{
"code": null,
"e": 4720,
"s": 4377,
"text": " = the depth of the shallowest solution. = number of nodes in level . Time complexity: Equivalent to the number of nodes traversed in BFS until the shallowest solution. Space complexity: Equivalent to how large can the fringe get. Completeness: BFS is complete, meaning for a given search tree, BFS will come up with a solution if it exists. "
},
{
"code": null,
"e": 4793,
"s": 4720,
"text": "Optimality: BFS is optimal as long as the costs of all edges are equal. "
},
{
"code": null,
"e": 5019,
"s": 4793,
"text": "UCS is different from BFS and DFS because here the costs come into play. In other words, traversing via different edges might not have the same cost. The goal is to find a path where the cumulative sum of costs is the least. "
},
{
"code": null,
"e": 5050,
"s": 5019,
"text": "Cost of a node is defined as: "
},
{
"code": null,
"e": 5121,
"s": 5050,
"text": " cost(node) = cumulative cost of all nodes from root\n cost(root) = 0"
},
{
"code": null,
"e": 5228,
"s": 5121,
"text": "Example: Question. Which solution would UCS find to move from node S to node G if run on the graph below? "
},
{
"code": null,
"e": 5714,
"s": 5228,
"text": "Solution. The equivalent search tree for the above graph is as follows. The cost of each node is the cumulative cost of reaching that node from the root. Based on the UCS strategy, the path with the least cumulative cost is chosen. Note that due to the many options in the fringe, the algorithm explores most of them so long as their cost is low, and discards them when a lower-cost path is found; these discarded traversals are not shown below. The actual traversal is shown in blue. "
},
{
"code": null,
"e": 5746,
"s": 5714,
"text": "Path: S -> A -> B -> G Cost: 5 "
},
{
"code": null,
"e": 5784,
"s": 5746,
"text": "Let = cost of solution. = arcs cost. "
},
{
"code": null,
"e": 5806,
"s": 5784,
"text": "Then effective depth "
},
{
"code": null,
"e": 5848,
"s": 5806,
"text": "Time complexity: , Space complexity: "
},
{
"code": null,
"e": 5861,
"s": 5848,
"text": "Advantages: "
},
{
"code": null,
"e": 5949,
"s": 5861,
"text": "UCS is complete only if states are finite and there should be no loop with zero weight."
},
{
"code": null,
"e": 5999,
"s": 5949,
"text": "UCS is optimal only if there is no negative cost."
},
{
"code": null,
"e": 6015,
"s": 5999,
"text": "Disadvantages: "
},
{
"code": null,
"e": 6054,
"s": 6015,
"text": "Explores options in every “direction”."
},
{
"code": null,
"e": 6087,
"s": 6054,
"text": "No information on goal location."
},
{
"code": null,
"e": 6314,
"s": 6087,
"text": "Here, the algorithms have information on the goal state, which helps in more efficient searching. This information is obtained by something called a heuristic. In this section, we will discuss the following search algorithms. "
},
{
"code": null,
"e": 6357,
"s": 6314,
"text": "Greedy SearchA* Tree SearchA* Graph Search"
},
{
"code": null,
"e": 6371,
"s": 6357,
"text": "Greedy Search"
},
{
"code": null,
"e": 6386,
"s": 6371,
"text": "A* Tree Search"
},
{
"code": null,
"e": 6402,
"s": 6386,
"text": "A* Graph Search"
},
{
"code": null,
"e": 6705,
"s": 6402,
"text": "Search Heuristics: In an informed search, a heuristic is a function that estimates how close a state is to the goal state. For example – Manhattan distance, Euclidean distance, etc. (Lesser the distance, closer the goal.) Different heuristics are used in different informed algorithms discussed below. "
},
{
"code": null,
"e": 6819,
"s": 6705,
"text": "In greedy search, we expand the node closest to the goal node. The “closeness” is estimated by a heuristic h(x). "
},
{
"code": null,
"e": 6977,
"s": 6819,
"text": "Heuristic: A heuristic h is defined as- h(x) = Estimate of distance of node x from the goal node. Lower the value of h(x), closer is the node from the goal. "
},
{
"code": null,
"e": 7074,
"s": 6977,
"text": "Strategy: Expand the node closest to the goal state, i.e. expand the node with a lower h value. "
},
{
"code": null,
"e": 7084,
"s": 7074,
"text": "Example: "
},
{
"code": null,
"e": 7207,
"s": 7084,
"text": "Question. Find the path from S to G using greedy search. The heuristic values h of each node below the name of the node. "
},
{
"code": null,
"e": 7507,
"s": 7207,
"text": "Solution. Starting from S, we can traverse to A(h=9) or D(h=5). We choose D, as it has the lower heuristic cost. Now from D, we can move to B(h=4) or E(h=3). We choose E with a lower heuristic cost. Finally, from E, we go to G(h=0). This entire traversal is shown in the search tree below, in blue. "
},
{
"code": null,
"e": 7533,
"s": 7507,
"text": "Path: S -> D -> E -> G "
},
{
"code": null,
"e": 7682,
"s": 7533,
"text": "Advantage: Works well with informed search problems, with fewer steps to reach a goal. Disadvantage: Can turn into unguided DFS in the worst case. "
},
{
"code": null,
"e": 7966,
"s": 7682,
"text": "A* Tree Search, or simply known as A* Search, combines the strengths of uniform-cost search and greedy search. In this search, the heuristic is the summation of the cost in UCS, denoted by g(x), and the cost in the greedy search, denoted by h(x). The summed cost is denoted by f(x). "
},
{
"code": null,
"e": 8044,
"s": 7966,
"text": "Heuristic: The following points should be noted wrt heuristics in A* search. "
},
{
"code": null,
"e": 8157,
"s": 8044,
"text": "Here, h(x) is called the forward cost and is an estimate of the distance of the current node from the goal node."
},
{
"code": null,
"e": 8252,
"s": 8157,
"text": "And, g(x) is called the backward cost and is the cumulative cost of a node from the root node."
},
{
"code": null,
"e": 8443,
"s": 8252,
"text": "A* search is optimal only when for all nodes, the forward cost for a node h(x) underestimates the actual cost h*(x) to reach the goal. This property of A* heuristic is called admissibility. "
},
{
"code": null,
"e": 8498,
"s": 8443,
"text": "Strategy: Choose the node with the lowest f(x) value. "
},
{
"code": null,
"e": 8508,
"s": 8498,
"text": "Example: "
},
{
"code": null,
"e": 8571,
"s": 8508,
"text": "Question. Find the path to reach from S to G using A* search. "
},
{
"code": null,
"e": 8760,
"s": 8571,
"text": "Solution. Starting from S, the algorithm computes g(x) + h(x) for all nodes in the fringe at each step, choosing the node with the lowest sum. The entire work is shown in the table below. "
},
{
"code": null,
"e": 8959,
"s": 8760,
"text": "Note that in the fourth set of iterations, we get two paths with equal summed cost f(x), so we expand them both in the next set. The path with a lower cost on further expansion is the chosen path. "
},
{
"code": null,
"e": 9223,
"s": 8959,
"text": "A* tree search works well, except that it takes time re-exploring the branches it has already explored. In other words, if the same node has expanded twice in different branches of the search tree, A* search might explore both of those branches, thus wasting time"
},
{
"code": null,
"e": 9354,
"s": 9223,
"text": "A* Graph Search, or simply Graph Search, removes this limitation by adding this rule: do not expand the same node more than once. "
},
{
"code": null,
"e": 9623,
"s": 9354,
"text": "Heuristic. Graph search is optimal only when the forward cost between two successive nodes A and B, given by h(A) – h (B), is less than or equal to the backward cost between those two nodes g(A -> B). This property of the graph search heuristic is called consistency. "
},
{
"code": null,
"e": 9632,
"s": 9623,
"text": "Example:"
},
{
"code": null,
"e": 9712,
"s": 9632,
"text": "Question. Use graph searches to find paths from S to G in the following graph. "
},
{
"code": null,
"e": 9886,
"s": 9712,
"text": "the Solution. We solve this question pretty much the same way we solved last question, but in this case, we keep a track of nodes explored so that we don’t re-explore them. "
},
{
"code": null,
"e": 9932,
"s": 9886,
"text": "Path: S -> D -> B -> C -> E -> G Cost: 7 "
},
{
"code": null,
"e": 9948,
"s": 9932,
"text": "MayankAggarwal2"
},
{
"code": null,
"e": 9969,
"s": 9948,
"text": "siddhibhanushali1234"
},
{
"code": null,
"e": 9993,
"s": 9969,
"text": "Artificial Intelligence"
},
{
"code": null,
"e": 10017,
"s": 9993,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 10034,
"s": 10017,
"text": "Machine Learning"
},
{
"code": null,
"e": 10053,
"s": 10034,
"text": "Technical Scripter"
},
{
"code": null,
"e": 10070,
"s": 10053,
"text": "Machine Learning"
}
]
|
Python DateTime astimezone() Method | 02 Sep, 2021
The astimezone() function is used to return a DateTime instance according to the specified time zone parameter tz.
Note: The returned DateTime instance is having the new UTC offset value as per the tz parameter. And If this function does not take parameter tz, then the returned DateTime object will have the local date, time, and time zone.
Syntax: astimezone(tz=None)
Parameters: This function accepts an optional parameter that is illustrated below:
tz: This is the specified timezone.
Return values: This function returns a datetime instance according to the specified time zone parameter tz. If the parameter tz is not specified then this function returns the local date, time and the time zone.
Example 1: In the below example, astimezone() function is taking the Singapore time zone object as its parameter. The Singapore timedelta() function is taking 5 hours as its parameter and its returned value is taken as the parameter of timezone() function. In this way, a DateTime along with Singapore timezone object is initialized for the function astimezone() to return its corresponding datetime instance.
Python3
# Python3 code for getting# a datetime instance according# to the specified time zone parameter tz # Importing datetime moduleimport datetime # Specifying Singapore timedelta and timezone# objectsgtTimeDelta = datetime.timedelta(hours=5)sgtTZObject = datetime.timezone(sgtTimeDelta, name="SGT") # Specifying a datetime along with Singapore# timezone objectd1 = datetime.datetime(2021, 8, 4, 10, 00, 00, 00, sgtTZObject) # Calling the astimezone() function over the above# specified Singapore timezoned2 = d1.astimezone(sgtTZObject) # Printing a datetime instance as per the above# specified Singapore timezoneprint("Singapore time from a datetime instance:{}".format(d2))
Output:
Singapore time from a datetime instance:2021-08-04 10:00:00+05:00
Example 2: In the below example, the astimezone() function does not accept any parameter, so this function returns the DateTime object having the local current date, time and the time zone. Here current date, time, and time zone are returned because of the datetime.now() function.
Python3
# Python3 code for getting# a datetime instance according# to the specified time zone parameter tz # Importing datetime moduleimport datetime # Calling now() function to return# current datetimed1 = datetime.datetime.now() # Calling the astimezone() function without# any timezone parameterd2 = d1.astimezone() # Printing the local current date, time and# timezoneprint(format(d2))
Output:
2021-08-04 06:41:15.128046+00:00
simmytarika5
Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Sep, 2021"
},
{
"code": null,
"e": 144,
"s": 28,
"text": "The astimezone() function is used to return a DateTime instance according to the specified time zone parameter tz. "
},
{
"code": null,
"e": 371,
"s": 144,
"text": "Note: The returned DateTime instance is having the new UTC offset value as per the tz parameter. And If this function does not take parameter tz, then the returned DateTime object will have the local date, time, and time zone."
},
{
"code": null,
"e": 399,
"s": 371,
"text": "Syntax: astimezone(tz=None)"
},
{
"code": null,
"e": 482,
"s": 399,
"text": "Parameters: This function accepts an optional parameter that is illustrated below:"
},
{
"code": null,
"e": 518,
"s": 482,
"text": "tz: This is the specified timezone."
},
{
"code": null,
"e": 730,
"s": 518,
"text": "Return values: This function returns a datetime instance according to the specified time zone parameter tz. If the parameter tz is not specified then this function returns the local date, time and the time zone."
},
{
"code": null,
"e": 1140,
"s": 730,
"text": "Example 1: In the below example, astimezone() function is taking the Singapore time zone object as its parameter. The Singapore timedelta() function is taking 5 hours as its parameter and its returned value is taken as the parameter of timezone() function. In this way, a DateTime along with Singapore timezone object is initialized for the function astimezone() to return its corresponding datetime instance."
},
{
"code": null,
"e": 1148,
"s": 1140,
"text": "Python3"
},
{
"code": "# Python3 code for getting# a datetime instance according# to the specified time zone parameter tz # Importing datetime moduleimport datetime # Specifying Singapore timedelta and timezone# objectsgtTimeDelta = datetime.timedelta(hours=5)sgtTZObject = datetime.timezone(sgtTimeDelta, name=\"SGT\") # Specifying a datetime along with Singapore# timezone objectd1 = datetime.datetime(2021, 8, 4, 10, 00, 00, 00, sgtTZObject) # Calling the astimezone() function over the above# specified Singapore timezoned2 = d1.astimezone(sgtTZObject) # Printing a datetime instance as per the above# specified Singapore timezoneprint(\"Singapore time from a datetime instance:{}\".format(d2))",
"e": 1873,
"s": 1148,
"text": null
},
{
"code": null,
"e": 1881,
"s": 1873,
"text": "Output:"
},
{
"code": null,
"e": 1947,
"s": 1881,
"text": "Singapore time from a datetime instance:2021-08-04 10:00:00+05:00"
},
{
"code": null,
"e": 2229,
"s": 1947,
"text": "Example 2: In the below example, the astimezone() function does not accept any parameter, so this function returns the DateTime object having the local current date, time and the time zone. Here current date, time, and time zone are returned because of the datetime.now() function."
},
{
"code": null,
"e": 2237,
"s": 2229,
"text": "Python3"
},
{
"code": "# Python3 code for getting# a datetime instance according# to the specified time zone parameter tz # Importing datetime moduleimport datetime # Calling now() function to return# current datetimed1 = datetime.datetime.now() # Calling the astimezone() function without# any timezone parameterd2 = d1.astimezone() # Printing the local current date, time and# timezoneprint(format(d2))",
"e": 2619,
"s": 2237,
"text": null
},
{
"code": null,
"e": 2627,
"s": 2619,
"text": "Output:"
},
{
"code": null,
"e": 2660,
"s": 2627,
"text": "2021-08-04 06:41:15.128046+00:00"
},
{
"code": null,
"e": 2673,
"s": 2660,
"text": "simmytarika5"
},
{
"code": null,
"e": 2680,
"s": 2673,
"text": "Picked"
},
{
"code": null,
"e": 2696,
"s": 2680,
"text": "Python-datetime"
},
{
"code": null,
"e": 2703,
"s": 2696,
"text": "Python"
}
]
|
How to swap two numbers without using a temporary variable? | 30 Jun, 2022
Given two variables, x, and y, swap two variables without using a third variable.
Method 1 (Using Arithmetic Operators)
The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ Program to swap two numbers without// using temporary variable#include <bits/stdc++.h>using namespace std; int main(){ int x = 10, y = 5; // Code to swap 'x' and 'y' x = x + y; // x now becomes 15 y = x - y; // y becomes 10 x = x - y; // x becomes 5 cout << "After Swapping: x =" << x << ", y=" << y;} // This code is contributed by mohit kumar.
#include <stdio.h>int main(){ int x = 10, y = 5; // Code to swap 'x' and 'y' x = x + y; // x now becomes 15 y = x - y; // y becomes 10 x = x - y; // x becomes 5 printf("After Swapping: x = %d, y = %d", x, y); return 0;}
// Java Program to swap two numbers without// using temporary variableimport java.io.*; class Geeks { public static void main(String a[]) { int x = 10; int y = 5; x = x + y; y = x - y; x = x - y; System.out.println("After swapping:" + " x = " + x + ", y = " + y); }} // This code is contributed by Mayank Tyagi
x = 10y = 5 # Code to swap 'x' and 'y' # x now becomes 15x = x + y # y becomes 10y = x - y # x becomes 5x = x - yprint("After Swapping: x =", x, " y =", y) # This code is contributed# by Sumit Sudhakar
// Program to swap two numbers without// using temporary variableusing System; class GFG { public static void Main() { int x = 10; int y = 5; x = x + y; y = x - y; x = x - y; Console.WriteLine("After swapping: x = " + x + ", y = " + y); }} // This code is contributed by Sam007
<?php// PHP Program to swap two// numbers without using// temporary variable$x = 10; $y = 5; // Code to swap 'x' and 'y'$x = $x + $y; // x now becomes 15$y = $x - $y; // y becomes 10$x = $x - $y; // x becomes 5 echo "After Swapping: x = ", $x, ", ", "y = ", $y; // This code is contributed by m_kit?>
<script> // Javascript program to swap two// numbers without using temporary// variable let x = 10, y = 5; // Code to swap 'x' and 'y' // x now becomes 15x = x + y; // y becomes 10y = x - y; // x becomes 5x = x - y; document.write("After Swapping: x =" + x + ", y=" + y); // This code is contributed by mukesh07 </script>
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.
After Swapping: x =5, y=10
Time Complexity: O(1).Auxiliary Space: O(1).
Multiplication and division can also be used for swapping.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ Program to swap two numbers without using temporary// variable#include <bits/stdc++.h>using namespace std; int main(){ // NOTE - for this code to work in a generalised sense, y // !- 0 to prevent zero division int x = 10, y = 5; // Code to swap 'x' and 'y' x = x * y; // x now becomes 50 y = x / y; // y becomes 10 x = x / y; // x becomes 5 cout << "After Swapping: x =" << x << ", y=" << y;} // This code is contributed by Aditya Kumar (adityakumar129)
// C Program to swap two numbers without using temporary// variable#include <stdio.h>int main(){ int x = 10, y = 5; // Code to swap 'x' and 'y' x = x * y; // x now becomes 50 y = x / y; // y becomes 10 x = x / y; // x becomes 5 printf("After Swapping: x = %d, y = %d", x, y); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java Program to swap two numbers without using temporary// variableimport java.io.*; class GFG { public static void main(String[] args) { int x = 10; int y = 5; // Code to swap 'x' and 'y' x = x * y; // x now becomes 50 y = x / y; // y becomes 10 x = x / y; // x becomes 5 System.out.println("After swaping:" + " x = " + x + ", y = " + y); }} // This code is contributed by Aditya Kumar (adityakumar129)
# Python3 program to# swap two numbers# without using# temporary variablex = 10y = 5 # code to swap# 'x' and 'y' # x now becomes 50x = x * y # y becomes 10y = x // y; # x becomes 5x = x // y; print("After Swapping: x =", x, " y =", y); # This code is contributed# by @ajit
// C# Program to swap two// numbers without using// temporary variableusing System; class GFG { static public void Main() { int x = 10; int y = 5; // Code to swap 'x' and 'y' x = x * y; // x now becomes 50 y = x / y; // y becomes 10 x = x / y; // x becomes 5 Console.WriteLine("After swaping:" + " x = " + x + ", y = " + y); }} // This code is contributed by ajit.
<?php// Driver code $x = 10; $y = 5; // Code to swap 'x' and 'y' $x = $x * $y; // x now becomes 50 $y = $x / $y; // y becomes 10 $x = $x / $y; // x becomes 5 echo "After Swapping: x = ", $x, " ", "y = ", $y; // This code is contributed by m_kit?>
<script> // Javascript program to swap two numbers// without using temporary variablevar x = 10;var y = 5; // Code to swap 'x' and 'y'x = x * y; // x now becomes 50y = x / y; // y becomes 10x = x / y; // x becomes 5 document.write("After swaping:" + " x = " + x + ", y = " + y); // This code is contributed by shikhasingrajput </script>
After Swapping: x =5, y=10
Time Complexity: O(1).Auxiliary Space: O(1).
Method 2 (Using Bitwise XOR) The bitwise XOR operator can be used to swap two variables. The XOR of two numbers x and y returns a number that has all the bits as 1 wherever bits of x and y differ. For example, XOR of 10 (In Binary 1010) and 5 (In Binary 0101) is 1111, and XOR of 7 (0111) and 5 (0101) is (0010).
C++
C
Java
Python3
C#
PHP
Javascript
// C++ code to swap using XOR#include <bits/stdc++.h> using namespace std; int main(){ int x = 10, y = 5; // Code to swap 'x' (1010) and 'y' (0101) x = x ^ y; // x now becomes 15 (1111) y = x ^ y; // y becomes 10 (1010) x = x ^ y; // x becomes 5 (0101) cout << "After Swapping: x =" << x << ", y=" << y; return 0;} // This code is contributed by mohit kumar.
// C code to swap using XOR#include <stdio.h>int main(){ int x = 10, y = 5; // Code to swap 'x' (1010) and 'y' (0101) x = x ^ y; // x now becomes 15 (1111) y = x ^ y; // y becomes 10 (1010) x = x ^ y; // x becomes 5 (0101) printf("After Swapping: x = %d, y = %d", x, y); return 0;}
// Java code to swap using XORimport java.io.*; public class GFG { public static void main(String a[]) { int x = 10; int y = 5; // Code to swap 'x' (1010) and 'y' (0101) x = x ^ y; // x now becomes 15 (1111) y = x ^ y; // y becomes 10 (1010) x = x ^ y; // x becomes 5 (0101) System.out.println("After swap: x = " + x + ", y = " + y); }} // This code is contributed by Mayank Tyagi
# Python3 code to swap using XOR x = 10y = 5 # Code to swap 'x' and 'y'x = x ^ y; # x now becomes 15 (1111)y = x ^ y; # y becomes 10 (1010)x = x ^ y; # x becomes 5 (0101) print ("After Swapping: x = ", x, " y =", y) # This code is contributed by# Sumit Sudhakar
// C# program to swap using XORusing System; class GFG { public static void Main() { int x = 10; int y = 5; // Code to swap 'x' (1010) // and 'y' (0101) // x now becomes 15 (1111) x = x ^ y; // y becomes 10 (1010) y = x ^ y; // x becomes 5 (0101) x = x ^ y; Console.WriteLine("After swap: x = " + x + ", y = " + y); }} // This code is contributed by ajit
<?php // Driver Code$x = 10;$y = 5; // Code to swap 'x' (1010)// and 'y' (0101) // x now becomes 15 (1111)$x = $x ^ $y; // y becomes 10 (1010)$y = $x ^ $y; // x becomes 5 (0101)$x = $x ^ $y; echo "After Swapping: x = ", $x, ", ", "y = ", $y; // This code is contributed by aj_36?>
<script> // Javascript code to swap using XOR let x = 10, y = 5; // Code to swap 'x' (1010) and 'y' (0101)x = x ^ y; // x now becomes 15 (1111)y = x ^ y; // y becomes 10 (1010)x = x ^ y; // x becomes 5 (0101) document.write("After Swapping: x =" + x + ", y=" + y); // This code is contributed by Mayank Tyagi </script>
After Swapping: x =5, y=10
Time Complexity: O(1).Auxiliary Space: O(1).
Problems with the above methods 1) The multiplication and division-based approach doesn’t work if one of the numbers is 0 as the product becomes 0 irrespective of the other number.2) Both Arithmetic solutions may cause an arithmetic overflow. If x and y are too large, addition and multiplication may go out of the integer range.3) When we use pointers to variable and make a function swap, all the above methods fail when both pointers point to the same variable. Let’s take a look at what will happen in this case if both are pointing to the same variable.
// Bitwise XOR based method x = x ^ x; // x becomes 0 x = x ^ x; // x remains 0 x = x ^ x; // x remains 0// Arithmetic based method x = x + x; // x becomes 2x x = x – x; // x becomes 0 x = x – x; // x remains 0
Let us see the following program.
C++
C
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std;void swap(int* xp, int* yp){ *xp = *xp ^ *yp; *yp = *xp ^ *yp; *xp = *xp ^ *yp;} // Driver codeint main(){ int x = 10; swap(&x, &x); cout << "After swap(&x, &x): x = " << x; return 0;} // This code is contributed by rathbhupendra
#include <stdio.h>void swap(int* xp, int* yp){ *xp = *xp ^ *yp; *yp = *xp ^ *yp; *xp = *xp ^ *yp;} int main(){ int x = 10; swap(&x, &x); printf("After swap(&x, &x): x = %d", x); return 0;}
class GFG { static void swap(int[] xp, int[] yp) { xp[0] = xp[0] ^ yp[0]; yp[0] = xp[0] ^ yp[0]; xp[0] = xp[0] ^ yp[0]; } // Driver code public static void main(String[] args) { int[] x = { 10 }; swap(x, x); System.out.println("After swap(&x, &x): x = " + x[0]); }} // This code is contributed by Aditya Kumar (adityakumar129)
def swap(xp, yp): xp[0] = xp[0] ^ yp[0] yp[0] = xp[0] ^ yp[0] xp[0] = xp[0] ^ yp[0] # Driver codex = [10]swap(x, x)print("After swap(&x, &x): x = ", x[0]) # This code is contributed by SHUBHAMSINGH10
// C# program to implement// the above approachusing System;class GFG { static void swap(int[] xp, int[] yp) { xp[0] = xp[0] ^ yp[0]; yp[0] = xp[0] ^ yp[0]; xp[0] = xp[0] ^ yp[0]; } // Driver code static void Main() { int[] x = { 10 }; swap(x, x); Console.WriteLine("After swap(&x," + "&x): x = " + x[0]); }} // This code is contributed by divyeshrabadiya07
<?phpfunction swap(&$xp, &$yp){ $xp = $xp ^ $yp; $yp = $xp ^ $yp; $xp = $xp ^ $yp;} // Driver Code$x = 10;swap($x, $x);print("After swap(&x, &x): x = " . $x); // This code is contributed// by chandan_jnu?>
<script> function swap(xp,yp) { xp[0] = xp[0] ^ yp[0]; yp[0] = xp[0] ^ yp[0]; xp[0] = xp[0] ^ yp[0]; } // Driver code let x=[10]; swap(x, x); document.write("After swap(&x, &x): x = " + x[0]); // This code is contributed by unknown2108 </script>
After swap(&x, &x): x = 0
Time Complexity: O(1).Auxiliary Space: O(1).
Swapping a variable with itself may be needed in many standard algorithms. For example, see this implementation of QuickSort where we may swap a variable with itself. The above problem can be avoided by putting a condition before the swapping.
C++
C
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std;void swap(int* xp, int* yp){ // Check if the two addresses are same if (xp == yp) return; *xp = *xp + *yp; *yp = *xp - *yp; *xp = *xp - *yp;} // Driver Codeint main(){ int x = 10; swap(&x, &x); cout << "After swap(&x, &x): x = " << x; return 0;} // This code is contributed by rathbhupendra
#include <stdio.h>void swap(int* xp, int* yp){ if (xp == yp) // Check if the two addresses are same return; *xp = *xp + *yp; *yp = *xp - *yp; *xp = *xp - *yp;}int main(){ int x = 10; swap(&x, &x); printf("After swap(&x, &x): x = %d", x); return 0;}
// Java program of above approachclass GFG { static void swap(int xp, int yp) { if (xp == yp) // Check if the two addresses are same return; xp = xp + yp; yp = xp - yp; xp = xp - yp; } // Driver code public static void main(String[] args) { int x = 10; swap(x, x); System.out.println("After swap(&x, &x): x = " + x); }} // This code is Contributed by Code_Mech.
# Python3 program of above approachdef swap(xp, yp): # Check if the two addresses are same if (xp[0] == yp[0]): return xp[0] = xp[0] + yp[0] yp[0] = xp[0] - yp[0] xp[0] = xp[0] - yp[0] # Driver Codex = [10]swap(x, x)print("After swap(&x, &x): x = ", x[0]) # This code is contributed by SHUBHAMSINGH10
// C# program of above approachusing System;class GFG { static void swap(int xp, int yp) { if (xp == yp) // Check if the two addresses are same return; xp = xp + yp; yp = xp - yp; xp = xp - yp; } // Driver code public static void Main() { int x = 10; swap(x, x); Console.WriteLine("After swap(&x, &x): x = " + x); }} // This code is Contributed by Code_Mech.
<?phpfunction swap($xp, $yp){ // Check if the two addresses // are same if ($xp == $yp) return; $xp = $xp + $yp; $yp = $xp - $yp; $xp = $xp - $yp;} // Driver Code$x = 10;swap($x, $x);echo("After swap(&x, &x): x = " . $x);return 0; // This code is contributed// by Code_Mech.
<script> function swap(xp, yp){ // Check if the two addresses are same if (xp == yp) return; xp[0] = xp[0] + yp[0]; yp[0] = xp[0] - yp[0]; xp[0]= xp[0] - yp[0];} // Driver Code x = 10; swap(x, x); document.write("After swap(&x , &x) : x = " + x);//This code is contributed by simranarora5sos</script>
After swap(&x, &x): x = 10
Time Complexity: O(1).Auxiliary Space: O(1).
Method 3 (A mixture of bitwise operators and arithmetic operators) The idea is the same as discussed in Method 1 but uses Bitwise addition and subtraction for swapping.
Below is the implementation of the above approach.
C++
C
Java
Python3
C#
Javascript
PHP
// C++ program to swap two numbers#include <bits/stdc++.h>using namespace std; // Function to swap the numbers.void swap(int& a, int& b){ // same as a = a + b a = (a & b) + (a | b); // same as b = a - b b = a + (~b) + 1; // same as a = a - b a = a + (~b) + 1;} // Driver Codeint main(){ int a = 5, b = 10; // Function Call swap(a, b); cout << "After swapping: a = " << a << ", b = " << b; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C++ program to swap two numbers#include <stdio.h> // Function to swap the numbers.void swap(int a, int b){ // same as a = a + b a = (a & b) + (a | b); // same as b = a - b b = a + (~b) + 1; // same as a = a - b a = a + (~b) + 1; printf("After swapping: a = %d , b = %d ",a,b);} // Driver Codeint main(){ int a = 5, b = 10; // Function Call swap(a, b); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to swap two numbersimport java.io.*; class GFG { public static void swap(int a, int b) { // same as a = a + b a = (a & b) + (a | b); // same as b = a - b b = a + (~b) + 1; // same as a = a - b a = a + (~b) + 1; System.out.print("After swapping: a = " + a + ", b = " + b); } public static void main(String[] args) { int a = 5, b = 10; // Function Call swap(a, b); }} // This code is contributed by Aditya Kumar (adityakumar129)
# Python3 program to swap two numbers # Function to swap the numbers def swap(a, b): # Same as a = a + b a = (a & b) + (a | b) # Same as b = a - b b = a + (~b) + 1 # Same as a = a - b a = a + (~b) + 1 print("After Swapping: a = ", a, ", b = ", b) # Driver codea = 5b = 10 # Function callswap(a, b) # This code is contributed by bunnyram19
// C# program to swap two numbersusing System;class GFG { static void swap(int a, int b) { // same as a = a + b a = (a & b) + (a | b); // same as b = a - b b = a + (~b) + 1; // same as a = a - b a = a + (~b) + 1; Console.Write("After swapping: a = " + a + ", b = " + b); } static void Main() { int a = 5, b = 10; // Function Call swap(a, b); }} // This code is contributed by divyesh072019
<script> // Javascript program to swap two numbers function swap(a, b) { // same as a = a + b a = (a & b) + (a | b); // same as b = a - b b = a + (~b) + 1; // same as a = a - b a = a + (~b) + 1; document.write("After swapping: a = " + a + ", b = " + b); } let a = 5, b = 10; // Function Call swap(a, b); // This code is contributed by suresh07.</script>
<?php // Driver Code$a = 5;$b = 10; echo("Before swap(a and b) " . $a . "and". $b."<br>");// same as a = a + b $a = ($a & $b) + ($a | $b); // same as b = a - b $b = $a + (~$b) + 1; // same as a = a - b $a = $a + (~$b) + 1; echo("After swap(a and b) " . $a. "and". $b);return 0; ?>
After swapping: a = 10, b = 5
Time Complexity: O(1)
Auxiliary Space: O(1)
Method 4 (One Line Expression)
We can write only one line to swap two numbers.
x = x ^ y ^ (y = x);
x = x + y – (y = x);
x = (x * y) / (y = x);
x , y = y, x (In Python)
C++
C
Java
Python3
C#
Javascript
#include <iostream>using namespace std; int main(){ int x = 10, y = 5; x = (x * y) / (y = x); cout << x << " " << y; return 0;} // This code is contributed by isha307
#include <stdio.h> int main() { int x = 10, y = 5; x = (x * y) / (y = x); printf("After Swapping: x = %d, y = %d", x, y); return 0;} // This code is contributed by isha307
/*package whatever //do not write package name here */import java.io.*; class GFG { public static void main(String[] args) { int x = 10; int y = 5; x = (x * y) / (y = x); System.out.println("After swaping:" + " x = " + x + ", y = " + y); }} // This code is contributed by isha307
# Python3 program to swap two numbers # Function to swap the numbersdef swap(x, y): x , y = y, x print("After Swapping: x = ", x, ", y = ", y) # Driver codex = 10y = 5 # Function callswap(x, y) # This code is contributed by kothavvsaakash
// C# program to swap two numbers using System; public class GFG{ static public void Main () { int x = 10; int y = 5; x = (x * y) / (y = x); Console.Write("After swaping:" + " x = " + x + ", y = " + y); }} // This code is contributed by kothavvsaakash
<script> // Javascript program to swap two// numbers without using temporary// variable let x = 10, y = 5; // Code to swap 'x' and 'y'x = (x * y)/(x = y); document.write("After Swapping: x =" + x + ", y=" + y); // This code is contributed by Abhijeet Kumar(abhijeet19403) </script>
5 10
Time Complexity: O(1)
Auxiliary Space: O(1)
To know more about swapping two variables in one line, click here.
Please comment if you find anything incorrect, or if you want to share more information about the topic discussed above
jit_t
mohit kumar 29
Chandan_Kumar
Code_Mech
ujjwalmittal
rathbhupendra
SHUBHAMSINGH10
Rajput-Ji
yashbeersingh42
divyeshrabadiya07
bunnyram19
divyesh072019
mayanktyagi1709
mukesh07
shikhasingrajput
suresh07
unknown2108
simranarora5sos
himanshu6003
akshitsaxenaa09
saurabh1990aror
adityakumar129
anandkumarshivam2266
chandan309kr
isha307
kothavvsaakash
abhijeet19403
Bitwise-XOR
Swap-Program
Bit Magic
Mathematical
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 135,
"s": 52,
"text": "Given two variables, x, and y, swap two variables without using a third variable. "
},
{
"code": null,
"e": 174,
"s": 135,
"text": "Method 1 (Using Arithmetic Operators) "
},
{
"code": null,
"e": 309,
"s": 174,
"text": "The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum. "
},
{
"code": null,
"e": 313,
"s": 309,
"text": "C++"
},
{
"code": null,
"e": 315,
"s": 313,
"text": "C"
},
{
"code": null,
"e": 320,
"s": 315,
"text": "Java"
},
{
"code": null,
"e": 328,
"s": 320,
"text": "Python3"
},
{
"code": null,
"e": 331,
"s": 328,
"text": "C#"
},
{
"code": null,
"e": 335,
"s": 331,
"text": "PHP"
},
{
"code": null,
"e": 346,
"s": 335,
"text": "Javascript"
},
{
"code": "// C++ Program to swap two numbers without// using temporary variable#include <bits/stdc++.h>using namespace std; int main(){ int x = 10, y = 5; // Code to swap 'x' and 'y' x = x + y; // x now becomes 15 y = x - y; // y becomes 10 x = x - y; // x becomes 5 cout << \"After Swapping: x =\" << x << \", y=\" << y;} // This code is contributed by mohit kumar.",
"e": 719,
"s": 346,
"text": null
},
{
"code": "#include <stdio.h>int main(){ int x = 10, y = 5; // Code to swap 'x' and 'y' x = x + y; // x now becomes 15 y = x - y; // y becomes 10 x = x - y; // x becomes 5 printf(\"After Swapping: x = %d, y = %d\", x, y); return 0;}",
"e": 963,
"s": 719,
"text": null
},
{
"code": "// Java Program to swap two numbers without// using temporary variableimport java.io.*; class Geeks { public static void main(String a[]) { int x = 10; int y = 5; x = x + y; y = x - y; x = x - y; System.out.println(\"After swapping:\" + \" x = \" + x + \", y = \" + y); }} // This code is contributed by Mayank Tyagi",
"e": 1353,
"s": 963,
"text": null
},
{
"code": "x = 10y = 5 # Code to swap 'x' and 'y' # x now becomes 15x = x + y # y becomes 10y = x - y # x becomes 5x = x - yprint(\"After Swapping: x =\", x, \" y =\", y) # This code is contributed# by Sumit Sudhakar",
"e": 1555,
"s": 1353,
"text": null
},
{
"code": "// Program to swap two numbers without// using temporary variableusing System; class GFG { public static void Main() { int x = 10; int y = 5; x = x + y; y = x - y; x = x - y; Console.WriteLine(\"After swapping: x = \" + x + \", y = \" + y); }} // This code is contributed by Sam007",
"e": 1911,
"s": 1555,
"text": null
},
{
"code": "<?php// PHP Program to swap two// numbers without using// temporary variable$x = 10; $y = 5; // Code to swap 'x' and 'y'$x = $x + $y; // x now becomes 15$y = $x - $y; // y becomes 10$x = $x - $y; // x becomes 5 echo \"After Swapping: x = \", $x, \", \", \"y = \", $y; // This code is contributed by m_kit?>",
"e": 2218,
"s": 1911,
"text": null
},
{
"code": "<script> // Javascript program to swap two// numbers without using temporary// variable let x = 10, y = 5; // Code to swap 'x' and 'y' // x now becomes 15x = x + y; // y becomes 10y = x - y; // x becomes 5x = x - y; document.write(\"After Swapping: x =\" + x + \", y=\" + y); // This code is contributed by mukesh07 </script>",
"e": 2540,
"s": 2218,
"text": null
},
{
"code": null,
"e": 2549,
"s": 2540,
"text": "Chapters"
},
{
"code": null,
"e": 2576,
"s": 2549,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 2626,
"s": 2576,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 2649,
"s": 2626,
"text": "captions off, selected"
},
{
"code": null,
"e": 2657,
"s": 2649,
"text": "English"
},
{
"code": null,
"e": 2681,
"s": 2657,
"text": "This is a modal window."
},
{
"code": null,
"e": 2750,
"s": 2681,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 2772,
"s": 2750,
"text": "End of dialog window."
},
{
"code": null,
"e": 2799,
"s": 2772,
"text": "After Swapping: x =5, y=10"
},
{
"code": null,
"e": 2844,
"s": 2799,
"text": "Time Complexity: O(1).Auxiliary Space: O(1)."
},
{
"code": null,
"e": 2905,
"s": 2844,
"text": "Multiplication and division can also be used for swapping. "
},
{
"code": null,
"e": 2909,
"s": 2905,
"text": "C++"
},
{
"code": null,
"e": 2911,
"s": 2909,
"text": "C"
},
{
"code": null,
"e": 2916,
"s": 2911,
"text": "Java"
},
{
"code": null,
"e": 2924,
"s": 2916,
"text": "Python3"
},
{
"code": null,
"e": 2927,
"s": 2924,
"text": "C#"
},
{
"code": null,
"e": 2931,
"s": 2927,
"text": "PHP"
},
{
"code": null,
"e": 2942,
"s": 2931,
"text": "Javascript"
},
{
"code": "// C++ Program to swap two numbers without using temporary// variable#include <bits/stdc++.h>using namespace std; int main(){ // NOTE - for this code to work in a generalised sense, y // !- 0 to prevent zero division int x = 10, y = 5; // Code to swap 'x' and 'y' x = x * y; // x now becomes 50 y = x / y; // y becomes 10 x = x / y; // x becomes 5 cout << \"After Swapping: x =\" << x << \", y=\" << y;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 3423,
"s": 2942,
"text": null
},
{
"code": "// C Program to swap two numbers without using temporary// variable#include <stdio.h>int main(){ int x = 10, y = 5; // Code to swap 'x' and 'y' x = x * y; // x now becomes 50 y = x / y; // y becomes 10 x = x / y; // x becomes 5 printf(\"After Swapping: x = %d, y = %d\", x, y); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 3795,
"s": 3423,
"text": null
},
{
"code": "// Java Program to swap two numbers without using temporary// variableimport java.io.*; class GFG { public static void main(String[] args) { int x = 10; int y = 5; // Code to swap 'x' and 'y' x = x * y; // x now becomes 50 y = x / y; // y becomes 10 x = x / y; // x becomes 5 System.out.println(\"After swaping:\" + \" x = \" + x + \", y = \" + y); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 4288,
"s": 3795,
"text": null
},
{
"code": "# Python3 program to# swap two numbers# without using# temporary variablex = 10y = 5 # code to swap# 'x' and 'y' # x now becomes 50x = x * y # y becomes 10y = x // y; # x becomes 5x = x // y; print(\"After Swapping: x =\", x, \" y =\", y); # This code is contributed# by @ajit",
"e": 4574,
"s": 4288,
"text": null
},
{
"code": "// C# Program to swap two// numbers without using// temporary variableusing System; class GFG { static public void Main() { int x = 10; int y = 5; // Code to swap 'x' and 'y' x = x * y; // x now becomes 50 y = x / y; // y becomes 10 x = x / y; // x becomes 5 Console.WriteLine(\"After swaping:\" + \" x = \" + x + \", y = \" + y); }} // This code is contributed by ajit.",
"e": 5024,
"s": 4574,
"text": null
},
{
"code": "<?php// Driver code $x = 10; $y = 5; // Code to swap 'x' and 'y' $x = $x * $y; // x now becomes 50 $y = $x / $y; // y becomes 10 $x = $x / $y; // x becomes 5 echo \"After Swapping: x = \", $x, \" \", \"y = \", $y; // This code is contributed by m_kit?>",
"e": 5301,
"s": 5024,
"text": null
},
{
"code": "<script> // Javascript program to swap two numbers// without using temporary variablevar x = 10;var y = 5; // Code to swap 'x' and 'y'x = x * y; // x now becomes 50y = x / y; // y becomes 10x = x / y; // x becomes 5 document.write(\"After swaping:\" + \" x = \" + x + \", y = \" + y); // This code is contributed by shikhasingrajput </script>",
"e": 5652,
"s": 5301,
"text": null
},
{
"code": null,
"e": 5679,
"s": 5652,
"text": "After Swapping: x =5, y=10"
},
{
"code": null,
"e": 5724,
"s": 5679,
"text": "Time Complexity: O(1).Auxiliary Space: O(1)."
},
{
"code": null,
"e": 6038,
"s": 5724,
"text": "Method 2 (Using Bitwise XOR) The bitwise XOR operator can be used to swap two variables. The XOR of two numbers x and y returns a number that has all the bits as 1 wherever bits of x and y differ. For example, XOR of 10 (In Binary 1010) and 5 (In Binary 0101) is 1111, and XOR of 7 (0111) and 5 (0101) is (0010). "
},
{
"code": null,
"e": 6042,
"s": 6038,
"text": "C++"
},
{
"code": null,
"e": 6044,
"s": 6042,
"text": "C"
},
{
"code": null,
"e": 6049,
"s": 6044,
"text": "Java"
},
{
"code": null,
"e": 6057,
"s": 6049,
"text": "Python3"
},
{
"code": null,
"e": 6060,
"s": 6057,
"text": "C#"
},
{
"code": null,
"e": 6064,
"s": 6060,
"text": "PHP"
},
{
"code": null,
"e": 6075,
"s": 6064,
"text": "Javascript"
},
{
"code": "// C++ code to swap using XOR#include <bits/stdc++.h> using namespace std; int main(){ int x = 10, y = 5; // Code to swap 'x' (1010) and 'y' (0101) x = x ^ y; // x now becomes 15 (1111) y = x ^ y; // y becomes 10 (1010) x = x ^ y; // x becomes 5 (0101) cout << \"After Swapping: x =\" << x << \", y=\" << y; return 0;} // This code is contributed by mohit kumar.",
"e": 6455,
"s": 6075,
"text": null
},
{
"code": "// C code to swap using XOR#include <stdio.h>int main(){ int x = 10, y = 5; // Code to swap 'x' (1010) and 'y' (0101) x = x ^ y; // x now becomes 15 (1111) y = x ^ y; // y becomes 10 (1010) x = x ^ y; // x becomes 5 (0101) printf(\"After Swapping: x = %d, y = %d\", x, y); return 0;}",
"e": 6761,
"s": 6455,
"text": null
},
{
"code": "// Java code to swap using XORimport java.io.*; public class GFG { public static void main(String a[]) { int x = 10; int y = 5; // Code to swap 'x' (1010) and 'y' (0101) x = x ^ y; // x now becomes 15 (1111) y = x ^ y; // y becomes 10 (1010) x = x ^ y; // x becomes 5 (0101) System.out.println(\"After swap: x = \" + x + \", y = \" + y); }} // This code is contributed by Mayank Tyagi",
"e": 7229,
"s": 6761,
"text": null
},
{
"code": "# Python3 code to swap using XOR x = 10y = 5 # Code to swap 'x' and 'y'x = x ^ y; # x now becomes 15 (1111)y = x ^ y; # y becomes 10 (1010)x = x ^ y; # x becomes 5 (0101) print (\"After Swapping: x = \", x, \" y =\", y) # This code is contributed by# Sumit Sudhakar",
"e": 7491,
"s": 7229,
"text": null
},
{
"code": "// C# program to swap using XORusing System; class GFG { public static void Main() { int x = 10; int y = 5; // Code to swap 'x' (1010) // and 'y' (0101) // x now becomes 15 (1111) x = x ^ y; // y becomes 10 (1010) y = x ^ y; // x becomes 5 (0101) x = x ^ y; Console.WriteLine(\"After swap: x = \" + x + \", y = \" + y); }} // This code is contributed by ajit",
"e": 7937,
"s": 7491,
"text": null
},
{
"code": "<?php // Driver Code$x = 10;$y = 5; // Code to swap 'x' (1010)// and 'y' (0101) // x now becomes 15 (1111)$x = $x ^ $y; // y becomes 10 (1010)$y = $x ^ $y; // x becomes 5 (0101)$x = $x ^ $y; echo \"After Swapping: x = \", $x, \", \", \"y = \", $y; // This code is contributed by aj_36?>",
"e": 8233,
"s": 7937,
"text": null
},
{
"code": "<script> // Javascript code to swap using XOR let x = 10, y = 5; // Code to swap 'x' (1010) and 'y' (0101)x = x ^ y; // x now becomes 15 (1111)y = x ^ y; // y becomes 10 (1010)x = x ^ y; // x becomes 5 (0101) document.write(\"After Swapping: x =\" + x + \", y=\" + y); // This code is contributed by Mayank Tyagi </script>",
"e": 8570,
"s": 8233,
"text": null
},
{
"code": null,
"e": 8597,
"s": 8570,
"text": "After Swapping: x =5, y=10"
},
{
"code": null,
"e": 8642,
"s": 8597,
"text": "Time Complexity: O(1).Auxiliary Space: O(1)."
},
{
"code": null,
"e": 9201,
"s": 8642,
"text": "Problems with the above methods 1) The multiplication and division-based approach doesn’t work if one of the numbers is 0 as the product becomes 0 irrespective of the other number.2) Both Arithmetic solutions may cause an arithmetic overflow. If x and y are too large, addition and multiplication may go out of the integer range.3) When we use pointers to variable and make a function swap, all the above methods fail when both pointers point to the same variable. Let’s take a look at what will happen in this case if both are pointing to the same variable."
},
{
"code": null,
"e": 9412,
"s": 9201,
"text": "// Bitwise XOR based method x = x ^ x; // x becomes 0 x = x ^ x; // x remains 0 x = x ^ x; // x remains 0// Arithmetic based method x = x + x; // x becomes 2x x = x – x; // x becomes 0 x = x – x; // x remains 0"
},
{
"code": null,
"e": 9447,
"s": 9412,
"text": "Let us see the following program. "
},
{
"code": null,
"e": 9451,
"s": 9447,
"text": "C++"
},
{
"code": null,
"e": 9453,
"s": 9451,
"text": "C"
},
{
"code": null,
"e": 9458,
"s": 9453,
"text": "Java"
},
{
"code": null,
"e": 9466,
"s": 9458,
"text": "Python3"
},
{
"code": null,
"e": 9469,
"s": 9466,
"text": "C#"
},
{
"code": null,
"e": 9473,
"s": 9469,
"text": "PHP"
},
{
"code": null,
"e": 9484,
"s": 9473,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;void swap(int* xp, int* yp){ *xp = *xp ^ *yp; *yp = *xp ^ *yp; *xp = *xp ^ *yp;} // Driver codeint main(){ int x = 10; swap(&x, &x); cout << \"After swap(&x, &x): x = \" << x; return 0;} // This code is contributed by rathbhupendra",
"e": 9779,
"s": 9484,
"text": null
},
{
"code": "#include <stdio.h>void swap(int* xp, int* yp){ *xp = *xp ^ *yp; *yp = *xp ^ *yp; *xp = *xp ^ *yp;} int main(){ int x = 10; swap(&x, &x); printf(\"After swap(&x, &x): x = %d\", x); return 0;}",
"e": 9989,
"s": 9779,
"text": null
},
{
"code": "class GFG { static void swap(int[] xp, int[] yp) { xp[0] = xp[0] ^ yp[0]; yp[0] = xp[0] ^ yp[0]; xp[0] = xp[0] ^ yp[0]; } // Driver code public static void main(String[] args) { int[] x = { 10 }; swap(x, x); System.out.println(\"After swap(&x, &x): x = \" + x[0]); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 10380,
"s": 9989,
"text": null
},
{
"code": "def swap(xp, yp): xp[0] = xp[0] ^ yp[0] yp[0] = xp[0] ^ yp[0] xp[0] = xp[0] ^ yp[0] # Driver codex = [10]swap(x, x)print(\"After swap(&x, &x): x = \", x[0]) # This code is contributed by SHUBHAMSINGH10",
"e": 10591,
"s": 10380,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;class GFG { static void swap(int[] xp, int[] yp) { xp[0] = xp[0] ^ yp[0]; yp[0] = xp[0] ^ yp[0]; xp[0] = xp[0] ^ yp[0]; } // Driver code static void Main() { int[] x = { 10 }; swap(x, x); Console.WriteLine(\"After swap(&x,\" + \"&x): x = \" + x[0]); }} // This code is contributed by divyeshrabadiya07",
"e": 11039,
"s": 10591,
"text": null
},
{
"code": "<?phpfunction swap(&$xp, &$yp){ $xp = $xp ^ $yp; $yp = $xp ^ $yp; $xp = $xp ^ $yp;} // Driver Code$x = 10;swap($x, $x);print(\"After swap(&x, &x): x = \" . $x); // This code is contributed// by chandan_jnu?>",
"e": 11254,
"s": 11039,
"text": null
},
{
"code": "<script> function swap(xp,yp) { xp[0] = xp[0] ^ yp[0]; yp[0] = xp[0] ^ yp[0]; xp[0] = xp[0] ^ yp[0]; } // Driver code let x=[10]; swap(x, x); document.write(\"After swap(&x, &x): x = \" + x[0]); // This code is contributed by unknown2108 </script>",
"e": 11600,
"s": 11254,
"text": null
},
{
"code": null,
"e": 11626,
"s": 11600,
"text": "After swap(&x, &x): x = 0"
},
{
"code": null,
"e": 11671,
"s": 11626,
"text": "Time Complexity: O(1).Auxiliary Space: O(1)."
},
{
"code": null,
"e": 11915,
"s": 11671,
"text": "Swapping a variable with itself may be needed in many standard algorithms. For example, see this implementation of QuickSort where we may swap a variable with itself. The above problem can be avoided by putting a condition before the swapping."
},
{
"code": null,
"e": 11919,
"s": 11915,
"text": "C++"
},
{
"code": null,
"e": 11921,
"s": 11919,
"text": "C"
},
{
"code": null,
"e": 11926,
"s": 11921,
"text": "Java"
},
{
"code": null,
"e": 11934,
"s": 11926,
"text": "Python3"
},
{
"code": null,
"e": 11937,
"s": 11934,
"text": "C#"
},
{
"code": null,
"e": 11941,
"s": 11937,
"text": "PHP"
},
{
"code": null,
"e": 11952,
"s": 11941,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;void swap(int* xp, int* yp){ // Check if the two addresses are same if (xp == yp) return; *xp = *xp + *yp; *yp = *xp - *yp; *xp = *xp - *yp;} // Driver Codeint main(){ int x = 10; swap(&x, &x); cout << \"After swap(&x, &x): x = \" << x; return 0;} // This code is contributed by rathbhupendra",
"e": 12322,
"s": 11952,
"text": null
},
{
"code": "#include <stdio.h>void swap(int* xp, int* yp){ if (xp == yp) // Check if the two addresses are same return; *xp = *xp + *yp; *yp = *xp - *yp; *xp = *xp - *yp;}int main(){ int x = 10; swap(&x, &x); printf(\"After swap(&x, &x): x = %d\", x); return 0;}",
"e": 12602,
"s": 12322,
"text": null
},
{
"code": "// Java program of above approachclass GFG { static void swap(int xp, int yp) { if (xp == yp) // Check if the two addresses are same return; xp = xp + yp; yp = xp - yp; xp = xp - yp; } // Driver code public static void main(String[] args) { int x = 10; swap(x, x); System.out.println(\"After swap(&x, &x): x = \" + x); }} // This code is Contributed by Code_Mech.",
"e": 13047,
"s": 12602,
"text": null
},
{
"code": "# Python3 program of above approachdef swap(xp, yp): # Check if the two addresses are same if (xp[0] == yp[0]): return xp[0] = xp[0] + yp[0] yp[0] = xp[0] - yp[0] xp[0] = xp[0] - yp[0] # Driver Codex = [10]swap(x, x)print(\"After swap(&x, &x): x = \", x[0]) # This code is contributed by SHUBHAMSINGH10",
"e": 13372,
"s": 13047,
"text": null
},
{
"code": "// C# program of above approachusing System;class GFG { static void swap(int xp, int yp) { if (xp == yp) // Check if the two addresses are same return; xp = xp + yp; yp = xp - yp; xp = xp - yp; } // Driver code public static void Main() { int x = 10; swap(x, x); Console.WriteLine(\"After swap(&x, &x): x = \" + x); }} // This code is Contributed by Code_Mech.",
"e": 13814,
"s": 13372,
"text": null
},
{
"code": "<?phpfunction swap($xp, $yp){ // Check if the two addresses // are same if ($xp == $yp) return; $xp = $xp + $yp; $yp = $xp - $yp; $xp = $xp - $yp;} // Driver Code$x = 10;swap($x, $x);echo(\"After swap(&x, &x): x = \" . $x);return 0; // This code is contributed// by Code_Mech.",
"e": 14114,
"s": 13814,
"text": null
},
{
"code": "<script> function swap(xp, yp){ // Check if the two addresses are same if (xp == yp) return; xp[0] = xp[0] + yp[0]; yp[0] = xp[0] - yp[0]; xp[0]= xp[0] - yp[0];} // Driver Code x = 10; swap(x, x); document.write(\"After swap(&x , &x) : x = \" + x);//This code is contributed by simranarora5sos</script>",
"e": 14452,
"s": 14114,
"text": null
},
{
"code": null,
"e": 14479,
"s": 14452,
"text": "After swap(&x, &x): x = 10"
},
{
"code": null,
"e": 14524,
"s": 14479,
"text": "Time Complexity: O(1).Auxiliary Space: O(1)."
},
{
"code": null,
"e": 14694,
"s": 14524,
"text": "Method 3 (A mixture of bitwise operators and arithmetic operators) The idea is the same as discussed in Method 1 but uses Bitwise addition and subtraction for swapping. "
},
{
"code": null,
"e": 14746,
"s": 14694,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 14750,
"s": 14746,
"text": "C++"
},
{
"code": null,
"e": 14752,
"s": 14750,
"text": "C"
},
{
"code": null,
"e": 14757,
"s": 14752,
"text": "Java"
},
{
"code": null,
"e": 14765,
"s": 14757,
"text": "Python3"
},
{
"code": null,
"e": 14768,
"s": 14765,
"text": "C#"
},
{
"code": null,
"e": 14779,
"s": 14768,
"text": "Javascript"
},
{
"code": null,
"e": 14783,
"s": 14779,
"text": "PHP"
},
{
"code": "// C++ program to swap two numbers#include <bits/stdc++.h>using namespace std; // Function to swap the numbers.void swap(int& a, int& b){ // same as a = a + b a = (a & b) + (a | b); // same as b = a - b b = a + (~b) + 1; // same as a = a - b a = a + (~b) + 1;} // Driver Codeint main(){ int a = 5, b = 10; // Function Call swap(a, b); cout << \"After swapping: a = \" << a << \", b = \" << b; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 15277,
"s": 14783,
"text": null
},
{
"code": "// C++ program to swap two numbers#include <stdio.h> // Function to swap the numbers.void swap(int a, int b){ // same as a = a + b a = (a & b) + (a | b); // same as b = a - b b = a + (~b) + 1; // same as a = a - b a = a + (~b) + 1; printf(\"After swapping: a = %d , b = %d \",a,b);} // Driver Codeint main(){ int a = 5, b = 10; // Function Call swap(a, b); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 15739,
"s": 15277,
"text": null
},
{
"code": "// Java program to swap two numbersimport java.io.*; class GFG { public static void swap(int a, int b) { // same as a = a + b a = (a & b) + (a | b); // same as b = a - b b = a + (~b) + 1; // same as a = a - b a = a + (~b) + 1; System.out.print(\"After swapping: a = \" + a + \", b = \" + b); } public static void main(String[] args) { int a = 5, b = 10; // Function Call swap(a, b); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 16270,
"s": 15739,
"text": null
},
{
"code": "# Python3 program to swap two numbers # Function to swap the numbers def swap(a, b): # Same as a = a + b a = (a & b) + (a | b) # Same as b = a - b b = a + (~b) + 1 # Same as a = a - b a = a + (~b) + 1 print(\"After Swapping: a = \", a, \", b = \", b) # Driver codea = 5b = 10 # Function callswap(a, b) # This code is contributed by bunnyram19",
"e": 16636,
"s": 16270,
"text": null
},
{
"code": "// C# program to swap two numbersusing System;class GFG { static void swap(int a, int b) { // same as a = a + b a = (a & b) + (a | b); // same as b = a - b b = a + (~b) + 1; // same as a = a - b a = a + (~b) + 1; Console.Write(\"After swapping: a = \" + a + \", b = \" + b); } static void Main() { int a = 5, b = 10; // Function Call swap(a, b); }} // This code is contributed by divyesh072019",
"e": 17141,
"s": 16636,
"text": null
},
{
"code": "<script> // Javascript program to swap two numbers function swap(a, b) { // same as a = a + b a = (a & b) + (a | b); // same as b = a - b b = a + (~b) + 1; // same as a = a - b a = a + (~b) + 1; document.write(\"After swapping: a = \" + a + \", b = \" + b); } let a = 5, b = 10; // Function Call swap(a, b); // This code is contributed by suresh07.</script>",
"e": 17591,
"s": 17141,
"text": null
},
{
"code": "<?php // Driver Code$a = 5;$b = 10; echo(\"Before swap(a and b) \" . $a . \"and\". $b.\"<br>\");// same as a = a + b $a = ($a & $b) + ($a | $b); // same as b = a - b $b = $a + (~$b) + 1; // same as a = a - b $a = $a + (~$b) + 1; echo(\"After swap(a and b) \" . $a. \"and\". $b);return 0; ?>",
"e": 17892,
"s": 17591,
"text": null
},
{
"code": null,
"e": 17922,
"s": 17892,
"text": "After swapping: a = 10, b = 5"
},
{
"code": null,
"e": 17944,
"s": 17922,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 17966,
"s": 17944,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 17998,
"s": 17966,
"text": "Method 4 (One Line Expression) "
},
{
"code": null,
"e": 18046,
"s": 17998,
"text": "We can write only one line to swap two numbers."
},
{
"code": null,
"e": 18067,
"s": 18046,
"text": "x = x ^ y ^ (y = x);"
},
{
"code": null,
"e": 18088,
"s": 18067,
"text": "x = x + y – (y = x);"
},
{
"code": null,
"e": 18111,
"s": 18088,
"text": "x = (x * y) / (y = x);"
},
{
"code": null,
"e": 18136,
"s": 18111,
"text": "x , y = y, x (In Python)"
},
{
"code": null,
"e": 18140,
"s": 18136,
"text": "C++"
},
{
"code": null,
"e": 18142,
"s": 18140,
"text": "C"
},
{
"code": null,
"e": 18147,
"s": 18142,
"text": "Java"
},
{
"code": null,
"e": 18155,
"s": 18147,
"text": "Python3"
},
{
"code": null,
"e": 18158,
"s": 18155,
"text": "C#"
},
{
"code": null,
"e": 18169,
"s": 18158,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; int main(){ int x = 10, y = 5; x = (x * y) / (y = x); cout << x << \" \" << y; return 0;} // This code is contributed by isha307",
"e": 18349,
"s": 18169,
"text": null
},
{
"code": "#include <stdio.h> int main() { int x = 10, y = 5; x = (x * y) / (y = x); printf(\"After Swapping: x = %d, y = %d\", x, y); return 0;} // This code is contributed by isha307",
"e": 18533,
"s": 18349,
"text": null
},
{
"code": "/*package whatever //do not write package name here */import java.io.*; class GFG { public static void main(String[] args) { int x = 10; int y = 5; x = (x * y) / (y = x); System.out.println(\"After swaping:\" + \" x = \" + x + \", y = \" + y); }} // This code is contributed by isha307",
"e": 18876,
"s": 18533,
"text": null
},
{
"code": "# Python3 program to swap two numbers # Function to swap the numbersdef swap(x, y): x , y = y, x print(\"After Swapping: x = \", x, \", y = \", y) # Driver codex = 10y = 5 # Function callswap(x, y) # This code is contributed by kothavvsaakash",
"e": 19121,
"s": 18876,
"text": null
},
{
"code": "// C# program to swap two numbers using System; public class GFG{ static public void Main () { int x = 10; int y = 5; x = (x * y) / (y = x); Console.Write(\"After swaping:\" + \" x = \" + x + \", y = \" + y); }} // This code is contributed by kothavvsaakash",
"e": 19411,
"s": 19121,
"text": null
},
{
"code": "<script> // Javascript program to swap two// numbers without using temporary// variable let x = 10, y = 5; // Code to swap 'x' and 'y'x = (x * y)/(x = y); document.write(\"After Swapping: x =\" + x + \", y=\" + y); // This code is contributed by Abhijeet Kumar(abhijeet19403) </script>",
"e": 19693,
"s": 19411,
"text": null
},
{
"code": null,
"e": 19698,
"s": 19693,
"text": "5 10"
},
{
"code": null,
"e": 19720,
"s": 19698,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 19742,
"s": 19720,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 19809,
"s": 19742,
"text": "To know more about swapping two variables in one line, click here."
},
{
"code": null,
"e": 19930,
"s": 19809,
"text": "Please comment if you find anything incorrect, or if you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 19936,
"s": 19930,
"text": "jit_t"
},
{
"code": null,
"e": 19951,
"s": 19936,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 19965,
"s": 19951,
"text": "Chandan_Kumar"
},
{
"code": null,
"e": 19975,
"s": 19965,
"text": "Code_Mech"
},
{
"code": null,
"e": 19988,
"s": 19975,
"text": "ujjwalmittal"
},
{
"code": null,
"e": 20002,
"s": 19988,
"text": "rathbhupendra"
},
{
"code": null,
"e": 20017,
"s": 20002,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 20027,
"s": 20017,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 20043,
"s": 20027,
"text": "yashbeersingh42"
},
{
"code": null,
"e": 20061,
"s": 20043,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 20072,
"s": 20061,
"text": "bunnyram19"
},
{
"code": null,
"e": 20086,
"s": 20072,
"text": "divyesh072019"
},
{
"code": null,
"e": 20102,
"s": 20086,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 20111,
"s": 20102,
"text": "mukesh07"
},
{
"code": null,
"e": 20128,
"s": 20111,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 20137,
"s": 20128,
"text": "suresh07"
},
{
"code": null,
"e": 20149,
"s": 20137,
"text": "unknown2108"
},
{
"code": null,
"e": 20165,
"s": 20149,
"text": "simranarora5sos"
},
{
"code": null,
"e": 20178,
"s": 20165,
"text": "himanshu6003"
},
{
"code": null,
"e": 20194,
"s": 20178,
"text": "akshitsaxenaa09"
},
{
"code": null,
"e": 20210,
"s": 20194,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 20225,
"s": 20210,
"text": "adityakumar129"
},
{
"code": null,
"e": 20246,
"s": 20225,
"text": "anandkumarshivam2266"
},
{
"code": null,
"e": 20259,
"s": 20246,
"text": "chandan309kr"
},
{
"code": null,
"e": 20267,
"s": 20259,
"text": "isha307"
},
{
"code": null,
"e": 20282,
"s": 20267,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 20296,
"s": 20282,
"text": "abhijeet19403"
},
{
"code": null,
"e": 20308,
"s": 20296,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 20321,
"s": 20308,
"text": "Swap-Program"
},
{
"code": null,
"e": 20331,
"s": 20321,
"text": "Bit Magic"
},
{
"code": null,
"e": 20344,
"s": 20331,
"text": "Mathematical"
},
{
"code": null,
"e": 20357,
"s": 20344,
"text": "Mathematical"
},
{
"code": null,
"e": 20367,
"s": 20357,
"text": "Bit Magic"
}
]
|
Minimum changes required to make all element in an array equal | 20 Feb, 2022
Given an array of length N, the task is to find minimum operation required to make all elements in the array equal. Operation is as follows:
Replace the value of one element of the array by one of its adjacent elements.
Examples:
Input: N = 4, arr[] = {2, 3, 3, 4}
Output: 2
Explanation:
Replace 2 and 4 by 3
Input: N = 4, arr[] = { 1, 2, 3, 4}
Output: 3
Approach:Let us assume that after performing the required minimum changes all elements of the array will become X. It is given that we are only allowed to replace the value of an element of the array with its adjacent element, So X should be one of the elements of the array.Also, as we need to make changes as minimum as possible X should be the maximum occurring element of the array. Once we find the value of X, we need only one change per non-equal element (elements which are not X) to make all elements of the array equal to X.
Find the count of the maximum occurring element of the array.
Minimum changes required to make all elements of the array equal is count of all elements – count of maximum occurring element
Below is the implementation of the above approach:
CPP
Java
C#
Python3
Javascript
// C++ program to find minimum// changes required to make// all elements of the array equal#include <bits/stdc++.h>using namespace std; // Function to count// of minimum changes// required to make all// elements equalint minChanges(int arr[], int n){ unordered_map<int, int> umap; // Store the count of // each element as key // value pair in unordered map for (int i = 0; i < n; i++) { umap[arr[i]]++; } int maxFreq = 0; // Find the count of // maximum occurring element for (auto p : umap) { maxFreq = max(maxFreq, p.second); } // Return count of all // element minus count // of maximum occurring element return n - maxFreq;} // Driver codeint main(){ int arr[] = { 2, 3, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << minChanges(arr, n) << '\n'; return 0;}
// Java program to find minimum// changes required to make// all elements of the array equalimport java.util.*; class GFG { // Function to count of minimum changes // required to make all elements equal static int minChanges(int arr[], int n) { Map<Integer, Integer> mp = new HashMap<>(); // Store the count of each element // as key value pair in map for (int i = 0; i < n; i++) { if (mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i]) + 1); } else { mp.put(arr[i], 1); } } int maxElem = 0; // Traverse through map and // find the maximum occurring element for (Map.Entry<Integer, Integer> entry : mp.entrySet()) { maxElem = Math.max(maxElem, entry.getValue()); } // Return count of all element minus // count of maximum occurring element return n - maxElem; } // Driver code public static void main(String[] args) { int arr[] = { 2, 3, 3, 4 }; int n = arr.length; // Function call System.out.println(minChanges(arr, n)); }}
// C# program to find minimum// changes required to make// all elements of the array equal using System;using System.Collections.Generic; class GFG { // Function to count of minimum changes // required to make all elements equal static int minChanges(int[] arr, int n) { Dictionary<int, int> mp = new Dictionary<int, int>(); // Store the count of each element // as key-value pair in Dictionary for (int i = 0; i < n; i++) { if (mp.ContainsKey(arr[i])) { var val = mp[arr[i]]; mp.Remove(arr[i]); mp.Add(arr[i], val + 1); } else { mp.Add(arr[i], 1); } } int maxElem = 0; // Traverse through the Dictionary and // find the maximum occurring element foreach(KeyValuePair<int, int> entry in mp) { maxElem = Math.Max(maxElem, entry.Value); } // Return count of all element minus // count of maximum occurring element return n - maxElem; } // Driver code public static void Main(string[] args) { int[] arr = { 2, 3, 3, 4 }; int n = arr.Length; // Function call Console.WriteLine(minChanges(arr, n)); }}
# Python3 program to find minimum# changes required to make# all elements of the array equal # Function to count of minimum changes# required to make all elements equaldef minChanges(arr, n): mp = dict() # Store the count of each element # as key-value pair in Dictionary for i in range(n): if arr[i] in mp.keys(): mp[arr[i]] += 1 else: mp[arr[i]] = 1 maxElem = 0 # Traverse through the Dictionary and # find the maximum occurring element for x in mp: maxElem = max(maxElem, mp[x]) # Return count of all element minus # count of maximum occurring element return n - maxElem # Driver code arr = [2, 3, 3, 4]n = len(arr) # Function callprint(minChanges(arr, n))
<script> // Javascript program to find minimum// changes required to make// all elements of the array equal // Function to count// of minimum changes// required to make all// elements equalfunction minChanges( arr, n){ var umap = new Map(); // Store the count of // each element as key // value pair in unordered map for (var i = 0; i < n; i++) { if(umap.has(arr[i])) { umap.set(arr[i], umap.get(arr[i])+1); } else { umap.set(arr[i], 1); } } var maxFreq = 0; // Find the count of // maximum occurring element umap.forEach((values,keys)=>{ maxFreq = Math.max(maxFreq, values); }); // Return count of all // element minus count // of maximum occurring element return n - maxFreq;} // Driver codevar arr = [ 2, 3, 3, 4 ];var n = arr.length;// Function calldocument.write( minChanges(arr, n) + '<br>'); </script>
2
Time Complexity: O(n)
Auxiliary Space: O(n)
ssonje99
rutvik_56
subham348
Arrays
Greedy
Mathematical
Arrays
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
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": 53,
"s": 25,
"text": "\n20 Feb, 2022"
},
{
"code": null,
"e": 195,
"s": 53,
"text": "Given an array of length N, the task is to find minimum operation required to make all elements in the array equal. Operation is as follows: "
},
{
"code": null,
"e": 274,
"s": 195,
"text": "Replace the value of one element of the array by one of its adjacent elements."
},
{
"code": null,
"e": 285,
"s": 274,
"text": "Examples: "
},
{
"code": null,
"e": 412,
"s": 285,
"text": "Input: N = 4, arr[] = {2, 3, 3, 4} \nOutput: 2\nExplanation:\nReplace 2 and 4 by 3\n\nInput: N = 4, arr[] = { 1, 2, 3, 4}\nOutput: 3"
},
{
"code": null,
"e": 949,
"s": 412,
"text": "Approach:Let us assume that after performing the required minimum changes all elements of the array will become X. It is given that we are only allowed to replace the value of an element of the array with its adjacent element, So X should be one of the elements of the array.Also, as we need to make changes as minimum as possible X should be the maximum occurring element of the array. Once we find the value of X, we need only one change per non-equal element (elements which are not X) to make all elements of the array equal to X. "
},
{
"code": null,
"e": 1011,
"s": 949,
"text": "Find the count of the maximum occurring element of the array."
},
{
"code": null,
"e": 1138,
"s": 1011,
"text": "Minimum changes required to make all elements of the array equal is count of all elements – count of maximum occurring element"
},
{
"code": null,
"e": 1190,
"s": 1138,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1194,
"s": 1190,
"text": "CPP"
},
{
"code": null,
"e": 1199,
"s": 1194,
"text": "Java"
},
{
"code": null,
"e": 1202,
"s": 1199,
"text": "C#"
},
{
"code": null,
"e": 1210,
"s": 1202,
"text": "Python3"
},
{
"code": null,
"e": 1221,
"s": 1210,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum// changes required to make// all elements of the array equal#include <bits/stdc++.h>using namespace std; // Function to count// of minimum changes// required to make all// elements equalint minChanges(int arr[], int n){ unordered_map<int, int> umap; // Store the count of // each element as key // value pair in unordered map for (int i = 0; i < n; i++) { umap[arr[i]]++; } int maxFreq = 0; // Find the count of // maximum occurring element for (auto p : umap) { maxFreq = max(maxFreq, p.second); } // Return count of all // element minus count // of maximum occurring element return n - maxFreq;} // Driver codeint main(){ int arr[] = { 2, 3, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << minChanges(arr, n) << '\\n'; return 0;}",
"e": 2088,
"s": 1221,
"text": null
},
{
"code": "// Java program to find minimum// changes required to make// all elements of the array equalimport java.util.*; class GFG { // Function to count of minimum changes // required to make all elements equal static int minChanges(int arr[], int n) { Map<Integer, Integer> mp = new HashMap<>(); // Store the count of each element // as key value pair in map for (int i = 0; i < n; i++) { if (mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i]) + 1); } else { mp.put(arr[i], 1); } } int maxElem = 0; // Traverse through map and // find the maximum occurring element for (Map.Entry<Integer, Integer> entry : mp.entrySet()) { maxElem = Math.max(maxElem, entry.getValue()); } // Return count of all element minus // count of maximum occurring element return n - maxElem; } // Driver code public static void main(String[] args) { int arr[] = { 2, 3, 3, 4 }; int n = arr.length; // Function call System.out.println(minChanges(arr, n)); }}",
"e": 3274,
"s": 2088,
"text": null
},
{
"code": "// C# program to find minimum// changes required to make// all elements of the array equal using System;using System.Collections.Generic; class GFG { // Function to count of minimum changes // required to make all elements equal static int minChanges(int[] arr, int n) { Dictionary<int, int> mp = new Dictionary<int, int>(); // Store the count of each element // as key-value pair in Dictionary for (int i = 0; i < n; i++) { if (mp.ContainsKey(arr[i])) { var val = mp[arr[i]]; mp.Remove(arr[i]); mp.Add(arr[i], val + 1); } else { mp.Add(arr[i], 1); } } int maxElem = 0; // Traverse through the Dictionary and // find the maximum occurring element foreach(KeyValuePair<int, int> entry in mp) { maxElem = Math.Max(maxElem, entry.Value); } // Return count of all element minus // count of maximum occurring element return n - maxElem; } // Driver code public static void Main(string[] args) { int[] arr = { 2, 3, 3, 4 }; int n = arr.Length; // Function call Console.WriteLine(minChanges(arr, n)); }}",
"e": 4561,
"s": 3274,
"text": null
},
{
"code": "# Python3 program to find minimum# changes required to make# all elements of the array equal # Function to count of minimum changes# required to make all elements equaldef minChanges(arr, n): mp = dict() # Store the count of each element # as key-value pair in Dictionary for i in range(n): if arr[i] in mp.keys(): mp[arr[i]] += 1 else: mp[arr[i]] = 1 maxElem = 0 # Traverse through the Dictionary and # find the maximum occurring element for x in mp: maxElem = max(maxElem, mp[x]) # Return count of all element minus # count of maximum occurring element return n - maxElem # Driver code arr = [2, 3, 3, 4]n = len(arr) # Function callprint(minChanges(arr, n))",
"e": 5305,
"s": 4561,
"text": null
},
{
"code": "<script> // Javascript program to find minimum// changes required to make// all elements of the array equal // Function to count// of minimum changes// required to make all// elements equalfunction minChanges( arr, n){ var umap = new Map(); // Store the count of // each element as key // value pair in unordered map for (var i = 0; i < n; i++) { if(umap.has(arr[i])) { umap.set(arr[i], umap.get(arr[i])+1); } else { umap.set(arr[i], 1); } } var maxFreq = 0; // Find the count of // maximum occurring element umap.forEach((values,keys)=>{ maxFreq = Math.max(maxFreq, values); }); // Return count of all // element minus count // of maximum occurring element return n - maxFreq;} // Driver codevar arr = [ 2, 3, 3, 4 ];var n = arr.length;// Function calldocument.write( minChanges(arr, n) + '<br>'); </script>",
"e": 6235,
"s": 5305,
"text": null
},
{
"code": null,
"e": 6237,
"s": 6235,
"text": "2"
},
{
"code": null,
"e": 6261,
"s": 6239,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 6283,
"s": 6261,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 6292,
"s": 6283,
"text": "ssonje99"
},
{
"code": null,
"e": 6302,
"s": 6292,
"text": "rutvik_56"
},
{
"code": null,
"e": 6312,
"s": 6302,
"text": "subham348"
},
{
"code": null,
"e": 6319,
"s": 6312,
"text": "Arrays"
},
{
"code": null,
"e": 6326,
"s": 6319,
"text": "Greedy"
},
{
"code": null,
"e": 6339,
"s": 6326,
"text": "Mathematical"
},
{
"code": null,
"e": 6346,
"s": 6339,
"text": "Arrays"
},
{
"code": null,
"e": 6353,
"s": 6346,
"text": "Greedy"
},
{
"code": null,
"e": 6366,
"s": 6353,
"text": "Mathematical"
},
{
"code": null,
"e": 6464,
"s": 6366,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6532,
"s": 6464,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 6576,
"s": 6532,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 6608,
"s": 6576,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 6656,
"s": 6608,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 6670,
"s": 6656,
"text": "Linear Search"
},
{
"code": null,
"e": 6721,
"s": 6670,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 6772,
"s": 6721,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 6832,
"s": 6772,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 6890,
"s": 6832,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
]
|
Bootstrap shown.bs.tab event | The shown.bs.event fires when the tab is completely displayed. After that the alert generates as shown below −
$('.nav-tabs a').on('shown.bs.tab', function(){
alert('New tab is now visible!');
});
The tabs are displayed using the show() method −
$(".nav-tabs a").click(function(){
$(this).tab('show');
});
You can try to run the following code to implement the shown.bs.tab event −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Topic</h2>
<ul class="nav nav-tabs">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#two">Ruby</a></li>
<li><a href="#three">JSP</a></li>
<li><a href="#four">Servlet</a></li>
<li><a href="#five">CSS</a></li>
</ul>
<div class="tab-content">
<div id="home" class="tab-pane fade in active">
<h3>Home</h3>
<p>This is demo text!</p>
</div>
<div id="two" class="tab-pane fade">
<h3>Ruby</h3>
<p>This is demo text!</p>
</div>
<div id="three" class="tab-pane fade">
<h3>JSP</h3>
<p>This is demo text!</p>
</div>
<div id="four" class="tab-pane fade">
<h3>Servlet</h3>
<p>This is demo text!</p>
</div>
<div id="five" class="tab-pane fade">
<h3>CSS</h3>
<p>This is demo text!</p>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$(".nav-tabs a").click(function(){
$(this).tab('show');
});
$('.nav-tabs a').on('show.bs.tab', function(){
alert('New tab will be visible now!');
});
$('.nav-tabs a').on('shown.bs.tab', function(){
alert('New tab is now visible!');
});
$('.nav-tabs a').on('hide.bs.tab', function(e){
alert('Previous tab will hide now!');
});
$('.nav-tabs a').on('hidden.bs.tab', function(){
alert('Previous Tab is hidden now!');
});
});
</script>
</body>
</html> | [
{
"code": null,
"e": 1173,
"s": 1062,
"text": "The shown.bs.event fires when the tab is completely displayed. After that the alert generates as shown below −"
},
{
"code": null,
"e": 1261,
"s": 1173,
"text": "$('.nav-tabs a').on('shown.bs.tab', function(){\n alert('New tab is now visible!');\n});"
},
{
"code": null,
"e": 1310,
"s": 1261,
"text": "The tabs are displayed using the show() method −"
},
{
"code": null,
"e": 1372,
"s": 1310,
"text": "$(\".nav-tabs a\").click(function(){\n $(this).tab('show');\n});"
},
{
"code": null,
"e": 1448,
"s": 1372,
"text": "You can try to run the following code to implement the shown.bs.tab event −"
},
{
"code": null,
"e": 1458,
"s": 1448,
"text": "Live Demo"
},
{
"code": null,
"e": 3483,
"s": 1458,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>\n </head>\n\n <body>\n\n <div class=\"container\">\n <h2>Topic</h2>\n <ul class=\"nav nav-tabs\">\n <li class=\"active\"><a href=\"#home\">Home</a></li>\n <li><a href=\"#two\">Ruby</a></li>\n <li><a href=\"#three\">JSP</a></li>\n <li><a href=\"#four\">Servlet</a></li>\n <li><a href=\"#five\">CSS</a></li>\n </ul>\n\n <div class=\"tab-content\">\n <div id=\"home\" class=\"tab-pane fade in active\">\n <h3>Home</h3>\n <p>This is demo text!</p>\n </div>\n \n <div id=\"two\" class=\"tab-pane fade\">\n <h3>Ruby</h3>\n <p>This is demo text!</p>\n </div>\n <div id=\"three\" class=\"tab-pane fade\">\n <h3>JSP</h3>\n <p>This is demo text!</p>\n </div>\n <div id=\"four\" class=\"tab-pane fade\">\n <h3>Servlet</h3>\n <p>This is demo text!</p>\n </div>\n <div id=\"five\" class=\"tab-pane fade\">\n <h3>CSS</h3>\n <p>This is demo text!</p>\n </div>\n </div>\n </div>\n\n <script>\n $(document).ready(function(){\n $(\".nav-tabs a\").click(function(){\n $(this).tab('show');\n });\n $('.nav-tabs a').on('show.bs.tab', function(){\n alert('New tab will be visible now!');\n });\n $('.nav-tabs a').on('shown.bs.tab', function(){\n alert('New tab is now visible!');\n });\n $('.nav-tabs a').on('hide.bs.tab', function(e){\n alert('Previous tab will hide now!');\n });\n $('.nav-tabs a').on('hidden.bs.tab', function(){\n alert('Previous Tab is hidden now!');\n });\n });\n\n </script>\n\n </body>\n</html>"
}
]
|
Revealing Robustness in Linear Optimization Problems using Monte Carlo Simulation in Python | by Tellef Solberg | Towards Data Science | We will do the following:> Construct a deterministic linear programming problem using PuLP> Apply Monte Carlo simulations on the problem> Interpret the results using data visualization
The linear programming problem we are going to solve is the following:
A manufacturer of specialized industrial windows has three products in its product line, and these are called ‘Small’, ‘Medium’ and ‘Large’. We get the following data:
1. The associated operating profits pr. product is 12, 12.5 and 12 respectively. 2. The working hours needed pr. product is 2.5, 3 and 8 respectively with a total of 1000 hours available for production.3. The square feet needed pr. product is 18, 18 and 19 respectively with a total of 1500 square feet available at the plant4. A delivery contract forces production of at least 8 Large windows
Using the data above, determine the profit-maximizing production plan for the manufacturer:
Let's implement this in python with the linear programming package, PuLP. PuLP can easily be installed by writing the following text in the cmd-line:
pip install pulp
The implementation of the linear program goes as follows:
The optimized objective function and decision variables gives the following:
Objective Function = 1021.00
Production of Large = 8Production of Medium = 74Production of Small = 0
Thus, no other production plan will give higher profits than this exact combination. It seems that ‘Medium’ is profitable and also does not consume too much of the constraints, so a big allocation to this product seems valid. However, what if the demand for Medium sized windows is quite volatile? Do we still risk a production of as much as 74?
Let's assume that the profits of ‘Medium’ windows follow a normal distribution of N(0,2) based on historical figures.
We make these alterations to the objective function and set a seed of choice. These changes can be found on lines 3,6,7 and 18. All else is kept equal:
The slightly changed optimization program now gives us the following results:
Objective Function = 984.00
Production of ‘Large’ = 8Production of ‘Medium’ = 0Production of ‘Small’ = 74
Note that the new optimized production plan sets production of medium sized windows to zero! As we clearly can see, exposing the deterministic model to randomness can truly reveal the robustness of the production plan. When inspecting the objective function further, we can see that for this particular simulation experiment, the profit of ‘Medium’ is set to 10.5 (this can be done by printing the model variable). This obviously favors more production of the small sized windows as the profits are higher relative to ‘Medium’ and it also consumes less working hours.
However, we should not be satisfied with just one experiment. Therefore, let's conduct 1000 Monte Carlo simulations on this optimization problem and interpret the results in histograms:
The code above generates the following histograms of optimized decision variables:
From the 1000 simulation runs, there are several interesting insights. Firstly, and obviously not shockingly, the production of Large windows will always remain at 8. This is due to the working hours consumption of 8 hours pr. unit which is significantly more than for the other two. Secondly, we see that the optimal choice of ‘Small’ and ‘Medium’ shifts between 0 and 74 with no observations in between. Since ‘Medium’ initially has a better profit than ‘Small’ by 0.5, it is optimal to max out production on the product in 600 simulation runs. And likewise, production of 74 small windows is optimal in 40% of the simulation runs. As a production planner, this is very valuable information, and strategies should be put in place to mitigate the risk of committing to the wrong production plan. It seems that trusting deterministic models such as the initial one might have dramatic consequences.
To conclude, one should be very careful to follow the output of deterministic optimization models. Running simulations and exposing it to randomness (even in the slightest) should reveal how well the optimal proposition was in the first place.
A good analogy i like to use is: a soldier is working on his optimal shooting position in order to keep a steady aim. When the sergeant comes by and tries to disturb the solider slightly, we get a good sense of how the soldiers aim and shooting position really is. Here, Aiming is optimization and getting disturbed is simulation. | [
{
"code": null,
"e": 357,
"s": 172,
"text": "We will do the following:> Construct a deterministic linear programming problem using PuLP> Apply Monte Carlo simulations on the problem> Interpret the results using data visualization"
},
{
"code": null,
"e": 428,
"s": 357,
"text": "The linear programming problem we are going to solve is the following:"
},
{
"code": null,
"e": 596,
"s": 428,
"text": "A manufacturer of specialized industrial windows has three products in its product line, and these are called ‘Small’, ‘Medium’ and ‘Large’. We get the following data:"
},
{
"code": null,
"e": 990,
"s": 596,
"text": "1. The associated operating profits pr. product is 12, 12.5 and 12 respectively. 2. The working hours needed pr. product is 2.5, 3 and 8 respectively with a total of 1000 hours available for production.3. The square feet needed pr. product is 18, 18 and 19 respectively with a total of 1500 square feet available at the plant4. A delivery contract forces production of at least 8 Large windows"
},
{
"code": null,
"e": 1082,
"s": 990,
"text": "Using the data above, determine the profit-maximizing production plan for the manufacturer:"
},
{
"code": null,
"e": 1232,
"s": 1082,
"text": "Let's implement this in python with the linear programming package, PuLP. PuLP can easily be installed by writing the following text in the cmd-line:"
},
{
"code": null,
"e": 1249,
"s": 1232,
"text": "pip install pulp"
},
{
"code": null,
"e": 1307,
"s": 1249,
"text": "The implementation of the linear program goes as follows:"
},
{
"code": null,
"e": 1384,
"s": 1307,
"text": "The optimized objective function and decision variables gives the following:"
},
{
"code": null,
"e": 1413,
"s": 1384,
"text": "Objective Function = 1021.00"
},
{
"code": null,
"e": 1485,
"s": 1413,
"text": "Production of Large = 8Production of Medium = 74Production of Small = 0"
},
{
"code": null,
"e": 1831,
"s": 1485,
"text": "Thus, no other production plan will give higher profits than this exact combination. It seems that ‘Medium’ is profitable and also does not consume too much of the constraints, so a big allocation to this product seems valid. However, what if the demand for Medium sized windows is quite volatile? Do we still risk a production of as much as 74?"
},
{
"code": null,
"e": 1949,
"s": 1831,
"text": "Let's assume that the profits of ‘Medium’ windows follow a normal distribution of N(0,2) based on historical figures."
},
{
"code": null,
"e": 2101,
"s": 1949,
"text": "We make these alterations to the objective function and set a seed of choice. These changes can be found on lines 3,6,7 and 18. All else is kept equal:"
},
{
"code": null,
"e": 2179,
"s": 2101,
"text": "The slightly changed optimization program now gives us the following results:"
},
{
"code": null,
"e": 2207,
"s": 2179,
"text": "Objective Function = 984.00"
},
{
"code": null,
"e": 2285,
"s": 2207,
"text": "Production of ‘Large’ = 8Production of ‘Medium’ = 0Production of ‘Small’ = 74"
},
{
"code": null,
"e": 2853,
"s": 2285,
"text": "Note that the new optimized production plan sets production of medium sized windows to zero! As we clearly can see, exposing the deterministic model to randomness can truly reveal the robustness of the production plan. When inspecting the objective function further, we can see that for this particular simulation experiment, the profit of ‘Medium’ is set to 10.5 (this can be done by printing the model variable). This obviously favors more production of the small sized windows as the profits are higher relative to ‘Medium’ and it also consumes less working hours."
},
{
"code": null,
"e": 3039,
"s": 2853,
"text": "However, we should not be satisfied with just one experiment. Therefore, let's conduct 1000 Monte Carlo simulations on this optimization problem and interpret the results in histograms:"
},
{
"code": null,
"e": 3122,
"s": 3039,
"text": "The code above generates the following histograms of optimized decision variables:"
},
{
"code": null,
"e": 4021,
"s": 3122,
"text": "From the 1000 simulation runs, there are several interesting insights. Firstly, and obviously not shockingly, the production of Large windows will always remain at 8. This is due to the working hours consumption of 8 hours pr. unit which is significantly more than for the other two. Secondly, we see that the optimal choice of ‘Small’ and ‘Medium’ shifts between 0 and 74 with no observations in between. Since ‘Medium’ initially has a better profit than ‘Small’ by 0.5, it is optimal to max out production on the product in 600 simulation runs. And likewise, production of 74 small windows is optimal in 40% of the simulation runs. As a production planner, this is very valuable information, and strategies should be put in place to mitigate the risk of committing to the wrong production plan. It seems that trusting deterministic models such as the initial one might have dramatic consequences."
},
{
"code": null,
"e": 4265,
"s": 4021,
"text": "To conclude, one should be very careful to follow the output of deterministic optimization models. Running simulations and exposing it to randomness (even in the slightest) should reveal how well the optimal proposition was in the first place."
}
]
|
Titanic dataset-Advanced data exploration in Python | Towards Data Science | Unique vignettes tumbled out during the course of my discussions with the Titanic dataset. Some of them well documented in the past and some not. A few examples:
Would you feel safer if you were traveling Second class or Third class? Contrary to popular opinion made famous by Hollywood movies, you had DOUBLE the chance of surviving the Titanic as an adult male if you travelled THIRD class instead SECOND class
“What’s in a Name? That which we call a rose, By any other name would smell as sweet” — Act II, Scene II. Unfortunately the Titanic data set seems to violently disagree with Juliet (& the old Bard) for people with short names had extremely high mortality rate on the Titanic compared to people with long names
A case for Altruism on the high seas — Darwin was proved wrong that night, but does the data speak of any other acts of altruism that went undocumented? 3 separate pieces of evidence present themselves on closer inspection
Oops Errata on the Titanic dataset tutorial blogs — One original mistake, several copies
Females on the Titanic may have been charged a little more — But males paid with a lot more
Correlation is not Causation — The fallacy of the ‘Survival of the Groups’ conclusion
What is the single biggest indicator of survival on the Titanic data set — No it is none of the 11 columns listed in the dataset
Fill in the blanks — Is there a vital clue regarding the female-children that seems to have overlooked while filling the missing ages?
No matter what the leaders say — going solo does not necessarily mean you had lower chances of survival. If you were a female, you WOULD want to go solo in order to survive the Titanic. Upon probing why, the data narrates a heart-wrenching tale involving the ultimate act of sacrifice that played out on that fateful night more than 100 years back...
It is almost a decade since the Titanic competition was hosted by Kaggle. It is like the proverbial ‘Rite of Passage’ for any aspiring data scientist. You can see some of today’s grandmasters at Kaggle who are amongst the world’s best data scientists leave their indelible stamp on this dataset sometime in the past. It is a ridiculously simple and small dataset but provides a surprisingly good exercise in almost all aspects of data science and Machine learning — starting from data exploration/visualization to guessing missing values, feature engineering and to testing out a number of ML models.
The details of the competition may already be well known and I summarize it in just 2–3 sentences — It involves predicting whether passengers on the Titanic would survive or not..given a set of characteristics like their age, Sex, class of travel, port Embarked etc. The aspiring data scientist is supposed to make his model ‘learn’ from the training data set (which contain an additional column on whether the passenger survived or not) and apply these ‘learnings’ to the test data set and predict which of the passengers in the test dataset survives.
Though many years have passed, there is still a surprising amount of information hidden in the dataset. With a bit of coaxing though, it is more than willing to give up its secrets. So without much ado, we jump into transcripts of the discussions I had with this fascinating dataset in Python — a language I learnt just to converse with it. We will solely use the Kaggle dataset to come to our conclusions and will not refer to any external source of data. So this analysis is to be looked at from that perspective only and may/may not be a reflection on the actual events.
import pandas as pdimport seaborn as snsimport matplotlib.pyplot as plttest_data = pd.read_csv (‘/kaggle/input/titanic/test.csv’)train_data = pd.read_csv(“/kaggle/input/titanic/train.csv”)##These survival rates will be used as a referenceprint(round(train_data [['Pclass','Survived']].groupby(['Pclass']).mean()*100,1))print(round(train_data [['Sex', 'Pclass','Survived']].groupby(['Pclass', 'Sex']).mean()*100,1))
The basic observations are well known and are henceforth summarized in couple of quick sentences. The Sex of the passenger and the Class in which they travelled (Pclass) seem to have the highest correlation with survival. Age seems to play a role. Other factors like Port Embarked seem to play a small role. The numbers above seem to be in accordance with the general expectations as well.
We start our analysis with a Violen plot.
sns.violinplot(x=’Pclass’, y=’Age’, hue=’Survived’, split=True, data=train_data, palette={0: “r”, 1: “g”});
Straight away we see some puzzling things that need to investigated. Pclass 2 and 3 have a very sharp pronounced peaks of expiry near the 20–35 age range. This is not the case with Pclass 1 though. PClass 1 has far more survivors across all age levels except maybe after 50 or so. After 60 there is a sharp jump in expiry. This is not as sharp in Pclass 2 or 3. This is a curious phenomenon. Let us investigate a bit.
print('Pclass 1 survivors above Age 60:', round(len(train_data[(train_data['Pclass']==1) & (train_data['Age']>59) & (train_data['Survived']==True)])/len(train_data[(train_data['Pclass']==1) & (train_data['Age']>59)])*100,1), '%')print('Pclass 2 survivors above Age 60:', round(len(train_data[(train_data['Pclass']==2) & (train_data['Age']>59) & (train_data['Survived']==True)])/len(train_data[(train_data['Pclass']==2) & (train_data['Age']>59)])*100,1), '%')print('Pclass 3 survivors above Age 60:', round(len(train_data[(train_data['Pclass']==3) & (train_data['Age']>59) & (train_data['Survived']==True)])/len(train_data[(train_data['Pclass']==3) & (train_data['Age']>59)])*100,1), '%')print('Pclass1 survivors between 20-30 Age:',round(len(train_data[(train_data['Pclass']==1) & (train_data['Age']>19) & (train_data['Age']<31) & (train_data['Survived']==True)])/len(train_data[(train_data['Pclass']==1) & (train_data['Age']>19) & (train_data['Age']<31)])*100,1),'%')print('Pclass2 survivors between 20-30 Age:',round(len(train_data[(train_data['Pclass']==2) & (train_data['Age']>19) & (train_data['Age']<31) &(train_data['Survived']==True)])/len(train_data[(train_data['Pclass']==2)&(train_data['Age']>19) &(train_data['Age']<31)])*100,1),'%')print('Pclass3 survivors between 20-30 Age:',round(len(train_data[(train_data['Pclass']==3) & (train_data['Age']>19) & (train_data['Age']<31) &(train_data['Survived']==True)])/len(train_data[(train_data['Pclass']==3) & (train_data['Age']>19) &(train_data['Age']<31)])*100,1),'%')
Indeed in Pclass=1, there is nearly 2.5 times more survival chance if one is between 20–30 age as compared to 60. As the Pclass changes we can see how the survival gap narrows between the 2 age groups. What could explain this? Is this an act of altruism — letting the younger generation live? Why is this limited only to the first class? Is it just a quirk of data and does not mean much? A quick analysis of data shows that Pclass 2 and Pclass 3 have statistically insignificant count of older passengers. Any survivals would possibly skew the percentages. But Pclass1 has 17 people greater than 60 which is not an insignificant number.
One possibility is it that there were more males among the elderly and more females among the middleage group in Pclass 1..so that is the reason for the disparity. A quick series of commands reveal that only 2 males > 60 out of 14 in pclass 1 survive as compared to 9 out of 19 for middle age group. Thus even after accounting for all parameters we see that this difference of 14% survival versus a near 50% which is a mystery. It is not that the middle age folks pushed around the older lot. In fact much of the evacuation was orderly except for the very last few unfortunate minutes. Most of the folks who exipred were able bodied middle aged males..which is why I talked about Darwin beng proved wrong that night as the first act of altruism. But looks like there is a twist to this theory as far as first class passengers are concerned. It does look like some of the older males voluntarily made way for the younger males..Could this be the 2nd act of altruism on the Titanic? The data is very small but not entirely insignificant and it does point towards that direction.
Another stunning data presents itself when we further add the ‘Sex’ column to the filter. We see that NONE of the 33 Pclass 2 males in the middle age group (20–30) age group survives. The survival rate for Pclass2 Male passengers is 16% as we have seen earlier, so this is strange. In fact it is so curious that I extended the age ranges and found that only 4 out of 72 males between 20–60 age group survived. This is just 5% compared to the survival rate for Pclass2 males which is 16%. This could mean either of 2 things: Either in Pclass2 more kids survived than normal or there were more %age of kids in Pclass2 males. This means that adult males in Pclass 2 had actually less survival chance compared to Pclass 3 and kind of turns popular theories around the head. Let us check this...
Unbelievably fascinating and a wonder this has not been documented so far. To put it bluntly if you were an adult male, you had double the chances of survival if you got yourself booked in 3rd class on the Titanic rather than 2nd class! This does turn popular theories on the head.. We have discovered 3 acts of altruism so far on the Titanic. The first one was well known. The second is not very conclusive due to lack of enough data but is not statistically insignificant. The third was a big surprise to me. A huge chunk of Pclass 2 males voluntarily gave up their lives so that more females and children (from all classes) survive. Are there any more acts left? Let us see.
But before that let us analyze the Embarked column with a facetgrid plot.
fg = sns.FacetGrid(train_data, row='Embarked', aspect=2)fg.map(sns.pointplot, 'Pclass', 'Survived', 'Sex')fg.add_legend()
Did you notice something ridiculously strange happening on Embarked=C port? Those passengers who embarked on port C have totally reversed the odds for survival as far as Sex is concerned. Most of the males live and the females expire! This is FALSE info & can quickly be verified by a query to gather the %age of survivors grouped by Sex for Port C embarkation. Obviously the colors for Male & Female have got mixed up in the middle row. If your console warnings are suppressed you may not even notice it.. Luckily the warning is clear. Please use the ‘order’ parameter else you may get incorrect ordering
fg = sns.FacetGrid(train_data, row='Embarked', aspect=2)fg.map(sns.pointplot, 'Pclass', 'Survived', 'Sex', hue_order=['female','male'], order=[1,2,3],palette={'female':"r",'male': "g"})fg.add_legend()
Better! One very popular blog post (& at least a dozen other copies) make this erroneous observation and go on to other topics as if it were perfectly normal data behaviour. My sole intention in making this limited point is to request young readers not to go about the data exploration phases as if it were a formality that needed to be quickly gotten over with before jumping into the real thing — the ML modelling. Please dig into the data especially if you see patterns or anamolies which need further investigation.
Let us take very small deviation now.. Just for fun, I tried analyzing fares for women passengers to see if they differed from men. This was merely a distraction... and laying out (possible) proof of gender discrimination as far as fees were concerned was never on my agenda but here were the observations:
Looks like on an average, women’s tickets were priced higher by about 20% in Pclass 1, 8% in Pclass 2 and 4% in Pclass 3. I rest my case. Maybe the men bargained more to get better deals? In any case, the fares are clearly more favorably disposed to males but they got more than what they bargained for at the end. On a separate note, I sometimes feel we take the chivalry of these gentlemen for granted and assume that the same would repeat under any circumstances but this was clearly not the case in a few other parallel tragedies (women and children had lower mortality than males in those incidents). So there was definitely something special about these gentlemen on the Titanic..or maybe it was the crew and the leadership team that made it happen. We can only speculate...
Let us now turn our attention to a popular notion — that people in groups of 2–4 have good survival chances and groups >5 have lower chances.
train_data[‘FamilyCount’]=train_data[‘Parch’]+train_data[‘SibSp’]+1sns.countplot(x=’FamilyCount’, hue=’Survived’, data=train_data)
It appears as if solo travellers are at high risk. From 2–4 groups though the survival rate is high and then 5 onwards the survival rate dips completely. This observation is made by almost all Kaggle posts and indeed some of the very tall leaders have also made this observation in their analysis. Intuitively it may seem true — If you are travelling in a larger group, you would perhaps be made aware faster of the impeneding tragedy because of the sheer size of the group. On the other hand solo travellers, may have been fast asleep in their bunks and may have gotten the news late. As group size increases, perhaps it became more and more difficult to collect everyone & make a dash for safety and so maybe with larger groupsize the trend turns negative and survivals dip.
My initial conjecture was while this could be true, I felt that this could be a case of correlation instead of causation. In other words having larger groups did not ‘cause’ the survival rate to plunge. What I felt was actually happening is that large group sizes were more prevelant in Pclass 3 who anyway had a lower chance of survival based on the class of travel. In other words Pclass=3 was the causation of high mortality and groupsize>4 was just corelated to higher mortality. However I did feel that being solo DID increase mortality rate. Let us quickly see if all this is true.
It is indeed a corelation, not a causation! It is the Pclass which is playing a hidden role here. Let us replot the graph but do so at a common Pclass.
sns.countplot(x=’FamilyCount’,hue=’Survived’,data=train_data[(train_data.Pclass==3) & (train_data.FamilyCount >1)])
Situation looks gloomy now & quite the opposite from earlier graph. So groupsize does not seem to have a very major role to play in survival. Being solo or not does but beyond that the size of group does not seem to matter. It could unnecessarily give some false positives and one must think whether this information is relevant enough to be fed to the final ML model.
Even the ‘solo’ feature is worth a discussion. The general concession is that solo travellers have higher mortality rate. Let us check this.
Solo females buck the trend. But you may say this is not a fair comparision as females anyway have better survival rate. Let us do a final graph comparing mortality for Pclass 3 females between solo travellers & non-solo travellers.
plt.figure(figsize=(16, 6))sns.countplot(x='FamilyCount',hue='Survived',data=train_data[(train_data.Sex=='female') & (train_data.Pclass==3)])
We now see that the mortality rate percentage for solo females in Pclass 3 (or any Pclass for that matter) is much lower that mortality rates percentage for non-solo females. So basically if you were a solo woman traveller, you had much much better chance of survival compared to women with groups or families...and mind you the data is not statistically insignificant. What could be the reason for this extremely peculiar trend?
There were 60 women solo travellers in Pclass 3 compared to 84 non-solo woman travellers and it is here that perhaps we see the 4th and the greatest act of altruism seen aboard the the Titanic. While there can be other reasons for this, in my view this happened because the women here travelling with their husbands and male children(>12 years of age) did not possibly want to leave them even though they had a chance to do so!! Some individual acts of chivalry and altruism have been recognized on the Titanic, but this perhaps is the greatest of them all and it is a pity that this has not been called out so far.
We havent still analyzed the Name and the Ticket columns. When checking the correlation between variables, I found something unbelievable..Those people with lengthy Names had clear high chances of survival! Then it stuck me that maiden names are part of the name for married females. Thus if we sort by the length of the name, we get mostly all the women first and then later the men. Since it is undeniable that Woman across all Pclasses have clearly higher mortality than men, this explained the correlation. A number of other kernels too have made this interesting observation.
Another interesting aspect is that Names combined with Tickets allow us the ability to Group people. They will provide us valuable hints to who all are travelling together...which brings us to the last and most important point. I realized this while plotting the group size versus survival. While analyzing the data I noticed that while there is no connection between large groups and survival, there was a definite connection between survival of members within a group. This — more than Sex, Pclass and Age — determines if a person survives or not for a vast majority of the population (barring Pclass 1 and 2 females who almost always survive). More specifically within a group, if we do a sub-grouping based on Sex and age, we can get to a fine degree of prediction of survival. Grouping can be enhanced by building even maternal side relationships (using the maiden surname of the female passenger).
The Titanic dataset has a lot of missing ages. We end this blog by analyzing various perspectives from basic to advanced on how to do this. The simplest approach is to use the mean or median to fill all the missing ages. The mean age is around 30. However, one would be more accurate in imputing missing ages by calculating mean age of a group of ‘similar passengers’. For e.g., one could choose to calculate mean of Pclass1 passengers and assign it to all Pclass1 missing ages..and likeways for Pclass2 and Pclass3.
But we can further improvise on this. Because it is quite likely that (say)females on Pclass3 have a diff mean age than females on Pclass 1, so an even better approach (the one that most Kaggle leaders have taken) is to group people based on Sex, PClass. If one wants to further refine it, one could make use of the ‘Title’ and the PClass and it should give a slightly better result than Sex and Pclass. The ‘Title’ can be extracted from the name easily.
One can further improvise by building relationships and calculate missing values of ages. For e.g. say you have a husband-wife traveling and husband’s age is missing whereas the wife age is given. You could ‘guess’ the husband’s age as wife age+some number (like 5). Similarly you could guess a missing Sibling’s ages based on the other Sibling or a chid’s age from the parents.
Also, one could even use an ML model to predict the missing value of ages like a few kernels have done. But a pertinent question presents itself at this point. How much does the numerical value of age contribute to the survival? Will it make a lot of difference to the survival? The answer is NO. There are other factors which are far more important. HOWEVER the fact whether the person is a child or an adult or a senior citizen DOES play a critical role in survival. So long as one can categorize the missing ages as belonging to one of this group it is fine! In particular, we should be spending a lot more time worrying about whether the person in question (with the missing age) was a child or not? This makes a lot of difference to the survival chance. How do we do that? Well it is easy for male children because of the Title ‘Master’ which is prefixed to their names. But how do we identify a female child among the missing ages. There is no Title specific to female children. All unmarried females across all ages had the ‘Miss’ Title.
So here is a simple clue to identify such folks and impute their missing ages. I haven’t seen it being used in any kernel so far (at least the ones I have gone thru’ though). We can identify the such cases by checking the Parch flag. If Parch flag is >0 then they are most likely female children. And so it would be good to add this important heuristic after we are done with all the other steps...
train_data['Title'] = train_data.Name.str.extract(' ([A-Za-z]+)\.', expand=False) print ("Avg age of 'Miss' Title", round(train_data[train_data.Title=="Miss"]['Age'].mean()))print ("Avg age of 'Miss' Title travelling without Parents", round(train_data[(train_data.Title=="Miss") & (train_data.Parch==0)]['Age'].mean()))print ("Avg age of 'Miss' Title travelling with Parents", round(train_data[(train_data.Title=="Miss") & (train_data.Parch!=0)]['Age'].mean()), '\n')Avg age of ‘Miss’ Title 22Avg age of ‘Miss’ Title travelling without Parents 28Avg age of ‘Miss’ Title travelling with Parents 12 !!
See the HUGE difference! If we had used the average value without considering the Parch, we would have gone horribly wrong. Even here there is a huge gap between Pclasses and we need to take that into consideration before imputing the final values.
The Titanic dataset continue to surprise and inspire even a decade after it was made available. Top scores on the Titanic follow a pattern of waves. Every once in a few years, there is a renewed interest and the next generation of data scientists push the top score ever so slightly. It has been a couple of years since Chris Deotte — the current number 1 on Kaggle in terms of discussions and number 2 in terms of Notebooks — upped the ante with a score of 84% (Let us ignore the 100% scores and even the kernels with pretuned hyperparameters). I do hope the new budding data scientists reading this blog are motivated to take a re-look at this extremely captivating dataset and push the scores even higher. Knowing Chris, he would be the first one to clap if this were to happen!
All the best!
Do check my notebook titled — Captivating Conversations with the Titanic dataset in Python. https://www.kaggle.com/allohvk/captivating-conversations-with-the-titanic-dataset which has a lot of documentation and is extremely easy to follow even if one is a beginner to both ML and Python. | [
{
"code": null,
"e": 334,
"s": 172,
"text": "Unique vignettes tumbled out during the course of my discussions with the Titanic dataset. Some of them well documented in the past and some not. A few examples:"
},
{
"code": null,
"e": 585,
"s": 334,
"text": "Would you feel safer if you were traveling Second class or Third class? Contrary to popular opinion made famous by Hollywood movies, you had DOUBLE the chance of surviving the Titanic as an adult male if you travelled THIRD class instead SECOND class"
},
{
"code": null,
"e": 895,
"s": 585,
"text": "“What’s in a Name? That which we call a rose, By any other name would smell as sweet” — Act II, Scene II. Unfortunately the Titanic data set seems to violently disagree with Juliet (& the old Bard) for people with short names had extremely high mortality rate on the Titanic compared to people with long names"
},
{
"code": null,
"e": 1118,
"s": 895,
"text": "A case for Altruism on the high seas — Darwin was proved wrong that night, but does the data speak of any other acts of altruism that went undocumented? 3 separate pieces of evidence present themselves on closer inspection"
},
{
"code": null,
"e": 1207,
"s": 1118,
"text": "Oops Errata on the Titanic dataset tutorial blogs — One original mistake, several copies"
},
{
"code": null,
"e": 1299,
"s": 1207,
"text": "Females on the Titanic may have been charged a little more — But males paid with a lot more"
},
{
"code": null,
"e": 1385,
"s": 1299,
"text": "Correlation is not Causation — The fallacy of the ‘Survival of the Groups’ conclusion"
},
{
"code": null,
"e": 1514,
"s": 1385,
"text": "What is the single biggest indicator of survival on the Titanic data set — No it is none of the 11 columns listed in the dataset"
},
{
"code": null,
"e": 1649,
"s": 1514,
"text": "Fill in the blanks — Is there a vital clue regarding the female-children that seems to have overlooked while filling the missing ages?"
},
{
"code": null,
"e": 2000,
"s": 1649,
"text": "No matter what the leaders say — going solo does not necessarily mean you had lower chances of survival. If you were a female, you WOULD want to go solo in order to survive the Titanic. Upon probing why, the data narrates a heart-wrenching tale involving the ultimate act of sacrifice that played out on that fateful night more than 100 years back..."
},
{
"code": null,
"e": 2601,
"s": 2000,
"text": "It is almost a decade since the Titanic competition was hosted by Kaggle. It is like the proverbial ‘Rite of Passage’ for any aspiring data scientist. You can see some of today’s grandmasters at Kaggle who are amongst the world’s best data scientists leave their indelible stamp on this dataset sometime in the past. It is a ridiculously simple and small dataset but provides a surprisingly good exercise in almost all aspects of data science and Machine learning — starting from data exploration/visualization to guessing missing values, feature engineering and to testing out a number of ML models."
},
{
"code": null,
"e": 3154,
"s": 2601,
"text": "The details of the competition may already be well known and I summarize it in just 2–3 sentences — It involves predicting whether passengers on the Titanic would survive or not..given a set of characteristics like their age, Sex, class of travel, port Embarked etc. The aspiring data scientist is supposed to make his model ‘learn’ from the training data set (which contain an additional column on whether the passenger survived or not) and apply these ‘learnings’ to the test data set and predict which of the passengers in the test dataset survives."
},
{
"code": null,
"e": 3728,
"s": 3154,
"text": "Though many years have passed, there is still a surprising amount of information hidden in the dataset. With a bit of coaxing though, it is more than willing to give up its secrets. So without much ado, we jump into transcripts of the discussions I had with this fascinating dataset in Python — a language I learnt just to converse with it. We will solely use the Kaggle dataset to come to our conclusions and will not refer to any external source of data. So this analysis is to be looked at from that perspective only and may/may not be a reflection on the actual events."
},
{
"code": null,
"e": 4143,
"s": 3728,
"text": "import pandas as pdimport seaborn as snsimport matplotlib.pyplot as plttest_data = pd.read_csv (‘/kaggle/input/titanic/test.csv’)train_data = pd.read_csv(“/kaggle/input/titanic/train.csv”)##These survival rates will be used as a referenceprint(round(train_data [['Pclass','Survived']].groupby(['Pclass']).mean()*100,1))print(round(train_data [['Sex', 'Pclass','Survived']].groupby(['Pclass', 'Sex']).mean()*100,1))"
},
{
"code": null,
"e": 4533,
"s": 4143,
"text": "The basic observations are well known and are henceforth summarized in couple of quick sentences. The Sex of the passenger and the Class in which they travelled (Pclass) seem to have the highest correlation with survival. Age seems to play a role. Other factors like Port Embarked seem to play a small role. The numbers above seem to be in accordance with the general expectations as well."
},
{
"code": null,
"e": 4575,
"s": 4533,
"text": "We start our analysis with a Violen plot."
},
{
"code": null,
"e": 4683,
"s": 4575,
"text": "sns.violinplot(x=’Pclass’, y=’Age’, hue=’Survived’, split=True, data=train_data, palette={0: “r”, 1: “g”});"
},
{
"code": null,
"e": 5101,
"s": 4683,
"text": "Straight away we see some puzzling things that need to investigated. Pclass 2 and 3 have a very sharp pronounced peaks of expiry near the 20–35 age range. This is not the case with Pclass 1 though. PClass 1 has far more survivors across all age levels except maybe after 50 or so. After 60 there is a sharp jump in expiry. This is not as sharp in Pclass 2 or 3. This is a curious phenomenon. Let us investigate a bit."
},
{
"code": null,
"e": 6626,
"s": 5101,
"text": "print('Pclass 1 survivors above Age 60:', round(len(train_data[(train_data['Pclass']==1) & (train_data['Age']>59) & (train_data['Survived']==True)])/len(train_data[(train_data['Pclass']==1) & (train_data['Age']>59)])*100,1), '%')print('Pclass 2 survivors above Age 60:', round(len(train_data[(train_data['Pclass']==2) & (train_data['Age']>59) & (train_data['Survived']==True)])/len(train_data[(train_data['Pclass']==2) & (train_data['Age']>59)])*100,1), '%')print('Pclass 3 survivors above Age 60:', round(len(train_data[(train_data['Pclass']==3) & (train_data['Age']>59) & (train_data['Survived']==True)])/len(train_data[(train_data['Pclass']==3) & (train_data['Age']>59)])*100,1), '%')print('Pclass1 survivors between 20-30 Age:',round(len(train_data[(train_data['Pclass']==1) & (train_data['Age']>19) & (train_data['Age']<31) & (train_data['Survived']==True)])/len(train_data[(train_data['Pclass']==1) & (train_data['Age']>19) & (train_data['Age']<31)])*100,1),'%')print('Pclass2 survivors between 20-30 Age:',round(len(train_data[(train_data['Pclass']==2) & (train_data['Age']>19) & (train_data['Age']<31) &(train_data['Survived']==True)])/len(train_data[(train_data['Pclass']==2)&(train_data['Age']>19) &(train_data['Age']<31)])*100,1),'%')print('Pclass3 survivors between 20-30 Age:',round(len(train_data[(train_data['Pclass']==3) & (train_data['Age']>19) & (train_data['Age']<31) &(train_data['Survived']==True)])/len(train_data[(train_data['Pclass']==3) & (train_data['Age']>19) &(train_data['Age']<31)])*100,1),'%')"
},
{
"code": null,
"e": 7264,
"s": 6626,
"text": "Indeed in Pclass=1, there is nearly 2.5 times more survival chance if one is between 20–30 age as compared to 60. As the Pclass changes we can see how the survival gap narrows between the 2 age groups. What could explain this? Is this an act of altruism — letting the younger generation live? Why is this limited only to the first class? Is it just a quirk of data and does not mean much? A quick analysis of data shows that Pclass 2 and Pclass 3 have statistically insignificant count of older passengers. Any survivals would possibly skew the percentages. But Pclass1 has 17 people greater than 60 which is not an insignificant number."
},
{
"code": null,
"e": 8341,
"s": 7264,
"text": "One possibility is it that there were more males among the elderly and more females among the middleage group in Pclass 1..so that is the reason for the disparity. A quick series of commands reveal that only 2 males > 60 out of 14 in pclass 1 survive as compared to 9 out of 19 for middle age group. Thus even after accounting for all parameters we see that this difference of 14% survival versus a near 50% which is a mystery. It is not that the middle age folks pushed around the older lot. In fact much of the evacuation was orderly except for the very last few unfortunate minutes. Most of the folks who exipred were able bodied middle aged males..which is why I talked about Darwin beng proved wrong that night as the first act of altruism. But looks like there is a twist to this theory as far as first class passengers are concerned. It does look like some of the older males voluntarily made way for the younger males..Could this be the 2nd act of altruism on the Titanic? The data is very small but not entirely insignificant and it does point towards that direction."
},
{
"code": null,
"e": 9132,
"s": 8341,
"text": "Another stunning data presents itself when we further add the ‘Sex’ column to the filter. We see that NONE of the 33 Pclass 2 males in the middle age group (20–30) age group survives. The survival rate for Pclass2 Male passengers is 16% as we have seen earlier, so this is strange. In fact it is so curious that I extended the age ranges and found that only 4 out of 72 males between 20–60 age group survived. This is just 5% compared to the survival rate for Pclass2 males which is 16%. This could mean either of 2 things: Either in Pclass2 more kids survived than normal or there were more %age of kids in Pclass2 males. This means that adult males in Pclass 2 had actually less survival chance compared to Pclass 3 and kind of turns popular theories around the head. Let us check this..."
},
{
"code": null,
"e": 9810,
"s": 9132,
"text": "Unbelievably fascinating and a wonder this has not been documented so far. To put it bluntly if you were an adult male, you had double the chances of survival if you got yourself booked in 3rd class on the Titanic rather than 2nd class! This does turn popular theories on the head.. We have discovered 3 acts of altruism so far on the Titanic. The first one was well known. The second is not very conclusive due to lack of enough data but is not statistically insignificant. The third was a big surprise to me. A huge chunk of Pclass 2 males voluntarily gave up their lives so that more females and children (from all classes) survive. Are there any more acts left? Let us see."
},
{
"code": null,
"e": 9884,
"s": 9810,
"text": "But before that let us analyze the Embarked column with a facetgrid plot."
},
{
"code": null,
"e": 10006,
"s": 9884,
"text": "fg = sns.FacetGrid(train_data, row='Embarked', aspect=2)fg.map(sns.pointplot, 'Pclass', 'Survived', 'Sex')fg.add_legend()"
},
{
"code": null,
"e": 10612,
"s": 10006,
"text": "Did you notice something ridiculously strange happening on Embarked=C port? Those passengers who embarked on port C have totally reversed the odds for survival as far as Sex is concerned. Most of the males live and the females expire! This is FALSE info & can quickly be verified by a query to gather the %age of survivors grouped by Sex for Port C embarkation. Obviously the colors for Male & Female have got mixed up in the middle row. If your console warnings are suppressed you may not even notice it.. Luckily the warning is clear. Please use the ‘order’ parameter else you may get incorrect ordering"
},
{
"code": null,
"e": 10813,
"s": 10612,
"text": "fg = sns.FacetGrid(train_data, row='Embarked', aspect=2)fg.map(sns.pointplot, 'Pclass', 'Survived', 'Sex', hue_order=['female','male'], order=[1,2,3],palette={'female':\"r\",'male': \"g\"})fg.add_legend()"
},
{
"code": null,
"e": 11333,
"s": 10813,
"text": "Better! One very popular blog post (& at least a dozen other copies) make this erroneous observation and go on to other topics as if it were perfectly normal data behaviour. My sole intention in making this limited point is to request young readers not to go about the data exploration phases as if it were a formality that needed to be quickly gotten over with before jumping into the real thing — the ML modelling. Please dig into the data especially if you see patterns or anamolies which need further investigation."
},
{
"code": null,
"e": 11640,
"s": 11333,
"text": "Let us take very small deviation now.. Just for fun, I tried analyzing fares for women passengers to see if they differed from men. This was merely a distraction... and laying out (possible) proof of gender discrimination as far as fees were concerned was never on my agenda but here were the observations:"
},
{
"code": null,
"e": 12421,
"s": 11640,
"text": "Looks like on an average, women’s tickets were priced higher by about 20% in Pclass 1, 8% in Pclass 2 and 4% in Pclass 3. I rest my case. Maybe the men bargained more to get better deals? In any case, the fares are clearly more favorably disposed to males but they got more than what they bargained for at the end. On a separate note, I sometimes feel we take the chivalry of these gentlemen for granted and assume that the same would repeat under any circumstances but this was clearly not the case in a few other parallel tragedies (women and children had lower mortality than males in those incidents). So there was definitely something special about these gentlemen on the Titanic..or maybe it was the crew and the leadership team that made it happen. We can only speculate..."
},
{
"code": null,
"e": 12563,
"s": 12421,
"text": "Let us now turn our attention to a popular notion — that people in groups of 2–4 have good survival chances and groups >5 have lower chances."
},
{
"code": null,
"e": 12694,
"s": 12563,
"text": "train_data[‘FamilyCount’]=train_data[‘Parch’]+train_data[‘SibSp’]+1sns.countplot(x=’FamilyCount’, hue=’Survived’, data=train_data)"
},
{
"code": null,
"e": 13471,
"s": 12694,
"text": "It appears as if solo travellers are at high risk. From 2–4 groups though the survival rate is high and then 5 onwards the survival rate dips completely. This observation is made by almost all Kaggle posts and indeed some of the very tall leaders have also made this observation in their analysis. Intuitively it may seem true — If you are travelling in a larger group, you would perhaps be made aware faster of the impeneding tragedy because of the sheer size of the group. On the other hand solo travellers, may have been fast asleep in their bunks and may have gotten the news late. As group size increases, perhaps it became more and more difficult to collect everyone & make a dash for safety and so maybe with larger groupsize the trend turns negative and survivals dip."
},
{
"code": null,
"e": 14059,
"s": 13471,
"text": "My initial conjecture was while this could be true, I felt that this could be a case of correlation instead of causation. In other words having larger groups did not ‘cause’ the survival rate to plunge. What I felt was actually happening is that large group sizes were more prevelant in Pclass 3 who anyway had a lower chance of survival based on the class of travel. In other words Pclass=3 was the causation of high mortality and groupsize>4 was just corelated to higher mortality. However I did feel that being solo DID increase mortality rate. Let us quickly see if all this is true."
},
{
"code": null,
"e": 14211,
"s": 14059,
"text": "It is indeed a corelation, not a causation! It is the Pclass which is playing a hidden role here. Let us replot the graph but do so at a common Pclass."
},
{
"code": null,
"e": 14327,
"s": 14211,
"text": "sns.countplot(x=’FamilyCount’,hue=’Survived’,data=train_data[(train_data.Pclass==3) & (train_data.FamilyCount >1)])"
},
{
"code": null,
"e": 14696,
"s": 14327,
"text": "Situation looks gloomy now & quite the opposite from earlier graph. So groupsize does not seem to have a very major role to play in survival. Being solo or not does but beyond that the size of group does not seem to matter. It could unnecessarily give some false positives and one must think whether this information is relevant enough to be fed to the final ML model."
},
{
"code": null,
"e": 14837,
"s": 14696,
"text": "Even the ‘solo’ feature is worth a discussion. The general concession is that solo travellers have higher mortality rate. Let us check this."
},
{
"code": null,
"e": 15070,
"s": 14837,
"text": "Solo females buck the trend. But you may say this is not a fair comparision as females anyway have better survival rate. Let us do a final graph comparing mortality for Pclass 3 females between solo travellers & non-solo travellers."
},
{
"code": null,
"e": 15212,
"s": 15070,
"text": "plt.figure(figsize=(16, 6))sns.countplot(x='FamilyCount',hue='Survived',data=train_data[(train_data.Sex=='female') & (train_data.Pclass==3)])"
},
{
"code": null,
"e": 15642,
"s": 15212,
"text": "We now see that the mortality rate percentage for solo females in Pclass 3 (or any Pclass for that matter) is much lower that mortality rates percentage for non-solo females. So basically if you were a solo woman traveller, you had much much better chance of survival compared to women with groups or families...and mind you the data is not statistically insignificant. What could be the reason for this extremely peculiar trend?"
},
{
"code": null,
"e": 16258,
"s": 15642,
"text": "There were 60 women solo travellers in Pclass 3 compared to 84 non-solo woman travellers and it is here that perhaps we see the 4th and the greatest act of altruism seen aboard the the Titanic. While there can be other reasons for this, in my view this happened because the women here travelling with their husbands and male children(>12 years of age) did not possibly want to leave them even though they had a chance to do so!! Some individual acts of chivalry and altruism have been recognized on the Titanic, but this perhaps is the greatest of them all and it is a pity that this has not been called out so far."
},
{
"code": null,
"e": 16839,
"s": 16258,
"text": "We havent still analyzed the Name and the Ticket columns. When checking the correlation between variables, I found something unbelievable..Those people with lengthy Names had clear high chances of survival! Then it stuck me that maiden names are part of the name for married females. Thus if we sort by the length of the name, we get mostly all the women first and then later the men. Since it is undeniable that Woman across all Pclasses have clearly higher mortality than men, this explained the correlation. A number of other kernels too have made this interesting observation."
},
{
"code": null,
"e": 17743,
"s": 16839,
"text": "Another interesting aspect is that Names combined with Tickets allow us the ability to Group people. They will provide us valuable hints to who all are travelling together...which brings us to the last and most important point. I realized this while plotting the group size versus survival. While analyzing the data I noticed that while there is no connection between large groups and survival, there was a definite connection between survival of members within a group. This — more than Sex, Pclass and Age — determines if a person survives or not for a vast majority of the population (barring Pclass 1 and 2 females who almost always survive). More specifically within a group, if we do a sub-grouping based on Sex and age, we can get to a fine degree of prediction of survival. Grouping can be enhanced by building even maternal side relationships (using the maiden surname of the female passenger)."
},
{
"code": null,
"e": 18260,
"s": 17743,
"text": "The Titanic dataset has a lot of missing ages. We end this blog by analyzing various perspectives from basic to advanced on how to do this. The simplest approach is to use the mean or median to fill all the missing ages. The mean age is around 30. However, one would be more accurate in imputing missing ages by calculating mean age of a group of ‘similar passengers’. For e.g., one could choose to calculate mean of Pclass1 passengers and assign it to all Pclass1 missing ages..and likeways for Pclass2 and Pclass3."
},
{
"code": null,
"e": 18715,
"s": 18260,
"text": "But we can further improvise on this. Because it is quite likely that (say)females on Pclass3 have a diff mean age than females on Pclass 1, so an even better approach (the one that most Kaggle leaders have taken) is to group people based on Sex, PClass. If one wants to further refine it, one could make use of the ‘Title’ and the PClass and it should give a slightly better result than Sex and Pclass. The ‘Title’ can be extracted from the name easily."
},
{
"code": null,
"e": 19094,
"s": 18715,
"text": "One can further improvise by building relationships and calculate missing values of ages. For e.g. say you have a husband-wife traveling and husband’s age is missing whereas the wife age is given. You could ‘guess’ the husband’s age as wife age+some number (like 5). Similarly you could guess a missing Sibling’s ages based on the other Sibling or a chid’s age from the parents."
},
{
"code": null,
"e": 20139,
"s": 19094,
"text": "Also, one could even use an ML model to predict the missing value of ages like a few kernels have done. But a pertinent question presents itself at this point. How much does the numerical value of age contribute to the survival? Will it make a lot of difference to the survival? The answer is NO. There are other factors which are far more important. HOWEVER the fact whether the person is a child or an adult or a senior citizen DOES play a critical role in survival. So long as one can categorize the missing ages as belonging to one of this group it is fine! In particular, we should be spending a lot more time worrying about whether the person in question (with the missing age) was a child or not? This makes a lot of difference to the survival chance. How do we do that? Well it is easy for male children because of the Title ‘Master’ which is prefixed to their names. But how do we identify a female child among the missing ages. There is no Title specific to female children. All unmarried females across all ages had the ‘Miss’ Title."
},
{
"code": null,
"e": 20538,
"s": 20139,
"text": "So here is a simple clue to identify such folks and impute their missing ages. I haven’t seen it being used in any kernel so far (at least the ones I have gone thru’ though). We can identify the such cases by checking the Parch flag. If Parch flag is >0 then they are most likely female children. And so it would be good to add this important heuristic after we are done with all the other steps..."
},
{
"code": null,
"e": 21138,
"s": 20538,
"text": "train_data['Title'] = train_data.Name.str.extract(' ([A-Za-z]+)\\.', expand=False) print (\"Avg age of 'Miss' Title\", round(train_data[train_data.Title==\"Miss\"]['Age'].mean()))print (\"Avg age of 'Miss' Title travelling without Parents\", round(train_data[(train_data.Title==\"Miss\") & (train_data.Parch==0)]['Age'].mean()))print (\"Avg age of 'Miss' Title travelling with Parents\", round(train_data[(train_data.Title==\"Miss\") & (train_data.Parch!=0)]['Age'].mean()), '\\n')Avg age of ‘Miss’ Title 22Avg age of ‘Miss’ Title travelling without Parents 28Avg age of ‘Miss’ Title travelling with Parents 12 !!"
},
{
"code": null,
"e": 21387,
"s": 21138,
"text": "See the HUGE difference! If we had used the average value without considering the Parch, we would have gone horribly wrong. Even here there is a huge gap between Pclasses and we need to take that into consideration before imputing the final values."
},
{
"code": null,
"e": 22169,
"s": 21387,
"text": "The Titanic dataset continue to surprise and inspire even a decade after it was made available. Top scores on the Titanic follow a pattern of waves. Every once in a few years, there is a renewed interest and the next generation of data scientists push the top score ever so slightly. It has been a couple of years since Chris Deotte — the current number 1 on Kaggle in terms of discussions and number 2 in terms of Notebooks — upped the ante with a score of 84% (Let us ignore the 100% scores and even the kernels with pretuned hyperparameters). I do hope the new budding data scientists reading this blog are motivated to take a re-look at this extremely captivating dataset and push the scores even higher. Knowing Chris, he would be the first one to clap if this were to happen!"
},
{
"code": null,
"e": 22183,
"s": 22169,
"text": "All the best!"
}
]
|
Building a multi-output Convolutional Neural Network with Keras | by Rodrigo Bressan | Towards Data Science | In this post, we will be exploring the Keras functional API in order to build a multi-output Deep Learning model. We will show how to train a single model that is capable of predicting three distinct outputs. By using the UTK Face dataset, which is composed of over 20 thousand pictures of people in uncontrolled environments, we will predict the age, gender and sex for each record presented in the dataset, reaching an accuracy of 91% for gender and 78% for race.
The UTKFace dataset is a large dataset composed of over 20 thousand face images with their respective annotations of age, gender and ethnicity. The images are properly cropped into the face region, but display some variations in pose, illumination, resolution, etc.
In order to retrieve the annotations of each record, we need to parse the filenames. Each record is stored in the following format: age_gender_race_date&time.jpg
Where:
age is an integer from 0 to 116
gender is an integer in which 0 represents male and 1 represents female
race is an integer from 0 to 4, denoting white, black, asian, indian and others, respectively
date and time, denoting when the picture was taken
If you want to know more about this dataset, please check their website.
Let’s start by importing some libraries and creating our dictionary to help us on parsing the information from the dataset, along with some other information (dataset location, training split, width and height of the samples).
import numpy as np import pandas as pdimport osimport globimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsdataset_folder_name = 'UTKFace'TRAIN_TEST_SPLIT = 0.7IM_WIDTH = IM_HEIGHT = 198dataset_dict = { 'race_id': { 0: 'white', 1: 'black', 2: 'asian', 3: 'indian', 4: 'others' }, 'gender_id': { 0: 'male', 1: 'female' }}dataset_dict['gender_alias'] = dict((g, i) for i, g in dataset_dict['gender_id'].items())dataset_dict['race_alias'] = dict((r, i) for i, r in dataset_dict['race_id'].items())
Let’s also define a function to help us on extracting the data from our dataset. This function will be used to iterate over each file of the UTK dataset and return a Pandas Dataframe containing all the fields (age, gender and sex) of our records.
def parse_dataset(dataset_path, ext='jpg'): """ Used to extract information about our dataset. It does iterate over all images and return a DataFrame with the data (age, gender and sex) of all files. """ def parse_info_from_file(path): """ Parse information from a single file """ try: filename = os.path.split(path)[1] filename = os.path.splitext(filename)[0] age, gender, race, _ = filename.split('_') return int(age), dataset_dict['gender_id'][int(gender)], dataset_dict['race_id'][int(race)] except Exception as ex: return None, None, None files = glob.glob(os.path.join(dataset_path, "*.%s" % ext)) records = [] for file in files: info = parse_info_from_file(file) records.append(info) df = pd.DataFrame(records) df['file'] = files df.columns = ['age', 'gender', 'race', 'file'] df = df.dropna() return dfdf = parse_dataset(dataset_folder_name)df.head()
As an important step to understand not only the distribution of our dataset, but as well the predictions generated by our model, it is a recommended practice to perform some data visualization process on our dataset. We will start by defining a helper function to generate pie plots based on a given Pandas series:
import plotly.graph_objects as godef plot_distribution(pd_series): labels = pd_series.value_counts().index.tolist() counts = pd_series.value_counts().values.tolist() pie_plot = go.Pie(labels=labels, values=counts, hole=.3) fig = go.Figure(data=[pie_plot]) fig.update_layout(title_text='Distribution for %s' % pd_series.name) fig.show()
Let’s start by plotting the race distribution with our predefined plot_distribution method.
plot_distribution(df['race'])
Having a quick glance at this plot, we can see that almost half of the samples are from the white race, so we can expect this group to have a great accuracy. Other races such as black, Indian and Asian also show a good number of samples, probably leading us to good accuracy numbers as well. The race ‘others’ (Hispanics, Latinos, etc) on the other side, show a small number of samples, being more likely to have a small accuracy.
plot_distribution(df['gender'])
For both male and female samples, we have quite a good balanced number of records, so we should have a great accuracy for both classes when using our model.
Let’s also plot how our age feature is distributed over the dataset by using a simple histogram with 20 bins/sectors.
import plotly.express as pxfig = px.histogram(df, x="age", nbins=20)fig.update_layout(title_text='Age distribution')fig.show()
We can also display this same plot in a pie plot. Let’s group the age column into bins and then plot it with a pie chart
bins = [0, 10, 20, 30, 40, 60, 80, np.inf]names = ['<10', '10-20', '20-30', '30-40', '40-60', '60-80', '80+']age_binned = pd.cut(df['age'], bins, labels=names)plot_distribution(age_binned)
We can observe that our dataset is mostly composed of individuals whose age varies between 20 and 30 years, followed by individuals ranging from 30 to 40 years and then 40 to 60 years old. These groups represent around 70% of our dataset, so we can assume that we are going to have good accuracy in predicting individuals in these ranges.
We could also perform some multi-variate analysis on our dataset, but since the scope of this post is to demonstrate the usage of a multi-output model with Keras, we won’t be covering it — maybe another time, if you guys are interested.
In order to input our data to our Keras multi-output model, we will create a helper object to work as a data generator for our dataset. This will be done by generating batches of data, which will be used to feed our multi-output model with both the images and their labels. This step is also done instead of just loading all the dataset into the memory at once, which could lead to an out of memory error.
from keras.utils import to_categoricalfrom PIL import Imageclass UtkFaceDataGenerator(): """ Data generator for the UTKFace dataset. This class should be used when training our Keras multi-output model. """ def __init__(self, df): self.df = df def generate_split_indexes(self): p = np.random.permutation(len(self.df)) train_up_to = int(len(self.df) * TRAIN_TEST_SPLIT) train_idx = p[:train_up_to] test_idx = p[train_up_to:] train_up_to = int(train_up_to * TRAIN_TEST_SPLIT) train_idx, valid_idx = train_idx[:train_up_to], train_idx[train_up_to:] # converts alias to id self.df['gender_id'] = self.df['gender'].map(lambda gender: dataset_dict['gender_alias'][gender]) self.df['race_id'] = self.df['race'].map(lambda race: dataset_dict['race_alias'][race]) self.max_age = self.df['age'].max() return train_idx, valid_idx, test_idx def preprocess_image(self, img_path): """ Used to perform some minor preprocessing on the image before inputting into the network. """ im = Image.open(img_path) im = im.resize((IM_WIDTH, IM_HEIGHT)) im = np.array(im) / 255.0 return im def generate_images(self, image_idx, is_training, batch_size=16): """ Used to generate a batch with images when training/testing/validating our Keras model. """ # arrays to store our batched data images, ages, races, genders = [], [], [], [] while True: for idx in image_idx: person = self.df.iloc[idx] age = person['age'] race = person['race_id'] gender = person['gender_id'] file = person['file'] im = self.preprocess_image(file) ages.append(age / self.max_age) races.append(to_categorical(race, len(dataset_dict['race_id']))) genders.append(to_categorical(gender, len(dataset_dict['gender_id']))) images.append(im) # yielding condition if len(images) >= batch_size: yield np.array(images), [np.array(ages), np.array(races), np.array(genders)] images, ages, races, genders = [], [], [], [] if not is_training: break data_generator = UtkFaceDataGenerator(df)train_idx, valid_idx, test_idx = data_generator.generate_split_indexes()
In this step, we will define our multi-output Keras model. Our model will be composed of three major branches, one for each available feature: age, gender and race.
The default structure for our convolutional layers is based on a Conv2D layer with a ReLU activation, followed by a BatchNormalization layer, a MaxPooling and then finally a Dropout layer. Each of these layers is then followed by the final Dense layer. This step is repeated for each of the outputs we are trying to predict.
These default layers are defined on the make_default_hidden_layers method, which will be reused on building each of the branches of our model. In the code shown below we will define the class that will be responsible for creating our multi-output model.
from keras.models import Modelfrom keras.layers.normalization import BatchNormalizationfrom keras.layers.convolutional import Conv2Dfrom keras.layers.convolutional import MaxPooling2Dfrom keras.layers.core import Activationfrom keras.layers.core import Dropoutfrom keras.layers.core import Lambdafrom keras.layers.core import Densefrom keras.layers import Flattenfrom keras.layers import Inputimport tensorflow as tfclass UtkMultiOutputModel(): """ Used to generate our multi-output model. This CNN contains three branches, one for age, other for sex and another for race. Each branch contains a sequence of Convolutional Layers that is defined on the make_default_hidden_layers method. """ def make_default_hidden_layers(self, inputs): """ Used to generate a default set of hidden layers. The structure used in this network is defined as: Conv2D -> BatchNormalization -> Pooling -> Dropout """ x = Conv2D(16, (3, 3), padding="same")(inputs) x = Activation("relu")(x) x = BatchNormalization(axis=-1)(x) x = MaxPooling2D(pool_size=(3, 3))(x) x = Dropout(0.25)(x) x = Conv2D(32, (3, 3), padding="same")(x) x = Activation("relu")(x) x = BatchNormalization(axis=-1)(x) x = MaxPooling2D(pool_size=(2, 2))(x) x = Dropout(0.25)(x) x = Conv2D(32, (3, 3), padding="same")(x) x = Activation("relu")(x) x = BatchNormalization(axis=-1)(x) x = MaxPooling2D(pool_size=(2, 2))(x) x = Dropout(0.25)(x) return x def build_race_branch(self, inputs, num_races): """ Used to build the race branch of our face recognition network. This branch is composed of three Conv -> BN -> Pool -> Dropout blocks, followed by the Dense output layer. """ x = self.make_default_hidden_layers(inputs) x = Flatten()(x) x = Dense(128)(x) x = Activation("relu")(x) x = BatchNormalization()(x) x = Dropout(0.5)(x) x = Dense(num_races)(x) x = Activation("softmax", name="race_output")(x) return x def build_gender_branch(self, inputs, num_genders=2): """ Used to build the gender branch of our face recognition network. This branch is composed of three Conv -> BN -> Pool -> Dropout blocks, followed by the Dense output layer. """ x = Lambda(lambda c: tf.image.rgb_to_grayscale(c))(inputs) x = self.make_default_hidden_layers(inputs) x = Flatten()(x) x = Dense(128)(x) x = Activation("relu")(x) x = BatchNormalization()(x) x = Dropout(0.5)(x) x = Dense(num_genders)(x) x = Activation("sigmoid", name="gender_output")(x) return x def build_age_branch(self, inputs): """ Used to build the age branch of our face recognition network. This branch is composed of three Conv -> BN -> Pool -> Dropout blocks, followed by the Dense output layer. """ x = self.make_default_hidden_layers(inputs) x = Flatten()(x) x = Dense(128)(x) x = Activation("relu")(x) x = BatchNormalization()(x) x = Dropout(0.5)(x) x = Dense(1)(x) x = Activation("linear", name="age_output")(x) return x def assemble_full_model(self, width, height, num_races): """ Used to assemble our multi-output model CNN. """ input_shape = (height, width, 3) inputs = Input(shape=input_shape) age_branch = self.build_age_branch(inputs) race_branch = self.build_race_branch(inputs, num_races) gender_branch = self.build_gender_branch(inputs) model = Model(inputs=inputs, outputs = [age_branch, race_branch, gender_branch], name="face_net") return model model = UtkMultiOutputModel().assemble_full_model(IM_WIDTH, IM_HEIGHT, num_races=len(dataset_dict['race_alias']))
Let’s give a look into our model structure, to have a better understanding of what we are building. We can see from it that we have a single input, that in our case is the image we are feeding the CNN, which does decompose into three separated branches, each with their own set of Convolutional layers, followed by their respective Dense layers.
Now it’s time to train our multi-output model, once we have both the data ready to use and the model architecture defined. But before doing this step, we need to compile our model. For this task, we will use a learning rate of 0.0004 and an Adam optimizer — but you can be feel free to try with other hyperparameters as well. We will also use custom loss weights and a custom loss function for each feature. When building our optimizer, let’s use a decay based on the learning rate divided by the number of epochs, so we will slowly be decreasing our learning rate over the epochs.
from keras.optimizers import Adaminit_lr = 1e-4epochs = 100opt = Adam(lr=init_lr, decay=init_lr / epochs)model.compile(optimizer=opt, loss={ 'age_output': 'mse', 'race_output': 'categorical_crossentropy', 'gender_output': 'binary_crossentropy'}, loss_weights={ 'age_output': 4., 'race_output': 1.5, 'gender_output': 0.1}, metrics={ 'age_output': 'mae', 'race_output': 'accuracy', 'gender_output': 'accuracy'})
Now let’s train our model with a batch size of 32 for both valid and train sets. We will be using a ModelCheckpoint callback in order to save the model on disk at the end of each epoch.
from keras.callbacks import ModelCheckpointbatch_size = 32valid_batch_size = 32train_gen = data_generator.generate_images(train_idx, is_training=True, batch_size=batch_size)valid_gen = data_generator.generate_images(valid_idx, is_training=True, batch_size=valid_batch_size)callbacks = [ ModelCheckpoint("./model_checkpoint", monitor='val_loss')]history = model.fit_generator(train_gen, steps_per_epoch=len(train_idx)//batch_size, epochs=epochs, callbacks=callbacks, validation_data=valid_gen, validation_steps=len(valid_idx)//valid_batch_size)
Once we have our model trained, let’s give a better look into how our model performed on both training and validation sets over the epochs:
plt.clf()fig = go.Figure()fig.add_trace(go.Scatter( y=history.history['race_output_acc'], name='Train'))fig.add_trace(go.Scatter( y=history.history['val_race_output_acc'], name='Valid'))fig.update_layout(height=500, width=700, title='Accuracy for race feature', xaxis_title='Epoch', yaxis_title='Accuracy')fig.show()
We can see that by epoch 50 our model stabilizes itself on the validation set, only increasing on the training one, with an accuracy of approximately 80%.
plt.clf()fig = go.Figure()fig.add_trace(go.Scatter( y=history.history['gender_output_acc'], name='Train'))fig.add_trace(go.Scatter( y=history.history['val_gender_output_acc'], name='Valid'))fig.update_layout(height=500, width=700, title='Accuracy for gender feature', xaxis_title='Epoch', yaxis_title='Accuracy')fig.show()
Similarly to the race feature, we can see that our model is able to learn most of the patterns to properly predict the gender from a given individual by the 30th epoch, with an accuracy of approximately 90%.
plt.clf()fig = go.Figure()fig.add_trace(go.Scattergl( y=history.history['age_output_mean_absolute_error'], name='Train'))fig.add_trace(go.Scattergl( y=history.history['val_age_output_mean_absolute_error'], name='Valid'))fig.update_layout(height=500, width=700, title='Mean Absolute Error for age feature', xaxis_title='Epoch', yaxis_title='Mean Absolute Error')fig.show()
In the task of predicting the age feature, we can see that our model takes around 60 epochs to properly stabilize its learning process, with a mean absolute error of 0.09.
fig = go.Figure()fig.add_trace(go.Scattergl( y=history.history['loss'], name='Train'))fig.add_trace(go.Scattergl( y=history.history['val_loss'], name='Valid'))fig.update_layout(height=500, width=700, title='Overall loss', xaxis_title='Epoch', yaxis_title='Loss')fig.show()
We can notice that by the epoch 50 our model starts to stabilize with a loss value of approximately 1.4. There is also a peak in the loss curve which does appear in the Mean Absolute Error for the age feature, which could explain the influence on the learning of the age feature on the overall loss.
In order to assess how our model performs on the test set, let’s use our UTK data generator class, but this time using the test indexes. We will then call the predict_generator method from our trained model, which will output the predictions for the test set.
test_batch_size = 128test_generator = data_generator.generate_images(test_idx, is_training=False, batch_size=test_batch_size)age_pred, race_pred, gender_pred = model.predict_generator(test_generator, steps=len(test_idx)//test_batch_size)
Let’s iterate one more time over all our test samples, in order to have their labels into a single list. We will also extract the argmax of each record, in order to retrieve the top predictions and ground truths.
test_generator = data_generator.generate_images(test_idx, is_training=False, batch_size=test_batch_size)samples = 0images, age_true, race_true, gender_true = [], [], [], []for test_batch in test_generator: image = test_batch[0] labels = test_batch[1] images.extend(image) age_true.extend(labels[0]) race_true.extend(labels[1]) gender_true.extend(labels[2]) age_true = np.array(age_true)race_true = np.array(race_true)gender_true = np.array(gender_true)race_true, gender_true = race_true.argmax(axis=-1), gender_true.argmax(axis=-1)race_pred, gender_pred = race_pred.argmax(axis=-1), gender_pred.argmax(axis=-1)age_true = age_true * data_generator.max_ageage_pred = age_pred * data_generator.max_age
And finally, let’s print the classification reports for each feature on the test set.
from sklearn.metrics import classification_reportcr_race = classification_report(race_true, race_pred, target_names=dataset_dict['race_alias'].keys())print(cr_race)precision recall f1-score support white 0.80 0.91 0.85 2994 black 0.86 0.82 0.84 1327 asian 0.86 0.79 0.83 1046 indian 0.74 0.74 0.74 1171 others 0.38 0.19 0.25 502 accuracy 0.80 7040 macro avg 0.73 0.69 0.70 7040weighted avg 0.78 0.80 0.78 7040
From the report above, we can see that our model is excellent at predicting Asian and black individuals, with a precision of 86%, followed by white people 80% and Indian with 74%. The race ‘others’ shows a precision of only 38%, but we need to take into consideration that this group is composed of different races and ethnicities along with a few samples, when compared to the other groups. The weighted accuracy for this classification task is 78%, showing that our classifier was able to properly learn patterns to distinguish different types of races.
cr_gender = classification_report(gender_true, gender_pred, target_names=dataset_dict['gender_alias'].keys())print(cr_gender)precision recall f1-score support male 0.94 0.87 0.91 3735 female 0.87 0.94 0.90 3305 accuracy 0.90 7040 macro avg 0.90 0.91 0.90 7040weighted avg 0.91 0.90 0.90 7040
From this report, we can notice that our model is excellent at predicting the gender of a given individual, with a weighted accuracy of 91% for this task.
from sklearn.metrics import r2_scoreprint('R2 score for age: ', r2_score(age_true, age_pred))
R2 score for age: 0.5823979466456328
UTK Face Dataset: http://aicip.eecs.utk.edu/wiki/UTKFace
Keras Multi-output documentation: https://keras.io/getting-started/functional-api-guide/
SanjayaSubedi post on multi-output model: https://sanjayasubedi.com.np/deeplearning/multioutput-keras/
PyImageSearch post on FashionNet: https://www.pyimagesearch.com/2018/06/04/keras-multiple-outputs-and-multiple-losses/ | [
{
"code": null,
"e": 638,
"s": 172,
"text": "In this post, we will be exploring the Keras functional API in order to build a multi-output Deep Learning model. We will show how to train a single model that is capable of predicting three distinct outputs. By using the UTK Face dataset, which is composed of over 20 thousand pictures of people in uncontrolled environments, we will predict the age, gender and sex for each record presented in the dataset, reaching an accuracy of 91% for gender and 78% for race."
},
{
"code": null,
"e": 904,
"s": 638,
"text": "The UTKFace dataset is a large dataset composed of over 20 thousand face images with their respective annotations of age, gender and ethnicity. The images are properly cropped into the face region, but display some variations in pose, illumination, resolution, etc."
},
{
"code": null,
"e": 1066,
"s": 904,
"text": "In order to retrieve the annotations of each record, we need to parse the filenames. Each record is stored in the following format: age_gender_race_date&time.jpg"
},
{
"code": null,
"e": 1073,
"s": 1066,
"text": "Where:"
},
{
"code": null,
"e": 1105,
"s": 1073,
"text": "age is an integer from 0 to 116"
},
{
"code": null,
"e": 1177,
"s": 1105,
"text": "gender is an integer in which 0 represents male and 1 represents female"
},
{
"code": null,
"e": 1271,
"s": 1177,
"text": "race is an integer from 0 to 4, denoting white, black, asian, indian and others, respectively"
},
{
"code": null,
"e": 1322,
"s": 1271,
"text": "date and time, denoting when the picture was taken"
},
{
"code": null,
"e": 1395,
"s": 1322,
"text": "If you want to know more about this dataset, please check their website."
},
{
"code": null,
"e": 1622,
"s": 1395,
"text": "Let’s start by importing some libraries and creating our dictionary to help us on parsing the information from the dataset, along with some other information (dataset location, training split, width and height of the samples)."
},
{
"code": null,
"e": 2204,
"s": 1622,
"text": "import numpy as np import pandas as pdimport osimport globimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsdataset_folder_name = 'UTKFace'TRAIN_TEST_SPLIT = 0.7IM_WIDTH = IM_HEIGHT = 198dataset_dict = { 'race_id': { 0: 'white', 1: 'black', 2: 'asian', 3: 'indian', 4: 'others' }, 'gender_id': { 0: 'male', 1: 'female' }}dataset_dict['gender_alias'] = dict((g, i) for i, g in dataset_dict['gender_id'].items())dataset_dict['race_alias'] = dict((r, i) for i, r in dataset_dict['race_id'].items())"
},
{
"code": null,
"e": 2451,
"s": 2204,
"text": "Let’s also define a function to help us on extracting the data from our dataset. This function will be used to iterate over each file of the UTK dataset and return a Pandas Dataframe containing all the fields (age, gender and sex) of our records."
},
{
"code": null,
"e": 3477,
"s": 2451,
"text": "def parse_dataset(dataset_path, ext='jpg'): \"\"\" Used to extract information about our dataset. It does iterate over all images and return a DataFrame with the data (age, gender and sex) of all files. \"\"\" def parse_info_from_file(path): \"\"\" Parse information from a single file \"\"\" try: filename = os.path.split(path)[1] filename = os.path.splitext(filename)[0] age, gender, race, _ = filename.split('_') return int(age), dataset_dict['gender_id'][int(gender)], dataset_dict['race_id'][int(race)] except Exception as ex: return None, None, None files = glob.glob(os.path.join(dataset_path, \"*.%s\" % ext)) records = [] for file in files: info = parse_info_from_file(file) records.append(info) df = pd.DataFrame(records) df['file'] = files df.columns = ['age', 'gender', 'race', 'file'] df = df.dropna() return dfdf = parse_dataset(dataset_folder_name)df.head()"
},
{
"code": null,
"e": 3792,
"s": 3477,
"text": "As an important step to understand not only the distribution of our dataset, but as well the predictions generated by our model, it is a recommended practice to perform some data visualization process on our dataset. We will start by defining a helper function to generate pie plots based on a given Pandas series:"
},
{
"code": null,
"e": 4154,
"s": 3792,
"text": "import plotly.graph_objects as godef plot_distribution(pd_series): labels = pd_series.value_counts().index.tolist() counts = pd_series.value_counts().values.tolist() pie_plot = go.Pie(labels=labels, values=counts, hole=.3) fig = go.Figure(data=[pie_plot]) fig.update_layout(title_text='Distribution for %s' % pd_series.name) fig.show()"
},
{
"code": null,
"e": 4246,
"s": 4154,
"text": "Let’s start by plotting the race distribution with our predefined plot_distribution method."
},
{
"code": null,
"e": 4276,
"s": 4246,
"text": "plot_distribution(df['race'])"
},
{
"code": null,
"e": 4707,
"s": 4276,
"text": "Having a quick glance at this plot, we can see that almost half of the samples are from the white race, so we can expect this group to have a great accuracy. Other races such as black, Indian and Asian also show a good number of samples, probably leading us to good accuracy numbers as well. The race ‘others’ (Hispanics, Latinos, etc) on the other side, show a small number of samples, being more likely to have a small accuracy."
},
{
"code": null,
"e": 4739,
"s": 4707,
"text": "plot_distribution(df['gender'])"
},
{
"code": null,
"e": 4896,
"s": 4739,
"text": "For both male and female samples, we have quite a good balanced number of records, so we should have a great accuracy for both classes when using our model."
},
{
"code": null,
"e": 5014,
"s": 4896,
"text": "Let’s also plot how our age feature is distributed over the dataset by using a simple histogram with 20 bins/sectors."
},
{
"code": null,
"e": 5141,
"s": 5014,
"text": "import plotly.express as pxfig = px.histogram(df, x=\"age\", nbins=20)fig.update_layout(title_text='Age distribution')fig.show()"
},
{
"code": null,
"e": 5262,
"s": 5141,
"text": "We can also display this same plot in a pie plot. Let’s group the age column into bins and then plot it with a pie chart"
},
{
"code": null,
"e": 5451,
"s": 5262,
"text": "bins = [0, 10, 20, 30, 40, 60, 80, np.inf]names = ['<10', '10-20', '20-30', '30-40', '40-60', '60-80', '80+']age_binned = pd.cut(df['age'], bins, labels=names)plot_distribution(age_binned)"
},
{
"code": null,
"e": 5790,
"s": 5451,
"text": "We can observe that our dataset is mostly composed of individuals whose age varies between 20 and 30 years, followed by individuals ranging from 30 to 40 years and then 40 to 60 years old. These groups represent around 70% of our dataset, so we can assume that we are going to have good accuracy in predicting individuals in these ranges."
},
{
"code": null,
"e": 6027,
"s": 5790,
"text": "We could also perform some multi-variate analysis on our dataset, but since the scope of this post is to demonstrate the usage of a multi-output model with Keras, we won’t be covering it — maybe another time, if you guys are interested."
},
{
"code": null,
"e": 6433,
"s": 6027,
"text": "In order to input our data to our Keras multi-output model, we will create a helper object to work as a data generator for our dataset. This will be done by generating batches of data, which will be used to feed our multi-output model with both the images and their labels. This step is also done instead of just loading all the dataset into the memory at once, which could lead to an out of memory error."
},
{
"code": null,
"e": 9032,
"s": 6433,
"text": "from keras.utils import to_categoricalfrom PIL import Imageclass UtkFaceDataGenerator(): \"\"\" Data generator for the UTKFace dataset. This class should be used when training our Keras multi-output model. \"\"\" def __init__(self, df): self.df = df def generate_split_indexes(self): p = np.random.permutation(len(self.df)) train_up_to = int(len(self.df) * TRAIN_TEST_SPLIT) train_idx = p[:train_up_to] test_idx = p[train_up_to:] train_up_to = int(train_up_to * TRAIN_TEST_SPLIT) train_idx, valid_idx = train_idx[:train_up_to], train_idx[train_up_to:] # converts alias to id self.df['gender_id'] = self.df['gender'].map(lambda gender: dataset_dict['gender_alias'][gender]) self.df['race_id'] = self.df['race'].map(lambda race: dataset_dict['race_alias'][race]) self.max_age = self.df['age'].max() return train_idx, valid_idx, test_idx def preprocess_image(self, img_path): \"\"\" Used to perform some minor preprocessing on the image before inputting into the network. \"\"\" im = Image.open(img_path) im = im.resize((IM_WIDTH, IM_HEIGHT)) im = np.array(im) / 255.0 return im def generate_images(self, image_idx, is_training, batch_size=16): \"\"\" Used to generate a batch with images when training/testing/validating our Keras model. \"\"\" # arrays to store our batched data images, ages, races, genders = [], [], [], [] while True: for idx in image_idx: person = self.df.iloc[idx] age = person['age'] race = person['race_id'] gender = person['gender_id'] file = person['file'] im = self.preprocess_image(file) ages.append(age / self.max_age) races.append(to_categorical(race, len(dataset_dict['race_id']))) genders.append(to_categorical(gender, len(dataset_dict['gender_id']))) images.append(im) # yielding condition if len(images) >= batch_size: yield np.array(images), [np.array(ages), np.array(races), np.array(genders)] images, ages, races, genders = [], [], [], [] if not is_training: break data_generator = UtkFaceDataGenerator(df)train_idx, valid_idx, test_idx = data_generator.generate_split_indexes() "
},
{
"code": null,
"e": 9197,
"s": 9032,
"text": "In this step, we will define our multi-output Keras model. Our model will be composed of three major branches, one for each available feature: age, gender and race."
},
{
"code": null,
"e": 9522,
"s": 9197,
"text": "The default structure for our convolutional layers is based on a Conv2D layer with a ReLU activation, followed by a BatchNormalization layer, a MaxPooling and then finally a Dropout layer. Each of these layers is then followed by the final Dense layer. This step is repeated for each of the outputs we are trying to predict."
},
{
"code": null,
"e": 9776,
"s": 9522,
"text": "These default layers are defined on the make_default_hidden_layers method, which will be reused on building each of the branches of our model. In the code shown below we will define the class that will be responsible for creating our multi-output model."
},
{
"code": null,
"e": 13751,
"s": 9776,
"text": "from keras.models import Modelfrom keras.layers.normalization import BatchNormalizationfrom keras.layers.convolutional import Conv2Dfrom keras.layers.convolutional import MaxPooling2Dfrom keras.layers.core import Activationfrom keras.layers.core import Dropoutfrom keras.layers.core import Lambdafrom keras.layers.core import Densefrom keras.layers import Flattenfrom keras.layers import Inputimport tensorflow as tfclass UtkMultiOutputModel(): \"\"\" Used to generate our multi-output model. This CNN contains three branches, one for age, other for sex and another for race. Each branch contains a sequence of Convolutional Layers that is defined on the make_default_hidden_layers method. \"\"\" def make_default_hidden_layers(self, inputs): \"\"\" Used to generate a default set of hidden layers. The structure used in this network is defined as: Conv2D -> BatchNormalization -> Pooling -> Dropout \"\"\" x = Conv2D(16, (3, 3), padding=\"same\")(inputs) x = Activation(\"relu\")(x) x = BatchNormalization(axis=-1)(x) x = MaxPooling2D(pool_size=(3, 3))(x) x = Dropout(0.25)(x) x = Conv2D(32, (3, 3), padding=\"same\")(x) x = Activation(\"relu\")(x) x = BatchNormalization(axis=-1)(x) x = MaxPooling2D(pool_size=(2, 2))(x) x = Dropout(0.25)(x) x = Conv2D(32, (3, 3), padding=\"same\")(x) x = Activation(\"relu\")(x) x = BatchNormalization(axis=-1)(x) x = MaxPooling2D(pool_size=(2, 2))(x) x = Dropout(0.25)(x) return x def build_race_branch(self, inputs, num_races): \"\"\" Used to build the race branch of our face recognition network. This branch is composed of three Conv -> BN -> Pool -> Dropout blocks, followed by the Dense output layer. \"\"\" x = self.make_default_hidden_layers(inputs) x = Flatten()(x) x = Dense(128)(x) x = Activation(\"relu\")(x) x = BatchNormalization()(x) x = Dropout(0.5)(x) x = Dense(num_races)(x) x = Activation(\"softmax\", name=\"race_output\")(x) return x def build_gender_branch(self, inputs, num_genders=2): \"\"\" Used to build the gender branch of our face recognition network. This branch is composed of three Conv -> BN -> Pool -> Dropout blocks, followed by the Dense output layer. \"\"\" x = Lambda(lambda c: tf.image.rgb_to_grayscale(c))(inputs) x = self.make_default_hidden_layers(inputs) x = Flatten()(x) x = Dense(128)(x) x = Activation(\"relu\")(x) x = BatchNormalization()(x) x = Dropout(0.5)(x) x = Dense(num_genders)(x) x = Activation(\"sigmoid\", name=\"gender_output\")(x) return x def build_age_branch(self, inputs): \"\"\" Used to build the age branch of our face recognition network. This branch is composed of three Conv -> BN -> Pool -> Dropout blocks, followed by the Dense output layer. \"\"\" x = self.make_default_hidden_layers(inputs) x = Flatten()(x) x = Dense(128)(x) x = Activation(\"relu\")(x) x = BatchNormalization()(x) x = Dropout(0.5)(x) x = Dense(1)(x) x = Activation(\"linear\", name=\"age_output\")(x) return x def assemble_full_model(self, width, height, num_races): \"\"\" Used to assemble our multi-output model CNN. \"\"\" input_shape = (height, width, 3) inputs = Input(shape=input_shape) age_branch = self.build_age_branch(inputs) race_branch = self.build_race_branch(inputs, num_races) gender_branch = self.build_gender_branch(inputs) model = Model(inputs=inputs, outputs = [age_branch, race_branch, gender_branch], name=\"face_net\") return model model = UtkMultiOutputModel().assemble_full_model(IM_WIDTH, IM_HEIGHT, num_races=len(dataset_dict['race_alias']))"
},
{
"code": null,
"e": 14097,
"s": 13751,
"text": "Let’s give a look into our model structure, to have a better understanding of what we are building. We can see from it that we have a single input, that in our case is the image we are feeding the CNN, which does decompose into three separated branches, each with their own set of Convolutional layers, followed by their respective Dense layers."
},
{
"code": null,
"e": 14679,
"s": 14097,
"text": "Now it’s time to train our multi-output model, once we have both the data ready to use and the model architecture defined. But before doing this step, we need to compile our model. For this task, we will use a learning rate of 0.0004 and an Adam optimizer — but you can be feel free to try with other hyperparameters as well. We will also use custom loss weights and a custom loss function for each feature. When building our optimizer, let’s use a decay based on the learning rate divided by the number of epochs, so we will slowly be decreasing our learning rate over the epochs."
},
{
"code": null,
"e": 15287,
"s": 14679,
"text": "from keras.optimizers import Adaminit_lr = 1e-4epochs = 100opt = Adam(lr=init_lr, decay=init_lr / epochs)model.compile(optimizer=opt, loss={ 'age_output': 'mse', 'race_output': 'categorical_crossentropy', 'gender_output': 'binary_crossentropy'}, loss_weights={ 'age_output': 4., 'race_output': 1.5, 'gender_output': 0.1}, metrics={ 'age_output': 'mae', 'race_output': 'accuracy', 'gender_output': 'accuracy'})"
},
{
"code": null,
"e": 15473,
"s": 15287,
"text": "Now let’s train our model with a batch size of 32 for both valid and train sets. We will be using a ModelCheckpoint callback in order to save the model on disk at the end of each epoch."
},
{
"code": null,
"e": 16115,
"s": 15473,
"text": "from keras.callbacks import ModelCheckpointbatch_size = 32valid_batch_size = 32train_gen = data_generator.generate_images(train_idx, is_training=True, batch_size=batch_size)valid_gen = data_generator.generate_images(valid_idx, is_training=True, batch_size=valid_batch_size)callbacks = [ ModelCheckpoint(\"./model_checkpoint\", monitor='val_loss')]history = model.fit_generator(train_gen, steps_per_epoch=len(train_idx)//batch_size, epochs=epochs, callbacks=callbacks, validation_data=valid_gen, validation_steps=len(valid_idx)//valid_batch_size)"
},
{
"code": null,
"e": 16255,
"s": 16115,
"text": "Once we have our model trained, let’s give a better look into how our model performed on both training and validation sets over the epochs:"
},
{
"code": null,
"e": 16717,
"s": 16255,
"text": "plt.clf()fig = go.Figure()fig.add_trace(go.Scatter( y=history.history['race_output_acc'], name='Train'))fig.add_trace(go.Scatter( y=history.history['val_race_output_acc'], name='Valid'))fig.update_layout(height=500, width=700, title='Accuracy for race feature', xaxis_title='Epoch', yaxis_title='Accuracy')fig.show()"
},
{
"code": null,
"e": 16872,
"s": 16717,
"text": "We can see that by epoch 50 our model stabilizes itself on the validation set, only increasing on the training one, with an accuracy of approximately 80%."
},
{
"code": null,
"e": 17340,
"s": 16872,
"text": "plt.clf()fig = go.Figure()fig.add_trace(go.Scatter( y=history.history['gender_output_acc'], name='Train'))fig.add_trace(go.Scatter( y=history.history['val_gender_output_acc'], name='Valid'))fig.update_layout(height=500, width=700, title='Accuracy for gender feature', xaxis_title='Epoch', yaxis_title='Accuracy')fig.show()"
},
{
"code": null,
"e": 17548,
"s": 17340,
"text": "Similarly to the race feature, we can see that our model is able to learn most of the patterns to properly predict the gender from a given individual by the 30th epoch, with an accuracy of approximately 90%."
},
{
"code": null,
"e": 18065,
"s": 17548,
"text": "plt.clf()fig = go.Figure()fig.add_trace(go.Scattergl( y=history.history['age_output_mean_absolute_error'], name='Train'))fig.add_trace(go.Scattergl( y=history.history['val_age_output_mean_absolute_error'], name='Valid'))fig.update_layout(height=500, width=700, title='Mean Absolute Error for age feature', xaxis_title='Epoch', yaxis_title='Mean Absolute Error')fig.show()"
},
{
"code": null,
"e": 18237,
"s": 18065,
"text": "In the task of predicting the age feature, we can see that our model takes around 60 epochs to properly stabilize its learning process, with a mean absolute error of 0.09."
},
{
"code": null,
"e": 18655,
"s": 18237,
"text": "fig = go.Figure()fig.add_trace(go.Scattergl( y=history.history['loss'], name='Train'))fig.add_trace(go.Scattergl( y=history.history['val_loss'], name='Valid'))fig.update_layout(height=500, width=700, title='Overall loss', xaxis_title='Epoch', yaxis_title='Loss')fig.show()"
},
{
"code": null,
"e": 18955,
"s": 18655,
"text": "We can notice that by the epoch 50 our model starts to stabilize with a loss value of approximately 1.4. There is also a peak in the loss curve which does appear in the Mean Absolute Error for the age feature, which could explain the influence on the learning of the age feature on the overall loss."
},
{
"code": null,
"e": 19215,
"s": 18955,
"text": "In order to assess how our model performs on the test set, let’s use our UTK data generator class, but this time using the test indexes. We will then call the predict_generator method from our trained model, which will output the predictions for the test set."
},
{
"code": null,
"e": 19512,
"s": 19215,
"text": "test_batch_size = 128test_generator = data_generator.generate_images(test_idx, is_training=False, batch_size=test_batch_size)age_pred, race_pred, gender_pred = model.predict_generator(test_generator, steps=len(test_idx)//test_batch_size)"
},
{
"code": null,
"e": 19725,
"s": 19512,
"text": "Let’s iterate one more time over all our test samples, in order to have their labels into a single list. We will also extract the argmax of each record, in order to retrieve the top predictions and ground truths."
},
{
"code": null,
"e": 20449,
"s": 19725,
"text": "test_generator = data_generator.generate_images(test_idx, is_training=False, batch_size=test_batch_size)samples = 0images, age_true, race_true, gender_true = [], [], [], []for test_batch in test_generator: image = test_batch[0] labels = test_batch[1] images.extend(image) age_true.extend(labels[0]) race_true.extend(labels[1]) gender_true.extend(labels[2]) age_true = np.array(age_true)race_true = np.array(race_true)gender_true = np.array(gender_true)race_true, gender_true = race_true.argmax(axis=-1), gender_true.argmax(axis=-1)race_pred, gender_pred = race_pred.argmax(axis=-1), gender_pred.argmax(axis=-1)age_true = age_true * data_generator.max_ageage_pred = age_pred * data_generator.max_age"
},
{
"code": null,
"e": 20535,
"s": 20449,
"text": "And finally, let’s print the classification reports for each feature on the test set."
},
{
"code": null,
"e": 21163,
"s": 20535,
"text": "from sklearn.metrics import classification_reportcr_race = classification_report(race_true, race_pred, target_names=dataset_dict['race_alias'].keys())print(cr_race)precision recall f1-score support white 0.80 0.91 0.85 2994 black 0.86 0.82 0.84 1327 asian 0.86 0.79 0.83 1046 indian 0.74 0.74 0.74 1171 others 0.38 0.19 0.25 502 accuracy 0.80 7040 macro avg 0.73 0.69 0.70 7040weighted avg 0.78 0.80 0.78 7040"
},
{
"code": null,
"e": 21719,
"s": 21163,
"text": "From the report above, we can see that our model is excellent at predicting Asian and black individuals, with a precision of 86%, followed by white people 80% and Indian with 74%. The race ‘others’ shows a precision of only 38%, but we need to take into consideration that this group is composed of different races and ethnicities along with a few samples, when compared to the other groups. The weighted accuracy for this classification task is 78%, showing that our classifier was able to properly learn patterns to distinguish different types of races."
},
{
"code": null,
"e": 22149,
"s": 21719,
"text": "cr_gender = classification_report(gender_true, gender_pred, target_names=dataset_dict['gender_alias'].keys())print(cr_gender)precision recall f1-score support male 0.94 0.87 0.91 3735 female 0.87 0.94 0.90 3305 accuracy 0.90 7040 macro avg 0.90 0.91 0.90 7040weighted avg 0.91 0.90 0.90 7040"
},
{
"code": null,
"e": 22304,
"s": 22149,
"text": "From this report, we can notice that our model is excellent at predicting the gender of a given individual, with a weighted accuracy of 91% for this task."
},
{
"code": null,
"e": 22398,
"s": 22304,
"text": "from sklearn.metrics import r2_scoreprint('R2 score for age: ', r2_score(age_true, age_pred))"
},
{
"code": null,
"e": 22435,
"s": 22398,
"text": "R2 score for age: 0.5823979466456328"
},
{
"code": null,
"e": 22492,
"s": 22435,
"text": "UTK Face Dataset: http://aicip.eecs.utk.edu/wiki/UTKFace"
},
{
"code": null,
"e": 22581,
"s": 22492,
"text": "Keras Multi-output documentation: https://keras.io/getting-started/functional-api-guide/"
},
{
"code": null,
"e": 22684,
"s": 22581,
"text": "SanjayaSubedi post on multi-output model: https://sanjayasubedi.com.np/deeplearning/multioutput-keras/"
}
]
|
Assertion in Selenium WebDriver using TestNg - GeeksforGeeks | 06 Oct, 2021
Prerequisite – Selenium Actual result is compared with expected result with the help of Assertion. It means verification is done to check if the state of the application is the same to what we are expecting or not. For creating assertion we are going to use the Assert class provided by TestNG.
There are two types of Assertion:-
Hard Assertions. Soft assertions.
Hard Assertions.
Soft assertions.
These are explained as following below.
1. Hard Assertions : When any assert statement fails this type of assertion throws an exception immediately and continues with the next test in the test suite.
Hard Assertion can be of following types:-
1. assertEquals – This is used to compare expected and actual values in the selenium webdriver. The assertion passes with no exception whenever the expected and actual values are same. But, if the actual and expected values are not same then assert fails with an exception and the test is marked as failed.
Syntax :
Assert.assertEquals(actual, expected);
2. assertNotEquals – This is just the opposite of assertEquals. The assertion passes with no exception whenever the expected and actual values are not same. But, if the actual and expected values are same then assert fails with an exception and the test is marked as failed.
Syntax :
Assert.assertNotEquals(actual, expected, message);
3. assertTrue – This type of assertion is used when you are checking if condition is true. That is when we are dealing with boolean values this assertion is used. Whenever test case passes it returns true and if condition is false then it skips the current method and jumps to next.
Syntax :
Assert.assertTrue(condition);
4. assertFalse – It checks if value returned is false or not. Whenever test case passes it aborts the method and gives an exception.
Syntax :
Assert.assertFalse(condition);
5. assertNull – This assertion checks if the object is null or not. It aborts the test if object is null and gives an exception.
Syntax :
Assert.assertNull(object);
6. assertNotNull – This assertion checks if object is null or not. It aborts the test if object is not null that is if object is having any value and gives an exception.
Syntax :
Assert.assertNotNull(object);
2. Soft Assertion : These types of Assertions are the type of assertions do not throw an exception when an assertion fails and continues with the next step after the assert statement.
surinderdawra388
selenium
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Software Engineering | Requirements Engineering Process
Software Requirement Specification (SRS) Format
DFD for Library Management System
Levels in Data Flow Diagrams (DFD)
Software Testing | Basics
Software Engineering | White box Testing
Software Engineering | SDLC V-Model
What is DFD(Data Flow Diagram)?
Software Engineering | Iterative Waterfall Model
Difference between IAAS, PAAS and SAAS | [
{
"code": null,
"e": 24628,
"s": 24600,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 24924,
"s": 24628,
"text": "Prerequisite – Selenium Actual result is compared with expected result with the help of Assertion. It means verification is done to check if the state of the application is the same to what we are expecting or not. For creating assertion we are going to use the Assert class provided by TestNG. "
},
{
"code": null,
"e": 24960,
"s": 24924,
"text": "There are two types of Assertion:- "
},
{
"code": null,
"e": 24995,
"s": 24960,
"text": "Hard Assertions. Soft assertions. "
},
{
"code": null,
"e": 25013,
"s": 24995,
"text": "Hard Assertions. "
},
{
"code": null,
"e": 25031,
"s": 25013,
"text": "Soft assertions. "
},
{
"code": null,
"e": 25072,
"s": 25031,
"text": "These are explained as following below. "
},
{
"code": null,
"e": 25233,
"s": 25072,
"text": "1. Hard Assertions : When any assert statement fails this type of assertion throws an exception immediately and continues with the next test in the test suite. "
},
{
"code": null,
"e": 25277,
"s": 25233,
"text": "Hard Assertion can be of following types:- "
},
{
"code": null,
"e": 25585,
"s": 25277,
"text": "1. assertEquals – This is used to compare expected and actual values in the selenium webdriver. The assertion passes with no exception whenever the expected and actual values are same. But, if the actual and expected values are not same then assert fails with an exception and the test is marked as failed. "
},
{
"code": null,
"e": 25595,
"s": 25585,
"text": "Syntax : "
},
{
"code": null,
"e": 25635,
"s": 25595,
"text": "Assert.assertEquals(actual, expected); "
},
{
"code": null,
"e": 25911,
"s": 25635,
"text": "2. assertNotEquals – This is just the opposite of assertEquals. The assertion passes with no exception whenever the expected and actual values are not same. But, if the actual and expected values are same then assert fails with an exception and the test is marked as failed. "
},
{
"code": null,
"e": 25921,
"s": 25911,
"text": "Syntax : "
},
{
"code": null,
"e": 25973,
"s": 25921,
"text": "Assert.assertNotEquals(actual, expected, message); "
},
{
"code": null,
"e": 26257,
"s": 25973,
"text": "3. assertTrue – This type of assertion is used when you are checking if condition is true. That is when we are dealing with boolean values this assertion is used. Whenever test case passes it returns true and if condition is false then it skips the current method and jumps to next. "
},
{
"code": null,
"e": 26267,
"s": 26257,
"text": "Syntax : "
},
{
"code": null,
"e": 26298,
"s": 26267,
"text": "Assert.assertTrue(condition); "
},
{
"code": null,
"e": 26432,
"s": 26298,
"text": "4. assertFalse – It checks if value returned is false or not. Whenever test case passes it aborts the method and gives an exception. "
},
{
"code": null,
"e": 26442,
"s": 26432,
"text": "Syntax : "
},
{
"code": null,
"e": 26474,
"s": 26442,
"text": "Assert.assertFalse(condition); "
},
{
"code": null,
"e": 26604,
"s": 26474,
"text": "5. assertNull – This assertion checks if the object is null or not. It aborts the test if object is null and gives an exception. "
},
{
"code": null,
"e": 26614,
"s": 26604,
"text": "Syntax : "
},
{
"code": null,
"e": 26641,
"s": 26614,
"text": "Assert.assertNull(object);"
},
{
"code": null,
"e": 26812,
"s": 26641,
"text": "6. assertNotNull – This assertion checks if object is null or not. It aborts the test if object is not null that is if object is having any value and gives an exception. "
},
{
"code": null,
"e": 26822,
"s": 26812,
"text": "Syntax : "
},
{
"code": null,
"e": 26853,
"s": 26822,
"text": "Assert.assertNotNull(object); "
},
{
"code": null,
"e": 27038,
"s": 26853,
"text": "2. Soft Assertion : These types of Assertions are the type of assertions do not throw an exception when an assertion fails and continues with the next step after the assert statement. "
},
{
"code": null,
"e": 27055,
"s": 27038,
"text": "surinderdawra388"
},
{
"code": null,
"e": 27064,
"s": 27055,
"text": "selenium"
},
{
"code": null,
"e": 27085,
"s": 27064,
"text": "Software Engineering"
},
{
"code": null,
"e": 27183,
"s": 27085,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27192,
"s": 27183,
"text": "Comments"
},
{
"code": null,
"e": 27205,
"s": 27192,
"text": "Old Comments"
},
{
"code": null,
"e": 27261,
"s": 27205,
"text": "Software Engineering | Requirements Engineering Process"
},
{
"code": null,
"e": 27309,
"s": 27261,
"text": "Software Requirement Specification (SRS) Format"
},
{
"code": null,
"e": 27343,
"s": 27309,
"text": "DFD for Library Management System"
},
{
"code": null,
"e": 27378,
"s": 27343,
"text": "Levels in Data Flow Diagrams (DFD)"
},
{
"code": null,
"e": 27404,
"s": 27378,
"text": "Software Testing | Basics"
},
{
"code": null,
"e": 27445,
"s": 27404,
"text": "Software Engineering | White box Testing"
},
{
"code": null,
"e": 27481,
"s": 27445,
"text": "Software Engineering | SDLC V-Model"
},
{
"code": null,
"e": 27513,
"s": 27481,
"text": "What is DFD(Data Flow Diagram)?"
},
{
"code": null,
"e": 27562,
"s": 27513,
"text": "Software Engineering | Iterative Waterfall Model"
}
]
|
Character replacement after removing duplicates from a string - GeeksforGeeks | 22 Apr, 2021
Given a string. The task is to replace each character of the minimized string by a character present at index ‘IND‘ of the original string. The minimized string is the string obtained by removing all duplicates from the original string keeping the order of elements same.
IND for any index in the minimized string is calculated as:
IND = (square of ascii value of minimized string character) % (length of original string)
Examples:
Input : geeks
Output : sesg
Explanation : minimized string = geks
length of original string = 5
ascii value of g = 103
IND for g = (103*103) % 5 = 4
replacement character for g = s
character 's' present at index 4 of original string
Similarly,
replacement character for e = e
replacement character for k = s
replacement character for s = g
Input : helloworld
Output : oeoeeoh
Approach:Below is the step by step algorithm for string minimization:
1. Initialize flagchar[26] = {0}
2. for i=0 to str.length()-1
3. ch = str[i]
4. if flagchar[ch-97] == 0 then
5. mstr = mstr + ch
6. flagchar[ch-97] = 1
7. End if
8. End of loop
9. return mstr // minimized string
Algorithm for character replacement:
1. Replace each character of minimized string as described
in the problem statement and example
2. Compute final string
Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program for character replacement// after string minimization#include <bits/stdc++.h>using namespace std; // Function to minimize stringstring minimize(string str){ string mstr = " "; int l, i, flagchar[26] = { 0 }; char ch; l = str.length(); // duplicate characters are removed for (i = 0; i < str.length(); i++) { ch = str.at(i); // checks if character has previously occurred or not // if not then add it to the minimized string 'mstr' if (flagchar[ch - 97] == 0) { mstr = mstr + ch; flagchar[ch - 97] = 1; } } return mstr; // minimized string} // Utility function to print the// minimized, replaced stringvoid replaceMinimizeUtil(string str){ string minimizedStr, finalStr = ""; int i, index, l; char ch; l = str.length(); minimizedStr = minimize(str); // minimized string // Creating final string by replacing character for (i = 0; i < minimizedStr.length(); i++) { ch = minimizedStr.at(i); // index calculation index = (ch * ch) % l; finalStr = finalStr + str.at(index); } cout << "Final string: " << finalStr; // final string} // Driver programint main(){ string str = "geeks"; replaceMinimizeUtil(str); return 0;}
// Java program for character replacement// after String minimization class GFG { // Function to minimize String static String minimize(String str) { String mstr = " "; int l, i, flagchar[] = new int[26]; char ch; l = str.length(); // duplicate characters are removed for (i = 0; i < str.length(); i++) { ch = str.charAt(i); // checks if character has previously occurred or not // if not then add it to the minimized String 'mstr' if (flagchar[ch - 97] == 0) { mstr = mstr + ch; flagchar[ch - 97] = 1; } } return mstr; // minimized String } // Utility function to print the // minimized, replaced String static void replaceMinimizeUtil(String str) { String minimizedStr, finalStr = ""; int i, index, l; char ch; l = str.length(); minimizedStr = minimize(str); // minimized String // Creating final String by replacing character for (i = 0; i < minimizedStr.length(); i++) { ch = minimizedStr.charAt(i); // index calculation index = (ch * ch) % l; finalStr = finalStr + str.charAt(index); } // final String System.out.println("Final String: " + finalStr); } // Driver program public static void main(String[] args) { String str = "geeks"; replaceMinimizeUtil(str); }}// This code is contributed by Rajput-JI
# Python3 program for character# replacement after string minimization # Function to minimize stringdef minimize(string): mstr = " " flagchar = [0] * 26 l = len(string) # Duplicate characters are removed for i in range(0, len(string)): ch = string[i] # checks if character has previously occurred or not # if not then add it to the minimized string 'mstr' if flagchar[ord(ch)-97] == 0: mstr = mstr + ch flagchar[ord(ch)-97] = 1 return mstr # minimized string # Utility function to print the# minimized, replaced stringdef replaceMinimizeUtil(string): finalStr = "" l = len(string) minimizedStr = minimize(string) # minimized string # Creating final string by replacing character for i in range(0, len(minimizedStr)): ch = ord(minimizedStr[i]) # index calculation index = (ch * ch) % l finalStr = finalStr + string[index] print("Final string:", finalStr) # final string # Driver programif __name__ == "__main__": string = "geeks" replaceMinimizeUtil(string) # This code is contributed by Rituraj Jain
// C# program for character replacement// after String minimizationusing System; class GFG { // Function to minimize String static String minimize(string str) { string mstr = " "; int l, i; int[] flagchar = new int[26]; char ch; l = str.Length; // duplicate characters are removed for (i = 0; i < str.Length; i++) { ch = str[i]; // checks if character has previously // occurred or not if not then add it // to the minimized String 'mstr' if (flagchar[ch - 97] == 0) { mstr = mstr + ch; flagchar[ch - 97] = 1; } } return mstr; // minimized String } // Utility function to print the // minimized, replaced String static void replaceMinimizeUtil(string str) { string minimizedStr, finalStr = ""; int i, index, l; char ch; l = str.Length; minimizedStr = minimize(str); // minimized String // Creating final String by // replacing character for (i = 0; i < minimizedStr.Length; i++) { ch = minimizedStr[i]; // index calculation index = (ch * ch) % l; finalStr = finalStr + str[index]; } // final String Console.Write("Final String: " + finalStr); } // Driver Code public static void Main() { string str = "geeks"; replaceMinimizeUtil(str); }} // This code is contributed// by ChitraNayal
<?php// PHP program for character replacement// after string minimization // Function to minimize stringfunction minimize($str){ $mstr = " "; $flagchar=array_fill(0, 26, 0); $l = strlen($str); // duplicate characters are removed for ($i = 0; $i < strlen($str); $i++) { $ch = $str[$i]; // checks if character has previously occurred or not // if not then add it to the minimized string 'mstr' if ($flagchar[ord($ch) - 97] == 0) { $mstr .=$ch; $flagchar[ord($ch) - 97] = 1; } } return $mstr; // minimized string} // Utility function to print the// minimized, replaced stringfunction replaceMinimizeUtil($str){ $finalStr = ""; $l = strlen($str); $minimizedStr = minimize($str); // minimized string // Creating final string by replacing character for ($i = 0; $i < strlen($minimizedStr); $i++) { $ch = $minimizedStr[$i]; // index calculation $index = (ord($ch) * ord($ch)) % $l; $finalStr = $finalStr.$str[$index]; } echo "Final string: ".$finalStr; // final string} // Driver code$str = "geeks"; replaceMinimizeUtil($str); // This code is contributed by mits?>
<script> // Javascript program for character replacement// after String minimization // Function to minimize Stringfunction minimize(str){ let mstr = " "; let l, i, flagchar = new Array(26); for(let i = 0; i < 26; i++) { flagchar[i] = 0; } let ch; l = str.length; // Duplicate characters are removed for(i = 0; i < str.length; i++) { ch = str[i]; // Checks if character has previously // occurred or not if not then add it // to the minimized String 'mstr' if (flagchar[ch.charCodeAt(0) - 97] == 0) { mstr = mstr + ch; flagchar[ch.charCodeAt(0) - 97] = 1; } } // Minimized String return mstr;} // Utility function to print the// minimized, replaced Stringfunction replaceMinimizeUtil(str){ let minimizedStr, finalStr = ""; let i, index, l; let ch; l = str.length; // Minimized String minimizedStr = minimize(str); // Creating final String by replacing character for(i = 0; i < minimizedStr.length; i++) { ch = minimizedStr[i].charCodeAt(0); // Index calculation index = (ch * ch) % l; finalStr = finalStr + str[index]; } // Final String document.write("Final String: " + finalStr);} // Driver codelet str = "geeks"; replaceMinimizeUtil(str); // This code is contributed by avanitrachhadiya2155 </script>
Final string: ssesg
Time Complexity: O(n)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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.
Rajput-Ji
ukasp
rituraj_jain
Mithun Kumar
Akanksha_Rai
avanitrachhadiya2155
cpp-string
Hash
Strings
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Quadratic Probing in Hashing
Load Factor and Rehashing
Implementing own Hash Table with Open Addressing Linear Probing
Practice Problems on Hashing
Advantages of BST over Hash Table
Longest Common Subsequence | DP-4
Reverse a string in Java
Write a program to print all permutations of a given string
KMP Algorithm for Pattern Searching
C++ Data Types | [
{
"code": null,
"e": 24766,
"s": 24738,
"text": "\n22 Apr, 2021"
},
{
"code": null,
"e": 25038,
"s": 24766,
"text": "Given a string. The task is to replace each character of the minimized string by a character present at index ‘IND‘ of the original string. The minimized string is the string obtained by removing all duplicates from the original string keeping the order of elements same."
},
{
"code": null,
"e": 25099,
"s": 25038,
"text": "IND for any index in the minimized string is calculated as: "
},
{
"code": null,
"e": 25189,
"s": 25099,
"text": "IND = (square of ascii value of minimized string character) % (length of original string)"
},
{
"code": null,
"e": 25200,
"s": 25189,
"text": "Examples: "
},
{
"code": null,
"e": 25672,
"s": 25200,
"text": "Input : geeks\nOutput : sesg\nExplanation : minimized string = geks\n length of original string = 5 \n ascii value of g = 103\n IND for g = (103*103) % 5 = 4\n replacement character for g = s \n character 's' present at index 4 of original string\nSimilarly,\nreplacement character for e = e \nreplacement character for k = s \nreplacement character for s = g \n\nInput : helloworld\nOutput : oeoeeoh"
},
{
"code": null,
"e": 25744,
"s": 25672,
"text": "Approach:Below is the step by step algorithm for string minimization: "
},
{
"code": null,
"e": 26021,
"s": 25744,
"text": " 1. Initialize flagchar[26] = {0}\n 2. for i=0 to str.length()-1\n 3. ch = str[i]\n 4. if flagchar[ch-97] == 0 then\n 5. mstr = mstr + ch\n 6. flagchar[ch-97] = 1\n 7. End if\n 8. End of loop\n 9. return mstr // minimized string"
},
{
"code": null,
"e": 26059,
"s": 26021,
"text": "Algorithm for character replacement: "
},
{
"code": null,
"e": 26195,
"s": 26059,
"text": " 1. Replace each character of minimized string as described\n in the problem statement and example\n 2. Compute final string "
},
{
"code": null,
"e": 26243,
"s": 26195,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 26247,
"s": 26243,
"text": "C++"
},
{
"code": null,
"e": 26252,
"s": 26247,
"text": "Java"
},
{
"code": null,
"e": 26260,
"s": 26252,
"text": "Python3"
},
{
"code": null,
"e": 26263,
"s": 26260,
"text": "C#"
},
{
"code": null,
"e": 26267,
"s": 26263,
"text": "PHP"
},
{
"code": null,
"e": 26278,
"s": 26267,
"text": "Javascript"
},
{
"code": "// C++ program for character replacement// after string minimization#include <bits/stdc++.h>using namespace std; // Function to minimize stringstring minimize(string str){ string mstr = \" \"; int l, i, flagchar[26] = { 0 }; char ch; l = str.length(); // duplicate characters are removed for (i = 0; i < str.length(); i++) { ch = str.at(i); // checks if character has previously occurred or not // if not then add it to the minimized string 'mstr' if (flagchar[ch - 97] == 0) { mstr = mstr + ch; flagchar[ch - 97] = 1; } } return mstr; // minimized string} // Utility function to print the// minimized, replaced stringvoid replaceMinimizeUtil(string str){ string minimizedStr, finalStr = \"\"; int i, index, l; char ch; l = str.length(); minimizedStr = minimize(str); // minimized string // Creating final string by replacing character for (i = 0; i < minimizedStr.length(); i++) { ch = minimizedStr.at(i); // index calculation index = (ch * ch) % l; finalStr = finalStr + str.at(index); } cout << \"Final string: \" << finalStr; // final string} // Driver programint main(){ string str = \"geeks\"; replaceMinimizeUtil(str); return 0;}",
"e": 27563,
"s": 26278,
"text": null
},
{
"code": "// Java program for character replacement// after String minimization class GFG { // Function to minimize String static String minimize(String str) { String mstr = \" \"; int l, i, flagchar[] = new int[26]; char ch; l = str.length(); // duplicate characters are removed for (i = 0; i < str.length(); i++) { ch = str.charAt(i); // checks if character has previously occurred or not // if not then add it to the minimized String 'mstr' if (flagchar[ch - 97] == 0) { mstr = mstr + ch; flagchar[ch - 97] = 1; } } return mstr; // minimized String } // Utility function to print the // minimized, replaced String static void replaceMinimizeUtil(String str) { String minimizedStr, finalStr = \"\"; int i, index, l; char ch; l = str.length(); minimizedStr = minimize(str); // minimized String // Creating final String by replacing character for (i = 0; i < minimizedStr.length(); i++) { ch = minimizedStr.charAt(i); // index calculation index = (ch * ch) % l; finalStr = finalStr + str.charAt(index); } // final String System.out.println(\"Final String: \" + finalStr); } // Driver program public static void main(String[] args) { String str = \"geeks\"; replaceMinimizeUtil(str); }}// This code is contributed by Rajput-JI",
"e": 29091,
"s": 27563,
"text": null
},
{
"code": "# Python3 program for character# replacement after string minimization # Function to minimize stringdef minimize(string): mstr = \" \" flagchar = [0] * 26 l = len(string) # Duplicate characters are removed for i in range(0, len(string)): ch = string[i] # checks if character has previously occurred or not # if not then add it to the minimized string 'mstr' if flagchar[ord(ch)-97] == 0: mstr = mstr + ch flagchar[ord(ch)-97] = 1 return mstr # minimized string # Utility function to print the# minimized, replaced stringdef replaceMinimizeUtil(string): finalStr = \"\" l = len(string) minimizedStr = minimize(string) # minimized string # Creating final string by replacing character for i in range(0, len(minimizedStr)): ch = ord(minimizedStr[i]) # index calculation index = (ch * ch) % l finalStr = finalStr + string[index] print(\"Final string:\", finalStr) # final string # Driver programif __name__ == \"__main__\": string = \"geeks\" replaceMinimizeUtil(string) # This code is contributed by Rituraj Jain",
"e": 30293,
"s": 29091,
"text": null
},
{
"code": "// C# program for character replacement// after String minimizationusing System; class GFG { // Function to minimize String static String minimize(string str) { string mstr = \" \"; int l, i; int[] flagchar = new int[26]; char ch; l = str.Length; // duplicate characters are removed for (i = 0; i < str.Length; i++) { ch = str[i]; // checks if character has previously // occurred or not if not then add it // to the minimized String 'mstr' if (flagchar[ch - 97] == 0) { mstr = mstr + ch; flagchar[ch - 97] = 1; } } return mstr; // minimized String } // Utility function to print the // minimized, replaced String static void replaceMinimizeUtil(string str) { string minimizedStr, finalStr = \"\"; int i, index, l; char ch; l = str.Length; minimizedStr = minimize(str); // minimized String // Creating final String by // replacing character for (i = 0; i < minimizedStr.Length; i++) { ch = minimizedStr[i]; // index calculation index = (ch * ch) % l; finalStr = finalStr + str[index]; } // final String Console.Write(\"Final String: \" + finalStr); } // Driver Code public static void Main() { string str = \"geeks\"; replaceMinimizeUtil(str); }} // This code is contributed// by ChitraNayal",
"e": 31823,
"s": 30293,
"text": null
},
{
"code": "<?php// PHP program for character replacement// after string minimization // Function to minimize stringfunction minimize($str){ $mstr = \" \"; $flagchar=array_fill(0, 26, 0); $l = strlen($str); // duplicate characters are removed for ($i = 0; $i < strlen($str); $i++) { $ch = $str[$i]; // checks if character has previously occurred or not // if not then add it to the minimized string 'mstr' if ($flagchar[ord($ch) - 97] == 0) { $mstr .=$ch; $flagchar[ord($ch) - 97] = 1; } } return $mstr; // minimized string} // Utility function to print the// minimized, replaced stringfunction replaceMinimizeUtil($str){ $finalStr = \"\"; $l = strlen($str); $minimizedStr = minimize($str); // minimized string // Creating final string by replacing character for ($i = 0; $i < strlen($minimizedStr); $i++) { $ch = $minimizedStr[$i]; // index calculation $index = (ord($ch) * ord($ch)) % $l; $finalStr = $finalStr.$str[$index]; } echo \"Final string: \".$finalStr; // final string} // Driver code$str = \"geeks\"; replaceMinimizeUtil($str); // This code is contributed by mits?>",
"e": 33033,
"s": 31823,
"text": null
},
{
"code": "<script> // Javascript program for character replacement// after String minimization // Function to minimize Stringfunction minimize(str){ let mstr = \" \"; let l, i, flagchar = new Array(26); for(let i = 0; i < 26; i++) { flagchar[i] = 0; } let ch; l = str.length; // Duplicate characters are removed for(i = 0; i < str.length; i++) { ch = str[i]; // Checks if character has previously // occurred or not if not then add it // to the minimized String 'mstr' if (flagchar[ch.charCodeAt(0) - 97] == 0) { mstr = mstr + ch; flagchar[ch.charCodeAt(0) - 97] = 1; } } // Minimized String return mstr;} // Utility function to print the// minimized, replaced Stringfunction replaceMinimizeUtil(str){ let minimizedStr, finalStr = \"\"; let i, index, l; let ch; l = str.length; // Minimized String minimizedStr = minimize(str); // Creating final String by replacing character for(i = 0; i < minimizedStr.length; i++) { ch = minimizedStr[i].charCodeAt(0); // Index calculation index = (ch * ch) % l; finalStr = finalStr + str[index]; } // Final String document.write(\"Final String: \" + finalStr);} // Driver codelet str = \"geeks\"; replaceMinimizeUtil(str); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 34452,
"s": 33033,
"text": null
},
{
"code": null,
"e": 34472,
"s": 34452,
"text": "Final string: ssesg"
},
{
"code": null,
"e": 34496,
"s": 34474,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 34922,
"s": 34496,
"text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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": 34932,
"s": 34922,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34938,
"s": 34932,
"text": "ukasp"
},
{
"code": null,
"e": 34951,
"s": 34938,
"text": "rituraj_jain"
},
{
"code": null,
"e": 34964,
"s": 34951,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 34977,
"s": 34964,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 34998,
"s": 34977,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 35009,
"s": 34998,
"text": "cpp-string"
},
{
"code": null,
"e": 35014,
"s": 35009,
"text": "Hash"
},
{
"code": null,
"e": 35022,
"s": 35014,
"text": "Strings"
},
{
"code": null,
"e": 35027,
"s": 35022,
"text": "Hash"
},
{
"code": null,
"e": 35035,
"s": 35027,
"text": "Strings"
},
{
"code": null,
"e": 35133,
"s": 35035,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35142,
"s": 35133,
"text": "Comments"
},
{
"code": null,
"e": 35155,
"s": 35142,
"text": "Old Comments"
},
{
"code": null,
"e": 35184,
"s": 35155,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 35210,
"s": 35184,
"text": "Load Factor and Rehashing"
},
{
"code": null,
"e": 35274,
"s": 35210,
"text": "Implementing own Hash Table with Open Addressing Linear Probing"
},
{
"code": null,
"e": 35303,
"s": 35274,
"text": "Practice Problems on Hashing"
},
{
"code": null,
"e": 35337,
"s": 35303,
"text": "Advantages of BST over Hash Table"
},
{
"code": null,
"e": 35371,
"s": 35337,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 35396,
"s": 35371,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 35456,
"s": 35396,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 35492,
"s": 35456,
"text": "KMP Algorithm for Pattern Searching"
}
]
|
What is the relation between 'null' and '0' in JavaScript? | There is a lot of curiosity arises when we are dealing with false values and it is even more especially when dealing with "null" and "0" because of their properties. When we try to compare "null" and "0", we will come across typical scenarios. For greater than(>), less than(<) and equal to(=) we will get Boolean false as output. But when there is greater than or equal(>=) Boolean true will be executed as output.
Here the question that arises is how can a value is not greater than 0, not equal to 0, but greater than and equal to 0?
In the following example, three conditions such as greater than, less than and equal to were checked in between null and 0. In all three cases, the result obtained is false.
Live Demo
<html>
<body>
<script>
if(null > 0){
document.write("null is greater than 0");
}
else if(null < 0) {
document.write("null is less than 0");
}
else if(null == 0){
document.write("null is equal to 0");
}
else {
document.write("It is a typical relationship");
}
</script>
</body>
</html>
It is a typical relationship
In the following example, null is not greater than 0 and not equal to 0, but greater than or equal to 0. It looks very odd to hear. Because in mathematics if we have two numbers i.e a, b and if a is not less than the b then the possible scenarios are either a is greater than b or a is equal to b.
Coming to 'null' and '0', the mathematical expectations won't hold. This is a typical case to deal with in javascript.
Live Demo
<html>
<body>
<script>
if(null > 0){
document.write("null is greater than 0");
}
else if(null == 0){
document.write("null is equal to 0");
}
else if(null>=0) {
document.write("null is greater than or equal to 0 ");
}
</script>
</body>
</html>
null is greater than or equal to 0 | [
{
"code": null,
"e": 1480,
"s": 1062,
"text": "There is a lot of curiosity arises when we are dealing with false values and it is even more especially when dealing with \"null\" and \"0\" because of their properties. When we try to compare \"null\" and \"0\", we will come across typical scenarios. For greater than(>), less than(<) and equal to(=) we will get Boolean false as output. But when there is greater than or equal(>=) Boolean true will be executed as output. "
},
{
"code": null,
"e": 1601,
"s": 1480,
"text": "Here the question that arises is how can a value is not greater than 0, not equal to 0, but greater than and equal to 0?"
},
{
"code": null,
"e": 1775,
"s": 1601,
"text": "In the following example, three conditions such as greater than, less than and equal to were checked in between null and 0. In all three cases, the result obtained is false."
},
{
"code": null,
"e": 1786,
"s": 1775,
"text": " Live Demo"
},
{
"code": null,
"e": 2161,
"s": 1786,
"text": "<html>\n<body>\n <script>\n if(null > 0){\n document.write(\"null is greater than 0\");\n }\n else if(null < 0) {\n document.write(\"null is less than 0\");\n }\n else if(null == 0){\n document.write(\"null is equal to 0\");\n }\n else {\n document.write(\"It is a typical relationship\");\n }\n </script>\n</body>\n</html>"
},
{
"code": null,
"e": 2190,
"s": 2161,
"text": "It is a typical relationship"
},
{
"code": null,
"e": 2488,
"s": 2190,
"text": "In the following example, null is not greater than 0 and not equal to 0, but greater than or equal to 0. It looks very odd to hear. Because in mathematics if we have two numbers i.e a, b and if a is not less than the b then the possible scenarios are either a is greater than b or a is equal to b."
},
{
"code": null,
"e": 2607,
"s": 2488,
"text": "Coming to 'null' and '0', the mathematical expectations won't hold. This is a typical case to deal with in javascript."
},
{
"code": null,
"e": 2617,
"s": 2607,
"text": "Live Demo"
},
{
"code": null,
"e": 2929,
"s": 2617,
"text": "<html>\n<body>\n <script>\n if(null > 0){\n document.write(\"null is greater than 0\");\n }\n else if(null == 0){\n document.write(\"null is equal to 0\");\n }\n else if(null>=0) {\n document.write(\"null is greater than or equal to 0 \");\n }\n </script>\n</body>\n</html>"
},
{
"code": null,
"e": 2964,
"s": 2929,
"text": "null is greater than or equal to 0"
}
]
|
Different Colors of Points and Lines in Base R Plot Legend - GeeksforGeeks | 25 Aug, 2021
In this article, we are going to see how to plot different colors of points and lines in base R Programing Language.
Creating a dataset for demonstration:
R
A <- matrix( c( c(0,1,2,3,5), c(1,3,4,2,4)), ncol=2 )B <- matrix( c( c(3,1,2,3,4), c(4,2,1,1,2)), ncol=2 )C <- matrix( c( c(1,1,2,4,5), c(4,4,0,1,2)), ncol=2 )data <- data.frame(A,B)data
Output:
Let’s see in the above code where ‘A’,’B’,’C’ are the names of a matrix with vector input inside c() consisting of values. It also contains the number of rows, i.e., and ‘ncol’ as two.
After creating the matrix, now we will plot the lines and points.
Syntax: plot(x, y, type = “l”, lty = 1)
lines(x, y, type = “l”, lty = 1)
Parameters:
x, y: coordinate vectors of points to join
type: character indicating the type of plotting. Allowed value is : “p” for points
lty: line types. Line types can either be specified as an integer (0=blank, 1=solid (default), 2=dashed, 3=dotted, 4=dotdash, 5=longdash, 6=twodash) or as one of the character strings “blank”, “solid”, “dashed”, “dotted”, “dotdash”, “longdash”, or “twodash”, where “blank” uses ‘invisible lines’ (i.e., does not draw them).
R
# Plotting the lines and points# here type b means we are plotting# both points and lineplot( 0, type = "b", xlim = c(0,5), ylim = c(0,5) ) # defining the line column and colourlines( A, col = "red" ) # defining the point column and colour# here pch means the type of symbol# we can choose from 1 to 25points( A, col = "yellow", pch = 16 )lines( C, col = "green" )points( C, col = "pink", pch = 15 )lines( B, col = "blue" )points( B, col = "violet", pch = 17 )
Output:
In this above graph, we have lines and points plotted. There is no specification which line represents what, In order to do that we’ll the legend function to give them the same labels.
When adding a legend to a plot, there is the main way to modify the legend position. You can set the argument x to “top”, “topleft”, “topright”, “bottom”, “bottomleft”, “bottomright”, “left”, “right” or “center”, In this scenario you don’t have to set the argument y.
In the code below, after plotting the graph we now add a legend with pch=c(NA, NA) it means that the legend section did not show the ‘pch’ meaning the points symbol’s which we can vary from 1 to 25 as per the user’s choice.
R
A <- matrix( c( c(0,1,2,3,5), c(1,3,4,2,4)), ncol=2 )B <- matrix( c( c(3,1,2,3,4), c(4,2,1,1,2)), ncol=2 )C <- matrix( c( c(1,1,2,4,5), c(4,4,0,1,2)), ncol=2 )data <- data.frame(A,B) plot( 0, type = "b", xlim = c(0,5), ylim = c(0,5) )lines( A, col = "red" )points( A, col = "yellow", pch = 16 )lines( C, col = "green" )points( C, col = "pink", pch = 15 )lines( B, col = "blue" )points( B, col = "violet", pch = 17 ) legend( x = "topright", legend = c("Red line, Yellow points","Blue line, iolet points","Green line,Pink points"), col = c("red","blue","green"), lwd=1, lty=c(1,1,1), pch=c(NA,NA), cex = 0.5 )
Output:
Now we will just overlap the legend, symbols, as we have observed previously, the lines, are visible line the legend instead of point symbols.
So what we will do, we will assign the values to “pch” which we can vary from 1 to 25 as per the user choice every number represents a point shape i.e. pch =1, which is an empty circle, pch = 19 (solid circle), pch = 21 (filled circle), etc.
R
# dataA <- matrix( c( c(0,1,2,3,5), c(1,3,4,2,4)), ncol=2 )B <- matrix( c( c(3,1,2,3,4), c(4,2,1,1,2)), ncol=2 )C <- matrix( c( c(1,1,2,4,5), c(4,4,0,1,2)), ncol=2 )data <- data.frame(A,B) # plotplot( 0, type = "b", xlim=c(0,5), ylim=c(0,5) )lines( A, col = "red" )points( A, col = "yellow", pch=16 )lines( C, col = "green" )points( C, col = "pink", pch=15 )lines( B, col = "blue" )points( B, col = "violet", pch=17 ) # legendlegend( x="topright", legend=c("Red line, Yellow points","Blue line, iolet points","Green line,Pink points"), col=c("red","blue","green"), lwd=1, lty=c(1,1,1), pch=c(NA,NA),cex=0.5 ) legend( x="topright", legend=c("Red line, Yellow points","Blue line, violet points","Green line,Pink points"), col=c("yellow","purple","pink"), lwd=1, lty=c(0,0,0), pch=c(16,15,17),cex=0.5 )
Output
.
anikakapoor
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Control Statements in R Programming
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
Logistic Regression in R Programming
Linear Discriminant Analysis in R Programming
How to filter R DataFrame by values in a column?
How to change Colors in ggplot2 Line Plot in R ?
How to import an Excel File into R ? | [
{
"code": null,
"e": 24876,
"s": 24848,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 24993,
"s": 24876,
"text": "In this article, we are going to see how to plot different colors of points and lines in base R Programing Language."
},
{
"code": null,
"e": 25031,
"s": 24993,
"text": "Creating a dataset for demonstration:"
},
{
"code": null,
"e": 25033,
"s": 25031,
"text": "R"
},
{
"code": "A <- matrix( c( c(0,1,2,3,5), c(1,3,4,2,4)), ncol=2 )B <- matrix( c( c(3,1,2,3,4), c(4,2,1,1,2)), ncol=2 )C <- matrix( c( c(1,1,2,4,5), c(4,4,0,1,2)), ncol=2 )data <- data.frame(A,B)data",
"e": 25220,
"s": 25033,
"text": null
},
{
"code": null,
"e": 25230,
"s": 25220,
"text": " Output:"
},
{
"code": null,
"e": 25415,
"s": 25230,
"text": "Let’s see in the above code where ‘A’,’B’,’C’ are the names of a matrix with vector input inside c() consisting of values. It also contains the number of rows, i.e., and ‘ncol’ as two."
},
{
"code": null,
"e": 25481,
"s": 25415,
"text": "After creating the matrix, now we will plot the lines and points."
},
{
"code": null,
"e": 25522,
"s": 25481,
"text": "Syntax: plot(x, y, type = “l”, lty = 1) "
},
{
"code": null,
"e": 25569,
"s": 25522,
"text": " lines(x, y, type = “l”, lty = 1)"
},
{
"code": null,
"e": 25581,
"s": 25569,
"text": "Parameters:"
},
{
"code": null,
"e": 25624,
"s": 25581,
"text": "x, y: coordinate vectors of points to join"
},
{
"code": null,
"e": 25707,
"s": 25624,
"text": "type: character indicating the type of plotting. Allowed value is : “p” for points"
},
{
"code": null,
"e": 26032,
"s": 25707,
"text": "lty: line types. Line types can either be specified as an integer (0=blank, 1=solid (default), 2=dashed, 3=dotted, 4=dotdash, 5=longdash, 6=twodash) or as one of the character strings “blank”, “solid”, “dashed”, “dotted”, “dotdash”, “longdash”, or “twodash”, where “blank” uses ‘invisible lines’ (i.e., does not draw them). "
},
{
"code": null,
"e": 26034,
"s": 26032,
"text": "R"
},
{
"code": "# Plotting the lines and points# here type b means we are plotting# both points and lineplot( 0, type = \"b\", xlim = c(0,5), ylim = c(0,5) ) # defining the line column and colourlines( A, col = \"red\" ) # defining the point column and colour# here pch means the type of symbol# we can choose from 1 to 25points( A, col = \"yellow\", pch = 16 )lines( C, col = \"green\" )points( C, col = \"pink\", pch = 15 )lines( B, col = \"blue\" )points( B, col = \"violet\", pch = 17 )",
"e": 26499,
"s": 26034,
"text": null
},
{
"code": null,
"e": 26507,
"s": 26499,
"text": "Output:"
},
{
"code": null,
"e": 26692,
"s": 26507,
"text": "In this above graph, we have lines and points plotted. There is no specification which line represents what, In order to do that we’ll the legend function to give them the same labels."
},
{
"code": null,
"e": 26961,
"s": 26692,
"text": "When adding a legend to a plot, there is the main way to modify the legend position. You can set the argument x to “top”, “topleft”, “topright”, “bottom”, “bottomleft”, “bottomright”, “left”, “right” or “center”, In this scenario you don’t have to set the argument y."
},
{
"code": null,
"e": 27186,
"s": 26961,
"text": "In the code below, after plotting the graph we now add a legend with pch=c(NA, NA) it means that the legend section did not show the ‘pch’ meaning the points symbol’s which we can vary from 1 to 25 as per the user’s choice."
},
{
"code": null,
"e": 27188,
"s": 27186,
"text": "R"
},
{
"code": "A <- matrix( c( c(0,1,2,3,5), c(1,3,4,2,4)), ncol=2 )B <- matrix( c( c(3,1,2,3,4), c(4,2,1,1,2)), ncol=2 )C <- matrix( c( c(1,1,2,4,5), c(4,4,0,1,2)), ncol=2 )data <- data.frame(A,B) plot( 0, type = \"b\", xlim = c(0,5), ylim = c(0,5) )lines( A, col = \"red\" )points( A, col = \"yellow\", pch = 16 )lines( C, col = \"green\" )points( C, col = \"pink\", pch = 15 )lines( B, col = \"blue\" )points( B, col = \"violet\", pch = 17 ) legend( x = \"topright\", legend = c(\"Red line, Yellow points\",\"Blue line, iolet points\",\"Green line,Pink points\"), col = c(\"red\",\"blue\",\"green\"), lwd=1, lty=c(1,1,1), pch=c(NA,NA), cex = 0.5 )",
"e": 27844,
"s": 27188,
"text": null
},
{
"code": null,
"e": 27852,
"s": 27844,
"text": "Output:"
},
{
"code": null,
"e": 27995,
"s": 27852,
"text": "Now we will just overlap the legend, symbols, as we have observed previously, the lines, are visible line the legend instead of point symbols."
},
{
"code": null,
"e": 28237,
"s": 27995,
"text": "So what we will do, we will assign the values to “pch” which we can vary from 1 to 25 as per the user choice every number represents a point shape i.e. pch =1, which is an empty circle, pch = 19 (solid circle), pch = 21 (filled circle), etc."
},
{
"code": null,
"e": 28239,
"s": 28237,
"text": "R"
},
{
"code": "# dataA <- matrix( c( c(0,1,2,3,5), c(1,3,4,2,4)), ncol=2 )B <- matrix( c( c(3,1,2,3,4), c(4,2,1,1,2)), ncol=2 )C <- matrix( c( c(1,1,2,4,5), c(4,4,0,1,2)), ncol=2 )data <- data.frame(A,B) # plotplot( 0, type = \"b\", xlim=c(0,5), ylim=c(0,5) )lines( A, col = \"red\" )points( A, col = \"yellow\", pch=16 )lines( C, col = \"green\" )points( C, col = \"pink\", pch=15 )lines( B, col = \"blue\" )points( B, col = \"violet\", pch=17 ) # legendlegend( x=\"topright\", legend=c(\"Red line, Yellow points\",\"Blue line, iolet points\",\"Green line,Pink points\"), col=c(\"red\",\"blue\",\"green\"), lwd=1, lty=c(1,1,1), pch=c(NA,NA),cex=0.5 ) legend( x=\"topright\", legend=c(\"Red line, Yellow points\",\"Blue line, violet points\",\"Green line,Pink points\"), col=c(\"yellow\",\"purple\",\"pink\"), lwd=1, lty=c(0,0,0), pch=c(16,15,17),cex=0.5 )",
"e": 29111,
"s": 28239,
"text": null
},
{
"code": null,
"e": 29118,
"s": 29111,
"text": "Output"
},
{
"code": null,
"e": 29120,
"s": 29118,
"text": "."
},
{
"code": null,
"e": 29132,
"s": 29120,
"text": "anikakapoor"
},
{
"code": null,
"e": 29139,
"s": 29132,
"text": "Picked"
},
{
"code": null,
"e": 29148,
"s": 29139,
"text": "R-Charts"
},
{
"code": null,
"e": 29157,
"s": 29148,
"text": "R-Graphs"
},
{
"code": null,
"e": 29165,
"s": 29157,
"text": "R-plots"
},
{
"code": null,
"e": 29176,
"s": 29165,
"text": "R Language"
},
{
"code": null,
"e": 29274,
"s": 29176,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29283,
"s": 29274,
"text": "Comments"
},
{
"code": null,
"e": 29296,
"s": 29283,
"text": "Old Comments"
},
{
"code": null,
"e": 29332,
"s": 29296,
"text": "Control Statements in R Programming"
},
{
"code": null,
"e": 29384,
"s": 29332,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29408,
"s": 29384,
"text": "Data Visualization in R"
},
{
"code": null,
"e": 29443,
"s": 29408,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29481,
"s": 29443,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29518,
"s": 29481,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 29564,
"s": 29518,
"text": "Linear Discriminant Analysis in R Programming"
},
{
"code": null,
"e": 29613,
"s": 29564,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29662,
"s": 29613,
"text": "How to change Colors in ggplot2 Line Plot in R ?"
}
]
|
GATE | GATE-CS-2014-(Set-1) | Question 65 - GeeksforGeeks | 15 Oct, 2019
Given the following schema:
employees(emp-id, first-name, last-name, hire-date, dept-id, salary)
departments(dept-id, dept-name, manager-id, location-id)
You want to display the last names and hire dates of all latest hires in their respective departments in the location ID 1700. You issue the following query:
SQL> SELECT last-name, hire-date
FROM employees
WHERE (dept-id, hire-date) IN ( SELECT dept-id, MAX(hire-date)
FROM employees JOIN departments USING(dept-id)
WHERE location-id = 1700
GROUP BY dept-id);
What is the outcome?(A) It executes but does not give the correct result.(B) It executes and gives the correct result.(C) It generates an error because of pairwise comparison.(D) It generates an error because the GROUP BY clause cannot be used with table joins in a subqueryAnswer: (B)Explanation: The given query uses below inner query.
SELECT dept-id, MAX(hire-date)
FROM employees JOIN departments USING(dept-id)
WHERE location-id = 1700
GROUP BY dept-id
The inner query produces last max hire-date in every department located at location id 1700.
The outer query simply picks all pairs of inner query. Therefore, the query produces correct result.
SELECT last-name, hire-date
FROM employees
WHERE (dept-id, hire-date) IN
(Inner-Query);
Quiz of this Question
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2019 | Question 27
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2000 | Question 43
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 65
GATE | Gate IT 2007 | Question 30 | [
{
"code": null,
"e": 24466,
"s": 24438,
"text": "\n15 Oct, 2019"
},
{
"code": null,
"e": 24494,
"s": 24466,
"text": "Given the following schema:"
},
{
"code": null,
"e": 24631,
"s": 24494,
"text": " employees(emp-id, first-name, last-name, hire-date, dept-id, salary)\n departments(dept-id, dept-name, manager-id, location-id) "
},
{
"code": null,
"e": 24789,
"s": 24631,
"text": "You want to display the last names and hire dates of all latest hires in their respective departments in the location ID 1700. You issue the following query:"
},
{
"code": null,
"e": 25113,
"s": 24789,
"text": "SQL> SELECT last-name, hire-date\n FROM employees\n WHERE (dept-id, hire-date) IN ( SELECT dept-id, MAX(hire-date)\n FROM employees JOIN departments USING(dept-id)\n WHERE location-id = 1700\n GROUP BY dept-id); "
},
{
"code": null,
"e": 25451,
"s": 25113,
"text": "What is the outcome?(A) It executes but does not give the correct result.(B) It executes and gives the correct result.(C) It generates an error because of pairwise comparison.(D) It generates an error because the GROUP BY clause cannot be used with table joins in a subqueryAnswer: (B)Explanation: The given query uses below inner query."
},
{
"code": null,
"e": 25587,
"s": 25451,
"text": "SELECT dept-id, MAX(hire-date)\n FROM employees JOIN departments USING(dept-id)\n WHERE location-id = 1700\n GROUP BY dept-id\n"
},
{
"code": null,
"e": 25680,
"s": 25587,
"text": "The inner query produces last max hire-date in every department located at location id 1700."
},
{
"code": null,
"e": 25781,
"s": 25680,
"text": "The outer query simply picks all pairs of inner query. Therefore, the query produces correct result."
},
{
"code": null,
"e": 25886,
"s": 25781,
"text": "SELECT last-name, hire-date\n FROM employees\n WHERE (dept-id, hire-date) IN\n (Inner-Query); \n"
},
{
"code": null,
"e": 25908,
"s": 25886,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 25929,
"s": 25908,
"text": "GATE-CS-2014-(Set-1)"
},
{
"code": null,
"e": 25955,
"s": 25929,
"text": "GATE-GATE-CS-2014-(Set-1)"
},
{
"code": null,
"e": 25960,
"s": 25955,
"text": "GATE"
},
{
"code": null,
"e": 26058,
"s": 25960,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26092,
"s": 26058,
"text": "GATE | GATE CS 2019 | Question 27"
},
{
"code": null,
"e": 26126,
"s": 26092,
"text": "GATE | GATE-IT-2004 | Question 66"
},
{
"code": null,
"e": 26168,
"s": 26126,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 26202,
"s": 26168,
"text": "GATE | GATE-CS-2006 | Question 49"
},
{
"code": null,
"e": 26235,
"s": 26202,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 26269,
"s": 26235,
"text": "GATE | GATE-CS-2000 | Question 43"
},
{
"code": null,
"e": 26311,
"s": 26269,
"text": "GATE | GATE-CS-2017 (Set 2) | Question 42"
},
{
"code": null,
"e": 26353,
"s": 26311,
"text": "GATE | GATE CS 2021 | Set 1 | Question 47"
},
{
"code": null,
"e": 26387,
"s": 26353,
"text": "GATE | GATE CS 2011 | Question 65"
}
]
|
C library function - raise() | The C library function int raise(int sig) causes signal sig to be generated. The sig argument is compatible with the SIG macros.
Following is the declaration for signal() function.
int raise(int sig)
sig − This is the signal number to send. Following are few important standard signal constants −
sig − This is the signal number to send. Following are few important standard signal constants −
SIGABRT
(Signal Abort) Abnormal termination, such as is initiated by the abort function.
SIGFPE
(Signal Floating-Point Exception) Erroneous arithmetic operation, such as zero divide or an operation resulting in overflow (not necessarily with a floating-point operation).
SIGILL
(Signal Illegal Instruction) Invalid function image, such as an illegal instruction. This is generally due to a corruption in the code or to an attempt to execute data.
SIGINT
(Signal Interrupt) Interactive attention signal. Generally generated by the application user.
SIGSEGV
(Signal Segmentation Violation) Invalid access to storage − When a program tries to read or write outside the memory it is allocated for it.
SIGTERM
(Signal Terminate) Termination request sent to program.
This function returns zero if successful, and non-zero otherwise.
The following example shows the usage of signal() function.
#include <signal.h>
#include <stdio.h>
void signal_catchfunc(int);
int main () {
int ret;
ret = signal(SIGINT, signal_catchfunc);
if( ret == SIG_ERR) {
printf("Error: unable to set signal handler.\n");
exit(0);
}
printf("Going to raise a signal\n");
ret = raise(SIGINT);
if( ret !=0 ) {
printf("Error: unable to raise SIGINT signal.\n");
exit(0);
}
printf("Exiting...\n");
return(0);
}
void signal_catchfunc(int signal) {
printf("!! signal caught !!\n");
}
Let us compile and run the above program to will produce the following result −
Going to raise a signal
!! signal caught !!
Exiting...
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2136,
"s": 2007,
"text": "The C library function int raise(int sig) causes signal sig to be generated. The sig argument is compatible with the SIG macros."
},
{
"code": null,
"e": 2188,
"s": 2136,
"text": "Following is the declaration for signal() function."
},
{
"code": null,
"e": 2207,
"s": 2188,
"text": "int raise(int sig)"
},
{
"code": null,
"e": 2304,
"s": 2207,
"text": "sig − This is the signal number to send. Following are few important standard signal constants −"
},
{
"code": null,
"e": 2401,
"s": 2304,
"text": "sig − This is the signal number to send. Following are few important standard signal constants −"
},
{
"code": null,
"e": 2409,
"s": 2401,
"text": "SIGABRT"
},
{
"code": null,
"e": 2490,
"s": 2409,
"text": "(Signal Abort) Abnormal termination, such as is initiated by the abort function."
},
{
"code": null,
"e": 2497,
"s": 2490,
"text": "SIGFPE"
},
{
"code": null,
"e": 2672,
"s": 2497,
"text": "(Signal Floating-Point Exception) Erroneous arithmetic operation, such as zero divide or an operation resulting in overflow (not necessarily with a floating-point operation)."
},
{
"code": null,
"e": 2679,
"s": 2672,
"text": "SIGILL"
},
{
"code": null,
"e": 2848,
"s": 2679,
"text": "(Signal Illegal Instruction) Invalid function image, such as an illegal instruction. This is generally due to a corruption in the code or to an attempt to execute data."
},
{
"code": null,
"e": 2855,
"s": 2848,
"text": "SIGINT"
},
{
"code": null,
"e": 2949,
"s": 2855,
"text": "(Signal Interrupt) Interactive attention signal. Generally generated by the application user."
},
{
"code": null,
"e": 2957,
"s": 2949,
"text": "SIGSEGV"
},
{
"code": null,
"e": 3098,
"s": 2957,
"text": "(Signal Segmentation Violation) Invalid access to storage − When a program tries to read or write outside the memory it is allocated for it."
},
{
"code": null,
"e": 3106,
"s": 3098,
"text": "SIGTERM"
},
{
"code": null,
"e": 3162,
"s": 3106,
"text": "(Signal Terminate) Termination request sent to program."
},
{
"code": null,
"e": 3228,
"s": 3162,
"text": "This function returns zero if successful, and non-zero otherwise."
},
{
"code": null,
"e": 3288,
"s": 3228,
"text": "The following example shows the usage of signal() function."
},
{
"code": null,
"e": 3812,
"s": 3288,
"text": "#include <signal.h>\n#include <stdio.h>\n\nvoid signal_catchfunc(int);\n\nint main () {\n int ret;\n\n ret = signal(SIGINT, signal_catchfunc);\n\n if( ret == SIG_ERR) {\n printf(\"Error: unable to set signal handler.\\n\");\n exit(0);\n }\n printf(\"Going to raise a signal\\n\");\n ret = raise(SIGINT);\n \n if( ret !=0 ) {\n printf(\"Error: unable to raise SIGINT signal.\\n\");\n exit(0);\n }\n\n printf(\"Exiting...\\n\");\n return(0);\n}\n\nvoid signal_catchfunc(int signal) {\n printf(\"!! signal caught !!\\n\");\n}"
},
{
"code": null,
"e": 3892,
"s": 3812,
"text": "Let us compile and run the above program to will produce the following result −"
},
{
"code": null,
"e": 3948,
"s": 3892,
"text": "Going to raise a signal\n!! signal caught !!\nExiting...\n"
},
{
"code": null,
"e": 3981,
"s": 3948,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3996,
"s": 3981,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4031,
"s": 3996,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4046,
"s": 4031,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4081,
"s": 4046,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 4095,
"s": 4081,
"text": " Asif Hussain"
},
{
"code": null,
"e": 4128,
"s": 4095,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4146,
"s": 4128,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 4181,
"s": 4146,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4200,
"s": 4181,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 4233,
"s": 4200,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4245,
"s": 4233,
"text": " Amit Diwan"
},
{
"code": null,
"e": 4252,
"s": 4245,
"text": " Print"
},
{
"code": null,
"e": 4263,
"s": 4252,
"text": " Add Notes"
}
]
|
Python - Arrays | Array is a container which can hold a fix number of items and these items should be of the same type. Most of the data structures make use of arrays to implement their algorithms. Following are the important terms to understand the concept of Array.
Element− Each item stored in an array is called an element.
Index − Each location of an element in an array has a numerical index, which is used to identify the element.
Arrays can be declared in various ways in different languages. Below is an illustration.
As per the above illustration, following are the important points to be considered.
Index starts with 0.
Index starts with 0.
Array length is 10 which means it can store 10 elements.
Array length is 10 which means it can store 10 elements.
Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9.
Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9.
Following are the basic operations supported by an array.
Traverse − print all the array elements one by one.
Traverse − print all the array elements one by one.
Insertion − Adds an element at the given index.
Insertion − Adds an element at the given index.
Deletion − Deletes an element at the given index.
Deletion − Deletes an element at the given index.
Search − Searches an element using the given index or by the value.
Search − Searches an element using the given index or by the value.
Update − Updates an element at the given index.
Update − Updates an element at the given index.
Array is created in Python by importing array module to the python program. Then the array is declared as shown eblow.
from array import *
arrayName = array(typecode, [Initializers])
Typecode are the codes that are used to define the type of value the array will hold. Some common typecodes used are:
Before lookign at various array operations lets create and print an array using python.
The below code creates an array named array1.
from array import *
array1 = array('i', [10,20,30,40,50])
for x in array1:
print(x)
When we compile and execute the above program, it produces the following result −
10
20
30
40
50
We can access each element of an array using the index of the element. The below code shows how
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1[0])
print (array1[2])
When we compile and execute the above program, it produces the following result − which shows the element is inserted at index position 1.
10
30
Insert operation is to insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of array.
Here, we add a data element at the middle of the array using the python in-built insert() method.
from array import *
array1 = array('i', [10,20,30,40,50])
array1.insert(1,60)
for x in array1:
print(x)
When we compile and execute the above program, it produces the following result which shows the element is inserted at index position 1.
10
60
20
30
40
50
Deletion refers to removing an existing element from the array and re-organizing all elements of an array.
Here, we remove a data element at the middle of the array using the python in-built remove() method.
from array import *
array1 = array('i', [10,20,30,40,50])
array1.remove(40)
for x in array1:
print(x)
When we compile and execute the above program, it produces the following result which shows the element is removed form the array.
10
20
30
50
You can perform a search for an array element based on its value or its index.
Here, we search a data element using the python in-built index() method.
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1.index(40))
When we compile and execute the above program, it produces the following result which shows the index of the element. If the value is not present in the array then th eprogram returns an error.
3
Update operation refers to updating an existing element from the array at a given index.
Here, we simply reassign a new value to the desired index we want to update.
from array import *
array1 = array('i', [10,20,30,40,50])
array1[2] = 80
for x in array1:
print(x)
When we compile and execute the above program, it produces the following result which shows the new value at the index position 2.
10
20
80
40
50
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2494,
"s": 2244,
"text": "Array is a container which can hold a fix number of items and these items should be of the same type. Most of the data structures make use of arrays to implement their algorithms. Following are the important terms to understand the concept of Array."
},
{
"code": null,
"e": 2554,
"s": 2494,
"text": "Element− Each item stored in an array is called an element."
},
{
"code": null,
"e": 2664,
"s": 2554,
"text": "Index − Each location of an element in an array has a numerical index, which is used to identify the element."
},
{
"code": null,
"e": 2753,
"s": 2664,
"text": "Arrays can be declared in various ways in different languages. Below is an illustration."
},
{
"code": null,
"e": 2837,
"s": 2753,
"text": "As per the above illustration, following are the important points to be considered."
},
{
"code": null,
"e": 2858,
"s": 2837,
"text": "Index starts with 0."
},
{
"code": null,
"e": 2879,
"s": 2858,
"text": "Index starts with 0."
},
{
"code": null,
"e": 2936,
"s": 2879,
"text": "Array length is 10 which means it can store 10 elements."
},
{
"code": null,
"e": 2993,
"s": 2936,
"text": "Array length is 10 which means it can store 10 elements."
},
{
"code": null,
"e": 3091,
"s": 2993,
"text": "Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9."
},
{
"code": null,
"e": 3189,
"s": 3091,
"text": "Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9."
},
{
"code": null,
"e": 3247,
"s": 3189,
"text": "Following are the basic operations supported by an array."
},
{
"code": null,
"e": 3299,
"s": 3247,
"text": "Traverse − print all the array elements one by one."
},
{
"code": null,
"e": 3351,
"s": 3299,
"text": "Traverse − print all the array elements one by one."
},
{
"code": null,
"e": 3399,
"s": 3351,
"text": "Insertion − Adds an element at the given index."
},
{
"code": null,
"e": 3447,
"s": 3399,
"text": "Insertion − Adds an element at the given index."
},
{
"code": null,
"e": 3497,
"s": 3447,
"text": "Deletion − Deletes an element at the given index."
},
{
"code": null,
"e": 3547,
"s": 3497,
"text": "Deletion − Deletes an element at the given index."
},
{
"code": null,
"e": 3615,
"s": 3547,
"text": "Search − Searches an element using the given index or by the value."
},
{
"code": null,
"e": 3683,
"s": 3615,
"text": "Search − Searches an element using the given index or by the value."
},
{
"code": null,
"e": 3731,
"s": 3683,
"text": "Update − Updates an element at the given index."
},
{
"code": null,
"e": 3779,
"s": 3731,
"text": "Update − Updates an element at the given index."
},
{
"code": null,
"e": 3898,
"s": 3779,
"text": "Array is created in Python by importing array module to the python program. Then the array is declared as shown eblow."
},
{
"code": null,
"e": 3964,
"s": 3898,
"text": "\nfrom array import *\n\narrayName = array(typecode, [Initializers])"
},
{
"code": null,
"e": 4082,
"s": 3964,
"text": "Typecode are the codes that are used to define the type of value the array will hold. Some common typecodes used are:"
},
{
"code": null,
"e": 4170,
"s": 4082,
"text": "Before lookign at various array operations lets create and print an array using python."
},
{
"code": null,
"e": 4216,
"s": 4170,
"text": "The below code creates an array named array1."
},
{
"code": null,
"e": 4303,
"s": 4216,
"text": "from array import *\n\narray1 = array('i', [10,20,30,40,50])\n\nfor x in array1:\n print(x)"
},
{
"code": null,
"e": 4385,
"s": 4303,
"text": "When we compile and execute the above program, it produces the following result −"
},
{
"code": null,
"e": 4403,
"s": 4385,
"text": "\n10\n20\n30\n40\n50\n\n"
},
{
"code": null,
"e": 4500,
"s": 4403,
"text": "We can access each element of an array using the index of the element. The below code shows how "
},
{
"code": null,
"e": 4598,
"s": 4500,
"text": "\nfrom array import *\n\narray1 = array('i', [10,20,30,40,50])\n\nprint (array1[0])\n\nprint (array1[2])"
},
{
"code": null,
"e": 4737,
"s": 4598,
"text": "When we compile and execute the above program, it produces the following result − which shows the element is inserted at index position 1."
},
{
"code": null,
"e": 4746,
"s": 4737,
"text": "\n10\n30\n\n"
},
{
"code": null,
"e": 4922,
"s": 4746,
"text": "Insert operation is to insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of array."
},
{
"code": null,
"e": 5020,
"s": 4922,
"text": "Here, we add a data element at the middle of the array using the python in-built insert() method."
},
{
"code": null,
"e": 5129,
"s": 5020,
"text": "\nfrom array import *\n\narray1 = array('i', [10,20,30,40,50])\n\narray1.insert(1,60)\n\nfor x in array1:\n print(x)"
},
{
"code": null,
"e": 5266,
"s": 5129,
"text": "When we compile and execute the above program, it produces the following result which shows the element is inserted at index position 1."
},
{
"code": null,
"e": 5287,
"s": 5266,
"text": "\n10\n60\n20\n30\n40\n50\n\n"
},
{
"code": null,
"e": 5394,
"s": 5287,
"text": "Deletion refers to removing an existing element from the array and re-organizing all elements of an array."
},
{
"code": null,
"e": 5495,
"s": 5394,
"text": "Here, we remove a data element at the middle of the array using the python in-built remove() method."
},
{
"code": null,
"e": 5602,
"s": 5495,
"text": "\nfrom array import *\n\narray1 = array('i', [10,20,30,40,50])\n\narray1.remove(40)\n\nfor x in array1:\n print(x)"
},
{
"code": null,
"e": 5733,
"s": 5602,
"text": "When we compile and execute the above program, it produces the following result which shows the element is removed form the array."
},
{
"code": null,
"e": 5746,
"s": 5733,
"text": "10\n20\n30\n50\n"
},
{
"code": null,
"e": 5825,
"s": 5746,
"text": "You can perform a search for an array element based on its value or its index."
},
{
"code": null,
"e": 5898,
"s": 5825,
"text": "Here, we search a data element using the python in-built index() method."
},
{
"code": null,
"e": 5985,
"s": 5898,
"text": "\nfrom array import *\n\narray1 = array('i', [10,20,30,40,50])\n\nprint (array1.index(40))\n"
},
{
"code": null,
"e": 6179,
"s": 5985,
"text": "When we compile and execute the above program, it produces the following result which shows the index of the element. If the value is not present in the array then th eprogram returns an error."
},
{
"code": null,
"e": 6182,
"s": 6179,
"text": "3\n"
},
{
"code": null,
"e": 6271,
"s": 6182,
"text": "Update operation refers to updating an existing element from the array at a given index."
},
{
"code": null,
"e": 6348,
"s": 6271,
"text": "Here, we simply reassign a new value to the desired index we want to update."
},
{
"code": null,
"e": 6453,
"s": 6348,
"text": "\nfrom array import *\n\narray1 = array('i', [10,20,30,40,50])\n\narray1[2] = 80\n\nfor x in array1:\n print(x)\n"
},
{
"code": null,
"e": 6584,
"s": 6453,
"text": "When we compile and execute the above program, it produces the following result which shows the new value at the index position 2."
},
{
"code": null,
"e": 6600,
"s": 6584,
"text": "10\n20\n80\n40\n50\n"
},
{
"code": null,
"e": 6637,
"s": 6600,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6653,
"s": 6637,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6686,
"s": 6653,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6705,
"s": 6686,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6740,
"s": 6705,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 6762,
"s": 6740,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 6796,
"s": 6762,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6824,
"s": 6796,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6859,
"s": 6824,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 6873,
"s": 6859,
"text": " Lets Kode It"
},
{
"code": null,
"e": 6906,
"s": 6873,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6923,
"s": 6906,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6930,
"s": 6923,
"text": " Print"
},
{
"code": null,
"e": 6941,
"s": 6930,
"text": " Add Notes"
}
]
|
Calculate number of nodes in all subtrees | Using DFS - GeeksforGeeks | 30 Jun, 2021
Given a tree in the form of adjacency list we have to calculate the number of nodes in the subtree of each node while calculating the number of nodes in the subtree of a particular node that node will also be added as a node in subtree hence the number of nodes in subtree of leaves is 1. Examples:
Input : Consider the Graph mentioned below:
Output : Nodes in subtree of 1 : 5
Nodes in subtree of 2 : 1
Nodes in subtree of 3 : 1
Nodes in subtree of 4 : 3
Nodes in subtree of 5 : 1
Input : Consider the Graph mentioned below:
Output : Nodes in subtree of 1 : 7
Nodes in subtree of 2 : 2
Nodes in subtree of 3 : 1
Nodes in subtree of 4 : 3
Nodes in subtree of 5 : 1
Nodes in subtree of 6 : 1
Nodes in subtree of 7 : 1
Explanation: First we should calculate value count[s] : the number of nodes in subtree of node s. Where subtree contains the node itself and all the nodes in the subtree of its children. Thus, we can calculate the number of nodes recursively using the concept of DFS and DP, where we should process each edge only once and count[] value of children used in calculating count[] of its parent expressing the concept of DP(Dynamic programming). Time Complexity : O(n) [in processing of all (n-1) edges].
Algorithm :
void numberOfNodes(int s, int e)
{
vector::iterator u;
count1[s] = 1;
for (u = adj[s].begin(); u != adj[s].end(); u++)
{
// condition to omit reverse path
// path from children to parent
if (*u == e)
continue;
// recursive call for DFS
numberOfNodes(*u, s);
// update count[] value of parent using
// its children
count1[s] += count1[*u];
}
}
C++
Java
Python3
C#
Javascript
// CPP code to find number of nodes// in subtree of each node#include <bits/stdc++.h>using namespace std; const int N = 8; // variables used to store data globallyint count1[N]; // adjacency list representation of treevector<int> adj[N]; // function to calculate no. of nodes in a subtreevoid numberOfNodes(int s, int e){ vector<int>::iterator u; count1[s] = 1; for (u = adj[s].begin(); u != adj[s].end(); u++) { // condition to omit reverse path // path from children to parent if (*u == e) continue; // recursive call for DFS numberOfNodes(*u, s); // update count[] value of parent using // its children count1[s] += count1[*u]; }} // function to add edges in graphvoid addEdge(int a, int b){ adj[a].push_back(b); adj[b].push_back(a);} // function to print resultvoid printNumberOfNodes(){ for (int i = 1; i < N; i++) { cout << "\nNodes in subtree of " << i; cout << ": " << count1[i]; }} // driver functionint main(){ // insertion of nodes in graph addEdge(1, 2); addEdge(1, 4); addEdge(1, 5); addEdge(2, 6); addEdge(4, 3); addEdge(4, 7); // call to perform dfs calculation // making 1 as root of tree numberOfNodes(1, 0); // print result printNumberOfNodes(); return 0;}
// A Java code to find number of nodes// in subtree of each nodeimport java.util.ArrayList; public class NodesInSubtree{ // variables used to store data globally static final int N = 8; static int count1[] = new int[N]; // adjacency list representation of tree static ArrayList<Integer> adj[] = new ArrayList[N]; // function to calculate no. of nodes in a subtree static void numberOfNodes(int s, int e) { count1[s] = 1; for(Integer u: adj[s]) { // condition to omit reverse path // path from children to parent if(u == e) continue; // recursive call for DFS numberOfNodes(u ,s); // update count[] value of parent using // its children count1[s] += count1[u]; } } // function to add edges in graph static void addEdge(int a, int b) { adj[a].add(b); adj[b].add(a); } // function to print result static void printNumberOfNodes() { for (int i = 1; i < N; i++) System.out.println("Node of a subtree of "+ i+ " : "+ count1[i]); } // Driver function public static void main(String[] args) { // Creating list for all nodes for(int i = 0; i < N; i++) adj[i] = new ArrayList<>(); // insertion of nodes in graph addEdge(1, 2); addEdge(1, 4); addEdge(1, 5); addEdge(2, 6); addEdge(4, 3); addEdge(4, 7); // call to perform dfs calculation // making 1 as root of tree numberOfNodes(1, 0); // print result printNumberOfNodes(); } }// This code is contributed by Sumit Ghosh
# Python3 code to find the number of# nodes in the subtree of each nodeN = 8 # variables used to store data globallycount1 = [0] * (N) # Adjacency list representation of treeadj = [[] for i in range(N)] # Function to calculate no. of# nodes in subtreedef numberOfNodes(s, e): count1[s] = 1 for u in adj[s]: # Condition to omit reverse path # path from children to parent if u == e: continue # recursive call for DFS numberOfNodes(u, s) # update count[] value of parent # using its children count1[s] += count1[u] # Function to add edges in graphdef addEdge(a, b): adj[a].append(b) adj[b].append(a) # Function to print resultdef printNumberOfNodes(): for i in range(1, N): print("Nodes in subtree of", i, ":", count1[i]) # Driver Codeif __name__ == "__main__": # insertion of nodes in graph addEdge(1, 2) addEdge(1, 4) addEdge(1, 5) addEdge(2, 6) addEdge(4, 3) addEdge(4, 7) # call to perform dfs calculation # making 1 as root of tree numberOfNodes(1, 0) # print result printNumberOfNodes() # This code is contributed by Rituraj Jain
// C# code to find number of nodes// in subtree of each nodeusing System;using System.Collections.Generic;class GFG{ // variables used to store data globally static readonly int N = 8; static int []count1 = new int[N]; // adjacency list representation of tree static List<int> []adj = new List<int>[N]; // function to calculate no. of nodes in a subtree static void numberOfNodes(int s, int e) { count1[s] = 1; foreach(int u in adj[s]) { // condition to omit reverse path // path from children to parent if(u == e) continue; // recursive call for DFS numberOfNodes(u, s); // update count[] value of parent using // its children count1[s] += count1[u]; } } // function to add edges in graph static void addEdge(int a, int b) { adj[a].Add(b); adj[b].Add(a); } // function to print result static void printNumberOfNodes() { for (int i = 1; i < N; i++) Console.WriteLine("Node of a subtree of "+ i + " : "+ count1[i]); } // Driver Code public static void Main(String[] args) { // Creating list for all nodes for(int i = 0; i < N; i++) adj[i] = new List<int>(); // insertion of nodes in graph addEdge(1, 2); addEdge(1, 4); addEdge(1, 5); addEdge(2, 6); addEdge(4, 3); addEdge(4, 7); // call to perform dfs calculation // making 1 as root of tree numberOfNodes(1, 0); // print result printNumberOfNodes(); }} // This code is contributed by PrinciRaj1992
<script> // A Javascript code to find number of nodes // in subtree of each node // variables used to store data globally let N = 8; let count1 = new Array(N); // adjacency list representation of tree let adj = new Array(N); // function to calculate no. of nodes in a subtree function numberOfNodes(s, e) { count1[s] = 1; for(let u = 0; u < adj[s].length; u++) { // condition to omit reverse path // path from children to parent if(adj[s][u] == e) continue; // recursive call for DFS numberOfNodes(adj[s][u] ,s); // update count[] value of parent using // its children count1[s] += count1[adj[s][u]]; } } // function to add edges in graph function addEdge(a, b) { adj[a].push(b); adj[b].push(a); } // function to print result function printNumberOfNodes() { for (let i = 1; i < N; i++) document.write("Node of a subtree of "+ i+ " : "+ count1[i] + "</br>"); } // Creating list for all nodes for(let i = 0; i < N; i++) adj[i] = []; // insertion of nodes in graph addEdge(1, 2); addEdge(1, 4); addEdge(1, 5); addEdge(2, 6); addEdge(4, 3); addEdge(4, 7); // call to perform dfs calculation // making 1 as root of tree numberOfNodes(1, 0); // print result printNumberOfNodes(); // This code is contributed by suresh07.</script>
Output:
Nodes in subtree of 1: 7
Nodes in subtree of 2: 2
Nodes in subtree of 3: 1
Nodes in subtree of 4: 3
Nodes in subtree of 5: 1
Nodes in subtree of 6: 1
Nodes in subtree of 7: 1
Input and Output illustration:
This article is contributed by Shivam Pradhan (anuj_charm). 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.
rituraj_jain
princiraj1992
Akanksha_Rai
suresh07
DFS
Tree
DFS
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inorder Tree Traversal without Recursion
Binary Tree | Set 3 (Types of Binary Tree)
Binary Tree | Set 2 (Properties)
A program to check if a binary tree is BST or not
Decision Tree
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Construct Tree from given Inorder and Preorder traversals
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
BFS vs DFS for Binary Tree | [
{
"code": null,
"e": 25232,
"s": 25204,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 25533,
"s": 25232,
"text": "Given a tree in the form of adjacency list we have to calculate the number of nodes in the subtree of each node while calculating the number of nodes in the subtree of a particular node that node will also be added as a node in subtree hence the number of nodes in subtree of leaves is 1. Examples: "
},
{
"code": null,
"e": 25577,
"s": 25533,
"text": "Input : Consider the Graph mentioned below:"
},
{
"code": null,
"e": 25797,
"s": 25577,
"text": "Output : Nodes in subtree of 1 : 5\n Nodes in subtree of 2 : 1\n Nodes in subtree of 3 : 1\n Nodes in subtree of 4 : 3\n Nodes in subtree of 5 : 1\n\nInput : Consider the Graph mentioned below:"
},
{
"code": null,
"e": 26042,
"s": 25797,
"text": "Output : Nodes in subtree of 1 : 7\n Nodes in subtree of 2 : 2\n Nodes in subtree of 3 : 1\n Nodes in subtree of 4 : 3\n Nodes in subtree of 5 : 1\n Nodes in subtree of 6 : 1\n Nodes in subtree of 7 : 1"
},
{
"code": null,
"e": 26544,
"s": 26042,
"text": "Explanation: First we should calculate value count[s] : the number of nodes in subtree of node s. Where subtree contains the node itself and all the nodes in the subtree of its children. Thus, we can calculate the number of nodes recursively using the concept of DFS and DP, where we should process each edge only once and count[] value of children used in calculating count[] of its parent expressing the concept of DP(Dynamic programming). Time Complexity : O(n) [in processing of all (n-1) edges]. "
},
{
"code": null,
"e": 27014,
"s": 26544,
"text": "Algorithm :\nvoid numberOfNodes(int s, int e)\n{\n vector::iterator u;\n count1[s] = 1;\n for (u = adj[s].begin(); u != adj[s].end(); u++)\n {\n // condition to omit reverse path\n // path from children to parent \n if (*u == e)\n continue;\n \n // recursive call for DFS\n numberOfNodes(*u, s);\n \n // update count[] value of parent using\n // its children\n count1[s] += count1[*u];\n }\n}"
},
{
"code": null,
"e": 27022,
"s": 27018,
"text": "C++"
},
{
"code": null,
"e": 27027,
"s": 27022,
"text": "Java"
},
{
"code": null,
"e": 27035,
"s": 27027,
"text": "Python3"
},
{
"code": null,
"e": 27038,
"s": 27035,
"text": "C#"
},
{
"code": null,
"e": 27049,
"s": 27038,
"text": "Javascript"
},
{
"code": "// CPP code to find number of nodes// in subtree of each node#include <bits/stdc++.h>using namespace std; const int N = 8; // variables used to store data globallyint count1[N]; // adjacency list representation of treevector<int> adj[N]; // function to calculate no. of nodes in a subtreevoid numberOfNodes(int s, int e){ vector<int>::iterator u; count1[s] = 1; for (u = adj[s].begin(); u != adj[s].end(); u++) { // condition to omit reverse path // path from children to parent if (*u == e) continue; // recursive call for DFS numberOfNodes(*u, s); // update count[] value of parent using // its children count1[s] += count1[*u]; }} // function to add edges in graphvoid addEdge(int a, int b){ adj[a].push_back(b); adj[b].push_back(a);} // function to print resultvoid printNumberOfNodes(){ for (int i = 1; i < N; i++) { cout << \"\\nNodes in subtree of \" << i; cout << \": \" << count1[i]; }} // driver functionint main(){ // insertion of nodes in graph addEdge(1, 2); addEdge(1, 4); addEdge(1, 5); addEdge(2, 6); addEdge(4, 3); addEdge(4, 7); // call to perform dfs calculation // making 1 as root of tree numberOfNodes(1, 0); // print result printNumberOfNodes(); return 0;}",
"e": 28406,
"s": 27049,
"text": null
},
{
"code": "// A Java code to find number of nodes// in subtree of each nodeimport java.util.ArrayList; public class NodesInSubtree{ // variables used to store data globally static final int N = 8; static int count1[] = new int[N]; // adjacency list representation of tree static ArrayList<Integer> adj[] = new ArrayList[N]; // function to calculate no. of nodes in a subtree static void numberOfNodes(int s, int e) { count1[s] = 1; for(Integer u: adj[s]) { // condition to omit reverse path // path from children to parent if(u == e) continue; // recursive call for DFS numberOfNodes(u ,s); // update count[] value of parent using // its children count1[s] += count1[u]; } } // function to add edges in graph static void addEdge(int a, int b) { adj[a].add(b); adj[b].add(a); } // function to print result static void printNumberOfNodes() { for (int i = 1; i < N; i++) System.out.println(\"Node of a subtree of \"+ i+ \" : \"+ count1[i]); } // Driver function public static void main(String[] args) { // Creating list for all nodes for(int i = 0; i < N; i++) adj[i] = new ArrayList<>(); // insertion of nodes in graph addEdge(1, 2); addEdge(1, 4); addEdge(1, 5); addEdge(2, 6); addEdge(4, 3); addEdge(4, 7); // call to perform dfs calculation // making 1 as root of tree numberOfNodes(1, 0); // print result printNumberOfNodes(); } }// This code is contributed by Sumit Ghosh",
"e": 30235,
"s": 28406,
"text": null
},
{
"code": "# Python3 code to find the number of# nodes in the subtree of each nodeN = 8 # variables used to store data globallycount1 = [0] * (N) # Adjacency list representation of treeadj = [[] for i in range(N)] # Function to calculate no. of# nodes in subtreedef numberOfNodes(s, e): count1[s] = 1 for u in adj[s]: # Condition to omit reverse path # path from children to parent if u == e: continue # recursive call for DFS numberOfNodes(u, s) # update count[] value of parent # using its children count1[s] += count1[u] # Function to add edges in graphdef addEdge(a, b): adj[a].append(b) adj[b].append(a) # Function to print resultdef printNumberOfNodes(): for i in range(1, N): print(\"Nodes in subtree of\", i, \":\", count1[i]) # Driver Codeif __name__ == \"__main__\": # insertion of nodes in graph addEdge(1, 2) addEdge(1, 4) addEdge(1, 5) addEdge(2, 6) addEdge(4, 3) addEdge(4, 7) # call to perform dfs calculation # making 1 as root of tree numberOfNodes(1, 0) # print result printNumberOfNodes() # This code is contributed by Rituraj Jain",
"e": 31462,
"s": 30235,
"text": null
},
{
"code": "// C# code to find number of nodes// in subtree of each nodeusing System;using System.Collections.Generic;class GFG{ // variables used to store data globally static readonly int N = 8; static int []count1 = new int[N]; // adjacency list representation of tree static List<int> []adj = new List<int>[N]; // function to calculate no. of nodes in a subtree static void numberOfNodes(int s, int e) { count1[s] = 1; foreach(int u in adj[s]) { // condition to omit reverse path // path from children to parent if(u == e) continue; // recursive call for DFS numberOfNodes(u, s); // update count[] value of parent using // its children count1[s] += count1[u]; } } // function to add edges in graph static void addEdge(int a, int b) { adj[a].Add(b); adj[b].Add(a); } // function to print result static void printNumberOfNodes() { for (int i = 1; i < N; i++) Console.WriteLine(\"Node of a subtree of \"+ i + \" : \"+ count1[i]); } // Driver Code public static void Main(String[] args) { // Creating list for all nodes for(int i = 0; i < N; i++) adj[i] = new List<int>(); // insertion of nodes in graph addEdge(1, 2); addEdge(1, 4); addEdge(1, 5); addEdge(2, 6); addEdge(4, 3); addEdge(4, 7); // call to perform dfs calculation // making 1 as root of tree numberOfNodes(1, 0); // print result printNumberOfNodes(); }} // This code is contributed by PrinciRaj1992",
"e": 33266,
"s": 31462,
"text": null
},
{
"code": "<script> // A Javascript code to find number of nodes // in subtree of each node // variables used to store data globally let N = 8; let count1 = new Array(N); // adjacency list representation of tree let adj = new Array(N); // function to calculate no. of nodes in a subtree function numberOfNodes(s, e) { count1[s] = 1; for(let u = 0; u < adj[s].length; u++) { // condition to omit reverse path // path from children to parent if(adj[s][u] == e) continue; // recursive call for DFS numberOfNodes(adj[s][u] ,s); // update count[] value of parent using // its children count1[s] += count1[adj[s][u]]; } } // function to add edges in graph function addEdge(a, b) { adj[a].push(b); adj[b].push(a); } // function to print result function printNumberOfNodes() { for (let i = 1; i < N; i++) document.write(\"Node of a subtree of \"+ i+ \" : \"+ count1[i] + \"</br>\"); } // Creating list for all nodes for(let i = 0; i < N; i++) adj[i] = []; // insertion of nodes in graph addEdge(1, 2); addEdge(1, 4); addEdge(1, 5); addEdge(2, 6); addEdge(4, 3); addEdge(4, 7); // call to perform dfs calculation // making 1 as root of tree numberOfNodes(1, 0); // print result printNumberOfNodes(); // This code is contributed by suresh07.</script>",
"e": 34875,
"s": 33266,
"text": null
},
{
"code": null,
"e": 34885,
"s": 34875,
"text": "Output: "
},
{
"code": null,
"e": 35060,
"s": 34885,
"text": "Nodes in subtree of 1: 7\nNodes in subtree of 2: 2\nNodes in subtree of 3: 1\nNodes in subtree of 4: 3\nNodes in subtree of 5: 1\nNodes in subtree of 6: 1\nNodes in subtree of 7: 1"
},
{
"code": null,
"e": 35093,
"s": 35060,
"text": "Input and Output illustration: "
},
{
"code": null,
"e": 35529,
"s": 35093,
"text": "This article is contributed by Shivam Pradhan (anuj_charm). 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": 35542,
"s": 35529,
"text": "rituraj_jain"
},
{
"code": null,
"e": 35556,
"s": 35542,
"text": "princiraj1992"
},
{
"code": null,
"e": 35569,
"s": 35556,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 35578,
"s": 35569,
"text": "suresh07"
},
{
"code": null,
"e": 35582,
"s": 35578,
"text": "DFS"
},
{
"code": null,
"e": 35587,
"s": 35582,
"text": "Tree"
},
{
"code": null,
"e": 35591,
"s": 35587,
"text": "DFS"
},
{
"code": null,
"e": 35596,
"s": 35591,
"text": "Tree"
},
{
"code": null,
"e": 35694,
"s": 35596,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35735,
"s": 35694,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 35778,
"s": 35735,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 35811,
"s": 35778,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 35861,
"s": 35811,
"text": "A program to check if a binary tree is BST or not"
},
{
"code": null,
"e": 35875,
"s": 35861,
"text": "Decision Tree"
},
{
"code": null,
"e": 35958,
"s": 35875,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 36016,
"s": 35958,
"text": "Construct Tree from given Inorder and Preorder traversals"
},
{
"code": null,
"e": 36052,
"s": 36016,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 36100,
"s": 36052,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.