title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Python - Negative Binomial Discrete Distribution in Statistics - GeeksforGeeks
10 Jan, 2020 scipy.stats.nbinom() is a Negative binomial discrete random variable. It is inherited from the of generic methods as an instance of the rv_discrete class. It completes the methods with details specific for this particular distribution. Parameters : x : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’). Results : Negative binomial discrete random variable Code #1 : Creating Negative binomial discrete random variable # importing library from scipy.stats import nbinom numargs = nbinom .numargs a, b = 0.2, 0.8rv = nbinom (a, b) print ("RV : \n", rv) Output : RV : scipy.stats._distn_infrastructure.rv_frozen object at 0x0000016A4C016208 Code #2 : Negative binomial discrete variates and probability distribution import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = nbinom .rvs(a, b, size = 10) print ("Random Variates : \n", R) # PDF x = np.linspace(nbinom.ppf(0.01, a, b), nbinom.ppf(0.99, a, b), 10)R = nbinom.ppf(x, 1, 3)print ("\nProbability Distribution : \n", R) Output : Random Variates : [0 0 0 0 0 0 0 0 0 0] Probability Distribution : [-1. nan nan nan nan nan nan nan nan nan] Code #3 : Graphical Representation. import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 2)) print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.ppf(distribution)) Output : Distribution : [0. 0.04081633 0.08163265 0.12244898 0.16326531 0.20408163 0.24489796 0.28571429 0.32653061 0.36734694 0.40816327 0.44897959 0.48979592 0.53061224 0.57142857 0.6122449 0.65306122 0.69387755 0.73469388 0.7755102 0.81632653 0.85714286 0.89795918 0.93877551 0.97959184 1.02040816 1.06122449 1.10204082 1.14285714 1.18367347 1.2244898 1.26530612 1.30612245 1.34693878 1.3877551 1.42857143 1.46938776 1.51020408 1.55102041 1.59183673 1.63265306 1.67346939 1.71428571 1.75510204 1.79591837 1.83673469 1.87755102 1.91836735 1.95918367 2. ] Code #4 : Varying Positional Arguments import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = nbinom.ppf(x, a, b) y2 = nbinom.pmf(x, a, b) plt.plot(x, y1, "*", x, y2, "r--") Output : Python scipy-stats-functions Python-scipy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n10 Jan, 2020" }, { "code": null, "e": 24137, "s": 23901, "text": "scipy.stats.nbinom() is a Negative binomial discrete random variable. It is inherited from the of generic methods as an instance of the rv_discrete class. It completes the methods with details specific for this particular distribution." }, { "code": null, "e": 24150, "s": 24137, "text": "Parameters :" }, { "code": null, "e": 24402, "s": 24150, "text": "x : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’)." }, { "code": null, "e": 24455, "s": 24402, "text": "Results : Negative binomial discrete random variable" }, { "code": null, "e": 24517, "s": 24455, "text": "Code #1 : Creating Negative binomial discrete random variable" }, { "code": "# importing library from scipy.stats import nbinom numargs = nbinom .numargs a, b = 0.2, 0.8rv = nbinom (a, b) print (\"RV : \\n\", rv) ", "e": 24661, "s": 24517, "text": null }, { "code": null, "e": 24670, "s": 24661, "text": "Output :" }, { "code": null, "e": 24751, "s": 24670, "text": "RV : \n scipy.stats._distn_infrastructure.rv_frozen object at 0x0000016A4C016208\n" }, { "code": null, "e": 24826, "s": 24751, "text": "Code #2 : Negative binomial discrete variates and probability distribution" }, { "code": "import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = nbinom .rvs(a, b, size = 10) print (\"Random Variates : \\n\", R) # PDF x = np.linspace(nbinom.ppf(0.01, a, b), nbinom.ppf(0.99, a, b), 10)R = nbinom.ppf(x, 1, 3)print (\"\\nProbability Distribution : \\n\", R) ", "e": 25127, "s": 24826, "text": null }, { "code": null, "e": 25136, "s": 25127, "text": "Output :" }, { "code": null, "e": 25252, "s": 25136, "text": "Random Variates : \n [0 0 0 0 0 0 0 0 0 0]\n\nProbability Distribution : \n [-1. nan nan nan nan nan nan nan nan nan]\n\n" }, { "code": null, "e": 25288, "s": 25252, "text": "Code #3 : Graphical Representation." }, { "code": "import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 2)) print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.ppf(distribution)) ", "e": 25499, "s": 25288, "text": null }, { "code": null, "e": 25508, "s": 25499, "text": "Output :" }, { "code": null, "e": 26088, "s": 25508, "text": "Distribution : \n [0. 0.04081633 0.08163265 0.12244898 0.16326531 0.20408163\n 0.24489796 0.28571429 0.32653061 0.36734694 0.40816327 0.44897959\n 0.48979592 0.53061224 0.57142857 0.6122449 0.65306122 0.69387755\n 0.73469388 0.7755102 0.81632653 0.85714286 0.89795918 0.93877551\n 0.97959184 1.02040816 1.06122449 1.10204082 1.14285714 1.18367347\n 1.2244898 1.26530612 1.30612245 1.34693878 1.3877551 1.42857143\n 1.46938776 1.51020408 1.55102041 1.59183673 1.63265306 1.67346939\n 1.71428571 1.75510204 1.79591837 1.83673469 1.87755102 1.91836735\n 1.95918367 2. ]\n " }, { "code": null, "e": 26127, "s": 26088, "text": "Code #4 : Varying Positional Arguments" }, { "code": "import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = nbinom.ppf(x, a, b) y2 = nbinom.pmf(x, a, b) plt.plot(x, y1, \"*\", x, y2, \"r--\") ", "e": 26329, "s": 26127, "text": null }, { "code": null, "e": 26338, "s": 26329, "text": "Output :" }, { "code": null, "e": 26367, "s": 26338, "text": "Python scipy-stats-functions" }, { "code": null, "e": 26380, "s": 26367, "text": "Python-scipy" }, { "code": null, "e": 26387, "s": 26380, "text": "Python" }, { "code": null, "e": 26485, "s": 26387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26494, "s": 26485, "text": "Comments" }, { "code": null, "e": 26507, "s": 26494, "text": "Old Comments" }, { "code": null, "e": 26539, "s": 26507, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26595, "s": 26539, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26637, "s": 26595, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26679, "s": 26637, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26715, "s": 26679, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26737, "s": 26715, "text": "Defaultdict in Python" }, { "code": null, "e": 26776, "s": 26737, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26803, "s": 26776, "text": "Python Classes and Objects" }, { "code": null, "e": 26834, "s": 26803, "text": "Python | os.path.join() method" } ]
Machine Learning Web Application Deployment in 5 steps | by Harsh Rana | Towards Data Science
Let me paint you a picture: You spent 2 months of your life working on a very exciting data science application. It involved advanced data collection, time-consuming data wrangling, hours of training and endless model micro-optimizations. Once you were finished, you had something that you were truly happy with. But today, 3 months since your blockbuster model was completed, it’s just sitting in a GitHub repository with your research notebooks and semi-documented code. You’ve gained 12 stars and 2 forks but wonder, “is this it? Do only 14 people in this entire world care about this awesome thing that I built? Should I have done something differently? If so, what?” If you’ve had this experience of creating something wonderful, only to have a handful of people interact with it and even fewer give you feedback, you’re not alone. I’ve made this mistake often and I have a lot of friends in data science who’ve also had similar experiences. Now, I don’t want to take away from folks who enjoy working on theoretical problems and thrive in research settings, but I do think there are data scientists out there who need to showcase their work for the world to see. Not only would this help non-technical folks such as recruiters see and understand your work, but it would also open up the door to receiving real-world feedback on projects. In this article, I’ll share how to deploy a machine learning web application to an Amazon AWS EC2 instance — without Amazon Beanstalk — to keep our deployment entirely free-tiered. You can check out a live demo of our end product here. While you can use your own models and application to follow along, I’ll be using one of my previous projects where I first built a sentiment analysis classifier and then a flask web application on top of that. You can find all my code for the model in this repository and for my web application in this one. I highly recommend the flask-based development tech stack as it is the easiest to deploy to AWS and should suffice for any basic application. Let’s be real, Amazon Web services (AWS) can be super intimidating for someone who’s never worked with web technologies and backend services before. Honestly, I’ve worked professionally as a full-stack web developer and I still had a hard time navigating and getting started with AWS, because it just offers so many different services! Do you need an S3 bucket? What about a Load Manager? You have to use Lambda requests right? Quick note: this guide is NOT meant for production or enterprise-level solutions and should only be used for basic personal projects. If you are interested in a more production-ready deployment guide, feel free to drop a comment, so I (or other Medium readers) can point you in the right direction. In this article, I’m really focusing on a lean application deployment for personal use. We’ll be using an AWS EC2 instance, which is basically a virtual server. It’s part of the free-tier offered by AWS and thus deploying your project through the steps mentioned below will be absolutely free. With those details out of the way, let's talk about how we’re going to deploy our basic application on a vanilla EC2 instance in 5 simple steps. At a very high level, our deployment steps can be seen in the chart above. We’ll start out by setting up an EC2 instance on which our application will run. This’ll involve utilizing a few guides but I’ll help you through this and mention common errors to save you time and frustration. Next, we’ll connect to our instance and migrate our code to it. This is where I’ll share the application we’ll be working with today, walk you through our Flask directory setup and API. After that, we’ll install project dependencies, followed by setting up a local Apache server to run on our EC2 instance which will be used to serve our application on the public port provided by the EC2 server. Let’s get started! Setting up an EC2 instance on AWS is really not super hard and has been covered by numerous different articles on TDS and beyond, so I will not be wasting your time by going through it again. Instead, I’ll point to the guides which helped me the most and walk through some common errors/questions that show up during setup. Remember, the goal of this step is to: Create an AWS account (if you haven’t already)Start up an EC2 server using the tutorials and guides I’ll point to belowEnsure your instance settings are correct Create an AWS account (if you haven’t already) Start up an EC2 server using the tutorials and guides I’ll point to below Ensure your instance settings are correct Here’s the great official guide to help you setup your instance: AWS official EC2 instance setup guide. You’ll want to make a few key changes to the setup as follows. In Step 1: Choose an Amazon Machine Image (AMI), pick the Ubuntu Server 16.04 LTS (HVM). Stick to the free tier option (t2.micro) because it’s got enough computing power for most small-scale personal projects. Instead of choosing the Review and Launch button, click through the different configuration options and stop at Step 6: Configure Security Group. Here, add a new security group with the following settings: This will allow users from anywhere in the world to be able to access a port on your running EC2 instance using HTTP, which is perfect for our web application. Now when you finish this step, review and click the launch button you’ll see the following dialog box: Make sure to select “Create a new key pair” (if you don’t already have one), and save this .pem file in a secure location. You’ll need this later on. Congratulations, your EC2 instance is now up and running! It’s time to connect to it and migrate your application. Now that our instance is up and running, we can connect to it. The connection process will look different based on your OS, so I can’t be of much help for Mac/Linux users, but here’s a great page with resources for you folks. I’ll be walking primarily through the Windows setup process, and again I’ll point you towards some good resources while mentioning hurdles and extra steps. I highly suggest using PuTTY as your SSH client because of its ease of use and simplicity. The best guide available to walk through the connection sequence is again the AWS official one, so feel free to work through that. Once you've completed generating your .ppk key from your .pem key and are ready to connect to your instance, the following details will help: Hostname: ubuntu@your_public_dns_name Where your public DNS name can be found on your AWS EC2 homepage by clicking “running instances”: The rest of the steps covered by the guide for connecting to your EC2 instance are fairly straight-forward, but make sure to save your settings in the PuTTY page so you don’t have to set this up every time. Note: your connection type is SSH and ensure that your .ppk file is connected under Connection > SSH > Auth before saving your settings. If everything went smoothly, after this step you’ll be able to access your instance using the PuTTY client. This will be a dark DOS-looking screen from the ’70s and that’s exactly what we’re looking for! Like I mentioned earlier in the article, we’re going to be deploying a machine learning web application that I built over the past 2 weeks. Before we get into code migration, a little knowledge about the model, application and project structure is necessary. The model is a basic sentiment analysis classifier with incremental learning capabilities. We created a single page application on top of this to help a user interact with our model. We have two Flask API routes which allow the user to enter a review/thought and receive a sentiment analysis, and provide feedback to the model allowing for ongoing learning. The project structure can be seen in the image on the right. All our assets (images, models, etc.) are in different sub-folders inside the same main folder static , our HTML page is inside the templates folder and our app.py file is in the python folder. We’ll be using the SCP command to help us transfer our files from our local computer (windows) to our EC2 instance. Before doing that, go ahead and create a directory (I called mine web_app, I would suggest using the same name to avoid any confusion) inside /home/ubuntu where your application will exist using the following command- mkdir web_app So your desired deployment location on your instance is /home/ubuntu/web_app. Now, you’ll have to download and unzip the application mentioned above into your local machine. You can find the project code in this GitHub repo. Once you have the project files in your local machine, you can use the following SCP command (from the windows terminal) to move your files from your local machine to your AWS EC2 instance: scp -i <path/to/pem/key> -r <local/path/to/project/folder> ubuntu@<instance/public/DNS>:/home/ubuntu/web_app Note: if you encounter an error with the following message “Permissions for ‘private-key’ are too open”, check out this awesome article about getting past that. Great! At this point, your project files should now all be in your EC2 instance. Ensure that the folder structure/paths are correct (ex: /home/ubuntu/web_app/python/app.py etc.) and now we can move on to the next step. Now, this step can be the most confusing for people because python environments, modules and other installations can quickly get complicated and cross-dependent. We’ll keep it simple by breaking this part into two main steps: Install pip and other python dependenciesInstall Apache and mod_wsgi on our EC2 instance Install pip and other python dependencies Install Apache and mod_wsgi on our EC2 instance Let's start by ensuring we’re running Python 3 and installing the correct version of Pip. Your EC2 instance should come pre-installed with python3. To check, use the following command: python3 -V You should see a version greater than 3.5. If that’s the case you can move on to the next step. If not, look through this official guide. Once you have python3 installed, you’ll need to download and install the correct pip version. To do so, use the following commands (in order): curl -O https://bootstrap.pypa.io/get-pip.py sudo python3 get-pip.py Now, you should have both python3 and pip installed. Before moving on to the next step run the following command to ensure everything is up-to-date: sudo apt-get update We’ll finish this step off by installing our web app dependencies (Flask and Scikit-learn) using the following commands: sudo pip install Flasksudo pip install scikit-learn Now we can move to the next step: installing Apache and mod_wsgi. To set up Apache you need two modules: Apache2 and mod_wsgi. Apache2 is our simple web server and mod_wsgi is an Apache module used for Python based web applications. To install the correct versions for python3, use the following commands: sudo apt-get install apache2sudo apt-get install libapache2-mod-wsgi-py At this point, the Apache server should be serving a default page on your AWS EC2 public DNS. To verify this, note the public DNS (ec2-xx-xxx-xx-xxx.compute-x.amazonaws.com/) from your AWS console and visit it in the browser. You should see a screen which looks like the one on the left. If you can see the Apache default screen, rejoice because you’re almost there! If not, feel free to use the comment section so myself and others can help you. You can also look through the Apache log file (/var/log/apache2/error.log) to try and debug yourself. You’ve set up python3 and pip, installed Apache and it’s required modules and are already serving up a page. Now, all that’s left is to setup Apache and point it towards your project folder and give it permission to access those files. To get our application running on the server, we need to set some Apache configurations. This involves two steps: set up server configurations/permissions and set up mod_wsgi configuration. To set up your server configuration, you need to edit the following file: /etc/apache2/sites-enabled/000-default.conf. This is a restricted file and thus you’ll have to use sudo to edit it. Use the following command: sudo vi /etc/apache2/sites-enabled/000-default.conf Add the following code block right after the line ServerAdmin webmaster@localhost: DocumentRoot /home/ubuntu/web_appWSGIDaemonProcess flaskapp threads=5 python-home=/usr/local/lib/python3.5/site-packages/ user=ubuntu WSGIScriptAlias / /home/ubuntu/web_app/static/flaskapp.wsgi<Directory /home/ubuntu/web_app> WSGIProcessGroup flaskapp WSGIApplicationGroup %{GLOBAL} Require all granted </Directory><Directory python> Require all granted </Directory><Directory static> Require all granted </Directory><Directory static/models> Require all granted </Directory> These configuration settings should point Apache towards the location of our web application and give it all the required permissions to interact with our files and models. The last step in our Apache setup is configuring mod_wsgi to support our Flask-based application. To do so, you have to create a file named flaskapp.wsgi in the static folder. Put the following code in that file: import sysimport sitesite.addsitedir(‘/home/ubuntu/.local/lib/python3.5/site-packages’)sys.path.insert(0, ‘/home/ubuntu/web_app/python’)from app import app as application These are configurations needed by Apache to locate your python dependencies and your project folder(s). Once you’ve made/modified these files and put in the appropriate code, your application is ready to run. Restart your server using the following command to see the changes take effect: sudo apachectl restart Hopefully, at this point, your web application is successfully running on your EC2 public DNS and is ready for the world to interact with! If you see a 403 or 500 error code, try to look through the Apache log file (/var/log/apache2/error.log) for clues about what went wrong. As always, you also use the comment section to share errors and I’ll do my best to help. If everything went smoothly, you should see our app when you visit your public DNS in a browser: You can check out a live demo here. I think the internet should be full of real world projects built by people to openly communicate ideas they’re most excited about. Learning how to build a model from scratch, designing and developing a web application around it and finally deploying it online for the world to see is a great step towards that goal. I hope some of you get inspired to build and share something of your own and if you do, don’t forget to pay it forward by inspiring others to do the same. I hope you enjoyed reading this article just as much as I enjoyed putting it together. If you have any questions, feedback or comments, feel free to get in touch with me through LinkedIn, or my website. Additionally, if you did end up building and deploying your own application, please share it with me because I’d love to see it!
[ { "code": null, "e": 199, "s": 171, "text": "Let me paint you a picture:" }, { "code": null, "e": 843, "s": 199, "text": "You spent 2 months of your life working on a very exciting data science application. It involved advanced data collection, time-consuming data wrangling, hours of training and endless model micro-optimizations. Once you were finished, you had something that you were truly happy with. But today, 3 months since your blockbuster model was completed, it’s just sitting in a GitHub repository with your research notebooks and semi-documented code. You’ve gained 12 stars and 2 forks but wonder, “is this it? Do only 14 people in this entire world care about this awesome thing that I built? Should I have done something differently? If so, what?”" }, { "code": null, "e": 1515, "s": 843, "text": "If you’ve had this experience of creating something wonderful, only to have a handful of people interact with it and even fewer give you feedback, you’re not alone. I’ve made this mistake often and I have a lot of friends in data science who’ve also had similar experiences. Now, I don’t want to take away from folks who enjoy working on theoretical problems and thrive in research settings, but I do think there are data scientists out there who need to showcase their work for the world to see. Not only would this help non-technical folks such as recruiters see and understand your work, but it would also open up the door to receiving real-world feedback on projects." }, { "code": null, "e": 1751, "s": 1515, "text": "In this article, I’ll share how to deploy a machine learning web application to an Amazon AWS EC2 instance — without Amazon Beanstalk — to keep our deployment entirely free-tiered. You can check out a live demo of our end product here." }, { "code": null, "e": 2201, "s": 1751, "text": "While you can use your own models and application to follow along, I’ll be using one of my previous projects where I first built a sentiment analysis classifier and then a flask web application on top of that. You can find all my code for the model in this repository and for my web application in this one. I highly recommend the flask-based development tech stack as it is the easiest to deploy to AWS and should suffice for any basic application." }, { "code": null, "e": 2629, "s": 2201, "text": "Let’s be real, Amazon Web services (AWS) can be super intimidating for someone who’s never worked with web technologies and backend services before. Honestly, I’ve worked professionally as a full-stack web developer and I still had a hard time navigating and getting started with AWS, because it just offers so many different services! Do you need an S3 bucket? What about a Load Manager? You have to use Lambda requests right?" }, { "code": null, "e": 3222, "s": 2629, "text": "Quick note: this guide is NOT meant for production or enterprise-level solutions and should only be used for basic personal projects. If you are interested in a more production-ready deployment guide, feel free to drop a comment, so I (or other Medium readers) can point you in the right direction. In this article, I’m really focusing on a lean application deployment for personal use. We’ll be using an AWS EC2 instance, which is basically a virtual server. It’s part of the free-tier offered by AWS and thus deploying your project through the steps mentioned below will be absolutely free." }, { "code": null, "e": 3367, "s": 3222, "text": "With those details out of the way, let's talk about how we’re going to deploy our basic application on a vanilla EC2 instance in 5 simple steps." }, { "code": null, "e": 4069, "s": 3367, "text": "At a very high level, our deployment steps can be seen in the chart above. We’ll start out by setting up an EC2 instance on which our application will run. This’ll involve utilizing a few guides but I’ll help you through this and mention common errors to save you time and frustration. Next, we’ll connect to our instance and migrate our code to it. This is where I’ll share the application we’ll be working with today, walk you through our Flask directory setup and API. After that, we’ll install project dependencies, followed by setting up a local Apache server to run on our EC2 instance which will be used to serve our application on the public port provided by the EC2 server. Let’s get started!" }, { "code": null, "e": 4432, "s": 4069, "text": "Setting up an EC2 instance on AWS is really not super hard and has been covered by numerous different articles on TDS and beyond, so I will not be wasting your time by going through it again. Instead, I’ll point to the guides which helped me the most and walk through some common errors/questions that show up during setup. Remember, the goal of this step is to:" }, { "code": null, "e": 4593, "s": 4432, "text": "Create an AWS account (if you haven’t already)Start up an EC2 server using the tutorials and guides I’ll point to belowEnsure your instance settings are correct" }, { "code": null, "e": 4640, "s": 4593, "text": "Create an AWS account (if you haven’t already)" }, { "code": null, "e": 4714, "s": 4640, "text": "Start up an EC2 server using the tutorials and guides I’ll point to below" }, { "code": null, "e": 4756, "s": 4714, "text": "Ensure your instance settings are correct" }, { "code": null, "e": 4923, "s": 4756, "text": "Here’s the great official guide to help you setup your instance: AWS official EC2 instance setup guide. You’ll want to make a few key changes to the setup as follows." }, { "code": null, "e": 5012, "s": 4923, "text": "In Step 1: Choose an Amazon Machine Image (AMI), pick the Ubuntu Server 16.04 LTS (HVM)." }, { "code": null, "e": 5339, "s": 5012, "text": "Stick to the free tier option (t2.micro) because it’s got enough computing power for most small-scale personal projects. Instead of choosing the Review and Launch button, click through the different configuration options and stop at Step 6: Configure Security Group. Here, add a new security group with the following settings:" }, { "code": null, "e": 5602, "s": 5339, "text": "This will allow users from anywhere in the world to be able to access a port on your running EC2 instance using HTTP, which is perfect for our web application. Now when you finish this step, review and click the launch button you’ll see the following dialog box:" }, { "code": null, "e": 5867, "s": 5602, "text": "Make sure to select “Create a new key pair” (if you don’t already have one), and save this .pem file in a secure location. You’ll need this later on. Congratulations, your EC2 instance is now up and running! It’s time to connect to it and migrate your application." }, { "code": null, "e": 6471, "s": 5867, "text": "Now that our instance is up and running, we can connect to it. The connection process will look different based on your OS, so I can’t be of much help for Mac/Linux users, but here’s a great page with resources for you folks. I’ll be walking primarily through the Windows setup process, and again I’ll point you towards some good resources while mentioning hurdles and extra steps. I highly suggest using PuTTY as your SSH client because of its ease of use and simplicity. The best guide available to walk through the connection sequence is again the AWS official one, so feel free to work through that." }, { "code": null, "e": 6613, "s": 6471, "text": "Once you've completed generating your .ppk key from your .pem key and are ready to connect to your instance, the following details will help:" }, { "code": null, "e": 6651, "s": 6613, "text": "Hostname: ubuntu@your_public_dns_name" }, { "code": null, "e": 6749, "s": 6651, "text": "Where your public DNS name can be found on your AWS EC2 homepage by clicking “running instances”:" }, { "code": null, "e": 7093, "s": 6749, "text": "The rest of the steps covered by the guide for connecting to your EC2 instance are fairly straight-forward, but make sure to save your settings in the PuTTY page so you don’t have to set this up every time. Note: your connection type is SSH and ensure that your .ppk file is connected under Connection > SSH > Auth before saving your settings." }, { "code": null, "e": 7297, "s": 7093, "text": "If everything went smoothly, after this step you’ll be able to access your instance using the PuTTY client. This will be a dark DOS-looking screen from the ’70s and that’s exactly what we’re looking for!" }, { "code": null, "e": 7914, "s": 7297, "text": "Like I mentioned earlier in the article, we’re going to be deploying a machine learning web application that I built over the past 2 weeks. Before we get into code migration, a little knowledge about the model, application and project structure is necessary. The model is a basic sentiment analysis classifier with incremental learning capabilities. We created a single page application on top of this to help a user interact with our model. We have two Flask API routes which allow the user to enter a review/thought and receive a sentiment analysis, and provide feedback to the model allowing for ongoing learning." }, { "code": null, "e": 8169, "s": 7914, "text": "The project structure can be seen in the image on the right. All our assets (images, models, etc.) are in different sub-folders inside the same main folder static , our HTML page is inside the templates folder and our app.py file is in the python folder." }, { "code": null, "e": 8503, "s": 8169, "text": "We’ll be using the SCP command to help us transfer our files from our local computer (windows) to our EC2 instance. Before doing that, go ahead and create a directory (I called mine web_app, I would suggest using the same name to avoid any confusion) inside /home/ubuntu where your application will exist using the following command-" }, { "code": null, "e": 8517, "s": 8503, "text": "mkdir web_app" }, { "code": null, "e": 8932, "s": 8517, "text": "So your desired deployment location on your instance is /home/ubuntu/web_app. Now, you’ll have to download and unzip the application mentioned above into your local machine. You can find the project code in this GitHub repo. Once you have the project files in your local machine, you can use the following SCP command (from the windows terminal) to move your files from your local machine to your AWS EC2 instance:" }, { "code": null, "e": 9041, "s": 8932, "text": "scp -i <path/to/pem/key> -r <local/path/to/project/folder> ubuntu@<instance/public/DNS>:/home/ubuntu/web_app" }, { "code": null, "e": 9202, "s": 9041, "text": "Note: if you encounter an error with the following message “Permissions for ‘private-key’ are too open”, check out this awesome article about getting past that." }, { "code": null, "e": 9421, "s": 9202, "text": "Great! At this point, your project files should now all be in your EC2 instance. Ensure that the folder structure/paths are correct (ex: /home/ubuntu/web_app/python/app.py etc.) and now we can move on to the next step." }, { "code": null, "e": 9647, "s": 9421, "text": "Now, this step can be the most confusing for people because python environments, modules and other installations can quickly get complicated and cross-dependent. We’ll keep it simple by breaking this part into two main steps:" }, { "code": null, "e": 9736, "s": 9647, "text": "Install pip and other python dependenciesInstall Apache and mod_wsgi on our EC2 instance" }, { "code": null, "e": 9778, "s": 9736, "text": "Install pip and other python dependencies" }, { "code": null, "e": 9826, "s": 9778, "text": "Install Apache and mod_wsgi on our EC2 instance" }, { "code": null, "e": 10011, "s": 9826, "text": "Let's start by ensuring we’re running Python 3 and installing the correct version of Pip. Your EC2 instance should come pre-installed with python3. To check, use the following command:" }, { "code": null, "e": 10022, "s": 10011, "text": "python3 -V" }, { "code": null, "e": 10303, "s": 10022, "text": "You should see a version greater than 3.5. If that’s the case you can move on to the next step. If not, look through this official guide. Once you have python3 installed, you’ll need to download and install the correct pip version. To do so, use the following commands (in order):" }, { "code": null, "e": 10372, "s": 10303, "text": "curl -O https://bootstrap.pypa.io/get-pip.py sudo python3 get-pip.py" }, { "code": null, "e": 10521, "s": 10372, "text": "Now, you should have both python3 and pip installed. Before moving on to the next step run the following command to ensure everything is up-to-date:" }, { "code": null, "e": 10541, "s": 10521, "text": "sudo apt-get update" }, { "code": null, "e": 10662, "s": 10541, "text": "We’ll finish this step off by installing our web app dependencies (Flask and Scikit-learn) using the following commands:" }, { "code": null, "e": 10714, "s": 10662, "text": "sudo pip install Flasksudo pip install scikit-learn" }, { "code": null, "e": 10780, "s": 10714, "text": "Now we can move to the next step: installing Apache and mod_wsgi." }, { "code": null, "e": 11020, "s": 10780, "text": "To set up Apache you need two modules: Apache2 and mod_wsgi. Apache2 is our simple web server and mod_wsgi is an Apache module used for Python based web applications. To install the correct versions for python3, use the following commands:" }, { "code": null, "e": 11092, "s": 11020, "text": "sudo apt-get install apache2sudo apt-get install libapache2-mod-wsgi-py" }, { "code": null, "e": 11380, "s": 11092, "text": "At this point, the Apache server should be serving a default page on your AWS EC2 public DNS. To verify this, note the public DNS (ec2-xx-xxx-xx-xxx.compute-x.amazonaws.com/) from your AWS console and visit it in the browser. You should see a screen which looks like the one on the left." }, { "code": null, "e": 11641, "s": 11380, "text": "If you can see the Apache default screen, rejoice because you’re almost there! If not, feel free to use the comment section so myself and others can help you. You can also look through the Apache log file (/var/log/apache2/error.log) to try and debug yourself." }, { "code": null, "e": 11877, "s": 11641, "text": "You’ve set up python3 and pip, installed Apache and it’s required modules and are already serving up a page. Now, all that’s left is to setup Apache and point it towards your project folder and give it permission to access those files." }, { "code": null, "e": 12067, "s": 11877, "text": "To get our application running on the server, we need to set some Apache configurations. This involves two steps: set up server configurations/permissions and set up mod_wsgi configuration." }, { "code": null, "e": 12284, "s": 12067, "text": "To set up your server configuration, you need to edit the following file: /etc/apache2/sites-enabled/000-default.conf. This is a restricted file and thus you’ll have to use sudo to edit it. Use the following command:" }, { "code": null, "e": 12336, "s": 12284, "text": "sudo vi /etc/apache2/sites-enabled/000-default.conf" }, { "code": null, "e": 12419, "s": 12336, "text": "Add the following code block right after the line ServerAdmin webmaster@localhost:" }, { "code": null, "e": 12996, "s": 12419, "text": "DocumentRoot /home/ubuntu/web_appWSGIDaemonProcess flaskapp threads=5 python-home=/usr/local/lib/python3.5/site-packages/ user=ubuntu WSGIScriptAlias / /home/ubuntu/web_app/static/flaskapp.wsgi<Directory /home/ubuntu/web_app> WSGIProcessGroup flaskapp WSGIApplicationGroup %{GLOBAL} Require all granted </Directory><Directory python> Require all granted </Directory><Directory static> Require all granted </Directory><Directory static/models> Require all granted </Directory>" }, { "code": null, "e": 13169, "s": 12996, "text": "These configuration settings should point Apache towards the location of our web application and give it all the required permissions to interact with our files and models." }, { "code": null, "e": 13382, "s": 13169, "text": "The last step in our Apache setup is configuring mod_wsgi to support our Flask-based application. To do so, you have to create a file named flaskapp.wsgi in the static folder. Put the following code in that file:" }, { "code": null, "e": 13553, "s": 13382, "text": "import sysimport sitesite.addsitedir(‘/home/ubuntu/.local/lib/python3.5/site-packages’)sys.path.insert(0, ‘/home/ubuntu/web_app/python’)from app import app as application" }, { "code": null, "e": 13843, "s": 13553, "text": "These are configurations needed by Apache to locate your python dependencies and your project folder(s). Once you’ve made/modified these files and put in the appropriate code, your application is ready to run. Restart your server using the following command to see the changes take effect:" }, { "code": null, "e": 13866, "s": 13843, "text": "sudo apachectl restart" }, { "code": null, "e": 14329, "s": 13866, "text": "Hopefully, at this point, your web application is successfully running on your EC2 public DNS and is ready for the world to interact with! If you see a 403 or 500 error code, try to look through the Apache log file (/var/log/apache2/error.log) for clues about what went wrong. As always, you also use the comment section to share errors and I’ll do my best to help. If everything went smoothly, you should see our app when you visit your public DNS in a browser:" }, { "code": null, "e": 14365, "s": 14329, "text": "You can check out a live demo here." }, { "code": null, "e": 14836, "s": 14365, "text": "I think the internet should be full of real world projects built by people to openly communicate ideas they’re most excited about. Learning how to build a model from scratch, designing and developing a web application around it and finally deploying it online for the world to see is a great step towards that goal. I hope some of you get inspired to build and share something of your own and if you do, don’t forget to pay it forward by inspiring others to do the same." } ]
Progressive Learning and Network Growing in TensorFlow | by Viviane | Towards Data Science
In many real world applications new training data becomes available after a network has already been trained. Especially with big neural networks, it would be very tedious to retrain the complete model every time new information becomes available. It would be much easier to simply add new nodes to the network for each new class or other information that was introduced and keep all the other previously trained weights. In this post I will give a brief overview on how to do this in TensorFlow and how the network performance is affected by it. I will demonstrate the procedure and results on the CIFAR-10 data set but the Git repository linked at the end of this post also provides code and results for MNIST and CIFAR-100 and can easily be adapted to any other data set of this kind. The network I use has a very simple structure of two convolutional layers followed by one fully connected layer with 512 neurons and one read out layer with as many neurons as classes in the data set. In the example of a progressively learning network here, training starts with six of the ten classes in CIFAR-10. After each epoch, one new class is introduced until, after five epochs, all ten classes are in the data set. In order for the network to train on a newly added class, it needs to have a new output node for this class. This means that the last layer of the network as well as the weights connected to it grow in size with every new class that is added. To implement this in TensorFlow, I reinitialize the complete last layer with a new layer of the new size. # Define initializer (old weights + random samples from them for the new node(s) )initializer = tf.constant_initializer(np.append(weights,np.random.choice(weights.flatten(),(512,1)),axis=1)) # Initialize new last layer of size (512 x numClasses) tf.variable_scope(tf.get_variable_scope(),reuse=tf.AUTO_REUSE): outLog,Wname = newLastInit(hidden_layer,numOutP,initializer) acc,CE = evaluate(outLog,desired) accuracy = tf.reduce_mean(tf.cast(acc, tf.float32)) cross_entropy = tf.reduce_mean(CE) learning_rate = 1e-4 optimizer = tf.train.AdamOptimizer(learning_rate,name='op_0')# get name of new layerweightName = Wname# define gradientsgradient = tf.gradients(cross_entropy, weightName)[0]# define training goaltraining_step = optimizer.minimize(cross_entropy)# get all uninitialized variablesuninitialized_vars = getUnititialized(tf.all_variables())# initialize all uninitialized variablesinit_new_vars_op = tf.initialize_variables(uninitialized_vars)# Start training for the next epochsession.run(init_new_vars_op) The weights connected to the new last layer are best initialized with the already trained weights from the previous epoch. The weights connected to the newly added node can be randomly sampled from the old weights or a random distribution. This weight initialization leads to significantly better results than initializing all weights with random numbers or a small constant since it preserves all information learned in the previous epoch(s). For all three weight initializations you can see a drop of performance whenever a new class is introduced. However, the drop for the first two initializations (constant and random initialization) is much bigger than when initializing with the old weights since the old weight initialization preserves already learned information and only the new class needs to be trained from the beginning on. When comparing the network performance of the old classes to the performance of the new class, one can see how the performance drop is mainly caused by the latter. The performance on the old classes is relatively untouched by a new class introduction. Looking at these graphs it seems as if adding a new class and growing the network has little to no effect on the already learned information on the old classes when preserving the old weights. But how does it effect the overall test accuracy (black line)? To compare network growing to a conventional training with all classes in the data set from the beginning onward, I train the network under each condition a hundred times and then compare the distribution of the resulting 100 test accuracies of each condition. Additionally, I add a condition called No Growing in which the last layer stays static (always containing 10 nodes) and only the data set grows over time. This corresponds to initializing a bigger output layer from the beginning on to leave some room for new classes without having to change the network structure during training but limits the maximal number of classes that can be added. The normal network training (M=0.50, SD=0.01) is significantly better than both of the continuously learning conditions (growing (M=0.48, SD=0.01) and no growing(M=0.49, SD=0.01)), p<0.001. However, the normal training had a strong advantage since it could train on each example for each class five times. The two continuously learning networks had much less time to train on the classes that were introduced later on. In the most extreme case, the images of the class introduced last were only seen once by the networks as opposed to five times by the normally trained network. When training for longer after the last class has been introduced one can see how the two continuously learning networks catch up to the normal network after 30 epochs of post training, from then on no significant difference can be found anymore, F(2,297), p=0.06. These results show that a network can be trained with iterative class introduction and can still reach a comparable performance to a network trained with all classes from the beginning on. The continuously learning networks take a bit more time to reach a performance comparable to the performance of a normally trained network but this effect can be explained by the lower exposure of the network to the classes which were added later on. In a real world application this can be a simple solution for adding new information to an already trained network without having to start training from scratch again.
[ { "code": null, "e": 719, "s": 172, "text": "In many real world applications new training data becomes available after a network has already been trained. Especially with big neural networks, it would be very tedious to retrain the complete model every time new information becomes available. It would be much easier to simply add new nodes to the network for each new class or other information that was introduced and keep all the other previously trained weights. In this post I will give a brief overview on how to do this in TensorFlow and how the network performance is affected by it." }, { "code": null, "e": 1161, "s": 719, "text": "I will demonstrate the procedure and results on the CIFAR-10 data set but the Git repository linked at the end of this post also provides code and results for MNIST and CIFAR-100 and can easily be adapted to any other data set of this kind. The network I use has a very simple structure of two convolutional layers followed by one fully connected layer with 512 neurons and one read out layer with as many neurons as classes in the data set." }, { "code": null, "e": 1733, "s": 1161, "text": "In the example of a progressively learning network here, training starts with six of the ten classes in CIFAR-10. After each epoch, one new class is introduced until, after five epochs, all ten classes are in the data set. In order for the network to train on a newly added class, it needs to have a new output node for this class. This means that the last layer of the network as well as the weights connected to it grow in size with every new class that is added. To implement this in TensorFlow, I reinitialize the complete last layer with a new layer of the new size." }, { "code": null, "e": 2872, "s": 1733, "text": "# Define initializer (old weights + random samples from them for the new node(s) )initializer = tf.constant_initializer(np.append(weights,np.random.choice(weights.flatten(),(512,1)),axis=1)) # Initialize new last layer of size (512 x numClasses) tf.variable_scope(tf.get_variable_scope(),reuse=tf.AUTO_REUSE): outLog,Wname = newLastInit(hidden_layer,numOutP,initializer) acc,CE = evaluate(outLog,desired) accuracy = tf.reduce_mean(tf.cast(acc, tf.float32)) cross_entropy = tf.reduce_mean(CE) learning_rate = 1e-4 optimizer = tf.train.AdamOptimizer(learning_rate,name='op_0')# get name of new layerweightName = Wname# define gradientsgradient = tf.gradients(cross_entropy, weightName)[0]# define training goaltraining_step = optimizer.minimize(cross_entropy)# get all uninitialized variablesuninitialized_vars = getUnititialized(tf.all_variables())# initialize all uninitialized variablesinit_new_vars_op = tf.initialize_variables(uninitialized_vars)# Start training for the next epochsession.run(init_new_vars_op)" }, { "code": null, "e": 3316, "s": 2872, "text": "The weights connected to the new last layer are best initialized with the already trained weights from the previous epoch. The weights connected to the newly added node can be randomly sampled from the old weights or a random distribution. This weight initialization leads to significantly better results than initializing all weights with random numbers or a small constant since it preserves all information learned in the previous epoch(s)." }, { "code": null, "e": 3963, "s": 3316, "text": "For all three weight initializations you can see a drop of performance whenever a new class is introduced. However, the drop for the first two initializations (constant and random initialization) is much bigger than when initializing with the old weights since the old weight initialization preserves already learned information and only the new class needs to be trained from the beginning on. When comparing the network performance of the old classes to the performance of the new class, one can see how the performance drop is mainly caused by the latter. The performance on the old classes is relatively untouched by a new class introduction." }, { "code": null, "e": 4219, "s": 3963, "text": "Looking at these graphs it seems as if adding a new class and growing the network has little to no effect on the already learned information on the old classes when preserving the old weights. But how does it effect the overall test accuracy (black line)?" }, { "code": null, "e": 4870, "s": 4219, "text": "To compare network growing to a conventional training with all classes in the data set from the beginning onward, I train the network under each condition a hundred times and then compare the distribution of the resulting 100 test accuracies of each condition. Additionally, I add a condition called No Growing in which the last layer stays static (always containing 10 nodes) and only the data set grows over time. This corresponds to initializing a bigger output layer from the beginning on to leave some room for new classes without having to change the network structure during training but limits the maximal number of classes that can be added." }, { "code": null, "e": 5449, "s": 4870, "text": "The normal network training (M=0.50, SD=0.01) is significantly better than both of the continuously learning conditions (growing (M=0.48, SD=0.01) and no growing(M=0.49, SD=0.01)), p<0.001. However, the normal training had a strong advantage since it could train on each example for each class five times. The two continuously learning networks had much less time to train on the classes that were introduced later on. In the most extreme case, the images of the class introduced last were only seen once by the networks as opposed to five times by the normally trained network." }, { "code": null, "e": 5714, "s": 5449, "text": "When training for longer after the last class has been introduced one can see how the two continuously learning networks catch up to the normal network after 30 epochs of post training, from then on no significant difference can be found anymore, F(2,297), p=0.06." } ]
How to repeat a string in JavaScript?
There are two ways to repeat a string in javascript. One way is to use string.repeat() method and the other way is to use the fill() method. Let's discuss them in detail. string.repeat(number); This method takes a number as a parameter and repeats the string those many numbers of times. Array(number).fill(string).join(''); This method initially takes a number and allocates those many numbers of spaces. It inserts the provided string in all those places and joins them to get a repeated string. In the following example, number 3 is sent into the repeat method as an argument. So the string is repeated for 3 times as shown in the output. Live Demo <html> <body> <script> const str = 'Tutorix, ' var res = str.repeat(3); document.write(res); </script> </body> </html> Tutorix, Tutorix, Tutorix, In the following example, Initially, an array is created with 3 slots and the provided string is kept in all those slots and later on, using join() method the elements in the array were joined and the output is displayed as shown. Live Demo <html> <body> <script> const str = 'Tutorialspoint ' var d = Array(3).fill(str).join('') document.write(d); </script> </body> </html> Tutorialspoint Tutorialspoint Tutorialspoint
[ { "code": null, "e": 1233, "s": 1062, "text": "There are two ways to repeat a string in javascript. One way is to use string.repeat() method and the other way is to use the fill() method. Let's discuss them in detail." }, { "code": null, "e": 1256, "s": 1233, "text": "string.repeat(number);" }, { "code": null, "e": 1350, "s": 1256, "text": "This method takes a number as a parameter and repeats the string those many numbers of times." }, { "code": null, "e": 1387, "s": 1350, "text": "Array(number).fill(string).join('');" }, { "code": null, "e": 1560, "s": 1387, "text": "This method initially takes a number and allocates those many numbers of spaces. It inserts the provided string in all those places and joins them to get a repeated string." }, { "code": null, "e": 1704, "s": 1560, "text": "In the following example, number 3 is sent into the repeat method as an argument. So the string is repeated for 3 times as shown in the output." }, { "code": null, "e": 1714, "s": 1704, "text": "Live Demo" }, { "code": null, "e": 1857, "s": 1714, "text": "<html>\n<body>\n <script>\n const str = 'Tutorix, '\n var res = str.repeat(3);\n document.write(res);\n </script>\n</body>\n</html>" }, { "code": null, "e": 1884, "s": 1857, "text": "Tutorix, Tutorix, Tutorix," }, { "code": null, "e": 2115, "s": 1884, "text": "In the following example, Initially, an array is created with 3 slots and the provided string is kept in all those slots and later on, using join() method the elements in the array were joined and the output is displayed as shown." }, { "code": null, "e": 2125, "s": 2115, "text": "Live Demo" }, { "code": null, "e": 2283, "s": 2125, "text": "<html>\n<body>\n <script>\n const str = 'Tutorialspoint '\n var d = Array(3).fill(str).join('')\n document.write(d);\n </script>\n</body>\n</html>" }, { "code": null, "e": 2328, "s": 2283, "text": "Tutorialspoint Tutorialspoint Tutorialspoint" } ]
Grouping Operators in LINQ
The operators put data into some groups based on a common shared attribute. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Operators { class Program { static void Main(string[] args) { List<int> numbers = new List<int>() { 35, 44, 200, 84, 3987, 4, 199, 329, 446, 208 }; IEnumerable<IGrouping<int, int>> query = from number in numbers group number by number % 2; foreach (var group in query) { Console.WriteLine(group.Key == 0 ? "\nEven numbers:" : "\nOdd numbers:"); foreach (int i in group) Console.WriteLine(i); } Console.ReadLine(); } } } Module Module1 Sub Main() Dim numbers As New System.Collections.Generic.List(Of Integer)( New Integer() {35, 44, 200, 84, 3987, 4, 199, 329, 446, 208}) Dim query = From number In numbers Group By Remainder = (number Mod 2) Into Group For Each group In query Console.WriteLine(If(group.Remainder = 0, vbCrLf &"Even numbers:", vbCrLf &"Odd numbers:")) For Each num In group.Group Console.WriteLine(num) Next Next Console.ReadLine() End Sub End Module When the above code in C# or VB is compiled and executed, it produces the following result − Odd numbers: 35 3987 199 329 Even numbers: 44 200 84 4 446 208 23 Lectures 1.5 hours Anadi Sharma 37 Lectures 13 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 1812, "s": 1736, "text": "The operators put data into some groups based on a common shared attribute." }, { "code": null, "e": 2509, "s": 1812, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Operators {\n class Program {\n static void Main(string[] args) {\n \n List<int> numbers = new List<int>() { 35, 44, 200, 84, 3987, 4, 199, 329, 446, 208 };\n\n IEnumerable<IGrouping<int, int>> query = from number in numbers \n\t\t group number by number % 2; \n\n foreach (var group in query) {\n Console.WriteLine(group.Key == 0 ? \"\\nEven numbers:\" : \"\\nOdd numbers:\");\n \n foreach (int i in group)\n Console.WriteLine(i);\n }\n\t\t\t\n Console.ReadLine(); \n }\n }\n}" }, { "code": null, "e": 3097, "s": 2509, "text": "Module Module1\n Sub Main()\n Dim numbers As New System.Collections.Generic.List(Of Integer)(\n New Integer() {35, 44, 200, 84, 3987, 4, 199, 329, 446, 208})\n\n Dim query = From number In numbers \n Group By Remainder = (number Mod 2) Into Group\n \n For Each group In query\n Console.WriteLine(If(group.Remainder = 0, vbCrLf &\"Even numbers:\", vbCrLf &\"Odd numbers:\"))\n\t\t \n For Each num In group.Group \n Console.WriteLine(num)\n Next \n\t\t \n Next\n\t \n Console.ReadLine()\n\t \n End Sub\n \nEnd Module" }, { "code": null, "e": 3190, "s": 3097, "text": "When the above code in C# or VB is compiled and executed, it produces the following result −" }, { "code": null, "e": 3266, "s": 3190, "text": "Odd numbers: \n35 \n3987 \n199 \n329 \n\nEven numbers: \n44 \n200 \n84 \n4 \n446 \n208\n" }, { "code": null, "e": 3301, "s": 3266, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3315, "s": 3301, "text": " Anadi Sharma" }, { "code": null, "e": 3349, "s": 3315, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 3367, "s": 3349, "text": " Trevoir Williams" }, { "code": null, "e": 3374, "s": 3367, "text": " Print" }, { "code": null, "e": 3385, "s": 3374, "text": " Add Notes" } ]
How to catch SyntaxError Exception in Python?
A SyntaxError occurs any time the parser finds source code it does not understand. This can be while importing a module, invoking exec, or calling eval(). Attributes of the exception can be used to find exactly what part of the input text caused the exception. We rewrite the given code to handle the exception and find its type try: print eval('six times seven') except SyntaxError, err: print 'Syntax error %s (%s-%s): %s' % \ (err.filename, err.lineno, err.offset, err.text) print err C:/Users/TutorialsPoint1/~.py Syntax error <string> (1-9): six times seven invalid syntax (<string>, line 1)
[ { "code": null, "e": 1323, "s": 1062, "text": "A SyntaxError occurs any time the parser finds source code it does not understand. This can be while importing a module, invoking exec, or calling eval(). Attributes of the exception can be used to find exactly what part of the input text caused the exception." }, { "code": null, "e": 1391, "s": 1323, "text": "We rewrite the given code to handle the exception and find its type" }, { "code": null, "e": 1550, "s": 1391, "text": "try:\nprint eval('six times seven')\nexcept SyntaxError, err:\nprint 'Syntax error %s (%s-%s): %s' % \\\n(err.filename, err.lineno, err.offset, err.text)\nprint err" }, { "code": null, "e": 1659, "s": 1550, "text": "C:/Users/TutorialsPoint1/~.py\nSyntax error <string> (1-9): six times seven\ninvalid syntax (<string>, line 1)" } ]
Tensorflow GPU installation made easy: Ubuntu Version | by Harveen Singh Chadha | Towards Data Science
Installing Tensorflow GPU on ubuntu is a challenge with the correct versions of cuda and cudnn. A year back, I wrote an article that discussed about installation of Tensorflow GPU with conda instead of pip with a single line command. Here is a link to that article. towardsdatascience.com This article has been read more than 250k times, but still some Ubuntu users are facing problems running Tensorflow GPU with correct versions of CUDA and CUDNN. I can understand the title of the article can be misleading but believe me if you follow step by step then proper installation on ubuntu even is easy. Check GPU compatibility with Tensorflow GPU!Switching on to Graphic CardChecking CUDA compatibility with Graphic CardDetermine Version of Tensorflow according to CUDADownload CUDA toolkitInstall CUDADownload cudnn and installVerify cudnn installationInstall Tensorflow-gpu using pip in a new enviroment using CondaVerify tensorflow is using GPU. Check GPU compatibility with Tensorflow GPU! Switching on to Graphic Card Checking CUDA compatibility with Graphic Card Determine Version of Tensorflow according to CUDA Download CUDA toolkit Install CUDA Download cudnn and install Verify cudnn installation Install Tensorflow-gpu using pip in a new enviroment using Conda Verify tensorflow is using GPU. Check GPU compatibility with Tensorflow GPU (From Here)Switching on to Graphic CardGo to Menu > Search for “Driver Settings” > Click on Additional Drivers Check GPU compatibility with Tensorflow GPU (From Here) Switching on to Graphic CardGo to Menu > Search for “Driver Settings” > Click on Additional Drivers Select NVIDIA Binary Driver which is Version 384 in my case. This is very important to note down because this driver version will help us in determining the CUDA version. Now if you will go to a terminal and type nvidia-smi you will get the driver version also. 3. Check the CUDA compatibility with your driver version from here. In our case since driver version was 384.130 so we can install CUDA 9.0 only 4. Determine version of Tensorflow according to CUDA After this step you should be very clear in your for 3 things:i) What Tensorflow Version you are going to install (tensorflow-gpu 1.12.0)ii) What CUDA version you are going to install (9.0)iii) What cudnn version you are going to install. (7) NOTE: The answers to these questions will change based on what driver version you are using currently. If you know answer to these 3 questions then you can already smell victory. 5. Download CUDA toolkitGo to this link and download the specific version of CUDA you are looking for you found in step 4 (CUDA 9.0 in this case) 6. CUDA installation You will get software licence, long press Enter. Now accept everything except the driver install. After installation you will recieve message: Now you have to enter certain paths in bashrc file so that you can access cuda. Open a terminal and run the commands sudo susudo gedit ~/.bashrc (Add following lines to end of the file) export PATH=/usr/local/cuda/bin:/usr/lib/:$PATHexport LD_LIBRARY_PATH=/usr/local/cuda/lib64:/usr/lib/nvidia-384:$LD_LIBRARY_PATHexport CUDA_HOME=/usr/local/cuda-9.0 Save and close the file and source the bashrc file for changes to take place. source ~/.bashrc Now open a terminal and write the command nvcc -V You will get the version of CUDA running. 6. Verify CUDA installation (optional): If you are happy with nvcc version then you can skip this step. Open a terminal and run these commands: cd /usr/local/cuda/samples/1_Utilities/deviceQuerysudo make./deviceQuery 7. Download cudnn compatible with CUDA and install Go to Link and install cudnn. Remember here download the version of cudnn which is compatible with CUDA which is 7 in this case. You will need a signup to NVIDIA site to download this. Install the cudnn packages in the following order runtime > developer > docs. Use the command sudo dpkg -i <package_name> 8. Verify cudnn installation To verify we cudnn installation, we will test one of the cudnn samples. Open a terminal and fire these commands: cp -r /usr/src/cudnn_samples_v7/ $HOMEcd $HOME/cudnn_samples_v7/mnistCUDNNmake clean && make./mnistCUDNN If cudnn is installed properly you will see a message like: Tests Passed 9. Download Miniconda and install. Remember to install it without root. Create a environment now where our tensorflow-gpu will be installed. conda create --name tf1 python=3.6 After executing this command a new environment named tf1 will be installed with python version of 3.6. Now activate the environment and execute the command to install tensorflow-gpu of the specific version we found out in step 4. source activate tf1pip install tensorflow-gpu==1.12 10. To test your tensorflow installation follow these steps: Open Terminal and activate environment using ‘source activate tf1’.Go to python console using ‘python’ Open Terminal and activate environment using ‘source activate tf1’. Go to python console using ‘python’ import tensorflow as tfsess = tf.Session(config=tf.ConfigProto(log_device_placement=True)) Now if you are able to see your GPU information in the terminal then CONGRATULATIONS, you have finally done it! Thanks for your time. Please connect with me on LinkedIn for further updates and articles on Data Science.
[ { "code": null, "e": 437, "s": 171, "text": "Installing Tensorflow GPU on ubuntu is a challenge with the correct versions of cuda and cudnn. A year back, I wrote an article that discussed about installation of Tensorflow GPU with conda instead of pip with a single line command. Here is a link to that article." }, { "code": null, "e": 460, "s": 437, "text": "towardsdatascience.com" }, { "code": null, "e": 772, "s": 460, "text": "This article has been read more than 250k times, but still some Ubuntu users are facing problems running Tensorflow GPU with correct versions of CUDA and CUDNN. I can understand the title of the article can be misleading but believe me if you follow step by step then proper installation on ubuntu even is easy." }, { "code": null, "e": 1118, "s": 772, "text": "Check GPU compatibility with Tensorflow GPU!Switching on to Graphic CardChecking CUDA compatibility with Graphic CardDetermine Version of Tensorflow according to CUDADownload CUDA toolkitInstall CUDADownload cudnn and installVerify cudnn installationInstall Tensorflow-gpu using pip in a new enviroment using CondaVerify tensorflow is using GPU." }, { "code": null, "e": 1163, "s": 1118, "text": "Check GPU compatibility with Tensorflow GPU!" }, { "code": null, "e": 1192, "s": 1163, "text": "Switching on to Graphic Card" }, { "code": null, "e": 1238, "s": 1192, "text": "Checking CUDA compatibility with Graphic Card" }, { "code": null, "e": 1288, "s": 1238, "text": "Determine Version of Tensorflow according to CUDA" }, { "code": null, "e": 1310, "s": 1288, "text": "Download CUDA toolkit" }, { "code": null, "e": 1323, "s": 1310, "text": "Install CUDA" }, { "code": null, "e": 1350, "s": 1323, "text": "Download cudnn and install" }, { "code": null, "e": 1376, "s": 1350, "text": "Verify cudnn installation" }, { "code": null, "e": 1441, "s": 1376, "text": "Install Tensorflow-gpu using pip in a new enviroment using Conda" }, { "code": null, "e": 1473, "s": 1441, "text": "Verify tensorflow is using GPU." }, { "code": null, "e": 1628, "s": 1473, "text": "Check GPU compatibility with Tensorflow GPU (From Here)Switching on to Graphic CardGo to Menu > Search for “Driver Settings” > Click on Additional Drivers" }, { "code": null, "e": 1684, "s": 1628, "text": "Check GPU compatibility with Tensorflow GPU (From Here)" }, { "code": null, "e": 1784, "s": 1684, "text": "Switching on to Graphic CardGo to Menu > Search for “Driver Settings” > Click on Additional Drivers" }, { "code": null, "e": 1955, "s": 1784, "text": "Select NVIDIA Binary Driver which is Version 384 in my case. This is very important to note down because this driver version will help us in determining the CUDA version." }, { "code": null, "e": 2046, "s": 1955, "text": "Now if you will go to a terminal and type nvidia-smi you will get the driver version also." }, { "code": null, "e": 2114, "s": 2046, "text": "3. Check the CUDA compatibility with your driver version from here." }, { "code": null, "e": 2191, "s": 2114, "text": "In our case since driver version was 384.130 so we can install CUDA 9.0 only" }, { "code": null, "e": 2244, "s": 2191, "text": "4. Determine version of Tensorflow according to CUDA" }, { "code": null, "e": 2487, "s": 2244, "text": "After this step you should be very clear in your for 3 things:i) What Tensorflow Version you are going to install (tensorflow-gpu 1.12.0)ii) What CUDA version you are going to install (9.0)iii) What cudnn version you are going to install. (7)" }, { "code": null, "e": 2590, "s": 2487, "text": "NOTE: The answers to these questions will change based on what driver version you are using currently." }, { "code": null, "e": 2666, "s": 2590, "text": "If you know answer to these 3 questions then you can already smell victory." }, { "code": null, "e": 2812, "s": 2666, "text": "5. Download CUDA toolkitGo to this link and download the specific version of CUDA you are looking for you found in step 4 (CUDA 9.0 in this case)" }, { "code": null, "e": 2833, "s": 2812, "text": "6. CUDA installation" }, { "code": null, "e": 2931, "s": 2833, "text": "You will get software licence, long press Enter. Now accept everything except the driver install." }, { "code": null, "e": 2976, "s": 2931, "text": "After installation you will recieve message:" }, { "code": null, "e": 3093, "s": 2976, "text": "Now you have to enter certain paths in bashrc file so that you can access cuda. Open a terminal and run the commands" }, { "code": null, "e": 3121, "s": 3093, "text": "sudo susudo gedit ~/.bashrc" }, { "code": null, "e": 3162, "s": 3121, "text": "(Add following lines to end of the file)" }, { "code": null, "e": 3327, "s": 3162, "text": "export PATH=/usr/local/cuda/bin:/usr/lib/:$PATHexport LD_LIBRARY_PATH=/usr/local/cuda/lib64:/usr/lib/nvidia-384:$LD_LIBRARY_PATHexport CUDA_HOME=/usr/local/cuda-9.0" }, { "code": null, "e": 3405, "s": 3327, "text": "Save and close the file and source the bashrc file for changes to take place." }, { "code": null, "e": 3422, "s": 3405, "text": "source ~/.bashrc" }, { "code": null, "e": 3464, "s": 3422, "text": "Now open a terminal and write the command" }, { "code": null, "e": 3472, "s": 3464, "text": "nvcc -V" }, { "code": null, "e": 3514, "s": 3472, "text": "You will get the version of CUDA running." }, { "code": null, "e": 3618, "s": 3514, "text": "6. Verify CUDA installation (optional): If you are happy with nvcc version then you can skip this step." }, { "code": null, "e": 3658, "s": 3618, "text": "Open a terminal and run these commands:" }, { "code": null, "e": 3731, "s": 3658, "text": "cd /usr/local/cuda/samples/1_Utilities/deviceQuerysudo make./deviceQuery" }, { "code": null, "e": 3782, "s": 3731, "text": "7. Download cudnn compatible with CUDA and install" }, { "code": null, "e": 3967, "s": 3782, "text": "Go to Link and install cudnn. Remember here download the version of cudnn which is compatible with CUDA which is 7 in this case. You will need a signup to NVIDIA site to download this." }, { "code": null, "e": 4061, "s": 3967, "text": "Install the cudnn packages in the following order runtime > developer > docs. Use the command" }, { "code": null, "e": 4089, "s": 4061, "text": "sudo dpkg -i <package_name>" }, { "code": null, "e": 4118, "s": 4089, "text": "8. Verify cudnn installation" }, { "code": null, "e": 4231, "s": 4118, "text": "To verify we cudnn installation, we will test one of the cudnn samples. Open a terminal and fire these commands:" }, { "code": null, "e": 4337, "s": 4231, "text": "cp -r /usr/src/cudnn_samples_v7/ $HOMEcd $HOME/cudnn_samples_v7/mnistCUDNNmake clean && make./mnistCUDNN" }, { "code": null, "e": 4410, "s": 4337, "text": "If cudnn is installed properly you will see a message like: Tests Passed" }, { "code": null, "e": 4482, "s": 4410, "text": "9. Download Miniconda and install. Remember to install it without root." }, { "code": null, "e": 4551, "s": 4482, "text": "Create a environment now where our tensorflow-gpu will be installed." }, { "code": null, "e": 4587, "s": 4551, "text": "conda create --name tf1 python=3.6" }, { "code": null, "e": 4817, "s": 4587, "text": "After executing this command a new environment named tf1 will be installed with python version of 3.6. Now activate the environment and execute the command to install tensorflow-gpu of the specific version we found out in step 4." }, { "code": null, "e": 4869, "s": 4817, "text": "source activate tf1pip install tensorflow-gpu==1.12" }, { "code": null, "e": 4930, "s": 4869, "text": "10. To test your tensorflow installation follow these steps:" }, { "code": null, "e": 5033, "s": 4930, "text": "Open Terminal and activate environment using ‘source activate tf1’.Go to python console using ‘python’" }, { "code": null, "e": 5101, "s": 5033, "text": "Open Terminal and activate environment using ‘source activate tf1’." }, { "code": null, "e": 5137, "s": 5101, "text": "Go to python console using ‘python’" }, { "code": null, "e": 5228, "s": 5137, "text": "import tensorflow as tfsess = tf.Session(config=tf.ConfigProto(log_device_placement=True))" }, { "code": null, "e": 5340, "s": 5228, "text": "Now if you are able to see your GPU information in the terminal then CONGRATULATIONS, you have finally done it!" } ]
How do I find the location of my Python site-packages directory?
You can find the location of Python site-packages directory by using the site module in the following way − >>> import site >>> site.getsitepackages() ['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] If you want the per user site packages directory, then run the following code in your shell − $ python -m site --user-site
[ { "code": null, "e": 1170, "s": 1062, "text": "You can find the location of Python site-packages directory by using the site module in the following way −" }, { "code": null, "e": 1292, "s": 1170, "text": ">>> import site\n>>> site.getsitepackages()\n['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']" }, { "code": null, "e": 1386, "s": 1292, "text": "If you want the per user site packages directory, then run the following code in your shell −" }, { "code": null, "e": 1415, "s": 1386, "text": "$ python -m site --user-site" } ]
Classification of Hotel Cancellations Using KNN and SMOTE | by Michael Grogan | Towards Data Science
In this particular example, the KNN algorithm is used to classify hotel bookings in terms of cancellation risk (1 = model predicts that the customer will cancel their booking, 0 = customer is not predicted to cancel their booking). Given that this dataset is unbalanced, i.e. there are more 0s (non-cancellations) than 1s (cancellations), the Synthetic Minority Oversampling Technique (SMOTE) is used to balance the classes in order to apply the KNN algorithm. Given the uneven nature of the dataset, it is necessary to oversample the minor class (1 = cancellations) in order to ensure that the KNN results are not skewed towards the major class. This can be done by using the SMOTE oversampling technique. After having imported and scaled the data using MinMaxScaler, SMOTE can be imported from the imblearn library. Counter is imported for the purposes of summarizing the class distributions. import imblearnprint(imblearn.__version__)from imblearn.over_sampling import SMOTEfrom collections import Counter Firstly, a train-test split is invoked to separate the data into training and validation data. x1_train, x1_val, y1_train, y1_val = train_test_split(x_scaled, y1, random_state=0) The original class distribution is comprised of 0: 21672, 1: 8373. >>> counter = Counter(y_train)>>> print(counter)Counter({0: 21672, 1: 8373}) However, after applying the SMOTE oversampling technique, we now see that the number of observations in each class are equal. >>> oversample = SMOTE()>>> x_train, y_train = oversample.fit_resample(x_train, y_train)>>> counter = Counter(y_train)>>> print(counter)Counter({1: 21672, 0: 21672}) The model is configured as follows: # KNNknn = KNeighborsClassifier(n_neighbors=10)model=knn.fit(x1_train, y1_train)pred = model.predict(x1_val)predprint("Training set score: {:.2f}".format(knn.score(x1_train, y1_train)))print("Validation set score: {:.2f}".format(knn.score(x1_val, y1_val)))# KNN Plotmglearn.plots.plot_knn_classification(n_neighbors=10)plt.show() The training and test set scores are generated: Training set score: 0.88Validation set score: 0.46 Here is a visual of the training classes versus test predictions as illustrated by the KNN model: Here is a breakdown of model performance according to a confusion matrix: [[2286 4980] [ 440 2309]] precision recall f1-score support 0 0.84 0.31 0.46 7266 1 0.32 0.84 0.46 2749 accuracy 0.46 10015 macro avg 0.58 0.58 0.46 10015weighted avg 0.70 0.46 0.46 10015 While overall accuracy is quite low at 46%, recall according to the f1-score is reasonably good at 84%. When working with classification data, one must also pay attention to the precision versus recall readings, as opposed to simply overall accuracy. - Precision = ((True Positive)/(True Positive + False Positive))- Recall = ((True Positive)/(True Positive + False Negative)) The two readings are often at odds with each other, i.e. it is often not possible to increase precision without reducing recall, and vice versa. An assessment as to the ideal metric to use depends in large part on the specific data under analysis. For example, cancer detection screenings that have false negatives (i.e. indicating patients do not have cancer when in fact they do), is a big no-no. Under this scenario, recall is the ideal metric. However, for emails — one might prefer to avoid false positives, i.e. sending an important email to the spam folder when in fact it is legitimate. The f1-score takes both precision and recall into account when devising a more general score. Which would be more important for predicting hotel cancellations? Well, from the point of view of a hotel — they would likely wish to identify customers who are ultimately going to cancel their booking with greater accuracy — this allows the hotel to better allocate rooms and resources. Identifying customers who are not going to cancel their bookings may not necessarily add value to the hotel’s analysis, as the hotel knows that a significant proportion of customers will ultimately follow through with their bookings in any case. Let us see how the results look when the model makes predictions on H2 (the test set). Here, we see that the f1-score accuracy has increased slightly to 52%. [[12569 33659] [ 4591 28511]] precision recall f1-score support 0 0.73 0.27 0.40 46228 1 0.46 0.86 0.60 33102 accuracy 0.52 79330 macro avg 0.60 0.57 0.50 79330weighted avg 0.62 0.52 0.48 79330 However, the recall for the cancellation class (1) stands at 86%. As mentioned, precision and recall are often at odds with each other simply due to the fact that false positives tend to increase recall, while false negatives tend to increase precision. Assuming that the hotel would like to maximise recall (i.e. tolerate a certain number of false positives while at the same time identifying all customers who will cancel their booking), then this model meets that criteria. Of all customers who cancel their booking, this model correctly identifies 86% of those customers. While a higher recall is assumed to be a better way to judge this model, this cannot necessarily come at the expense of lower accuracy. If recall is penalising false negatives, then it is also favouring false positives — having too many false positives defeats the purpose of the model — as this is essentially assuming that all customers will cancel, which is not the case. In this regard, accuracy and recall would ideally be maximised. For instance, an XGBoost model demonstrated a recall of 94% with an f1-score accuracy of 55% — both of which were slightly higher than in this example. In this example, we have examined how to use KNN as a classification algorithm, as well as the importance of precision versus recall in judging model performance. Many thanks for your time, and the associated GitHub repository for this example can be found here. Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice in any way. Antonio, Almedia and Nunes (2019). Hotel Booking Demand Datasets GitHub repository (Msanjayds): Cross-Validation calculation Machine Learning Mastery: SMOTE Oversampling for Imbalanced Classification with Python
[ { "code": null, "e": 404, "s": 172, "text": "In this particular example, the KNN algorithm is used to classify hotel bookings in terms of cancellation risk (1 = model predicts that the customer will cancel their booking, 0 = customer is not predicted to cancel their booking)." }, { "code": null, "e": 633, "s": 404, "text": "Given that this dataset is unbalanced, i.e. there are more 0s (non-cancellations) than 1s (cancellations), the Synthetic Minority Oversampling Technique (SMOTE) is used to balance the classes in order to apply the KNN algorithm." }, { "code": null, "e": 819, "s": 633, "text": "Given the uneven nature of the dataset, it is necessary to oversample the minor class (1 = cancellations) in order to ensure that the KNN results are not skewed towards the major class." }, { "code": null, "e": 879, "s": 819, "text": "This can be done by using the SMOTE oversampling technique." }, { "code": null, "e": 1067, "s": 879, "text": "After having imported and scaled the data using MinMaxScaler, SMOTE can be imported from the imblearn library. Counter is imported for the purposes of summarizing the class distributions." }, { "code": null, "e": 1181, "s": 1067, "text": "import imblearnprint(imblearn.__version__)from imblearn.over_sampling import SMOTEfrom collections import Counter" }, { "code": null, "e": 1276, "s": 1181, "text": "Firstly, a train-test split is invoked to separate the data into training and validation data." }, { "code": null, "e": 1360, "s": 1276, "text": "x1_train, x1_val, y1_train, y1_val = train_test_split(x_scaled, y1, random_state=0)" }, { "code": null, "e": 1427, "s": 1360, "text": "The original class distribution is comprised of 0: 21672, 1: 8373." }, { "code": null, "e": 1504, "s": 1427, "text": ">>> counter = Counter(y_train)>>> print(counter)Counter({0: 21672, 1: 8373})" }, { "code": null, "e": 1630, "s": 1504, "text": "However, after applying the SMOTE oversampling technique, we now see that the number of observations in each class are equal." }, { "code": null, "e": 1796, "s": 1630, "text": ">>> oversample = SMOTE()>>> x_train, y_train = oversample.fit_resample(x_train, y_train)>>> counter = Counter(y_train)>>> print(counter)Counter({1: 21672, 0: 21672})" }, { "code": null, "e": 1832, "s": 1796, "text": "The model is configured as follows:" }, { "code": null, "e": 2162, "s": 1832, "text": "# KNNknn = KNeighborsClassifier(n_neighbors=10)model=knn.fit(x1_train, y1_train)pred = model.predict(x1_val)predprint(\"Training set score: {:.2f}\".format(knn.score(x1_train, y1_train)))print(\"Validation set score: {:.2f}\".format(knn.score(x1_val, y1_val)))# KNN Plotmglearn.plots.plot_knn_classification(n_neighbors=10)plt.show()" }, { "code": null, "e": 2210, "s": 2162, "text": "The training and test set scores are generated:" }, { "code": null, "e": 2261, "s": 2210, "text": "Training set score: 0.88Validation set score: 0.46" }, { "code": null, "e": 2359, "s": 2261, "text": "Here is a visual of the training classes versus test predictions as illustrated by the KNN model:" }, { "code": null, "e": 2433, "s": 2359, "text": "Here is a breakdown of model performance according to a confusion matrix:" }, { "code": null, "e": 2777, "s": 2433, "text": "[[2286 4980] [ 440 2309]] precision recall f1-score support 0 0.84 0.31 0.46 7266 1 0.32 0.84 0.46 2749 accuracy 0.46 10015 macro avg 0.58 0.58 0.46 10015weighted avg 0.70 0.46 0.46 10015" }, { "code": null, "e": 2881, "s": 2777, "text": "While overall accuracy is quite low at 46%, recall according to the f1-score is reasonably good at 84%." }, { "code": null, "e": 3028, "s": 2881, "text": "When working with classification data, one must also pay attention to the precision versus recall readings, as opposed to simply overall accuracy." }, { "code": null, "e": 3154, "s": 3028, "text": "- Precision = ((True Positive)/(True Positive + False Positive))- Recall = ((True Positive)/(True Positive + False Negative))" }, { "code": null, "e": 3299, "s": 3154, "text": "The two readings are often at odds with each other, i.e. it is often not possible to increase precision without reducing recall, and vice versa." }, { "code": null, "e": 3602, "s": 3299, "text": "An assessment as to the ideal metric to use depends in large part on the specific data under analysis. For example, cancer detection screenings that have false negatives (i.e. indicating patients do not have cancer when in fact they do), is a big no-no. Under this scenario, recall is the ideal metric." }, { "code": null, "e": 3749, "s": 3602, "text": "However, for emails — one might prefer to avoid false positives, i.e. sending an important email to the spam folder when in fact it is legitimate." }, { "code": null, "e": 3843, "s": 3749, "text": "The f1-score takes both precision and recall into account when devising a more general score." }, { "code": null, "e": 3909, "s": 3843, "text": "Which would be more important for predicting hotel cancellations?" }, { "code": null, "e": 4377, "s": 3909, "text": "Well, from the point of view of a hotel — they would likely wish to identify customers who are ultimately going to cancel their booking with greater accuracy — this allows the hotel to better allocate rooms and resources. Identifying customers who are not going to cancel their bookings may not necessarily add value to the hotel’s analysis, as the hotel knows that a significant proportion of customers will ultimately follow through with their bookings in any case." }, { "code": null, "e": 4464, "s": 4377, "text": "Let us see how the results look when the model makes predictions on H2 (the test set)." }, { "code": null, "e": 4535, "s": 4464, "text": "Here, we see that the f1-score accuracy has increased slightly to 52%." }, { "code": null, "e": 4883, "s": 4535, "text": "[[12569 33659] [ 4591 28511]] precision recall f1-score support 0 0.73 0.27 0.40 46228 1 0.46 0.86 0.60 33102 accuracy 0.52 79330 macro avg 0.60 0.57 0.50 79330weighted avg 0.62 0.52 0.48 79330" }, { "code": null, "e": 5137, "s": 4883, "text": "However, the recall for the cancellation class (1) stands at 86%. As mentioned, precision and recall are often at odds with each other simply due to the fact that false positives tend to increase recall, while false negatives tend to increase precision." }, { "code": null, "e": 5360, "s": 5137, "text": "Assuming that the hotel would like to maximise recall (i.e. tolerate a certain number of false positives while at the same time identifying all customers who will cancel their booking), then this model meets that criteria." }, { "code": null, "e": 5459, "s": 5360, "text": "Of all customers who cancel their booking, this model correctly identifies 86% of those customers." }, { "code": null, "e": 5595, "s": 5459, "text": "While a higher recall is assumed to be a better way to judge this model, this cannot necessarily come at the expense of lower accuracy." }, { "code": null, "e": 5834, "s": 5595, "text": "If recall is penalising false negatives, then it is also favouring false positives — having too many false positives defeats the purpose of the model — as this is essentially assuming that all customers will cancel, which is not the case." }, { "code": null, "e": 6050, "s": 5834, "text": "In this regard, accuracy and recall would ideally be maximised. For instance, an XGBoost model demonstrated a recall of 94% with an f1-score accuracy of 55% — both of which were slightly higher than in this example." }, { "code": null, "e": 6213, "s": 6050, "text": "In this example, we have examined how to use KNN as a classification algorithm, as well as the importance of precision versus recall in judging model performance." }, { "code": null, "e": 6313, "s": 6213, "text": "Many thanks for your time, and the associated GitHub repository for this example can be found here." }, { "code": null, "e": 6541, "s": 6313, "text": "Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice in any way." }, { "code": null, "e": 6606, "s": 6541, "text": "Antonio, Almedia and Nunes (2019). Hotel Booking Demand Datasets" }, { "code": null, "e": 6666, "s": 6606, "text": "GitHub repository (Msanjayds): Cross-Validation calculation" } ]
Python program to find difference between two timestamps
Suppose we have two times in this format "Day dd Mon yyyy hh:mm:ss +/-xxxx", where Day is three letter day whose first letter is in uppercase. Mon is the name of month in three letters and finally + or - xxxx represents the timezone for example +0530 indicates it is 5 hours 30 minutes more than GMT (other formats like dd, hh, mm, ss are self-explanatory). We have to find absolute difference between two timestamps in seconds. To solve this using python we will use the datetime library. There is a function called strptime() this will convert string formatted date to datetime object. There are few format specifiers like below − %a indicates the day in three letter format %d indicates day in numeric format %b indicates month in three letter format %Y indicates year in yyyy format %H indicates hour in hh format %M indicates minutes in mm format %S indicates seconds in ss format %z indicates the timezone in +/- xxxx format So, if the input is like t1 = "Thu 15 Jul 2021 15:10:17 +0530" t2 = "Thu 15 Jul 2021 20:25:29 +0720", then the output will be 12312 To solve this, we will follow these steps − t1 := change first time format from given string to above mentioned format t2 := change second time format from given string to above mentioned format return difference between t1 and t2 in seconds Let us see the following implementation to get better understanding − from datetime import datetime def solve(t1, t2): t1 = datetime.strptime(t1, "%a %d %b %Y %H:%M:%S %z") t2 = datetime.strptime(t2, "%a %d %b %Y %H:%M:%S %z") return abs(int((t1-t2).total_seconds())) t1 = "Thu 15 Jul 2021 15:10:17 +0530" t2 = "Thu 15 Jul 2021 20:25:29 +0720" print(solve(t1, t2)) "Thu 15 Jul 2021 15:10:17 +0530", "Thu 15 Jul 2021 20:25:29 +0720" 12312
[ { "code": null, "e": 1491, "s": 1062, "text": "Suppose we have two times in this format \"Day dd Mon yyyy hh:mm:ss +/-xxxx\", where Day is three letter day whose first letter is in uppercase. Mon is the name of month in three letters and finally + or - xxxx represents the timezone for example +0530 indicates it is 5 hours 30 minutes more than GMT (other formats like dd, hh, mm, ss are self-explanatory). We have to find absolute difference between two timestamps in seconds." }, { "code": null, "e": 1695, "s": 1491, "text": "To solve this using python we will use the datetime library. There is a function called strptime() this will convert string formatted date to datetime object. There are few format specifiers like below −" }, { "code": null, "e": 1739, "s": 1695, "text": "%a indicates the day in three letter format" }, { "code": null, "e": 1774, "s": 1739, "text": "%d indicates day in numeric format" }, { "code": null, "e": 1816, "s": 1774, "text": "%b indicates month in three letter format" }, { "code": null, "e": 1849, "s": 1816, "text": "%Y indicates year in yyyy format" }, { "code": null, "e": 1880, "s": 1849, "text": "%H indicates hour in hh format" }, { "code": null, "e": 1914, "s": 1880, "text": "%M indicates minutes in mm format" }, { "code": null, "e": 1948, "s": 1914, "text": "%S indicates seconds in ss format" }, { "code": null, "e": 1993, "s": 1948, "text": "%z indicates the timezone in +/- xxxx format" }, { "code": null, "e": 2125, "s": 1993, "text": "So, if the input is like t1 = \"Thu 15 Jul 2021 15:10:17 +0530\" t2 = \"Thu 15 Jul 2021 20:25:29 +0720\", then the output will be 12312" }, { "code": null, "e": 2169, "s": 2125, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 2244, "s": 2169, "text": "t1 := change first time format from given string to above mentioned format" }, { "code": null, "e": 2320, "s": 2244, "text": "t2 := change second time format from given string to above mentioned format" }, { "code": null, "e": 2367, "s": 2320, "text": "return difference between t1 and t2 in seconds" }, { "code": null, "e": 2437, "s": 2367, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2743, "s": 2437, "text": "from datetime import datetime\n\ndef solve(t1, t2):\n t1 = datetime.strptime(t1, \"%a %d %b %Y %H:%M:%S %z\")\n t2 = datetime.strptime(t2, \"%a %d %b %Y %H:%M:%S %z\")\n return abs(int((t1-t2).total_seconds()))\n\nt1 = \"Thu 15 Jul 2021 15:10:17 +0530\"\nt2 = \"Thu 15 Jul 2021 20:25:29 +0720\"\nprint(solve(t1, t2))" }, { "code": null, "e": 2810, "s": 2743, "text": "\"Thu 15 Jul 2021 15:10:17 +0530\", \"Thu 15 Jul 2021 20:25:29 +0720\"" }, { "code": null, "e": 2816, "s": 2810, "text": "12312" } ]
Program to find correlation coefficient in C++
In this tutorial, we will be discussing a program to find correlation coefficient. For this we will be provided with two arrays. Our task is to find the correlation coefficient denoting the strength of the relation between the given values. Live Demo #include<bits/stdc++.h> using namespace std; //function returning correlation coefficient float find_coefficient(int X[], int Y[], int n){ int sum_X = 0, sum_Y = 0, sum_XY = 0; int squareSum_X = 0, squareSum_Y = 0; for (int i = 0; i < n; i++){ sum_X = sum_X + X[i]; sum_Y = sum_Y + Y[i]; sum_XY = sum_XY + X[i] * Y[i]; squareSum_X = squareSum_X + X[i] * X[i]; squareSum_Y = squareSum_Y + Y[i] * Y[i]; } float corr = (float)(n * sum_XY - sum_X * sum_Y) / sqrt((n * squareSum_X - sum_X * sum_X) * (n * squareSum_Y - sum_Y * sum_Y)); return corr; } int main(){ int X[] = {15, 18, 21, 24, 27}; int Y[] = {25, 25, 27, 31, 32}; int n = sizeof(X)/sizeof(X[0]); cout<<find_coefficient(X, Y, n); return 0; } 0.953463
[ { "code": null, "e": 1145, "s": 1062, "text": "In this tutorial, we will be discussing a program to find correlation coefficient." }, { "code": null, "e": 1303, "s": 1145, "text": "For this we will be provided with two arrays. Our task is to find the correlation coefficient denoting the strength of the relation between the given values." }, { "code": null, "e": 1314, "s": 1303, "text": " Live Demo" }, { "code": null, "e": 2076, "s": 1314, "text": "#include<bits/stdc++.h>\nusing namespace std;\n//function returning correlation coefficient\nfloat find_coefficient(int X[], int Y[], int n){\n int sum_X = 0, sum_Y = 0, sum_XY = 0;\n int squareSum_X = 0, squareSum_Y = 0;\n for (int i = 0; i < n; i++){\n sum_X = sum_X + X[i];\n sum_Y = sum_Y + Y[i];\n sum_XY = sum_XY + X[i] * Y[i];\n squareSum_X = squareSum_X + X[i] * X[i];\n squareSum_Y = squareSum_Y + Y[i] * Y[i];\n }\n float corr = (float)(n * sum_XY - sum_X * sum_Y) / sqrt((n * squareSum_X - sum_X * sum_X) * (n * squareSum_Y - sum_Y * sum_Y));\n return corr;\n}\nint main(){\n int X[] = {15, 18, 21, 24, 27};\n int Y[] = {25, 25, 27, 31, 32};\n int n = sizeof(X)/sizeof(X[0]);\n cout<<find_coefficient(X, Y, n);\n return 0;\n}" }, { "code": null, "e": 2085, "s": 2076, "text": "0.953463" } ]
How to change autopct text color to be white in a pie chart in Matplotlib?
To change the autopct text color to be white in a pie chart in Matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Make a list of hours, activities, and colors to plot pie chart. Make a list of '.Text' instances for the numeric labels, while making the pie chart. Iterate autotexts and set the color of autotext as white. To display the figure, use show() method. import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True plt.figure() hours = [8, 1, 11, 4] activities = ['sleeping', 'exercise', 'studying', 'working'] colors = ["grey", "green", "orange", "blue"] _, _, autotexts = plt.pie(hours, labels=activities, colors=colors, autopct="%.2f") for ins in autotexts: ins.set_color('white') plt.show()
[ { "code": null, "e": 1171, "s": 1062, "text": "To change the autopct text color to be white in a pie chart in Matplotlib, we can take the following steps −" }, { "code": null, "e": 1247, "s": 1171, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1311, "s": 1247, "text": "Make a list of hours,\nactivities, and colors to plot pie chart." }, { "code": null, "e": 1396, "s": 1311, "text": "Make a list of '.Text' instances for the numeric labels, while making the pie chart." }, { "code": null, "e": 1454, "s": 1396, "text": "Iterate autotexts and set the color of autotext as white." }, { "code": null, "e": 1496, "s": 1454, "text": "To display the figure, use show() method." }, { "code": null, "e": 1904, "s": 1496, "text": "import matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nplt.figure()\n\nhours = [8, 1, 11, 4]\nactivities = ['sleeping', 'exercise', 'studying', 'working']\ncolors = [\"grey\", \"green\", \"orange\", \"blue\"]\n_, _, autotexts = plt.pie(hours, labels=activities, colors=colors, autopct=\"%.2f\")\n\nfor ins in autotexts:\n ins.set_color('white')\n\nplt.show()" } ]
Kedro — A Python Framework for Reproducible Data Science Project | by Khuyen Tran | Towards Data Science
Have you ever passed your data to a list of functions and classes without knowing for sure how the output is like? You might try to save the data then check it in your Jupyter Notebook to make sure the output is as you expected. This approach works, but it is cumbersome. Another common issue is that it’s hard to understand the relationships between functions when looking at a Python script that contains both the code to create and execute functions. Your code looks even more complex and hard to follow as the project grows. Wouldn’t it be nicer if you can visualize how the inputs and outputs of different functions are connected like below? That is when Kedro comes in handy. Kedro is an open-source Python framework for creating reproducible, maintainable, and modular data science code. It borrows concepts from software engineering best-practice and applies them to machine learning code. Kedro allows you to: Create a data science from a cookie-cutter templateCreate a data science pipelineSlice a pipelineModularize a pipelineConfigure your data and parameters through a YAML fileEffortlessly analyze nodes’ outputs in a Jupyter NotebookVisualize your pipelineCreate documentation for your project Create a data science from a cookie-cutter template Create a data science pipeline Slice a pipeline Modularize a pipeline Configure your data and parameters through a YAML file Effortlessly analyze nodes’ outputs in a Jupyter Notebook Visualize your pipeline Create documentation for your project In this article, I will go through each of these features and explain how they can be helpful for your data science projects. To install Kedro, type: pip install kedro Have you ever contemplated how to structure your data science project so that it is logical and reasonably standardized? Wouldn’t it be nice if you can create a well-defined and standard project structure in one line of code? That could be easily done with Kedro. After installing Kedro, you can create a new empty project using: $ kedro new After going through a series of questions, a new project will be created with the structure like below: If we look at the project structure at a higher level, we can see that there are 5 main directories: conf: Store configuration files data: Store data docs: Store documentation of the project logs: Store log files notebooks: Store Jupyter Notebooks src: Store the main code Kedro requires some basic dependencies before using. These dependencies are specified under src/requirements.txt . To install these dependencies, type: $ kedro install And all necessary dependencies to run the pipelines will be installed in your environment. Now that we learn how to set up a data science project, let’s understand how to create a pipeline with Kedro. To create a new pipeline, type: $ kedro pipeline create <NAME> Since there are often 2 steps in a data science project: data processing and model training, we will create a pipeline called data_engineer and a pipeline called data_science : $ kedro pipeline create data_engineering$ kedro pipeline create data_science These two pipeline directories will be created under src/project_name : Each pipeline consists of 4 files: __init__.py README.md : specifies information about the pipeline node.py : contains nodes pipeline.py : contains pipelines A pipeline consists of multiple nodes. Each node is a Python function. For each node, there are input(s) and output(s): Visualization of the node get_classes: Inputs and outputs of each node can be specified using None , string, a list of strings, or a dictionary. Note that these strings are abstract names, not the real values. Why are names useful? If we know the name of each function’s inputs and outputs, we can easily grab a specific input or output by calling its name. Thus, there is less ambiguity in your code. You can find all node definition syntax here. A pipeline consists of a list of nodes. It connects the outputs of one node to the inputs of another node. For example, in the code below, 'classes' (output of the function get_classes ) and 'encoded_data' (output of the function encode_categorical_columns) are used as the inputs of the function split_data . Visualization of the pipeline above: Now that we have the node and the pipeline, let’s register these pipelines in the file src/project_name/pipeline_registry.py : After we have registered our pipelines, we can run these pipelines using: $ kedro run If you only want to run a specific pipeline, add --pipeline=<NAME> to the command kedro run : $ kedro run --pipeline=de Cool! If you prefer to run only a portion of a pipeline, you can slice the pipeline. Four options to slice a pipeline are: --from-nodes : Run the pipeline starting from certain nodes --to-nodes : Run the pipeline until reaching certain nodes --from-inputs : Run the pipeline starting from the nodes that produce certain inputs --to-outputs : Run the pipeline until reaching the nodes that produce certain outputs For example, $ kedro run --to-nodes=encode_categorical_columns ... allows you to run the pipeline until reaching the node encode_categorical_columns . Sometimes, you might want to reuse the same pipeline for different purposes. Kedro allows you to create modular pipelines, which are isolated and can be reused. For example, instead of writing two separate pipelines “cook lunch pipeline” and “cook dinner pipeline”, you can write a pipeline called “cook pipeline”. Then, turn “cook pipeline” into “cook meat pipeline” and the “cook vegetable pipeline” by switching the inputs and outputs of “cook pipeline” with new values. Modular pipelines are nice since they are portable, easier to develop, test, and maintain. Find instructions on how to modularize your Kedro pipeline here. Kedro also allows you to specify the parameters for a function using a YAML file. This is very nice because you can view all of your parameters from a file without digging into the source code. To configure your project with a configuration file, start with putting the parameters used for the data_engineering pipeline in the conf/base/parameters/data_engineering.yml file. Now, accessing a parameter from the pipeline is simple. All we need to do is to add params: before the name of parameter we want to access. In the example below, we use params:test_data_ratio to access the parameter test_data_ratio from the configuration file. Now you might wonder: how do we access the data from the pipeline? Kedro allows you to load and save data with Data Catalog. Data Catalog is located under conf/base/catalog.yml . Data Catalog is a configuration file that allows you to specify the data type, and the location where the data is saved. For example, to save the encoded_data output from the encode_categorical_columns node, ... we can insert the name encoded_data to the conf/base/catalog.yml file. Under encoded_data , we specify the dataset’s type and its location. pandas.CSVDataSet tells Kedro that we want to save encoded_data as a CSV and load it using pandas. Kedro also supports other dataset types such as pickle, parquet, excel, plot, Spark, SQL, etc. Find all datasets that Kedro supports here. Using a Data Catalog to manage loading and saving of data is very nice because you can specify: the locations of each file how the data is saved and loaded ... by only editing one file. The next time when you forget the locations of your datasets, you can look at this configuration file to find their information. Have you ever wanted to quickly check the outputs of a function from a Jupyter Notebook? Normally, you need to first save the data: ... then load it into a Jupyter Notebook: With Kedro, saving and loading data don’t require extra code. To start a Kedro’s Jupyter session, type: $ kedro jupyter notebook After running the pipeline that produces the output encoded_data specified in the catalog.yml file, ... we can easily load the data in the notebook using catalog.load : If you want to specify how to save and load the outputencoded_data, add load_args and save_args under encoded_data . Note that the configuration above will be equivalent to: All parameters inside src/base can also be easily loaded withcontext.params . Sometimes you might want to experiment with new Python functions and observe their outputs in the notebook. Luckily, Kedro allows you to run a pipeline inside a notebook: For quick testing, you can also convert functions from a Jupyter Notebook into Kedro nodes. If you are confused about the structure of your pipeline, you can visualize the entire pipeline using kedro-viz. Start with installing kedro-viz: pip install kedro-viz Then type: $ kedro viz ... to visualize your pipelines. A website will be automatically open in your browser. You should see something like the below: The visualization captures the relationships between datasets and nodes. Clicking a node will provide you more information about that node such as its parameters, inputs, outputs, file path, and code. Documenting your project makes it easier for your team to understand your project and how to use your code. Kedro makes it easy for you to create documentation based on the code structure of your project and includes any docstrings defined in your code. To create documentation for your project, type: $ kedro build-docs And documentation for your project will be automatically created under docs/build/html ! You can browse the documentation by either open docs/build/html/index.html or run: $ kedro build-docs --open ... to automatically open the documentation after building. Your documentation should look similar to below: Congratulations! You have just learned how to create reproducible and maintainable data science projects using Kedro. It might take a little bit of time to learn Kedro, but once your data science is set up with Kedro, you will find it much less overwhelming to maintain and update your projects. I hope this article will give you the motivation to use Kedro in your existing or future data science project. The source code of the demo project in this article could be found here: github.com I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter. Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
[ { "code": null, "e": 286, "s": 171, "text": "Have you ever passed your data to a list of functions and classes without knowing for sure how the output is like?" }, { "code": null, "e": 443, "s": 286, "text": "You might try to save the data then check it in your Jupyter Notebook to make sure the output is as you expected. This approach works, but it is cumbersome." }, { "code": null, "e": 625, "s": 443, "text": "Another common issue is that it’s hard to understand the relationships between functions when looking at a Python script that contains both the code to create and execute functions." }, { "code": null, "e": 700, "s": 625, "text": "Your code looks even more complex and hard to follow as the project grows." }, { "code": null, "e": 818, "s": 700, "text": "Wouldn’t it be nicer if you can visualize how the inputs and outputs of different functions are connected like below?" }, { "code": null, "e": 853, "s": 818, "text": "That is when Kedro comes in handy." }, { "code": null, "e": 1069, "s": 853, "text": "Kedro is an open-source Python framework for creating reproducible, maintainable, and modular data science code. It borrows concepts from software engineering best-practice and applies them to machine learning code." }, { "code": null, "e": 1090, "s": 1069, "text": "Kedro allows you to:" }, { "code": null, "e": 1380, "s": 1090, "text": "Create a data science from a cookie-cutter templateCreate a data science pipelineSlice a pipelineModularize a pipelineConfigure your data and parameters through a YAML fileEffortlessly analyze nodes’ outputs in a Jupyter NotebookVisualize your pipelineCreate documentation for your project" }, { "code": null, "e": 1432, "s": 1380, "text": "Create a data science from a cookie-cutter template" }, { "code": null, "e": 1463, "s": 1432, "text": "Create a data science pipeline" }, { "code": null, "e": 1480, "s": 1463, "text": "Slice a pipeline" }, { "code": null, "e": 1502, "s": 1480, "text": "Modularize a pipeline" }, { "code": null, "e": 1557, "s": 1502, "text": "Configure your data and parameters through a YAML file" }, { "code": null, "e": 1615, "s": 1557, "text": "Effortlessly analyze nodes’ outputs in a Jupyter Notebook" }, { "code": null, "e": 1639, "s": 1615, "text": "Visualize your pipeline" }, { "code": null, "e": 1677, "s": 1639, "text": "Create documentation for your project" }, { "code": null, "e": 1803, "s": 1677, "text": "In this article, I will go through each of these features and explain how they can be helpful for your data science projects." }, { "code": null, "e": 1827, "s": 1803, "text": "To install Kedro, type:" }, { "code": null, "e": 1845, "s": 1827, "text": "pip install kedro" }, { "code": null, "e": 2071, "s": 1845, "text": "Have you ever contemplated how to structure your data science project so that it is logical and reasonably standardized? Wouldn’t it be nice if you can create a well-defined and standard project structure in one line of code?" }, { "code": null, "e": 2175, "s": 2071, "text": "That could be easily done with Kedro. After installing Kedro, you can create a new empty project using:" }, { "code": null, "e": 2187, "s": 2175, "text": "$ kedro new" }, { "code": null, "e": 2291, "s": 2187, "text": "After going through a series of questions, a new project will be created with the structure like below:" }, { "code": null, "e": 2392, "s": 2291, "text": "If we look at the project structure at a higher level, we can see that there are 5 main directories:" }, { "code": null, "e": 2424, "s": 2392, "text": "conf: Store configuration files" }, { "code": null, "e": 2441, "s": 2424, "text": "data: Store data" }, { "code": null, "e": 2482, "s": 2441, "text": "docs: Store documentation of the project" }, { "code": null, "e": 2504, "s": 2482, "text": "logs: Store log files" }, { "code": null, "e": 2539, "s": 2504, "text": "notebooks: Store Jupyter Notebooks" }, { "code": null, "e": 2564, "s": 2539, "text": "src: Store the main code" }, { "code": null, "e": 2716, "s": 2564, "text": "Kedro requires some basic dependencies before using. These dependencies are specified under src/requirements.txt . To install these dependencies, type:" }, { "code": null, "e": 2732, "s": 2716, "text": "$ kedro install" }, { "code": null, "e": 2823, "s": 2732, "text": "And all necessary dependencies to run the pipelines will be installed in your environment." }, { "code": null, "e": 2933, "s": 2823, "text": "Now that we learn how to set up a data science project, let’s understand how to create a pipeline with Kedro." }, { "code": null, "e": 2965, "s": 2933, "text": "To create a new pipeline, type:" }, { "code": null, "e": 2996, "s": 2965, "text": "$ kedro pipeline create <NAME>" }, { "code": null, "e": 3173, "s": 2996, "text": "Since there are often 2 steps in a data science project: data processing and model training, we will create a pipeline called data_engineer and a pipeline called data_science :" }, { "code": null, "e": 3250, "s": 3173, "text": "$ kedro pipeline create data_engineering$ kedro pipeline create data_science" }, { "code": null, "e": 3322, "s": 3250, "text": "These two pipeline directories will be created under src/project_name :" }, { "code": null, "e": 3357, "s": 3322, "text": "Each pipeline consists of 4 files:" }, { "code": null, "e": 3369, "s": 3357, "text": "__init__.py" }, { "code": null, "e": 3422, "s": 3369, "text": "README.md : specifies information about the pipeline" }, { "code": null, "e": 3447, "s": 3422, "text": "node.py : contains nodes" }, { "code": null, "e": 3480, "s": 3447, "text": "pipeline.py : contains pipelines" }, { "code": null, "e": 3551, "s": 3480, "text": "A pipeline consists of multiple nodes. Each node is a Python function." }, { "code": null, "e": 3600, "s": 3551, "text": "For each node, there are input(s) and output(s):" }, { "code": null, "e": 3639, "s": 3600, "text": "Visualization of the node get_classes:" }, { "code": null, "e": 3810, "s": 3639, "text": "Inputs and outputs of each node can be specified using None , string, a list of strings, or a dictionary. Note that these strings are abstract names, not the real values." }, { "code": null, "e": 4002, "s": 3810, "text": "Why are names useful? If we know the name of each function’s inputs and outputs, we can easily grab a specific input or output by calling its name. Thus, there is less ambiguity in your code." }, { "code": null, "e": 4048, "s": 4002, "text": "You can find all node definition syntax here." }, { "code": null, "e": 4155, "s": 4048, "text": "A pipeline consists of a list of nodes. It connects the outputs of one node to the inputs of another node." }, { "code": null, "e": 4358, "s": 4155, "text": "For example, in the code below, 'classes' (output of the function get_classes ) and 'encoded_data' (output of the function encode_categorical_columns) are used as the inputs of the function split_data ." }, { "code": null, "e": 4395, "s": 4358, "text": "Visualization of the pipeline above:" }, { "code": null, "e": 4522, "s": 4395, "text": "Now that we have the node and the pipeline, let’s register these pipelines in the file src/project_name/pipeline_registry.py :" }, { "code": null, "e": 4596, "s": 4522, "text": "After we have registered our pipelines, we can run these pipelines using:" }, { "code": null, "e": 4608, "s": 4596, "text": "$ kedro run" }, { "code": null, "e": 4702, "s": 4608, "text": "If you only want to run a specific pipeline, add --pipeline=<NAME> to the command kedro run :" }, { "code": null, "e": 4728, "s": 4702, "text": "$ kedro run --pipeline=de" }, { "code": null, "e": 4734, "s": 4728, "text": "Cool!" }, { "code": null, "e": 4851, "s": 4734, "text": "If you prefer to run only a portion of a pipeline, you can slice the pipeline. Four options to slice a pipeline are:" }, { "code": null, "e": 4911, "s": 4851, "text": "--from-nodes : Run the pipeline starting from certain nodes" }, { "code": null, "e": 4970, "s": 4911, "text": "--to-nodes : Run the pipeline until reaching certain nodes" }, { "code": null, "e": 5055, "s": 4970, "text": "--from-inputs : Run the pipeline starting from the nodes that produce certain inputs" }, { "code": null, "e": 5141, "s": 5055, "text": "--to-outputs : Run the pipeline until reaching the nodes that produce certain outputs" }, { "code": null, "e": 5154, "s": 5141, "text": "For example," }, { "code": null, "e": 5204, "s": 5154, "text": "$ kedro run --to-nodes=encode_categorical_columns" }, { "code": null, "e": 5292, "s": 5204, "text": "... allows you to run the pipeline until reaching the node encode_categorical_columns ." }, { "code": null, "e": 5453, "s": 5292, "text": "Sometimes, you might want to reuse the same pipeline for different purposes. Kedro allows you to create modular pipelines, which are isolated and can be reused." }, { "code": null, "e": 5607, "s": 5453, "text": "For example, instead of writing two separate pipelines “cook lunch pipeline” and “cook dinner pipeline”, you can write a pipeline called “cook pipeline”." }, { "code": null, "e": 5766, "s": 5607, "text": "Then, turn “cook pipeline” into “cook meat pipeline” and the “cook vegetable pipeline” by switching the inputs and outputs of “cook pipeline” with new values." }, { "code": null, "e": 5922, "s": 5766, "text": "Modular pipelines are nice since they are portable, easier to develop, test, and maintain. Find instructions on how to modularize your Kedro pipeline here." }, { "code": null, "e": 6116, "s": 5922, "text": "Kedro also allows you to specify the parameters for a function using a YAML file. This is very nice because you can view all of your parameters from a file without digging into the source code." }, { "code": null, "e": 6297, "s": 6116, "text": "To configure your project with a configuration file, start with putting the parameters used for the data_engineering pipeline in the conf/base/parameters/data_engineering.yml file." }, { "code": null, "e": 6437, "s": 6297, "text": "Now, accessing a parameter from the pipeline is simple. All we need to do is to add params: before the name of parameter we want to access." }, { "code": null, "e": 6558, "s": 6437, "text": "In the example below, we use params:test_data_ratio to access the parameter test_data_ratio from the configuration file." }, { "code": null, "e": 6625, "s": 6558, "text": "Now you might wonder: how do we access the data from the pipeline?" }, { "code": null, "e": 6737, "s": 6625, "text": "Kedro allows you to load and save data with Data Catalog. Data Catalog is located under conf/base/catalog.yml ." }, { "code": null, "e": 6858, "s": 6737, "text": "Data Catalog is a configuration file that allows you to specify the data type, and the location where the data is saved." }, { "code": null, "e": 6945, "s": 6858, "text": "For example, to save the encoded_data output from the encode_categorical_columns node," }, { "code": null, "e": 7089, "s": 6945, "text": "... we can insert the name encoded_data to the conf/base/catalog.yml file. Under encoded_data , we specify the dataset’s type and its location." }, { "code": null, "e": 7327, "s": 7089, "text": "pandas.CSVDataSet tells Kedro that we want to save encoded_data as a CSV and load it using pandas. Kedro also supports other dataset types such as pickle, parquet, excel, plot, Spark, SQL, etc. Find all datasets that Kedro supports here." }, { "code": null, "e": 7423, "s": 7327, "text": "Using a Data Catalog to manage loading and saving of data is very nice because you can specify:" }, { "code": null, "e": 7450, "s": 7423, "text": "the locations of each file" }, { "code": null, "e": 7483, "s": 7450, "text": "how the data is saved and loaded" }, { "code": null, "e": 7642, "s": 7483, "text": "... by only editing one file. The next time when you forget the locations of your datasets, you can look at this configuration file to find their information." }, { "code": null, "e": 7774, "s": 7642, "text": "Have you ever wanted to quickly check the outputs of a function from a Jupyter Notebook? Normally, you need to first save the data:" }, { "code": null, "e": 7816, "s": 7774, "text": "... then load it into a Jupyter Notebook:" }, { "code": null, "e": 7920, "s": 7816, "text": "With Kedro, saving and loading data don’t require extra code. To start a Kedro’s Jupyter session, type:" }, { "code": null, "e": 7945, "s": 7920, "text": "$ kedro jupyter notebook" }, { "code": null, "e": 8045, "s": 7945, "text": "After running the pipeline that produces the output encoded_data specified in the catalog.yml file," }, { "code": null, "e": 8114, "s": 8045, "text": "... we can easily load the data in the notebook using catalog.load :" }, { "code": null, "e": 8231, "s": 8114, "text": "If you want to specify how to save and load the outputencoded_data, add load_args and save_args under encoded_data ." }, { "code": null, "e": 8288, "s": 8231, "text": "Note that the configuration above will be equivalent to:" }, { "code": null, "e": 8366, "s": 8288, "text": "All parameters inside src/base can also be easily loaded withcontext.params ." }, { "code": null, "e": 8537, "s": 8366, "text": "Sometimes you might want to experiment with new Python functions and observe their outputs in the notebook. Luckily, Kedro allows you to run a pipeline inside a notebook:" }, { "code": null, "e": 8629, "s": 8537, "text": "For quick testing, you can also convert functions from a Jupyter Notebook into Kedro nodes." }, { "code": null, "e": 8775, "s": 8629, "text": "If you are confused about the structure of your pipeline, you can visualize the entire pipeline using kedro-viz. Start with installing kedro-viz:" }, { "code": null, "e": 8797, "s": 8775, "text": "pip install kedro-viz" }, { "code": null, "e": 8808, "s": 8797, "text": "Then type:" }, { "code": null, "e": 8820, "s": 8808, "text": "$ kedro viz" }, { "code": null, "e": 8948, "s": 8820, "text": "... to visualize your pipelines. A website will be automatically open in your browser. You should see something like the below:" }, { "code": null, "e": 9149, "s": 8948, "text": "The visualization captures the relationships between datasets and nodes. Clicking a node will provide you more information about that node such as its parameters, inputs, outputs, file path, and code." }, { "code": null, "e": 9403, "s": 9149, "text": "Documenting your project makes it easier for your team to understand your project and how to use your code. Kedro makes it easy for you to create documentation based on the code structure of your project and includes any docstrings defined in your code." }, { "code": null, "e": 9451, "s": 9403, "text": "To create documentation for your project, type:" }, { "code": null, "e": 9470, "s": 9451, "text": "$ kedro build-docs" }, { "code": null, "e": 9642, "s": 9470, "text": "And documentation for your project will be automatically created under docs/build/html ! You can browse the documentation by either open docs/build/html/index.html or run:" }, { "code": null, "e": 9668, "s": 9642, "text": "$ kedro build-docs --open" }, { "code": null, "e": 9728, "s": 9668, "text": "... to automatically open the documentation after building." }, { "code": null, "e": 9777, "s": 9728, "text": "Your documentation should look similar to below:" }, { "code": null, "e": 10073, "s": 9777, "text": "Congratulations! You have just learned how to create reproducible and maintainable data science projects using Kedro. It might take a little bit of time to learn Kedro, but once your data science is set up with Kedro, you will find it much less overwhelming to maintain and update your projects." }, { "code": null, "e": 10184, "s": 10073, "text": "I hope this article will give you the motivation to use Kedro in your existing or future data science project." }, { "code": null, "e": 10257, "s": 10184, "text": "The source code of the demo project in this article could be found here:" }, { "code": null, "e": 10268, "s": 10257, "text": "github.com" }, { "code": null, "e": 10428, "s": 10268, "text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter." } ]
How to convert String to StringBuilder and vice versa Java?
The String type is a class in Java, it is used to represent a set of characters. Strings in Java are immutable, you cannot change the value of a String once created. Since a String is immutable, if you try to reassign the value of a String. The reference of it will be pointed to the new String object leaving an unused String in the memory. Java provides StringBuffer class as a replacement of Strings in places where there is a necessity to make a lot of modifications to Strings of characters. You can modify/manipulate the contents of a StringBuffer over and over again without leaving behind a lot of new unused objects. The StringBuilder class was introduced as of Java 5 and the main difference between the StringBuffer and StringBuilder is that StringBuilder’s methods are not thread safe (not synchronized). It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However, if the thread safety is necessary, the best option is StringBuffer objects. The append() method of the StringBuilder class accepts a String value and adds it to the current object. To convert a String value to StringBuilder object just append it using the append() method. In the following Java program we are converting an array of Strings to a single StringBuilder object. public class StringToStringBuilder { public static void main(String args[]) { String strs[] = {"Arshad", "Althamas", "Johar", "Javed", "Raju", "Krishna" }; StringBuilder sb = new StringBuilder(); sb.append(strs[0]); sb.append(" "+strs[1]); sb.append(" "+strs[2]); sb.append(" "+strs[3]); sb.append(" "+strs[4]); sb.append(" "+strs[5]); System.out.println(sb.toString()); } } Arshad Althamas Johar Javed Raju Krishna The toString() method of the StringBuilder class reruns String value of the current object. To convert a StringBuilder to String value simple invoke the toString() method on it. In the following Java program we are converting an array of Strings to a singleStringusing the toString() method of the StringBuilder. public class StringToStringBuilder { public static void main(String args[]) { String strs[] = {"Arshad", "Althamas", "Johar", "Javed", "Raju", "Krishna" }; StringBuilder sb = new StringBuilder(); sb.append(strs[0]); sb.append(" "+strs[1]); sb.append(" "+strs[2]); sb.append(" "+strs[3]); sb.append(" "+strs[4]); sb.append(" "+strs[5]); String singleString = sb.toString(); System.out.println(singleString); } } Arshad Althamas Johar Javed Raju Krishna
[ { "code": null, "e": 1228, "s": 1062, "text": "The String type is a class in Java, it is used to represent a set of characters. Strings in Java are immutable, you cannot change the value of a String once created." }, { "code": null, "e": 1404, "s": 1228, "text": "Since a String is immutable, if you try to reassign the value of a String. The reference of it will be pointed to the new String object leaving an unused String in the memory." }, { "code": null, "e": 1559, "s": 1404, "text": "Java provides StringBuffer class as a replacement of Strings in places where there is a necessity to make a lot of modifications to Strings of characters." }, { "code": null, "e": 1688, "s": 1559, "text": "You can modify/manipulate the contents of a StringBuffer over and over again without leaving behind a lot of new unused objects." }, { "code": null, "e": 1879, "s": 1688, "text": "The StringBuilder class was introduced as of Java 5 and the main difference between the StringBuffer and StringBuilder is that StringBuilder’s methods are not thread safe (not synchronized)." }, { "code": null, "e": 2061, "s": 1879, "text": "It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However, if the thread safety is necessary, the best option is StringBuffer objects." }, { "code": null, "e": 2166, "s": 2061, "text": "The append() method of the StringBuilder class accepts a String value and adds it to the current object." }, { "code": null, "e": 2258, "s": 2166, "text": "To convert a String value to StringBuilder object just append it using the append() method." }, { "code": null, "e": 2360, "s": 2258, "text": "In the following Java program we are converting an array of Strings to a single StringBuilder object." }, { "code": null, "e": 2795, "s": 2360, "text": "public class StringToStringBuilder {\n public static void main(String args[]) {\n String strs[] = {\"Arshad\", \"Althamas\", \"Johar\", \"Javed\", \"Raju\", \"Krishna\" };\n StringBuilder sb = new StringBuilder();\n sb.append(strs[0]);\n sb.append(\" \"+strs[1]);\n sb.append(\" \"+strs[2]);\n sb.append(\" \"+strs[3]);\n sb.append(\" \"+strs[4]);\n sb.append(\" \"+strs[5]);\n System.out.println(sb.toString());\n }\n}" }, { "code": null, "e": 2836, "s": 2795, "text": "Arshad Althamas Johar Javed Raju Krishna" }, { "code": null, "e": 3014, "s": 2836, "text": "The toString() method of the StringBuilder class reruns String value of the current object. To convert a StringBuilder to String value simple invoke the toString() method on it." }, { "code": null, "e": 3149, "s": 3014, "text": "In the following Java program we are converting an array of Strings to a singleStringusing the toString() method of the StringBuilder." }, { "code": null, "e": 3626, "s": 3149, "text": "public class StringToStringBuilder {\n public static void main(String args[]) {\n String strs[] = {\"Arshad\", \"Althamas\", \"Johar\", \"Javed\", \"Raju\", \"Krishna\" };\n StringBuilder sb = new StringBuilder();\n sb.append(strs[0]);\n sb.append(\" \"+strs[1]);\n sb.append(\" \"+strs[2]);\n sb.append(\" \"+strs[3]);\n sb.append(\" \"+strs[4]);\n sb.append(\" \"+strs[5]);\n String singleString = sb.toString();\n System.out.println(singleString);\n }\n}" }, { "code": null, "e": 3667, "s": 3626, "text": "Arshad Althamas Johar Javed Raju Krishna" } ]
MySQL Sum Query with IF Condition?
The Sum() is an aggregate function in MySQL. You can use sum query with if condition. To understand the sum query with if condition, let us create a table. The query to create a table − mysql> create table SumWithIfCondition −> ( −> ModeOfPayment varchar(100) −> , −> Amount int −> ); Query OK, 0 rows affected (1.60 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into SumWithIfCondition values('Offline',10); Query OK, 1 row affected (0.21 sec) mysql> insert into SumWithIfCondition values('Online',100); Query OK, 1 row affected (0.16 sec) mysql> insert into SumWithIfCondition values('Offline',20); Query OK, 1 row affected (0.13 sec) mysql> insert into SumWithIfCondition values('Online',200); Query OK, 1 row affected (0.16 sec) mysql> insert into SumWithIfCondition values('Offline',30); Query OK, 1 row affected (0.11 sec) mysql> insert into SumWithIfCondition values('Online',300); Query OK, 1 row affected (0.17 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from SumWithIfCondition; The following is the output − +---------------+--------+ | ModeOfPayment | Amount | +---------------+--------+ | Offline | 10 | | Online | 100 | | Offline | 20 | | Online | 200 | | Offline | 30 | | Online | 300 | +---------------+--------+ 6 rows in set (0.00 sec) Here is the sum query with if condition. Case 1 - if for Online Mode of Payment The query is as follows − mysql> select sum(if(ModeOfPayment = 'Online',Amount,0)) as TotalAmount from SumWithIfCondition; The following is the output − +-------------+ | TotalAmount | +-------------+ | 600 | +-------------+ 1 row in set (0.00 sec) Case 2 - if for Offline Mode of Payment The query is as follows − mysql> select sum(if(ModeOfPayment = 'Offline',Amount,0)) as TotalAmount from SumWithIfCondition; The following is the output − +-------------+ | TotalAmount | +-------------+ | 60 | +-------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1218, "s": 1062, "text": "The Sum() is an aggregate function in MySQL. You can use sum query with if condition. To understand the sum query with if condition, let us create a table." }, { "code": null, "e": 1248, "s": 1218, "text": "The query to create a table −" }, { "code": null, "e": 1399, "s": 1248, "text": "mysql> create table SumWithIfCondition\n −> (\n −> ModeOfPayment varchar(100)\n −> ,\n −> Amount int\n −> );\nQuery OK, 0 rows affected (1.60 sec)" }, { "code": null, "e": 1480, "s": 1399, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2061, "s": 1480, "text": "mysql> insert into SumWithIfCondition values('Offline',10);\nQuery OK, 1 row affected (0.21 sec)\n\nmysql> insert into SumWithIfCondition values('Online',100);\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into SumWithIfCondition values('Offline',20);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into SumWithIfCondition values('Online',200);\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into SumWithIfCondition values('Offline',30);\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into SumWithIfCondition values('Online',300);\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 2146, "s": 2061, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2186, "s": 2146, "text": "mysql> select *from SumWithIfCondition;" }, { "code": null, "e": 2216, "s": 2186, "text": "The following is the output −" }, { "code": null, "e": 2511, "s": 2216, "text": "+---------------+--------+\n| ModeOfPayment | Amount |\n+---------------+--------+\n| Offline | 10 |\n| Online | 100 |\n| Offline | 20 |\n| Online | 200 |\n| Offline | 30 |\n| Online | 300 |\n+---------------+--------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2552, "s": 2511, "text": "Here is the sum query with if condition." }, { "code": null, "e": 2591, "s": 2552, "text": "Case 1 - if for Online Mode of Payment" }, { "code": null, "e": 2617, "s": 2591, "text": "The query is as follows −" }, { "code": null, "e": 2714, "s": 2617, "text": "mysql> select sum(if(ModeOfPayment = 'Online',Amount,0)) as TotalAmount from SumWithIfCondition;" }, { "code": null, "e": 2744, "s": 2714, "text": "The following is the output −" }, { "code": null, "e": 2848, "s": 2744, "text": "+-------------+\n| TotalAmount |\n+-------------+\n| 600 |\n+-------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 2888, "s": 2848, "text": "Case 2 - if for Offline Mode of Payment" }, { "code": null, "e": 2914, "s": 2888, "text": "The query is as follows −" }, { "code": null, "e": 3012, "s": 2914, "text": "mysql> select sum(if(ModeOfPayment = 'Offline',Amount,0)) as TotalAmount from SumWithIfCondition;" }, { "code": null, "e": 3042, "s": 3012, "text": "The following is the output −" }, { "code": null, "e": 3146, "s": 3042, "text": "+-------------+\n| TotalAmount |\n+-------------+\n| 60 |\n+-------------+\n1 row in set (0.00 sec)" } ]
Draw Multiple Overlaid Histograms with ggplot2 Package in R - GeeksforGeeks
17 Jun, 2021 In this article, we are going to see how to draw multiple overlaid histograms with the ggplot2 package in the R programming language. We will be drawing multiple overlaid histograms using the alpha argument of the geom_histogram() function from ggplot2 package. In this approach for drawing multiple overlaid histograms, the user first needs to install and import the ggplot2 package on the R console and call the geaom_histogram function with specifying the alpha argument of this function to a float value between 0 to 1 which will lead to the transparency of the different histogram plots on the same plot with the set of the data-frame as this function parameter to get multiple overlaid histograms in the R programming language. geom_histogram() function: This function is an in-built function of ggplot2 module. Syntax: geom_histogram(mapping = NULL, data = NULL, stat = “bin”, position = “stack”, ...) Parameters: mapping: The aesthetic mapping, usually constructed with aes or aes_string. Only needs to be set at the layer level if you are overriding the plot defaults. data: A layer-specific dataset – only needed if you want to override the plot defaults. stat: The statistical transformation to use on the data for this layer. position: The position adjustment to use for overlapping points on this layer To install and import the ggplot2 package in the R console, the user needs to follow the following syntax: install.packages("ggplot2") library("ggplot2") The alpha argument: This is a graphical parameter is a number from 0 to 1 opaque to transparent, it adjusts the transparency of the plot. Example 1: In this example, we will be taking 2 different 100 random data set to create 2 different histograms on the single plot using the alpha argument of the geom_histogram() function from the ggplot2 package in the R programming language. R library("ggplot2")data <- data.frame(values = c(rnorm(100), rnorm(100)), group = c(rep("A", 100), rep("B", 100))) ggplot(data, aes(x = values, fill = group)) +geom_histogram(position = "identity", alpha = 0.4, bins = 50) Output: Example 2: In this example, we will be taking 3 different data to create 3 different histograms on a single plot using the alpha argument of the geom_histogram() function from the ggplot2 package in the R programming language. R library("ggplot2")data <- data.frame(values = c(c(6,2,5,4,1,6,1,5,4,7), c(4,1,4,4,5,5,4,6,2,4), c(9,1,5,7,1,10,6,4,1,7)), group = c(rep("A", 10), rep("B", 10), rep("C", 10)))ggplot(data, aes(x = values, fill = group)) +geom_histogram(position = "identity", alpha = 0.4, bins = 50) Output: Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? Time Series Analysis in R
[ { "code": null, "e": 24851, "s": 24823, "text": "\n17 Jun, 2021" }, { "code": null, "e": 24985, "s": 24851, "text": "In this article, we are going to see how to draw multiple overlaid histograms with the ggplot2 package in the R programming language." }, { "code": null, "e": 25585, "s": 24985, "text": "We will be drawing multiple overlaid histograms using the alpha argument of the geom_histogram() function from ggplot2 package. In this approach for drawing multiple overlaid histograms, the user first needs to install and import the ggplot2 package on the R console and call the geaom_histogram function with specifying the alpha argument of this function to a float value between 0 to 1 which will lead to the transparency of the different histogram plots on the same plot with the set of the data-frame as this function parameter to get multiple overlaid histograms in the R programming language." }, { "code": null, "e": 25669, "s": 25585, "text": "geom_histogram() function: This function is an in-built function of ggplot2 module." }, { "code": null, "e": 25760, "s": 25669, "text": "Syntax: geom_histogram(mapping = NULL, data = NULL, stat = “bin”, position = “stack”, ...)" }, { "code": null, "e": 25772, "s": 25760, "text": "Parameters:" }, { "code": null, "e": 25929, "s": 25772, "text": "mapping: The aesthetic mapping, usually constructed with aes or aes_string. Only needs to be set at the layer level if you are overriding the plot defaults." }, { "code": null, "e": 26017, "s": 25929, "text": "data: A layer-specific dataset – only needed if you want to override the plot defaults." }, { "code": null, "e": 26089, "s": 26017, "text": "stat: The statistical transformation to use on the data for this layer." }, { "code": null, "e": 26167, "s": 26089, "text": "position: The position adjustment to use for overlapping points on this layer" }, { "code": null, "e": 26274, "s": 26167, "text": "To install and import the ggplot2 package in the R console, the user needs to follow the following syntax:" }, { "code": null, "e": 26361, "s": 26274, "text": "install.packages(\"ggplot2\") \nlibrary(\"ggplot2\")" }, { "code": null, "e": 26499, "s": 26361, "text": "The alpha argument: This is a graphical parameter is a number from 0 to 1 opaque to transparent, it adjusts the transparency of the plot." }, { "code": null, "e": 26510, "s": 26499, "text": "Example 1:" }, { "code": null, "e": 26743, "s": 26510, "text": "In this example, we will be taking 2 different 100 random data set to create 2 different histograms on the single plot using the alpha argument of the geom_histogram() function from the ggplot2 package in the R programming language." }, { "code": null, "e": 26745, "s": 26743, "text": "R" }, { "code": "library(\"ggplot2\")data <- data.frame(values = c(rnorm(100), rnorm(100)), group = c(rep(\"A\", 100), rep(\"B\", 100))) ggplot(data, aes(x = values, fill = group)) +geom_histogram(position = \"identity\", alpha = 0.4, bins = 50)", "e": 27042, "s": 26745, "text": null }, { "code": null, "e": 27050, "s": 27042, "text": "Output:" }, { "code": null, "e": 27061, "s": 27050, "text": "Example 2:" }, { "code": null, "e": 27277, "s": 27061, "text": "In this example, we will be taking 3 different data to create 3 different histograms on a single plot using the alpha argument of the geom_histogram() function from the ggplot2 package in the R programming language." }, { "code": null, "e": 27279, "s": 27277, "text": "R" }, { "code": "library(\"ggplot2\")data <- data.frame(values = c(c(6,2,5,4,1,6,1,5,4,7), c(4,1,4,4,5,5,4,6,2,4), c(9,1,5,7,1,10,6,4,1,7)), group = c(rep(\"A\", 10), rep(\"B\", 10), rep(\"C\", 10)))ggplot(data, aes(x = values, fill = group)) +geom_histogram(position = \"identity\", alpha = 0.4, bins = 50)", "e": 27692, "s": 27279, "text": null }, { "code": null, "e": 27700, "s": 27692, "text": "Output:" }, { "code": null, "e": 27707, "s": 27700, "text": "Picked" }, { "code": null, "e": 27716, "s": 27707, "text": "R-ggplot" }, { "code": null, "e": 27727, "s": 27716, "text": "R Language" }, { "code": null, "e": 27825, "s": 27727, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27834, "s": 27825, "text": "Comments" }, { "code": null, "e": 27847, "s": 27834, "text": "Old Comments" }, { "code": null, "e": 27899, "s": 27847, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27937, "s": 27899, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27972, "s": 27937, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28030, "s": 27972, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28079, "s": 28030, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28122, "s": 28079, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28172, "s": 28122, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 28189, "s": 28172, "text": "R - if statement" }, { "code": null, "e": 28226, "s": 28189, "text": "How to import an Excel File into R ?" } ]
Web2py - Introduction
web2py is defined as a free, open-source web framework for agile development which involves database-driven web applications; it is written in Python and programmable in Python. It is a full-stack framework; it consists of all the necessary components, a developer needs to build a fully functional web application. web2py framework follows the Model-View-Controller pattern of running web applications unlike traditional patterns. Model is a part of the application that includes logic for the data. The objects in model are used for retrieving and storing the data from the database. Model is a part of the application that includes logic for the data. The objects in model are used for retrieving and storing the data from the database. View is a part of the application, which helps in rendering the display of data to end users. The display of data is fetched from Model. View is a part of the application, which helps in rendering the display of data to end users. The display of data is fetched from Model. Controller is a part of the application, which handles user interaction. Controllers can read data from a view, control user input, and send input data to the specific model. Controller is a part of the application, which handles user interaction. Controllers can read data from a view, control user input, and send input data to the specific model. web2py has an in-built feature to manage cookies and sessions. After committing a transaction (in terms of SQL), the session is also stored simultaneously. web2py has an in-built feature to manage cookies and sessions. After committing a transaction (in terms of SQL), the session is also stored simultaneously. web2py has the capacity of running the tasks in scheduled intervals after the completion of certain actions. This can be achieved with CRON. web2py has the capacity of running the tasks in scheduled intervals after the completion of certain actions. This can be achieved with CRON. Take a look at the workflow diagram given below. The workflow diagram is described below. The Models, Views and Controller components make up the user web2py application. The Models, Views and Controller components make up the user web2py application. Multiple applications can be hosted in the same instance of web2py. Multiple applications can be hosted in the same instance of web2py. The browser sends the HTTP request to the server and the server interacts with Model, Controller and View to fetch the necessary output. The browser sends the HTTP request to the server and the server interacts with Model, Controller and View to fetch the necessary output. The arrows represent communication with the database engine(s). The database queries can be written in raw SQL or by using the web2py Database Abstraction Layer (which will be discussed in further chapters), so that web2py application code is independent of any database engine. The arrows represent communication with the database engine(s). The database queries can be written in raw SQL or by using the web2py Database Abstraction Layer (which will be discussed in further chapters), so that web2py application code is independent of any database engine. Model establishes the database connection with the database and interacts with the Controller. The Controller on the other hand interacts with the View to render the display of data. Model establishes the database connection with the database and interacts with the Controller. The Controller on the other hand interacts with the View to render the display of data. The Dispatcher maps the requested URL as given in HTTP response to a function call in the controller. The output of the function can be a string or a hash table. The Dispatcher maps the requested URL as given in HTTP response to a function call in the controller. The output of the function can be a string or a hash table. The data is rendered by the View. If the user requests an HTML page (the default), the data is rendered into an HTML page. If the user requests the same page in XML, web2py tries to find a view that can render the dictionary in XML. The data is rendered by the View. If the user requests an HTML page (the default), the data is rendered into an HTML page. If the user requests the same page in XML, web2py tries to find a view that can render the dictionary in XML. The supported protocols of web2py include HTML, XML, JSON, RSS, CSV, and RTF. The supported protocols of web2py include HTML, XML, JSON, RSS, CSV, and RTF. The model-view-controller representation of web2py is as follows − "db.py" is the model: db = DAL('sqlite://storage.sqlite') db.define_table(employee, Field('name'), Field(‘phone’)) The Model includes the logic of application data. It connects to the database as mentioned in the figure above. Consider SQLite is being used and is stored in storage.sqlite file with a table defined as employee. If the table does not exist, web2py helps by creating the respective table. The program "default.py" is the Controller. def employees(): grid = SQLFORM.grid(db.contact, user_signature = False) return locals() In web2py, URL mapping helps in accessing the functions and modules. For the above example, the Controller contains a single function (or "action") called employees. The action taken by the Controller returns a string or a Python dictionary, which is a combination of key and value including a local set of variables. "default/contacts.html" is the View. {{extend 'layout.html'}} <h1>Manage My Employees</h1> {{=grid}} For the given example, View displays the output after the associated controller function is executed. The purpose of this View is to render the variables in the dictionary, which is in the form of HTML. The View file is written in HTML, but it embeds Python code with the help of {{ and }} delimiters. The code embedded into HTML consists of Python code in the dictionary. web2py comes in binary packages for all the major operating systems like Windows, UNIX and Mac OS X. It is easy to install web2py because − It comprises of the Python interpreter, so you do not need to have it pre-installed. There is also a source code version that runs on all the operating systems. It comprises of the Python interpreter, so you do not need to have it pre-installed. There is also a source code version that runs on all the operating systems. The following link comprises of the binary packages of web2py for download as per the user’s need − www.web2py.com The following link comprises of the binary packages of web2py for download as per the user’s need − www.web2py.com The web2py framework requires no pre-installation unlike other frameworks. The user needs to download the zip file and unzip as per the operating system requirement. The web2py framework requires no pre-installation unlike other frameworks. The user needs to download the zip file and unzip as per the operating system requirement. The web2py framework is written in Python, which is a complete dynamic language that does not require any compilation or complicated installation to run. The web2py framework is written in Python, which is a complete dynamic language that does not require any compilation or complicated installation to run. It uses a virtual machine like other programming languages such as Java or .net and it can transparently byte-compile the source code written by the developers. It uses a virtual machine like other programming languages such as Java or .net and it can transparently byte-compile the source code written by the developers. Print Add Notes Bookmark this page
[ { "code": null, "e": 2209, "s": 1893, "text": "web2py is defined as a free, open-source web framework for agile development which involves database-driven web applications; it is written in Python and programmable in Python. It is a full-stack framework; it consists of all the necessary components, a developer needs to build a fully functional web application." }, { "code": null, "e": 2325, "s": 2209, "text": "web2py framework follows the Model-View-Controller pattern of running web applications unlike traditional patterns." }, { "code": null, "e": 2479, "s": 2325, "text": "Model is a part of the application that includes logic for the data. The objects in model are used for retrieving and storing the data from the database." }, { "code": null, "e": 2633, "s": 2479, "text": "Model is a part of the application that includes logic for the data. The objects in model are used for retrieving and storing the data from the database." }, { "code": null, "e": 2770, "s": 2633, "text": "View is a part of the application, which helps in rendering the display of data to end users. The display of data is fetched from Model." }, { "code": null, "e": 2907, "s": 2770, "text": "View is a part of the application, which helps in rendering the display of data to end users. The display of data is fetched from Model." }, { "code": null, "e": 3082, "s": 2907, "text": "Controller is a part of the application, which handles user interaction. Controllers can read data from a view, control user input, and send input data to the specific model." }, { "code": null, "e": 3257, "s": 3082, "text": "Controller is a part of the application, which handles user interaction. Controllers can read data from a view, control user input, and send input data to the specific model." }, { "code": null, "e": 3413, "s": 3257, "text": "web2py has an in-built feature to manage cookies and sessions. After committing a transaction (in terms of SQL), the session is also stored simultaneously." }, { "code": null, "e": 3569, "s": 3413, "text": "web2py has an in-built feature to manage cookies and sessions. After committing a transaction (in terms of SQL), the session is also stored simultaneously." }, { "code": null, "e": 3710, "s": 3569, "text": "web2py has the capacity of running the tasks in scheduled intervals after the completion of certain actions. This can be achieved with CRON." }, { "code": null, "e": 3851, "s": 3710, "text": "web2py has the capacity of running the tasks in scheduled intervals after the completion of certain actions. This can be achieved with CRON." }, { "code": null, "e": 3900, "s": 3851, "text": "Take a look at the workflow diagram given below." }, { "code": null, "e": 3941, "s": 3900, "text": "The workflow diagram is described below." }, { "code": null, "e": 4022, "s": 3941, "text": "The Models, Views and Controller components make up the user web2py application." }, { "code": null, "e": 4103, "s": 4022, "text": "The Models, Views and Controller components make up the user web2py application." }, { "code": null, "e": 4171, "s": 4103, "text": "Multiple applications can be hosted in the same instance of web2py." }, { "code": null, "e": 4239, "s": 4171, "text": "Multiple applications can be hosted in the same instance of web2py." }, { "code": null, "e": 4376, "s": 4239, "text": "The browser sends the HTTP request to the server and the server interacts with Model, Controller and View to fetch the necessary output." }, { "code": null, "e": 4513, "s": 4376, "text": "The browser sends the HTTP request to the server and the server interacts with Model, Controller and View to fetch the necessary output." }, { "code": null, "e": 4792, "s": 4513, "text": "The arrows represent communication with the database engine(s). The database queries can be written in raw SQL or by using the web2py Database Abstraction Layer (which will be discussed in further chapters), so that web2py application code is independent of any database engine." }, { "code": null, "e": 5071, "s": 4792, "text": "The arrows represent communication with the database engine(s). The database queries can be written in raw SQL or by using the web2py Database Abstraction Layer (which will be discussed in further chapters), so that web2py application code is independent of any database engine." }, { "code": null, "e": 5254, "s": 5071, "text": "Model establishes the database connection with the database and interacts with the Controller. The Controller on the other hand interacts with the View to render the display of data." }, { "code": null, "e": 5437, "s": 5254, "text": "Model establishes the database connection with the database and interacts with the Controller. The Controller on the other hand interacts with the View to render the display of data." }, { "code": null, "e": 5599, "s": 5437, "text": "The Dispatcher maps the requested URL as given in HTTP response to a function call in the controller. The output of the function can be a string or a hash table." }, { "code": null, "e": 5761, "s": 5599, "text": "The Dispatcher maps the requested URL as given in HTTP response to a function call in the controller. The output of the function can be a string or a hash table." }, { "code": null, "e": 5994, "s": 5761, "text": "The data is rendered by the View. If the user requests an HTML page (the default), the data is rendered into an HTML page. If the user requests the same page in XML, web2py tries to find a view that can render the dictionary in XML." }, { "code": null, "e": 6227, "s": 5994, "text": "The data is rendered by the View. If the user requests an HTML page (the default), the data is rendered into an HTML page. If the user requests the same page in XML, web2py tries to find a view that can render the dictionary in XML." }, { "code": null, "e": 6305, "s": 6227, "text": "The supported protocols of web2py include HTML, XML, JSON, RSS, CSV, and RTF." }, { "code": null, "e": 6383, "s": 6305, "text": "The supported protocols of web2py include HTML, XML, JSON, RSS, CSV, and RTF." }, { "code": null, "e": 6450, "s": 6383, "text": "The model-view-controller representation of web2py is as follows −" }, { "code": null, "e": 6566, "s": 6450, "text": "\"db.py\" is the model:\ndb = DAL('sqlite://storage.sqlite')\ndb.define_table(employee, Field('name'), Field(‘phone’))\n" }, { "code": null, "e": 6855, "s": 6566, "text": "The Model includes the logic of application data. It connects to the database as mentioned in the figure above. Consider SQLite is being used and is stored in storage.sqlite file with a table defined as employee. If the table does not exist, web2py helps by creating the respective table." }, { "code": null, "e": 6899, "s": 6855, "text": "The program \"default.py\" is the Controller." }, { "code": null, "e": 6994, "s": 6899, "text": "def employees():\n grid = SQLFORM.grid(db.contact, user_signature = False)\n return locals()" }, { "code": null, "e": 7160, "s": 6994, "text": "In web2py, URL mapping helps in accessing the functions and modules. For the above example, the Controller contains a single function (or \"action\") called employees." }, { "code": null, "e": 7312, "s": 7160, "text": "The action taken by the Controller returns a string or a Python dictionary, which is a combination of key and value including a local set of variables." }, { "code": null, "e": 7349, "s": 7312, "text": "\"default/contacts.html\" is the View." }, { "code": null, "e": 7413, "s": 7349, "text": "{{extend 'layout.html'}}\n<h1>Manage My Employees</h1>\n{{=grid}}" }, { "code": null, "e": 7515, "s": 7413, "text": "For the given example, View displays the output after the associated controller function is executed." }, { "code": null, "e": 7715, "s": 7515, "text": "The purpose of this View is to render the variables in the dictionary, which is in the form of HTML. The View file is written in HTML, but it embeds Python code with the help of {{ and }} delimiters." }, { "code": null, "e": 7786, "s": 7715, "text": "The code embedded into HTML consists of Python code in the dictionary." }, { "code": null, "e": 7887, "s": 7786, "text": "web2py comes in binary packages for all the major operating systems like Windows, UNIX and Mac OS X." }, { "code": null, "e": 7926, "s": 7887, "text": "It is easy to install web2py because −" }, { "code": null, "e": 8087, "s": 7926, "text": "It comprises of the Python interpreter, so you do not need to have it pre-installed. There is also a source code version that runs on all the operating systems." }, { "code": null, "e": 8248, "s": 8087, "text": "It comprises of the Python interpreter, so you do not need to have it pre-installed. There is also a source code version that runs on all the operating systems." }, { "code": null, "e": 8363, "s": 8248, "text": "The following link comprises of the binary packages of web2py for download as per the user’s need − www.web2py.com" }, { "code": null, "e": 8478, "s": 8363, "text": "The following link comprises of the binary packages of web2py for download as per the user’s need − www.web2py.com" }, { "code": null, "e": 8644, "s": 8478, "text": "The web2py framework requires no pre-installation unlike other frameworks. The user needs to download the zip file and unzip as per the operating system requirement." }, { "code": null, "e": 8810, "s": 8644, "text": "The web2py framework requires no pre-installation unlike other frameworks. The user needs to download the zip file and unzip as per the operating system requirement." }, { "code": null, "e": 8964, "s": 8810, "text": "The web2py framework is written in Python, which is a complete dynamic language that does not require any compilation or complicated installation to run." }, { "code": null, "e": 9118, "s": 8964, "text": "The web2py framework is written in Python, which is a complete dynamic language that does not require any compilation or complicated installation to run." }, { "code": null, "e": 9279, "s": 9118, "text": "It uses a virtual machine like other programming languages such as Java or .net and it can transparently byte-compile the source code written by the developers." }, { "code": null, "e": 9440, "s": 9279, "text": "It uses a virtual machine like other programming languages such as Java or .net and it can transparently byte-compile the source code written by the developers." }, { "code": null, "e": 9447, "s": 9440, "text": " Print" }, { "code": null, "e": 9458, "s": 9447, "text": " Add Notes" } ]
Area Calculation - Online Quiz
Following quiz provides Multiple Choice Questions (MCQs) related to Area Calculation. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz. Q 1 - The length of a rectangular plot is 9/2 times that of its broadness. On the off chance that the region of the plot is 200 square meters, then what is the length? A - 25 m B - 62 m C - 20 m D - none of these Let the breadth be x meters. Then, length =9x/2 meters. ∴ X*9x/2= 200 ⇒x2= 400/9 ⇒x= 20/3 ∴ Length = (9/2*20/3) m = 30m Q 2 - The edge of a rectangle and a square are 160m each. The range of the rectangle is not exactly that of the square by 100sq. meters. The length of the rectangle is: A - 30 m B - 40 m C - 50 m D - 60 m Each side of the square= 160/4m = 40m 2(L+b) =160 ⇒ (L+b) = 80 (40) 2-Lb= 100 ⇒ lb= (1600-100) = 1500 (L-b) 2= (L+b) 2- 4Lb= (80) 2-4*1500= (6400-6000) =400⇒L-b=20 ∴L+b= 80, L-b= 20 ⇒ 2L=100 ⇒ L= 50 m Q 3 - If the proportion of the ranges of two squares is 9:1, then the proportion of their edge is: A - 2:1 B - 3:1 C - 3:2 D - 4:1 Let their area be 9x2 and x2 sq. units. Then, their sides are respectively 3x units and x units. ∴ Their Perimeter are (4*3 x) and 4x units. Required ratio = 12x: 4x= 3:1 Q 4 - Range of four dividers of a room is 77m2 and its length and breadth Are 7.5m and 3.5m separately. The tallness of the room is? A - 3.5 m B - 5.4 m C - 6.77 m D - 7.7 m 2(7.5+3.5)*h= 77⇒h = 77/22= 7/2= 3.5 m Q 5 - The largest possible square is increased in a circle of unit radius. The area of the square is: A - 2 sq. unit B - π sq. unit C - 2√2π sq. unit D - 4√2π sq. unit Diagonal of the square = 2* Radius =(2*1)= 2 units Area of the square= [1/2* (2) 2] sq. units= 2 sq. unit Q 6 - A circle and a rectangle have same perimeter.The side of the rectangle is 18cm and 26 cm. what is the area of the circle? A - 88 cm2 B - 154 cm2 C - 616 cm2 D - 1250 cm2 Circumference of the circle= Perimeter of the rectangle = 2 (18+26) cm= 88cm 2*22/7* R= 88 ⇒ R= (88*7/44) =14 cm Area of the circle = πr2 = (22/7 *14*14) cm2 =616 cm2 Q 7 - On expanding every side of an equilateral triangle by 2cm, there is an increment of 2√3 cm2 in its zone. The length of every side of the Triangle is: A - 1cm B - √3 cm C - 3cm D - (2+√3) cm Let each side of the triangle be x cm. then, area = (√3/4) x2 cm2 ∴ √3/4 (x+2)2- √3/4 x2= 2√3 ⇒√3/4{(x+2)2- x2} =2√3 ⇒ √3/4* 4(x+1) = 2√3 ⇒ x+1= 2 ⇒x= 1 Q 8 - The range of a square is equivalent to the territory of a circle. What is the proportion between the side of the square and the span of the circle? A - √π:1 B - 1:√π C - 1:π D - π:1 Let the side of the square be a and radius of the circle be r. Then, a2 =πr2 ⇒a = √πr⇒ A/R=√π/1 ⇒a: r =√π:1 Q 9 - The region of a rhombus is 2016cm2 and its side is 65cm. The lengths of its diagonals are: A - 125 cm, 35 cm B - 126 cm, 32 cm C - 132 cm, 26 cm D - 135 cm, 25 cm 1/2 d1* d2=2016 ⇒d1*d2=4032 (1/2 d1)2+ (1/2 d2)2 = (65)2⇒d12+d22= 16900 ∴d12+d22+2d1d2 = (16900+8064) =24964 ⇒ (d1+d2)2= (158)2 ⇒d1+d2 =158 d12+d22-2d1d2 = (16900-8064) =8836 ⇒ (d1-d2)2= (94)2 ⇒d1-d2=94 d1+d2=158, d1-d2 =94 ⇒2d1=252 ⇒d1=126cm ⇒d2= (158-126) =32 cm ∴diagonals are 126 cm, 32 cm. Q 10 - A round greenery enclosure has an outline of 440 m. There is a 7m wide fringe inside the patio nursery along its outskirts. The territory of the fringe is: A - 2918m2 B - 2921 m2 C - 2924 m2 D - 2926 m2 2πR =440 ⇒ 2*22/7*R= 440 ⇒R= (440* 7/44)=70 m Outer radius = 70m, inner radius = (70-7) =63 m Required area = π [(70)2-(63)2] m2= 22/7 *(70+63) (70-63) m2 = (22*133) m2, = 2926m2 87 Lectures 22.5 hours Programming Line Print Add Notes Bookmark this page
[ { "code": null, "e": 4222, "s": 3892, "text": "Following quiz provides Multiple Choice Questions (MCQs) related to Area Calculation. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz." }, { "code": null, "e": 4390, "s": 4222, "text": "Q 1 - The length of a rectangular plot is 9/2 times that of its broadness. On the off chance that the region of the plot is 200 square meters, then what is the length?" }, { "code": null, "e": 4399, "s": 4390, "text": "A - 25 m" }, { "code": null, "e": 4408, "s": 4399, "text": "B - 62 m" }, { "code": null, "e": 4417, "s": 4408, "text": "C - 20 m" }, { "code": null, "e": 4435, "s": 4417, "text": "D - none of these" }, { "code": null, "e": 4555, "s": 4435, "text": "Let the breadth be x meters. Then, length =9x/2 meters.\n∴ X*9x/2= 200 ⇒x2= 400/9 ⇒x= 20/3\n∴ Length = (9/2*20/3) m = 30m" }, { "code": null, "e": 4724, "s": 4555, "text": "Q 2 - The edge of a rectangle and a square are 160m each. The range of the rectangle is not exactly that of the square by 100sq. meters. The length of the rectangle is:" }, { "code": null, "e": 4733, "s": 4724, "text": "A - 30 m" }, { "code": null, "e": 4742, "s": 4733, "text": "B - 40 m" }, { "code": null, "e": 4751, "s": 4742, "text": "C - 50 m" }, { "code": null, "e": 4761, "s": 4751, "text": "D - 60 m " }, { "code": null, "e": 4969, "s": 4761, "text": "Each side of the square= 160/4m = 40m\n2(L+b) =160 ⇒ (L+b) = 80\n(40) 2-Lb= 100 ⇒ lb= (1600-100) = 1500\n(L-b) 2= (L+b) 2- 4Lb= (80) 2-4*1500= (6400-6000) =400⇒L-b=20\n∴L+b= 80, L-b= 20 ⇒ 2L=100 ⇒ L= 50 m" }, { "code": null, "e": 5068, "s": 4969, "text": "Q 3 - If the proportion of the ranges of two squares is 9:1, then the proportion of their edge is:" }, { "code": null, "e": 5076, "s": 5068, "text": "A - 2:1" }, { "code": null, "e": 5084, "s": 5076, "text": "B - 3:1" }, { "code": null, "e": 5092, "s": 5084, "text": "C - 3:2" }, { "code": null, "e": 5100, "s": 5092, "text": "D - 4:1" }, { "code": null, "e": 5271, "s": 5100, "text": "Let their area be 9x2 and x2 sq. units.\nThen, their sides are respectively 3x units and x units.\n∴ Their Perimeter are (4*3 x) and 4x units.\nRequired ratio = 12x: 4x= 3:1" }, { "code": null, "e": 5404, "s": 5271, "text": "Q 4 - Range of four dividers of a room is 77m2 and its length and breadth Are 7.5m and 3.5m separately. The tallness of the room is?" }, { "code": null, "e": 5414, "s": 5404, "text": "A - 3.5 m" }, { "code": null, "e": 5424, "s": 5414, "text": "B - 5.4 m" }, { "code": null, "e": 5435, "s": 5424, "text": "C - 6.77 m" }, { "code": null, "e": 5445, "s": 5435, "text": "D - 7.7 m" }, { "code": null, "e": 5485, "s": 5445, "text": "2(7.5+3.5)*h= 77⇒h = 77/22= 7/2= 3.5 m" }, { "code": null, "e": 5587, "s": 5485, "text": "Q 5 - The largest possible square is increased in a circle of unit radius. The area of the square is:" }, { "code": null, "e": 5602, "s": 5587, "text": "A - 2 sq. unit" }, { "code": null, "e": 5617, "s": 5602, "text": "B - π sq. unit" }, { "code": null, "e": 5636, "s": 5617, "text": "C - 2√2π sq. unit " }, { "code": null, "e": 5654, "s": 5636, "text": "D - 4√2π sq. unit" }, { "code": null, "e": 5760, "s": 5654, "text": "Diagonal of the square = 2* Radius =(2*1)= 2 units\nArea of the square= [1/2* (2) 2] sq. units= 2 sq. unit" }, { "code": null, "e": 5888, "s": 5760, "text": "Q 6 - A circle and a rectangle have same perimeter.The side of the rectangle is 18cm and 26 cm. what is the area of the circle?" }, { "code": null, "e": 5899, "s": 5888, "text": "A - 88 cm2" }, { "code": null, "e": 5911, "s": 5899, "text": "B - 154 cm2" }, { "code": null, "e": 5923, "s": 5911, "text": "C - 616 cm2" }, { "code": null, "e": 5936, "s": 5923, "text": "D - 1250 cm2" }, { "code": null, "e": 6103, "s": 5936, "text": "Circumference of the circle= Perimeter of the rectangle\n= 2 (18+26) cm= 88cm\n2*22/7* R= 88 ⇒ R= (88*7/44) =14 cm\nArea of the circle = πr2 = (22/7 *14*14) cm2 =616 cm2" }, { "code": null, "e": 6259, "s": 6103, "text": "Q 7 - On expanding every side of an equilateral triangle by 2cm, there is an increment of 2√3 cm2 in its zone. The length of every side of the Triangle is:" }, { "code": null, "e": 6267, "s": 6259, "text": "A - 1cm" }, { "code": null, "e": 6277, "s": 6267, "text": "B - √3 cm" }, { "code": null, "e": 6285, "s": 6277, "text": "C - 3cm" }, { "code": null, "e": 6299, "s": 6285, "text": "D - (2+√3) cm" }, { "code": null, "e": 6452, "s": 6299, "text": "Let each side of the triangle be x cm. then, area = (√3/4) x2 cm2\n∴ √3/4 (x+2)2- √3/4 x2= 2√3 ⇒√3/4{(x+2)2- x2} =2√3\n⇒ √3/4* 4(x+1) = 2√3 ⇒ x+1= 2 ⇒x= 1" }, { "code": null, "e": 6606, "s": 6452, "text": "Q 8 - The range of a square is equivalent to the territory of a circle. What is the proportion between the side of the square and the span of the circle?" }, { "code": null, "e": 6615, "s": 6606, "text": "A - √π:1" }, { "code": null, "e": 6624, "s": 6615, "text": "B - 1:√π" }, { "code": null, "e": 6632, "s": 6624, "text": "C - 1:π" }, { "code": null, "e": 6640, "s": 6632, "text": "D - π:1" }, { "code": null, "e": 6755, "s": 6640, "text": "Let the side of the square be a and radius of the circle be r.\n Then, a2 =πr2 ⇒a = √πr⇒ A/R=√π/1 ⇒a: r =√π:1" }, { "code": null, "e": 6852, "s": 6755, "text": "Q 9 - The region of a rhombus is 2016cm2 and its side is 65cm. The lengths of its diagonals are:" }, { "code": null, "e": 6870, "s": 6852, "text": "A - 125 cm, 35 cm" }, { "code": null, "e": 6888, "s": 6870, "text": "B - 126 cm, 32 cm" }, { "code": null, "e": 6906, "s": 6888, "text": "C - 132 cm, 26 cm" }, { "code": null, "e": 6924, "s": 6906, "text": "D - 135 cm, 25 cm" }, { "code": null, "e": 7219, "s": 6924, "text": "1/2 d1* d2=2016 ⇒d1*d2=4032\n(1/2 d1)2+ (1/2 d2)2 = (65)2⇒d12+d22= 16900\n∴d12+d22+2d1d2 = (16900+8064) =24964 ⇒ (d1+d2)2= (158)2\n⇒d1+d2 =158\nd12+d22-2d1d2 = (16900-8064) =8836 ⇒ (d1-d2)2= (94)2\n⇒d1-d2=94\nd1+d2=158, d1-d2 =94 ⇒2d1=252 ⇒d1=126cm\n⇒d2= (158-126) =32 cm\n∴diagonals are 126 cm, 32 cm." }, { "code": null, "e": 7382, "s": 7219, "text": "Q 10 - A round greenery enclosure has an outline of 440 m. There is a 7m wide fringe inside the patio nursery along its outskirts. The territory of the fringe is:" }, { "code": null, "e": 7393, "s": 7382, "text": "A - 2918m2" }, { "code": null, "e": 7405, "s": 7393, "text": "B - 2921 m2" }, { "code": null, "e": 7417, "s": 7405, "text": "C - 2924 m2" }, { "code": null, "e": 7429, "s": 7417, "text": "D - 2926 m2" }, { "code": null, "e": 7608, "s": 7429, "text": "2πR =440 ⇒ 2*22/7*R= 440 ⇒R= (440* 7/44)=70 m\nOuter radius = 70m, inner radius = (70-7) =63 m\nRequired area = π [(70)2-(63)2] m2= 22/7 *(70+63) (70-63) m2\n= (22*133) m2, = 2926m2" }, { "code": null, "e": 7644, "s": 7608, "text": "\n 87 Lectures \n 22.5 hours \n" }, { "code": null, "e": 7662, "s": 7644, "text": " Programming Line" }, { "code": null, "e": 7669, "s": 7662, "text": " Print" }, { "code": null, "e": 7680, "s": 7669, "text": " Add Notes" } ]
C# Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type with square brackets: string[] cars; We have now declared a variable that holds an array of strings. To insert values to it, we can use an array literal - place the values in a comma-separated list, inside curly braces: string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; To create an array of integers, you could write: int[] myNum = {10, 20, 30, 40}; You access an array element by referring to the index number. This statement accesses the value of the first element in cars: string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; Console.WriteLine(cars[0]); // Outputs Volvo Try it Yourself » Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc. To change the value of a specific element, refer to the index number: cars[0] = "Opel"; string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; cars[0] = "Opel"; Console.WriteLine(cars[0]); // Now outputs Opel instead of Volvo Try it Yourself » To find out how many elements an array has, use the Length property: string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; Console.WriteLine(cars.Length); // Outputs 4 Try it Yourself » You can loop through the array elements with the for loop, and use the Length property to specify how many times the loop should run. The following example outputs all elements in the cars array: string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (int i = 0; i < cars.Length; i++) { Console.WriteLine(cars[i]); } Try it Yourself » There is also a foreach loop, which is used exclusively to loop through elements in an array: foreach (type variableName in arrayName) { // code block to be executed } The following example outputs all elements in the cars array, using a foreach loop: string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; foreach (string i in cars) { Console.WriteLine(i); } Try it Yourself » The example above can be read like this: for each string element (called i - as in index) in cars, print out the value of i. If you compare the for loop and foreach loop, you will see that the foreach method is easier to write, it does not require a counter (using the Length property), and it is more readable. There are many array methods available, for example Sort(), which sorts an array alphabetically or in an ascending order: // Sort a string string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; Array.Sort(cars); foreach (string i in cars) { Console.WriteLine(i); } // Sort an int int[] myNumbers = {5, 1, 8, 9}; Array.Sort(myNumbers); foreach (int i in myNumbers) { Console.WriteLine(i); } Try it Yourself » Other useful array methods, such as Min, Max, and Sum, can be found in the System.Linq namespace: using System; using System.Linq; namespace MyApplication { class Program { static void Main(string[] args) { int[] myNumbers = {5, 1, 8, 9}; Console.WriteLine(myNumbers.Max()); // returns the largest value Console.WriteLine(myNumbers.Min()); // returns the smallest value Console.WriteLine(myNumbers.Sum()); // returns the sum of elements } } } Try it Yourself » You will learn more about other namespaces in a later chapter. If you are familiar with C#, you might have seen arrays created with the new keyword, and perhaps you have seen arrays with a specified size as well. In C#, there are different ways to create an array: // Create an array of four elements, and add values later string[] cars = new string[4]; // Create an array of four elements and add values right away string[] cars = new string[4] {"Volvo", "BMW", "Ford", "Mazda"}; // Create an array of four elements without specifying the size string[] cars = new string[] {"Volvo", "BMW", "Ford", "Mazda"}; // Create an array of four elements, omitting the new keyword, and without specifying the size string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; It is up to you which option you choose. In our tutorial, we will often use the last option, as it is faster and easier to read. However, you should note that if you declare an array and initialize it later, you have to use the new keyword: // Declare an array string[] cars; // Add values, using new cars = new string[] {"Volvo", "BMW", "Ford"}; // Add values without using new (this will cause an error) cars = {"Volvo", "BMW", "Ford"}; Try it Yourself » Create an array of type string called cars. = {"Volvo", "BMW", "Ford", "Mazda"}; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 120, "s": 0, "text": "Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each \nvalue." }, { "code": null, "e": 188, "s": 120, "text": "To declare an array, define the variable type with square brackets:" }, { "code": null, "e": 204, "s": 188, "text": "string[] cars;\n" }, { "code": null, "e": 268, "s": 204, "text": "We have now declared a variable that holds an array of strings." }, { "code": null, "e": 387, "s": 268, "text": "To insert values to it, we can use an array literal - place the values in a comma-separated list, inside curly braces:" }, { "code": null, "e": 439, "s": 387, "text": "string[] cars = {\"Volvo\", \"BMW\", \"Ford\", \"Mazda\"};\n" }, { "code": null, "e": 488, "s": 439, "text": "To create an array of integers, you could write:" }, { "code": null, "e": 521, "s": 488, "text": "int[] myNum = {10, 20, 30, 40};\n" }, { "code": null, "e": 583, "s": 521, "text": "You access an array element by referring to the index number." }, { "code": null, "e": 647, "s": 583, "text": "This statement accesses the value of the first element in cars:" }, { "code": null, "e": 744, "s": 647, "text": "string[] cars = {\"Volvo\", \"BMW\", \"Ford\", \"Mazda\"};\nConsole.WriteLine(cars[0]);\n// Outputs Volvo\n" }, { "code": null, "e": 764, "s": 744, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 857, "s": 764, "text": "Note: Array indexes start with 0: [0] is the first element. [1] is the second \nelement, etc." }, { "code": null, "e": 927, "s": 857, "text": "To change the value of a specific element, refer to the index number:" }, { "code": null, "e": 946, "s": 927, "text": "cars[0] = \"Opel\";\n" }, { "code": null, "e": 1081, "s": 946, "text": "string[] cars = {\"Volvo\", \"BMW\", \"Ford\", \"Mazda\"};\ncars[0] = \"Opel\";\nConsole.WriteLine(cars[0]);\n// Now outputs Opel instead of Volvo\n" }, { "code": null, "e": 1101, "s": 1081, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1171, "s": 1101, "text": "To find out how many elements an array has, use the \nLength property:" }, { "code": null, "e": 1268, "s": 1171, "text": "string[] cars = {\"Volvo\", \"BMW\", \"Ford\", \"Mazda\"};\nConsole.WriteLine(cars.Length);\n// Outputs 4\n" }, { "code": null, "e": 1288, "s": 1268, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1424, "s": 1288, "text": "You can loop through the array elements with the for loop, and use the \nLength \nproperty to specify how many times the loop should run." }, { "code": null, "e": 1487, "s": 1424, "text": "The following example outputs all elements in the cars \narray:" }, { "code": null, "e": 1614, "s": 1487, "text": "string[] cars = {\"Volvo\", \"BMW\", \"Ford\", \"Mazda\"};\nfor (int i = 0; i < cars.Length; i++) \n{\n Console.WriteLine(cars[i]);\n}\n \n" }, { "code": null, "e": 1634, "s": 1614, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1728, "s": 1634, "text": "There is also a foreach loop, which is used exclusively to loop through elements in an array:" }, { "code": null, "e": 1806, "s": 1728, "text": "foreach (type variableName in arrayName) \n{\n // code block to be executed\n}\n" }, { "code": null, "e": 1891, "s": 1806, "text": "The following example outputs all elements in the cars \narray, using a foreach loop:" }, { "code": null, "e": 2001, "s": 1891, "text": "string[] cars = {\"Volvo\", \"BMW\", \"Ford\", \"Mazda\"};\nforeach (string i in cars) \n{\n Console.WriteLine(i);\n}\n \n" }, { "code": null, "e": 2021, "s": 2001, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 2148, "s": 2021, "text": "The example above can be read like this: for each\nstring element (called \ni - as in \nindex) in cars, print out the value of i." }, { "code": null, "e": 2336, "s": 2148, "text": "If you compare the for loop and foreach loop, you will see that the foreach method is easier to write, it \ndoes not require a counter (using the Length property), and it is more readable." }, { "code": null, "e": 2459, "s": 2336, "text": "There are many array methods available, for example Sort(), which sorts an array \nalphabetically or in an ascending order:" }, { "code": null, "e": 2603, "s": 2459, "text": "// Sort a string\nstring[] cars = {\"Volvo\", \"BMW\", \"Ford\", \"Mazda\"};\nArray.Sort(cars);\nforeach (string i in cars)\n{\n Console.WriteLine(i);\n}\n \n" }, { "code": null, "e": 2732, "s": 2603, "text": "// Sort an int\nint[] myNumbers = {5, 1, 8, 9};\nArray.Sort(myNumbers);\nforeach (int i in myNumbers)\n{\n Console.WriteLine(i);\n} \n" }, { "code": null, "e": 2752, "s": 2732, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 2853, "s": 2752, "text": "Other useful array methods, such as \nMin, \nMax, and \nSum, can be found in the System.Linq namespace:" }, { "code": null, "e": 3253, "s": 2853, "text": "using System;\nusing System.Linq;\n\nnamespace MyApplication\n{\n class Program\n {\n static void Main(string[] args)\n {\n int[] myNumbers = {5, 1, 8, 9};\n Console.WriteLine(myNumbers.Max()); // returns the largest value\n Console.WriteLine(myNumbers.Min()); // returns the smallest value\n Console.WriteLine(myNumbers.Sum()); // returns the sum of elements\n }\n }\n}\n \n \n \n \n" }, { "code": null, "e": 3273, "s": 3253, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 3336, "s": 3273, "text": "You will learn more about other namespaces in a later chapter." }, { "code": null, "e": 3538, "s": 3336, "text": "If you are familiar with C#, you might have seen arrays created with the new keyword, and perhaps you have seen arrays with a specified size as well. In C#, there are different ways to create an array:" }, { "code": null, "e": 4034, "s": 3538, "text": "// Create an array of four elements, and add values later\nstring[] cars = new string[4];\n\n// Create an array of four elements and add values right away \nstring[] cars = new string[4] {\"Volvo\", \"BMW\", \"Ford\", \"Mazda\"};\n\n// Create an array of four elements without specifying the size \nstring[] cars = new string[] {\"Volvo\", \"BMW\", \"Ford\", \"Mazda\"};\n\n// Create an array of four elements, omitting the new keyword, and without specifying the size\nstring[] cars = {\"Volvo\", \"BMW\", \"Ford\", \"Mazda\"};\n" }, { "code": null, "e": 4163, "s": 4034, "text": "It is up to you which option you choose. In our tutorial, we will often use the last option, as it is faster and easier to read." }, { "code": null, "e": 4275, "s": 4163, "text": "However, you should note that if you declare an array and initialize it later, you have to use the new keyword:" }, { "code": null, "e": 4476, "s": 4275, "text": "// Declare an array\nstring[] cars;\n\n// Add values, using new\ncars = new string[] {\"Volvo\", \"BMW\", \"Ford\"};\n\n// Add values without using new (this will cause an error)\ncars = {\"Volvo\", \"BMW\", \"Ford\"};\n" }, { "code": null, "e": 4496, "s": 4476, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 4540, "s": 4496, "text": "Create an array of type string called cars." }, { "code": null, "e": 4580, "s": 4540, "text": " = {\"Volvo\", \"BMW\", \"Ford\", \"Mazda\"};\n" }, { "code": null, "e": 4599, "s": 4580, "text": "Start the Exercise" }, { "code": null, "e": 4632, "s": 4599, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 4674, "s": 4632, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 4781, "s": 4674, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 4800, "s": 4781, "text": "[email protected]" } ]
Selenium - Drop Down Interaction
In this section, we will understand how to interact with Drop down Boxes. We can select an option using 'selectByVisibleText' or 'selectByIndex' or 'selectByValue' methods. Let us understand how to interact with a dropdown box using https://www.calculator.net/interest-calculator.html. We can also check if a dropdown box is selected/enabled/visible. import java.util.concurrent.TimeUnit; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.Select; public class webdriverdemo { public static void main(String[] args) throws InterruptedException { WebDriver driver = new FirefoxDriver(); //Puts a Implicit wait, Will wait for 10 seconds before throwing exception driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //Launch website driver.navigate().to("http://www.calculator.net/interest-calculator.html"); driver.manage().window().maximize(); //Selecting an item from Drop Down list Box Select dropdown = new Select(driver.findElement(By.id("ccompound"))); dropdown.selectByVisibleText("continuously"); //you can also use dropdown.selectByIndex(1) to select second element as //index starts with 0. //You can also use dropdown.selectByValue("annually"); System.out.println("The Output of the IsSelected " + driver.findElement(By.id("ccompound")).isSelected()); System.out.println("The Output of the IsEnabled " + driver.findElement(By.id("ccompound")).isEnabled()); System.out.println("The Output of the IsDisplayed " + driver.findElement(By.id("ccompound")).isDisplayed()); driver.close(); } } Upon execution, the dropdown is set with the specified value and the output of the commands are displayed in the console. 46 Lectures 5.5 hours Aditya Dua 296 Lectures 146 hours Arun Motoori 411 Lectures 38.5 hours In28Minutes Official 22 Lectures 7 hours Arun Motoori 118 Lectures 17 hours Arun Motoori 278 Lectures 38.5 hours Lets Kode It Print Add Notes Bookmark this page
[ { "code": null, "e": 2048, "s": 1875, "text": "In this section, we will understand how to interact with Drop down Boxes. We can select an option using 'selectByVisibleText' or 'selectByIndex' or 'selectByValue' methods." }, { "code": null, "e": 2226, "s": 2048, "text": "Let us understand how to interact with a dropdown box using https://www.calculator.net/interest-calculator.html. We can also check if a dropdown box is selected/enabled/visible." }, { "code": null, "e": 3627, "s": 2226, "text": "import java.util.concurrent.TimeUnit;\n\nimport org.openqa.selenium.*;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport org.openqa.selenium.support.ui.Select;\n\npublic class webdriverdemo {\n public static void main(String[] args) throws InterruptedException {\n \n WebDriver driver = new FirefoxDriver();\n \n //Puts a Implicit wait, Will wait for 10 seconds before throwing exception\n driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);\n \n //Launch website\n driver.navigate().to(\"http://www.calculator.net/interest-calculator.html\");\n driver.manage().window().maximize();\n \n //Selecting an item from Drop Down list Box\n Select dropdown = new Select(driver.findElement(By.id(\"ccompound\")));\n dropdown.selectByVisibleText(\"continuously\");\n \n //you can also use dropdown.selectByIndex(1) to select second element as\n //index starts with 0.\n //You can also use dropdown.selectByValue(\"annually\");\n \n System.out.println(\"The Output of the IsSelected \" +\n driver.findElement(By.id(\"ccompound\")).isSelected());\n System.out.println(\"The Output of the IsEnabled \" +\n driver.findElement(By.id(\"ccompound\")).isEnabled());\n System.out.println(\"The Output of the IsDisplayed \" +\n driver.findElement(By.id(\"ccompound\")).isDisplayed());\n \n driver.close();\n }\n}" }, { "code": null, "e": 3749, "s": 3627, "text": "Upon execution, the dropdown is set with the specified value and the output of the commands are displayed in the console." }, { "code": null, "e": 3784, "s": 3749, "text": "\n 46 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3796, "s": 3784, "text": " Aditya Dua" }, { "code": null, "e": 3832, "s": 3796, "text": "\n 296 Lectures \n 146 hours \n" }, { "code": null, "e": 3846, "s": 3832, "text": " Arun Motoori" }, { "code": null, "e": 3883, "s": 3846, "text": "\n 411 Lectures \n 38.5 hours \n" }, { "code": null, "e": 3905, "s": 3883, "text": " In28Minutes Official" }, { "code": null, "e": 3938, "s": 3905, "text": "\n 22 Lectures \n 7 hours \n" }, { "code": null, "e": 3952, "s": 3938, "text": " Arun Motoori" }, { "code": null, "e": 3987, "s": 3952, "text": "\n 118 Lectures \n 17 hours \n" }, { "code": null, "e": 4001, "s": 3987, "text": " Arun Motoori" }, { "code": null, "e": 4038, "s": 4001, "text": "\n 278 Lectures \n 38.5 hours \n" }, { "code": null, "e": 4052, "s": 4038, "text": " Lets Kode It" }, { "code": null, "e": 4059, "s": 4052, "text": " Print" }, { "code": null, "e": 4070, "s": 4059, "text": " Add Notes" } ]
How to check email Address Validation in Android on edit Text
This example demonstrates how to check email Address Validation in Android on edit Text. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:id = "@+id/parent" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:gravity = "center" android:orientation = "vertical"> <EditText android:id = "@+id/emailId" android:hint = "Enter Email id" android:layout_margin = "20dp" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> <Button android:id = "@+id/text" android:textSize = "18sp" android:textAlignment = "center" android:layout_width = "wrap_content" android:textColor = "#000" android:text = "Check validation" android:layout_height = "wrap_content" /> </LinearLayout> In the above code, we have taken edit text and button. When the user clicks on a button, it will check edit text data and validate that data. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { int view = R.layout.activity_main; Button button; EditText emailId; String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"; @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(view); button = findViewById(R.id.text); emailId = findViewById(R.id.emailId); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(emailId.getText().toString().isEmpty()) { Toast.makeText(getApplicationContext(),"enter email address",Toast.LENGTH_SHORT).show(); }else { if (emailId.getText().toString().trim().matches(emailPattern)) { Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(),"Invalid email address", Toast.LENGTH_SHORT).show(); } } } }); } } In the above code, we are validating edit text data as shown below - String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"; .................................... if(emailId.getText().toString().isEmpty()) { Toast.makeText(getApplicationContext(),"enter email address",Toast.LENGTH_SHORT).show(); }else { if (emailId.getText().toString().trim().matches(emailPattern)) { Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(),"Invalid email address", Toast.LENGTH_SHORT).show(); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − In the above result, we have entered valid email id and clicked a button. It is showing the correct validation message as a valid email address. Now enter wrong email id and click on a button. It will show the message as shown below - Click here to download the project code
[ { "code": null, "e": 1151, "s": 1062, "text": "This example demonstrates how to check email Address Validation in Android on edit Text." }, { "code": null, "e": 1280, "s": 1151, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1345, "s": 1280, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2238, "s": 1345, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:id = \"@+id/parent\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:gravity = \"center\"\n android:orientation = \"vertical\">\n <EditText\n android:id = \"@+id/emailId\"\n android:hint = \"Enter Email id\"\n android:layout_margin = \"20dp\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\" />\n <Button\n android:id = \"@+id/text\"\n android:textSize = \"18sp\"\n android:textAlignment = \"center\"\n android:layout_width = \"wrap_content\"\n android:textColor = \"#000\"\n android:text = \"Check validation\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2380, "s": 2238, "text": "In the above code, we have taken edit text and button. When the user clicks on a button, it will check edit text data and validate that data." }, { "code": null, "e": 2437, "s": 2380, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3964, "s": 2437, "text": "package com.example.andy.myapplication;\nimport android.content.res.Configuration;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n int view = R.layout.activity_main;\n Button button;\n EditText emailId;\n String emailPattern = \"[a-zA-Z0-9._-]+@[a-z]+\\\\.+[a-z]+\";\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(view);\n button = findViewById(R.id.text);\n emailId = findViewById(R.id.emailId);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if(emailId.getText().toString().isEmpty()) {\n Toast.makeText(getApplicationContext(),\"enter email address\",Toast.LENGTH_SHORT).show();\n }else {\n if (emailId.getText().toString().trim().matches(emailPattern)) {\n Toast.makeText(getApplicationContext(),\"valid email address\",Toast.LENGTH_SHORT).show();\n } else {\n Toast.makeText(getApplicationContext(),\"Invalid email address\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n });\n }\n}" }, { "code": null, "e": 4033, "s": 3964, "text": "In the above code, we are validating edit text data as shown below -" }, { "code": null, "e": 4555, "s": 4033, "text": "String emailPattern = \"[a-zA-Z0-9._-]+@[a-z]+\\\\.+[a-z]+\";\n\n....................................\n\nif(emailId.getText().toString().isEmpty()) {\n Toast.makeText(getApplicationContext(),\"enter email address\",Toast.LENGTH_SHORT).show();\n}else {\n if (emailId.getText().toString().trim().matches(emailPattern)) {\n Toast.makeText(getApplicationContext(),\"valid email address\",Toast.LENGTH_SHORT).show();\n } else {\n Toast.makeText(getApplicationContext(),\"Invalid email address\", Toast.LENGTH_SHORT).show();\n }\n}" }, { "code": null, "e": 4902, "s": 4555, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 5137, "s": 4902, "text": "In the above result, we have entered valid email id and clicked a button. It is showing the correct validation message as a valid email address. Now enter wrong email id and click on a button. It will show the message as shown below -" }, { "code": null, "e": 5177, "s": 5137, "text": "Click here to download the project code" } ]
C++ Program to Implement Radix Sort
Radix sort is non-comparative sorting algorithm. This sorting algorithm works on the integer keys by grouping digits which share the same position and value. The radix is the base of a number system. As we know that in decimal system the radix or base is 10. So for sorting some decimal numbers, we need 10 positional box to store numbers. Time Complexity: O(nk) Time Complexity: O(nk) Space Complexity: O(n+k) Space Complexity: O(n+k) Input − The unsorted list: 802 630 20 745 52 300 612 932 78 187 Output − Data after Sorting: 20 52 78 187 300 612 630 745 802 932 Input: An array of data, and the total number in the array, digit count of max number. Output: Sorted array. Begin define 10 lists as pocket for i := 0 to max -1 do m = 10i+1 p := 10i for j := 0 to n-1 do temp := array[j] mod m index := temp / p pocket[index].append(array[j]) done count := 0 for j := 0 to radix do while pocket[j] is not empty array[count] := get first node of pocket[j] and delete it count := count +1 done done End #include<iostream> #include<list> #include<cmath> using namespace std; void display(int *array, int size) { for(int i = 0; i<size; i++) cout << array[i] << " "; cout << endl; } void radixSort(int *arr, int n, int max) { int i, j, m, p = 1, index, temp, count = 0; list<int> pocket[10]; //radix of decimal number is 10 for(i = 0; i< max; i++) { m = pow(10, i+1); p = pow(10, i); for(j = 0; j<n; j++) { temp = arr[j]%m; index = temp/p; //find index for pocket array pocket[index].push_back(arr[j]); } count = 0; for(j = 0; j<10; j++) { //delete from linked lists and store to array while(!pocket[j].empty()) { arr[count] = *(pocket[j].begin()); pocket[j].erase(pocket[j].begin()); count++; } } } } int main() { int n, max; cout << "Enter the number of elements: "; cin >> n; cout << "Enter the maximum digit of elements: "; cin >> max; int arr[n]; //create an array with given number of elements cout << "Enter elements:" << endl; for(int i = 0; i<n; i++) { cin >> arr[i]; } cout << "Data before Sorting: "; display(arr, n); radixSort(arr, n, max); cout << "Data after Sorting: "; display(arr, n); } Enter the number of elements: 10 Enter the maximum digit of elements: 3 Enter elements: 802 630 20 745 52 300 612 932 78 187 Data before Sorting: 802 630 20 745 52 300 612 932 78 187 Data after Sorting: 20 52 78 187 300 612 630 745 802 932
[ { "code": null, "e": 1402, "s": 1062, "text": "Radix sort is non-comparative sorting algorithm. This sorting algorithm works on the integer keys by grouping digits which share the same position and value. The radix is the base of a number system. As we know that in decimal system the radix or base is 10. So for sorting some decimal numbers, we need 10 positional box to store numbers." }, { "code": null, "e": 1425, "s": 1402, "text": "Time Complexity: O(nk)" }, { "code": null, "e": 1448, "s": 1425, "text": "Time Complexity: O(nk)" }, { "code": null, "e": 1473, "s": 1448, "text": "Space Complexity: O(n+k)" }, { "code": null, "e": 1498, "s": 1473, "text": "Space Complexity: O(n+k)" }, { "code": null, "e": 1628, "s": 1498, "text": "Input − The unsorted list: 802 630 20 745 52 300 612 932 78 187\nOutput − Data after Sorting: 20 52 78 187 300 612 630 745 802 932" }, { "code": null, "e": 1715, "s": 1628, "text": "Input: An array of data, and the total number in the array, digit count of max number." }, { "code": null, "e": 1737, "s": 1715, "text": "Output: Sorted array." }, { "code": null, "e": 2147, "s": 1737, "text": "Begin\n define 10 lists as pocket\n for i := 0 to max -1 do\n m = 10i+1\n p := 10i\n for j := 0 to n-1 do\n temp := array[j] mod m\n index := temp / p\n pocket[index].append(array[j])\n done\n count := 0\n for j := 0 to radix do\n while pocket[j] is not empty\n array[count] := get first node of pocket[j] and delete it\n count := count +1\n done\n done\nEnd" }, { "code": null, "e": 3459, "s": 2147, "text": "#include<iostream>\n#include<list>\n#include<cmath>\nusing namespace std;\nvoid display(int *array, int size) {\n for(int i = 0; i<size; i++)\n cout << array[i] << \" \";\n cout << endl;\n}\nvoid radixSort(int *arr, int n, int max) {\n int i, j, m, p = 1, index, temp, count = 0;\n list<int> pocket[10]; //radix of decimal number is 10\n for(i = 0; i< max; i++) {\n m = pow(10, i+1);\n p = pow(10, i);\n for(j = 0; j<n; j++) {\n temp = arr[j]%m;\n index = temp/p; //find index for pocket array\n pocket[index].push_back(arr[j]);\n }\n count = 0;\n for(j = 0; j<10; j++) {\n //delete from linked lists and store to array\n while(!pocket[j].empty()) {\n arr[count] = *(pocket[j].begin());\n pocket[j].erase(pocket[j].begin());\n count++;\n }\n }\n }\n}\nint main() {\n int n, max;\n cout << \"Enter the number of elements: \";\n cin >> n;\n cout << \"Enter the maximum digit of elements: \";\n cin >> max;\n int arr[n]; //create an array with given number of elements\n cout << \"Enter elements:\" << endl;\n for(int i = 0; i<n; i++) {\n cin >> arr[i];\n }\n cout << \"Data before Sorting: \";\n display(arr, n);\n radixSort(arr, n, max);\n cout << \"Data after Sorting: \";\n display(arr, n);\n}" }, { "code": null, "e": 3699, "s": 3459, "text": "Enter the number of elements: 10\nEnter the maximum digit of elements: 3\nEnter elements:\n802 630 20 745 52 300 612 932 78 187\nData before Sorting: 802 630 20 745 52 300 612 932 78 187\nData after Sorting: 20 52 78 187 300 612 630 745 802 932" } ]
How to detect when an OptionMenu or Checkbutton changes in Tkinter?
Let us suppose that in a particular application, we have some fixed set of options or choices for the user in a drop-down list. The Options or Choices can be created using the OptionMenu Widget Constructor. OptionMenu(window, variable, choice1, choice2, choice3......) Once the option is created, it can be detected by a click event which generally prints whether a particular option is selected or not. For this example, we will simply create an application where a check button will be present with some choices from the range (1 to 9). By default, the button is set to “1” using the set method. Selecting other options will print the button on the screen. #Import the tkinter library from tkinter import * #Create an instance of tkinter frame tk = Tk() tk.geometry("700x300") #Create the option and Check Button Event def OptionMenu_CheckButton(event): print(var.get()) pass #Create the variables var = StringVar();var.set("1") options = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] OptionMenu(tk, var, *(options), command = OptionMenu_CheckButton).pack() tk.mainloop() Running the above code will trace the options selected by the user and print it on the screen.
[ { "code": null, "e": 1269, "s": 1062, "text": "Let us suppose that in a particular application, we have some fixed set of options or choices for the user in a drop-down list. The Options or Choices can be created using the OptionMenu Widget Constructor." }, { "code": null, "e": 1331, "s": 1269, "text": "OptionMenu(window, variable, choice1, choice2, choice3......)" }, { "code": null, "e": 1721, "s": 1331, "text": "Once the option is created, it can be detected by a click event which generally prints whether a particular option is selected or not. For this example, we will simply create an application where a check button will be present with some choices from the range (1 to 9). By default, the button is set to “1” using the set method. Selecting other options will print the button on the screen." }, { "code": null, "e": 2145, "s": 1721, "text": "#Import the tkinter library\nfrom tkinter import *\n\n#Create an instance of tkinter frame\ntk = Tk()\ntk.geometry(\"700x300\")\n\n#Create the option and Check Button Event\ndef OptionMenu_CheckButton(event):\n print(var.get())\n pass\n\n#Create the variables\nvar = StringVar();var.set(\"1\")\noptions = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"]\nOptionMenu(tk, var, *(options), command =\nOptionMenu_CheckButton).pack()\ntk.mainloop()" }, { "code": null, "e": 2240, "s": 2145, "text": "Running the above code will trace the options selected by the user and print it on\nthe screen." } ]
Adding Text on Image using Python | by Behic Guven | Towards Data Science
In this post, I will show you how to add text to your images using Python. This will a very simple project where we will use programming to do some design. After this post, you will be able to design your next flyer or business card using some python skills. Doesn’t that sound cool? Maybe not the best way to do the design but it’s possible :) As a person who likes design and programming, I thought this will be a great project where I can combine my both interests. This is actually a great part of programming, you can always find different areas to practice your skills. In my previous post I showed how to add text to your videos, and today we will do it on an image. Let’s begin! Import Pillow Library Choose an Image Font Selection Render the Text Export the Result Video Demonstration towardsdatascience.com First things first, let’s install the library that we will need for this project. After the installation is completed, we can import the library to use it in the project. The best way to install this library is using PIP, which is a python package manager tool. Works perfectly with most of the Python libraries. pip install pillow Great, now we can import it to our code. When working with big libraries, instead of importing the whole library, it’s better to practice to import the specific functions that will be used. This will save storage and time when running the program. For our simple project, we will just need three functions: Image, ImageFont, and ImageDraw. We can import all three of them in one line of code as follows: from PIL import Image, ImageFont, ImageDraw In this step, we will choose and import an image that we want to add text on it. I recommend using Unsplash, which is a great stock photo website to find a good quality image. Here is the image I’ve downloaded that also matches the Fall season: After downloading the image, make sure to copy it inside the same directory that your code is. This will help you to import it to the program. Let’s define a new variable and assign the image using open method. my_image = Image.open("nature.jpg") The good thing about this project, you can choose your font style. Customizing the font will give us more flexibility when designing. First, we will download the TTF(TrueType Font) file of the font we want to choose. After having the file in the same directory, we can import it to our program using ImageFont function. Here is the font I will use. title_font = ImageFont.truetype('playfair/playfair-font.ttf', 200) Now, we can move to the next step, where we will add the text. This step is where the magic happens. After choosing the image and font, it’s time to decide what to write. Firstly, we will define a text variable and assign a string to it. title_text = "The Beauty of Nature" Secondly, we will use the ImageDraw function to convert our image into an editable format. Thanks to the Pillow library, we can do it in one line. image_editable = ImageDraw.Draw(my_image) Thirdly, we will do the rendering. There are four parameters we will pass into the rendering function. I will share the descriptions of each parameter below the code with some helpful sources. image_editable.text((15,15), title_text, (237, 230, 211), font=title_font) Starting Coordinates: Pillow library uses a Cartesian pixel coordinate system, with (0,0) in the upper left corner. Text: String between single or double quotations Text color in RGB format: Google Picker is a great resource to find the best color. Search “Color Picker” on Google and it will show up. Font style: Google Fonts is a great resource to pick your font style, and you can also download the TTF(TrueType Font) file of the font family. towardsdatascience.com Well done! We are almost done. This will be the shortest step where will just export the edited image. Here is the code to export using the save method. my_image.save("result.jpg") lifexplorer.medium.com Congrats!! You have created a program that renders custom text on an image using Python. Not the best way to design an image, but the possibility of doing it using programming is cool. Hoping that you enjoyed reading this article and working on the project. I would be glad if you learned something new today. Working on hands-on programming projects like this one is the best way to sharpen your coding skills. Feel free to contact me if you have any questions while implementing the code. Follow my blog and youtube channel to stay inspired. Thank you,
[ { "code": null, "e": 516, "s": 171, "text": "In this post, I will show you how to add text to your images using Python. This will a very simple project where we will use programming to do some design. After this post, you will be able to design your next flyer or business card using some python skills. Doesn’t that sound cool? Maybe not the best way to do the design but it’s possible :)" }, { "code": null, "e": 858, "s": 516, "text": "As a person who likes design and programming, I thought this will be a great project where I can combine my both interests. This is actually a great part of programming, you can always find different areas to practice your skills. In my previous post I showed how to add text to your videos, and today we will do it on an image. Let’s begin!" }, { "code": null, "e": 880, "s": 858, "text": "Import Pillow Library" }, { "code": null, "e": 896, "s": 880, "text": "Choose an Image" }, { "code": null, "e": 911, "s": 896, "text": "Font Selection" }, { "code": null, "e": 927, "s": 911, "text": "Render the Text" }, { "code": null, "e": 945, "s": 927, "text": "Export the Result" }, { "code": null, "e": 965, "s": 945, "text": "Video Demonstration" }, { "code": null, "e": 988, "s": 965, "text": "towardsdatascience.com" }, { "code": null, "e": 1301, "s": 988, "text": "First things first, let’s install the library that we will need for this project. After the installation is completed, we can import the library to use it in the project. The best way to install this library is using PIP, which is a python package manager tool. Works perfectly with most of the Python libraries." }, { "code": null, "e": 1320, "s": 1301, "text": "pip install pillow" }, { "code": null, "e": 1660, "s": 1320, "text": "Great, now we can import it to our code. When working with big libraries, instead of importing the whole library, it’s better to practice to import the specific functions that will be used. This will save storage and time when running the program. For our simple project, we will just need three functions: Image, ImageFont, and ImageDraw." }, { "code": null, "e": 1724, "s": 1660, "text": "We can import all three of them in one line of code as follows:" }, { "code": null, "e": 1769, "s": 1724, "text": "from PIL import Image, ImageFont, ImageDraw " }, { "code": null, "e": 2014, "s": 1769, "text": "In this step, we will choose and import an image that we want to add text on it. I recommend using Unsplash, which is a great stock photo website to find a good quality image. Here is the image I’ve downloaded that also matches the Fall season:" }, { "code": null, "e": 2225, "s": 2014, "text": "After downloading the image, make sure to copy it inside the same directory that your code is. This will help you to import it to the program. Let’s define a new variable and assign the image using open method." }, { "code": null, "e": 2261, "s": 2225, "text": "my_image = Image.open(\"nature.jpg\")" }, { "code": null, "e": 2395, "s": 2261, "text": "The good thing about this project, you can choose your font style. Customizing the font will give us more flexibility when designing." }, { "code": null, "e": 2610, "s": 2395, "text": "First, we will download the TTF(TrueType Font) file of the font we want to choose. After having the file in the same directory, we can import it to our program using ImageFont function. Here is the font I will use." }, { "code": null, "e": 2677, "s": 2610, "text": "title_font = ImageFont.truetype('playfair/playfair-font.ttf', 200)" }, { "code": null, "e": 2740, "s": 2677, "text": "Now, we can move to the next step, where we will add the text." }, { "code": null, "e": 2915, "s": 2740, "text": "This step is where the magic happens. After choosing the image and font, it’s time to decide what to write. Firstly, we will define a text variable and assign a string to it." }, { "code": null, "e": 2951, "s": 2915, "text": "title_text = \"The Beauty of Nature\"" }, { "code": null, "e": 3098, "s": 2951, "text": "Secondly, we will use the ImageDraw function to convert our image into an editable format. Thanks to the Pillow library, we can do it in one line." }, { "code": null, "e": 3140, "s": 3098, "text": "image_editable = ImageDraw.Draw(my_image)" }, { "code": null, "e": 3333, "s": 3140, "text": "Thirdly, we will do the rendering. There are four parameters we will pass into the rendering function. I will share the descriptions of each parameter below the code with some helpful sources." }, { "code": null, "e": 3408, "s": 3333, "text": "image_editable.text((15,15), title_text, (237, 230, 211), font=title_font)" }, { "code": null, "e": 3524, "s": 3408, "text": "Starting Coordinates: Pillow library uses a Cartesian pixel coordinate system, with (0,0) in the upper left corner." }, { "code": null, "e": 3573, "s": 3524, "text": "Text: String between single or double quotations" }, { "code": null, "e": 3710, "s": 3573, "text": "Text color in RGB format: Google Picker is a great resource to find the best color. Search “Color Picker” on Google and it will show up." }, { "code": null, "e": 3854, "s": 3710, "text": "Font style: Google Fonts is a great resource to pick your font style, and you can also download the TTF(TrueType Font) file of the font family." }, { "code": null, "e": 3877, "s": 3854, "text": "towardsdatascience.com" }, { "code": null, "e": 4030, "s": 3877, "text": "Well done! We are almost done. This will be the shortest step where will just export the edited image. Here is the code to export using the save method." }, { "code": null, "e": 4058, "s": 4030, "text": "my_image.save(\"result.jpg\")" }, { "code": null, "e": 4081, "s": 4058, "text": "lifexplorer.medium.com" }, { "code": null, "e": 4493, "s": 4081, "text": "Congrats!! You have created a program that renders custom text on an image using Python. Not the best way to design an image, but the possibility of doing it using programming is cool. Hoping that you enjoyed reading this article and working on the project. I would be glad if you learned something new today. Working on hands-on programming projects like this one is the best way to sharpen your coding skills." }, { "code": null, "e": 4572, "s": 4493, "text": "Feel free to contact me if you have any questions while implementing the code." } ]
HTML | DOM Input Text Object - GeeksforGeeks
22 Feb, 2022 The Input Text Object in HTML DOM is used to represent the HTML <input> element with type=”text” attribute. The <input> element with type=”text” can be accessed by using getElementById() method. Syntax: It is used to access input text object. document.getElementById("id"); It is used to create input element. document.createElement("input"); Input Text Object Properties: Methods focus() : It is used to get focus to the input text field. blur () : It is used to remove focus from the text field . select () : It is used to select the content of the Input text field. Example 1: This example use getElementById() method to access <input> element with type=”text” attribute. html <!DOCTYPE html><html> <head> <title> HTML DOM Input Text Object </title></head> <body> <h1>GeeksForGeeks</h1> <h2>DOM Input Text Object</h2> <input type="text" id="text_id" value="Hello Geeks!"> <p>Click on button to display the text field</p> <button onclick="myGeeks()">Click Here!</button> <p id="GFG"></p> <!-- script to access text field --> <script> function myGeeks() { var txt = document.getElementById("text_id").value; document.getElementById("GFG").innerHTML = txt; } </script></body> </html> Output: Before click on the button: After click on the button: Example 2: This example use document.createElement() method to create <input> element with type=”text” attribute. html <!DOCTYPE html><html> <head> <title> HTML DOM Input Text Object </title></head> <body> <h1>GeeksForGeeks</h1> <h2>DOM Input Text Object</h2> <p>Click the button to create Text Field</p> <button onclick = "myGeeks()"> Click Here! </button> <!-- script to create th element --> <script> function myGeeks() { /* Create an input element */ var x = document.createElement("INPUT"); /* Set the type attribute */ x.setAttribute("type", "text"); /* Set the value to the attribute */ x.setAttribute("value", "Hello Geeks!"); /* Append node to the body */ document.body.appendChild(x); } </script> </body></html> Output: Before click on the button: After click on the button: Supported Browsers: Google Chrome Edge Mozilla Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ManasChhabra2 hritikbhatnagar2182 HTML-DOM Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 23649, "s": 23621, "text": "\n22 Feb, 2022" }, { "code": null, "e": 23844, "s": 23649, "text": "The Input Text Object in HTML DOM is used to represent the HTML <input> element with type=”text” attribute. The <input> element with type=”text” can be accessed by using getElementById() method." }, { "code": null, "e": 23854, "s": 23844, "text": "Syntax: " }, { "code": null, "e": 23895, "s": 23854, "text": "It is used to access input text object. " }, { "code": null, "e": 23926, "s": 23895, "text": "document.getElementById(\"id\");" }, { "code": null, "e": 23963, "s": 23926, "text": "It is used to create input element. " }, { "code": null, "e": 23996, "s": 23963, "text": "document.createElement(\"input\");" }, { "code": null, "e": 24027, "s": 23996, "text": "Input Text Object Properties: " }, { "code": null, "e": 24035, "s": 24027, "text": "Methods" }, { "code": null, "e": 24094, "s": 24035, "text": "focus() : It is used to get focus to the input text field." }, { "code": null, "e": 24153, "s": 24094, "text": "blur () : It is used to remove focus from the text field ." }, { "code": null, "e": 24223, "s": 24153, "text": "select () : It is used to select the content of the Input text field." }, { "code": null, "e": 24330, "s": 24223, "text": "Example 1: This example use getElementById() method to access <input> element with type=”text” attribute. " }, { "code": null, "e": 24335, "s": 24330, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM Input Text Object </title></head> <body> <h1>GeeksForGeeks</h1> <h2>DOM Input Text Object</h2> <input type=\"text\" id=\"text_id\" value=\"Hello Geeks!\"> <p>Click on button to display the text field</p> <button onclick=\"myGeeks()\">Click Here!</button> <p id=\"GFG\"></p> <!-- script to access text field --> <script> function myGeeks() { var txt = document.getElementById(\"text_id\").value; document.getElementById(\"GFG\").innerHTML = txt; } </script></body> </html> ", "e": 24979, "s": 24335, "text": null }, { "code": null, "e": 25017, "s": 24979, "text": "Output: Before click on the button: " }, { "code": null, "e": 25046, "s": 25017, "text": "After click on the button: " }, { "code": null, "e": 25162, "s": 25046, "text": "Example 2: This example use document.createElement() method to create <input> element with type=”text” attribute. " }, { "code": null, "e": 25167, "s": 25162, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM Input Text Object </title></head> <body> <h1>GeeksForGeeks</h1> <h2>DOM Input Text Object</h2> <p>Click the button to create Text Field</p> <button onclick = \"myGeeks()\"> Click Here! </button> <!-- script to create th element --> <script> function myGeeks() { /* Create an input element */ var x = document.createElement(\"INPUT\"); /* Set the type attribute */ x.setAttribute(\"type\", \"text\"); /* Set the value to the attribute */ x.setAttribute(\"value\", \"Hello Geeks!\"); /* Append node to the body */ document.body.appendChild(x); } </script> </body></html> ", "e": 26022, "s": 25167, "text": null }, { "code": null, "e": 26060, "s": 26022, "text": "Output: Before click on the button: " }, { "code": null, "e": 26089, "s": 26060, "text": "After click on the button: " }, { "code": null, "e": 26109, "s": 26089, "text": "Supported Browsers:" }, { "code": null, "e": 26123, "s": 26109, "text": "Google Chrome" }, { "code": null, "e": 26128, "s": 26123, "text": "Edge" }, { "code": null, "e": 26144, "s": 26128, "text": "Mozilla Firefox" }, { "code": null, "e": 26150, "s": 26144, "text": "Opera" }, { "code": null, "e": 26157, "s": 26150, "text": "Safari" }, { "code": null, "e": 26296, "s": 26159, "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": 26310, "s": 26296, "text": "ManasChhabra2" }, { "code": null, "e": 26330, "s": 26310, "text": "hritikbhatnagar2182" }, { "code": null, "e": 26339, "s": 26330, "text": "HTML-DOM" }, { "code": null, "e": 26346, "s": 26339, "text": "Picked" }, { "code": null, "e": 26351, "s": 26346, "text": "HTML" }, { "code": null, "e": 26368, "s": 26351, "text": "Web Technologies" }, { "code": null, "e": 26373, "s": 26368, "text": "HTML" }, { "code": null, "e": 26471, "s": 26373, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26480, "s": 26471, "text": "Comments" }, { "code": null, "e": 26493, "s": 26480, "text": "Old Comments" }, { "code": null, "e": 26555, "s": 26493, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26605, "s": 26555, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 26665, "s": 26605, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 26713, "s": 26665, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26774, "s": 26713, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 26830, "s": 26774, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26863, "s": 26830, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26925, "s": 26863, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26968, "s": 26925, "text": "How to fetch data from an API in ReactJS ?" } ]
Kali Linux – Sniffing and Spoofing
25 Sep, 2020 Sniffing is the process in which all the data packets passing in the network are monitored. Sniffers are usually used by network administrators to monitor and troubleshoot the network traffic. Whereas attackers use Sniffers to monitor and capture data packets to steal sensitive information containing password and user accounts. Sniffers can be hardware or software installed on the system. Spoofing is the process in which an intruder introduces fake traffic and pretends to be someone else (legal source or the legitimate entity). Spoofing is done by sending packets with incorrect source address over the network. The best way to deal and tackle with spoofing is to use a digital signature. Though Kali Linux comes packed with many tools for sniffing and spoofing the ones listed below, are mostly used by attackers these days. Wireshark is a network protocol analyzer that is termed to be the most used and best tool around the word. With Wireshark, you can see what is happening in your network and apply filters to get the most efficient results for what you are looking for. In Kali, Linux Wireshark is already installed and can be located under Applications — sniffing and spoofing — Wireshark. Wireshark is a GUI based tool, so once you click on the icon Wireshark GUI will open Once the GUI loads you can see several interfaces like Ethernet, Wi-Fi, Bluetooth, and so on, based on your connection to the network you can choose the interface and start capturing the network traffic. In this case, we are on Ethernet(eth0), so select the eth0 interface and click on the start capturing packets icon which is located in the top left corner. Once you start capturing packets it will look something like this : You can also apply specific filters for better searching, for example, if you want to track only HTTP requests you can use apply a display filter bar and apply all the filters you need for better track results. macchanger is the most used tool under sniffing and spoofing, macchanger can change your mac address, or we can say your physical address to hide your actual identity in the network. You can locate macchanger in Kali Linux under Applications — sniffing and spoofing — macchanger macchanger is a command-line based tool so once you click on macchanger a shell will pop up with the help menu Here is the example of macchanger tool application. Change random mac address: First, let’s change the network card’s hardware MAC address to a random address. First, we will find the MAC address of the eth0 network interface. To do this we execute macchanger with an option -s and an argument eth0. macchanger -s eth0 Now the network interface you are about to change a MAC address should be turned off before changing the mac address. Use ifconfig command to turn off your network interface. MITMPROXY is an SSL-capable man-in-the-middle HTTP proxy, providing a console interface that allows traffic flows to be inspected and edited at the moment they are captured. With mimproxy you can inspect and modify network traffic, save HTTP conversations for inspection, SSL inspection, and more. To open mitmproxy in Kali Linux you can simply locate it under Applications — sniffing and spoofing — mitmproxy or you can use a terminal and type the following command to display the help menu of the tool. mitmproxy -h Let’s see a simple example of using mitmproxy on port number, to do this you can simply use “mitmproxy -p portnumber”. In our case, let’s use port 80 mitmproxy -p 80 Burpsuite is a java based penetration testing framework that is recognized as an industry-standard tool. Burp has many use cases in penetration testing and can also be used as a sniffing tool between your browser and web servers to find parameters the web application uses. In Kali Linux, you can locate burpsuite under Applications — web analysis — burpsuite. To use burpsuite as a sniffing tool we need to configure it to behave like a proxy. Open burpsuite and go to options and select interface “127.0.0.1:8080” Now configure the browser proxy the same as the IP of burpsuite machine and the port. To start the interception go to Proxy — intercept and click “intercept is on”. Now all the requests going through your browser will be intercepted and you can navigate all the requests. Sniffing and spoofing deals a lot in information security, an intruder can track all the data flowing through your system, so make sure you follow the rules of CIA trait. Kali-Linux Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C tar command in Linux with examples SORT command in Linux/Unix with examples Compiling with g++ 'crontab' in Linux with Examples UDP Server-Client implementation in C touch command in Linux with Examples nohup Command in Linux with Examples echo command in Linux with Examples Cat command in Linux with examples
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Sep, 2020" }, { "code": null, "e": 420, "s": 28, "text": "Sniffing is the process in which all the data packets passing in the network are monitored. Sniffers are usually used by network administrators to monitor and troubleshoot the network traffic. Whereas attackers use Sniffers to monitor and capture data packets to steal sensitive information containing password and user accounts. Sniffers can be hardware or software installed on the system." }, { "code": null, "e": 723, "s": 420, "text": "Spoofing is the process in which an intruder introduces fake traffic and pretends to be someone else (legal source or the legitimate entity). Spoofing is done by sending packets with incorrect source address over the network. The best way to deal and tackle with spoofing is to use a digital signature." }, { "code": null, "e": 860, "s": 723, "text": "Though Kali Linux comes packed with many tools for sniffing and spoofing the ones listed below, are mostly used by attackers these days." }, { "code": null, "e": 1232, "s": 860, "text": "Wireshark is a network protocol analyzer that is termed to be the most used and best tool around the word. With Wireshark, you can see what is happening in your network and apply filters to get the most efficient results for what you are looking for. In Kali, Linux Wireshark is already installed and can be located under Applications — sniffing and spoofing — Wireshark." }, { "code": null, "e": 1318, "s": 1232, "text": "Wireshark is a GUI based tool, so once you click on the icon Wireshark GUI will open " }, { "code": null, "e": 1680, "s": 1318, "text": " Once the GUI loads you can see several interfaces like Ethernet, Wi-Fi, Bluetooth, and so on, based on your connection to the network you can choose the interface and start capturing the network traffic. In this case, we are on Ethernet(eth0), so select the eth0 interface and click on the start capturing packets icon which is located in the top left corner. " }, { "code": null, "e": 1748, "s": 1680, "text": "Once you start capturing packets it will look something like this :" }, { "code": null, "e": 1960, "s": 1748, "text": "You can also apply specific filters for better searching, for example, if you want to track only HTTP requests you can use apply a display filter bar and apply all the filters you need for better track results. " }, { "code": null, "e": 2143, "s": 1960, "text": "macchanger is the most used tool under sniffing and spoofing, macchanger can change your mac address, or we can say your physical address to hide your actual identity in the network." }, { "code": null, "e": 2239, "s": 2143, "text": "You can locate macchanger in Kali Linux under Applications — sniffing and spoofing — macchanger" }, { "code": null, "e": 2351, "s": 2239, "text": "macchanger is a command-line based tool so once you click on macchanger a shell will pop up with the help menu " }, { "code": null, "e": 2403, "s": 2351, "text": "Here is the example of macchanger tool application." }, { "code": null, "e": 2651, "s": 2403, "text": "Change random mac address: First, let’s change the network card’s hardware MAC address to a random address. First, we will find the MAC address of the eth0 network interface. To do this we execute macchanger with an option -s and an argument eth0." }, { "code": null, "e": 2671, "s": 2651, "text": "macchanger -s eth0\n" }, { "code": null, "e": 2847, "s": 2671, "text": "Now the network interface you are about to change a MAC address should be turned off before changing the mac address. Use ifconfig command to turn off your network interface. " }, { "code": null, "e": 3145, "s": 2847, "text": "MITMPROXY is an SSL-capable man-in-the-middle HTTP proxy, providing a console interface that allows traffic flows to be inspected and edited at the moment they are captured. With mimproxy you can inspect and modify network traffic, save HTTP conversations for inspection, SSL inspection, and more." }, { "code": null, "e": 3352, "s": 3145, "text": "To open mitmproxy in Kali Linux you can simply locate it under Applications — sniffing and spoofing — mitmproxy or you can use a terminal and type the following command to display the help menu of the tool." }, { "code": null, "e": 3365, "s": 3352, "text": "mitmproxy -h" }, { "code": null, "e": 3484, "s": 3365, "text": "Let’s see a simple example of using mitmproxy on port number, to do this you can simply use “mitmproxy -p portnumber”." }, { "code": null, "e": 3515, "s": 3484, "text": "In our case, let’s use port 80" }, { "code": null, "e": 3532, "s": 3515, "text": "mitmproxy -p 80\n" }, { "code": null, "e": 3806, "s": 3532, "text": "Burpsuite is a java based penetration testing framework that is recognized as an industry-standard tool. Burp has many use cases in penetration testing and can also be used as a sniffing tool between your browser and web servers to find parameters the web application uses." }, { "code": null, "e": 3893, "s": 3806, "text": "In Kali Linux, you can locate burpsuite under Applications — web analysis — burpsuite." }, { "code": null, "e": 4049, "s": 3893, "text": "To use burpsuite as a sniffing tool we need to configure it to behave like a proxy. Open burpsuite and go to options and select interface “127.0.0.1:8080”" }, { "code": null, "e": 4135, "s": 4049, "text": "Now configure the browser proxy the same as the IP of burpsuite machine and the port." }, { "code": null, "e": 4321, "s": 4135, "text": "To start the interception go to Proxy — intercept and click “intercept is on”. Now all the requests going through your browser will be intercepted and you can navigate all the requests." }, { "code": null, "e": 4492, "s": 4321, "text": "Sniffing and spoofing deals a lot in information security, an intruder can track all the data flowing through your system, so make sure you follow the rules of CIA trait." }, { "code": null, "e": 4503, "s": 4492, "text": "Kali-Linux" }, { "code": null, "e": 4514, "s": 4503, "text": "Linux-Unix" }, { "code": null, "e": 4612, "s": 4514, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4650, "s": 4612, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 4685, "s": 4650, "text": "tar command in Linux with examples" }, { "code": null, "e": 4726, "s": 4685, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 4745, "s": 4726, "text": "Compiling with g++" }, { "code": null, "e": 4778, "s": 4745, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 4816, "s": 4778, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 4853, "s": 4816, "text": "touch command in Linux with Examples" }, { "code": null, "e": 4890, "s": 4853, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 4926, "s": 4890, "text": "echo command in Linux with Examples" } ]
How to Change the Transparency of a Graph Plot in Matplotlib with Python?
25 Nov, 2020 Matplotlib is a library in Python and it is numerical — mathematical extension for NumPy library. Pyplot is a state-based interface to a matplotlib module which provides a MATLAB-like interface. There are various plots that can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc. In order to change the transparency of a graph plot in matplotlib we will use the matplotlib.pyplot.plot() function. The plot() function in pyplot module of matplotlib library is used to make 2D illustrations. Syntax: matplotlib.pyplot.plot(\*args, scalex=True, scaley=True, data=None, \*\*kwargs) Parameters: This method accept the following parameters that are described below: x, y: These parameter are the horizontal and vertical coordinates of the data points. x values are optional. fmt: This parameter is an optional parameter and it contains the string value. data: This parameter is an optional parameter and it is an object with labelled data. Returns: This returns the following: lines : This returns the list of Line2D objects representing the plotted data. Another argument that we are going to use is alpha argument, this argument is responsible for the transparency of any illustration depicted using matplotlib library. Its value ranges from 0 to 1, by default its value is 1 representing the opaqueness of the illustration. Example 1: Python3 # importing moduleimport matplotlib.pyplot as plt # assigning x and y coordinatesy = [0, 1, 2, 3, 4, 5]x = [0, 5, 10, 15, 20, 25] # depicting the visualizationplt.plot(x, y, color='green', alpha=0.25)plt.xlabel('x')plt.ylabel('y') # displaying the titleplt.title("Linear graph") plt.show() Output: In the above program, the linear graph is depicted with transparency i.e alpha=0.25. Example 2: Python3 # importing moduleimport matplotlib.pyplot as plt # assigning x and y coordinatesx = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]y = [] for i in range(len(x)): y.append(max(0, x[i])) # depicting the visualizationplt.plot(x, y, color='green', alpha=0.75)plt.xlabel('x')plt.ylabel('y') # displaying the titleplt.title(label="ReLU function graph", fontsize=40, color="green") Output: Here, the plot is quite opaque as the alphavalue is close to 1(opaque). Example 3: Python3 # importing modulesfrom matplotlib import pyplotimport numpy # assigning time values of the signal# initial time period, final time period# and phase anglesignalTime = numpy.arange(0, 100, 0.5) # getting the amplitude of the signalsignalAmplitude = numpy.sin(signalTime) # depicting the visualizationpyplot.plot(signalTime, signalAmplitude, color='green', alpha=0.1) pyplot.xlabel('Time')pyplot.ylabel('Amplitude') # displaying the titlepyplot.title("Signal", loc='right', rotation=45) Output: The above example depicts a signal with an alpha value 0.1. Example 4: Python3 # importing moduleimport matplotlib.pyplot as plt # assigning x and y coordinatesz = [i for i in range(0, 6)] for i in range(0, 11, 2): # depicting the visualization plt.plot(z, z, color='green', alpha=i/10) plt.xlabel('x') plt.ylabel('y') # displaying the title print('\nIllustration with alpha =', i/10) plt.show() Output: The above program depicts the same illustration with variable alpha values. Python-matplotlib Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Nov, 2020" }, { "code": null, "e": 332, "s": 28, "text": "Matplotlib is a library in Python and it is numerical — mathematical extension for NumPy library. Pyplot is a state-based interface to a matplotlib module which provides a MATLAB-like interface. There are various plots that can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc." }, { "code": null, "e": 543, "s": 332, "text": "In order to change the transparency of a graph plot in matplotlib we will use the matplotlib.pyplot.plot() function. The plot() function in pyplot module of matplotlib library is used to make 2D illustrations. " }, { "code": null, "e": 631, "s": 543, "text": "Syntax: matplotlib.pyplot.plot(\\*args, scalex=True, scaley=True, data=None, \\*\\*kwargs)" }, { "code": null, "e": 714, "s": 631, "text": "Parameters: This method accept the following parameters that are described below: " }, { "code": null, "e": 823, "s": 714, "text": "x, y: These parameter are the horizontal and vertical coordinates of the data points. x values are optional." }, { "code": null, "e": 902, "s": 823, "text": "fmt: This parameter is an optional parameter and it contains the string value." }, { "code": null, "e": 988, "s": 902, "text": "data: This parameter is an optional parameter and it is an object with labelled data." }, { "code": null, "e": 1026, "s": 988, "text": "Returns: This returns the following: " }, { "code": null, "e": 1105, "s": 1026, "text": "lines : This returns the list of Line2D objects representing the plotted data." }, { "code": null, "e": 1376, "s": 1105, "text": "Another argument that we are going to use is alpha argument, this argument is responsible for the transparency of any illustration depicted using matplotlib library. Its value ranges from 0 to 1, by default its value is 1 representing the opaqueness of the illustration." }, { "code": null, "e": 1388, "s": 1376, "text": "Example 1: " }, { "code": null, "e": 1396, "s": 1388, "text": "Python3" }, { "code": "# importing moduleimport matplotlib.pyplot as plt # assigning x and y coordinatesy = [0, 1, 2, 3, 4, 5]x = [0, 5, 10, 15, 20, 25] # depicting the visualizationplt.plot(x, y, color='green', alpha=0.25)plt.xlabel('x')plt.ylabel('y') # displaying the titleplt.title(\"Linear graph\") plt.show()", "e": 1690, "s": 1396, "text": null }, { "code": null, "e": 1698, "s": 1690, "text": "Output:" }, { "code": null, "e": 1783, "s": 1698, "text": "In the above program, the linear graph is depicted with transparency i.e alpha=0.25." }, { "code": null, "e": 1794, "s": 1783, "text": "Example 2:" }, { "code": null, "e": 1802, "s": 1794, "text": "Python3" }, { "code": "# importing moduleimport matplotlib.pyplot as plt # assigning x and y coordinatesx = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]y = [] for i in range(len(x)): y.append(max(0, x[i])) # depicting the visualizationplt.plot(x, y, color='green', alpha=0.75)plt.xlabel('x')plt.ylabel('y') # displaying the titleplt.title(label=\"ReLU function graph\", fontsize=40, color=\"green\")", "e": 2208, "s": 1802, "text": null }, { "code": null, "e": 2216, "s": 2208, "text": "Output:" }, { "code": null, "e": 2288, "s": 2216, "text": "Here, the plot is quite opaque as the alphavalue is close to 1(opaque)." }, { "code": null, "e": 2299, "s": 2288, "text": "Example 3:" }, { "code": null, "e": 2307, "s": 2299, "text": "Python3" }, { "code": "# importing modulesfrom matplotlib import pyplotimport numpy # assigning time values of the signal# initial time period, final time period# and phase anglesignalTime = numpy.arange(0, 100, 0.5) # getting the amplitude of the signalsignalAmplitude = numpy.sin(signalTime) # depicting the visualizationpyplot.plot(signalTime, signalAmplitude, color='green', alpha=0.1) pyplot.xlabel('Time')pyplot.ylabel('Amplitude') # displaying the titlepyplot.title(\"Signal\", loc='right', rotation=45)", "e": 2834, "s": 2307, "text": null }, { "code": null, "e": 2842, "s": 2834, "text": "Output:" }, { "code": null, "e": 2902, "s": 2842, "text": "The above example depicts a signal with an alpha value 0.1." }, { "code": null, "e": 2913, "s": 2902, "text": "Example 4:" }, { "code": null, "e": 2921, "s": 2913, "text": "Python3" }, { "code": "# importing moduleimport matplotlib.pyplot as plt # assigning x and y coordinatesz = [i for i in range(0, 6)] for i in range(0, 11, 2): # depicting the visualization plt.plot(z, z, color='green', alpha=i/10) plt.xlabel('x') plt.ylabel('y') # displaying the title print('\\nIllustration with alpha =', i/10) plt.show()", "e": 3269, "s": 2921, "text": null }, { "code": null, "e": 3277, "s": 3269, "text": "Output:" }, { "code": null, "e": 3353, "s": 3277, "text": "The above program depicts the same illustration with variable alpha values." }, { "code": null, "e": 3371, "s": 3353, "text": "Python-matplotlib" }, { "code": null, "e": 3395, "s": 3371, "text": "Technical Scripter 2020" }, { "code": null, "e": 3402, "s": 3395, "text": "Python" }, { "code": null, "e": 3421, "s": 3402, "text": "Technical Scripter" } ]
MongoDB – Insert Single Document Using MongoShell
27 Feb, 2020 In MongoDB, insert operations are used to add new documents in the collection. If the collection does not exist, then the insert operations create the collection by inserting documents. Or if the collection exists, then insert operations add new documents in the existing collection. You are allowed to add a single document in the collection using db.collection.insertOne() method. insertOne() is a mongo shell method, which can insert one document at a time. This method can be used in the multi-document transactions. In this method, you can add a document in the collection with or without _id field. If you add a document without _id field, then mongodb will automatically add a _id field and assign it with a unique ObjectId. Syntax: db.collection.deleteOne( <document>, { writeConcern: <document>, } ) Parameters: document: First parameter of this method. It represents a document that will insert in the collection. writeConcern: It is an optional parameter. It is only used when you do not want to use the default write concern. The type of this parameter is document. Return: This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled) and insertedId represents the _id field of the inserted document. Examples: In the following examples, we are working with: Database: GeeksforGeeks Collection: student In this example, we are inserting a document in the student collection without _id field using db.collection.insertOne() method. In this example, we are inserting a document in the student collection with _id field using db.collection.deleteOne() method. MongoDB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. System Design Tutorial ML | Linear Regression Docker - COPY Instruction Decision Tree Introduction with example Getting started with Machine Learning How to Run a Python Script using Docker? ML | Underfitting and Overfitting Clustering in Machine Learning Python | Decision tree implementation ML | Monte Carlo Tree Search (MCTS)
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Feb, 2020" }, { "code": null, "e": 411, "s": 28, "text": "In MongoDB, insert operations are used to add new documents in the collection. If the collection does not exist, then the insert operations create the collection by inserting documents. Or if the collection exists, then insert operations add new documents in the existing collection. You are allowed to add a single document in the collection using db.collection.insertOne() method." }, { "code": null, "e": 760, "s": 411, "text": "insertOne() is a mongo shell method, which can insert one document at a time. This method can be used in the multi-document transactions. In this method, you can add a document in the collection with or without _id field. If you add a document without _id field, then mongodb will automatically add a _id field and assign it with a unique ObjectId." }, { "code": null, "e": 768, "s": 760, "text": "Syntax:" }, { "code": null, "e": 859, "s": 768, "text": "db.collection.deleteOne(\n <document>,\n {\n writeConcern: <document>,\n \n }\n)" }, { "code": null, "e": 871, "s": 859, "text": "Parameters:" }, { "code": null, "e": 974, "s": 871, "text": "document: First parameter of this method. It represents a document that will insert in the collection." }, { "code": null, "e": 1128, "s": 974, "text": "writeConcern: It is an optional parameter. It is only used when you do not want to use the default write concern. The type of this parameter is document." }, { "code": null, "e": 1360, "s": 1128, "text": "Return: This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled) and insertedId represents the _id field of the inserted document." }, { "code": null, "e": 1370, "s": 1360, "text": "Examples:" }, { "code": null, "e": 1418, "s": 1370, "text": "In the following examples, we are working with:" }, { "code": null, "e": 1462, "s": 1418, "text": "Database: GeeksforGeeks\nCollection: student" }, { "code": null, "e": 1591, "s": 1462, "text": "In this example, we are inserting a document in the student collection without _id field using db.collection.insertOne() method." }, { "code": null, "e": 1717, "s": 1591, "text": "In this example, we are inserting a document in the student collection with _id field using db.collection.deleteOne() method." }, { "code": null, "e": 1725, "s": 1717, "text": "MongoDB" }, { "code": null, "e": 1751, "s": 1725, "text": "Advanced Computer Subject" }, { "code": null, "e": 1849, "s": 1751, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1872, "s": 1849, "text": "System Design Tutorial" }, { "code": null, "e": 1895, "s": 1872, "text": "ML | Linear Regression" }, { "code": null, "e": 1921, "s": 1895, "text": "Docker - COPY Instruction" }, { "code": null, "e": 1961, "s": 1921, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 1999, "s": 1961, "text": "Getting started with Machine Learning" }, { "code": null, "e": 2040, "s": 1999, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 2074, "s": 2040, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 2105, "s": 2074, "text": "Clustering in Machine Learning" }, { "code": null, "e": 2143, "s": 2105, "text": "Python | Decision tree implementation" } ]
Python Data Structures and Algorithms
06 Jul, 2022 This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc, and some user-defined data structures such as linked lists, trees, graphs, etc, and traversal as well as searching and sorting algorithms with the help of good and well-explained examples and practice questions. Python Lists are ordered collections of data just like arrays in other programming languages. It allows different types of elements in the list. The implementation of Python List is similar to Vectors in C++ or ArrayList in JAVA. The costly operation is inserting or deleting the element from the beginning of the List as all the elements are needed to be shifted. Insertion and deletion at the end of the list can also become costly in the case where the preallocated memory becomes full. Python3 List = [1, 2, 3, "GFG", 2.3]print(List) [1, 2, 3, 'GFG', 2.3] List elements can be accessed by the assigned index. In python starting index of the list, a sequence is 0 and the ending index is (if N elements are there) N-1. Python3 # Creating a List with# the use of multiple valuesList = ["Geeks", "For", "Geeks"]print("\nList containing multiple values: ")print(List) # Creating a Multi-Dimensional List# (By Nesting a list inside a List)List2 = [['Geeks', 'For'], ['Geeks']]print("\nMulti-Dimensional List: ")print(List2) # accessing a element from the# list using index numberprint("Accessing element from the list")print(List[0])print(List[2]) # accessing a element using# negative indexingprint("Accessing element using negative indexing") # print the last element of listprint(List[-1]) # print the third last element of listprint(List[-3]) List containing multiple values: ['Geeks', 'For', 'Geeks'] Multi-Dimensional List: [['Geeks', 'For'], ['Geeks']] Accessing element from the list Geeks Geeks Accessing element using negative indexing Geeks Geeks Python tuples are similar to lists but Tuples are immutable in nature i.e. once created it cannot be modified. Just like a List, a Tuple can also contain elements of various types. In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of the data sequence. Note: To create a tuple of one element there must be a trailing comma. For example, (8,) will create a tuple containing 8 as the element. Python3 # Creating a Tuple with# the use of StringsTuple = ('Geeks', 'For')print("\nTuple with the use of String: ")print(Tuple) # Creating a Tuple with# the use of listlist1 = [1, 2, 4, 5, 6]print("\nTuple using List: ")Tuple = tuple(list1) # Accessing element using indexingprint("First element of tuple")print(Tuple[0]) # Accessing element from last# negative indexingprint("\nLast element of tuple")print(Tuple[-1]) print("\nThird last element of tuple")print(Tuple[-3]) Tuple with the use of String: ('Geeks', 'For') Tuple using List: First element of tuple 1 Last element of tuple 6 Third last element of tuple 4 Python set is a mutable collection of data that does not allow any duplication. Sets are basically used to include membership testing and eliminating duplicate entries. The data structure used in this is Hashing, a popular technique to perform insertion, deletion, and traversal in O(1) on average. If Multiple values are present at the same index position, then the value is appended to that index position, to form a Linked List. In, CPython Sets are implemented using a dictionary with dummy variables, where key beings the members set with greater optimizations to the time complexity. Set Implementation: Sets with Numerous operations on a single HashTable: Python3 # Creating a Set with# a mixed type of values# (Having numbers and strings)Set = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])print("\nSet with the use of Mixed Values")print(Set) # Accessing element using# for loopprint("\nElements of set: ")for i in Set: print(i, end =" ")print() # Checking the element# using in keywordprint("Geeks" in Set) Set with the use of Mixed Values {1, 2, 4, 6, 'For', 'Geeks'} Elements of set: 1 2 4 6 For Geeks True Frozen sets in Python are immutable objects that only support methods and operators that produce a result without affecting the frozen set or sets to which they are applied. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation. Python3 # Same as {"a", "b","c"}normal_set = set(["a", "b","c"]) print("Normal Set")print(normal_set) # A frozen setfrozen_set = frozenset(["e", "f", "g"]) print("\nFrozen Set")print(frozen_set) # Uncommenting below line would cause error as# we are trying to add element to a frozen set# frozen_set.add("h") Normal Set {'a', 'b', 'c'} Frozen Set frozenset({'f', 'g', 'e'}) Python Strings is the immutable array of bytes representing Unicode characters. Python does not have a character data type, a single character is simply a string with a length of 1. Note: As strings are immutable, modifying a string will result in creating a new copy. Python3 String = "Welcome to GeeksForGeeks"print("Creating String: ")print(String) # Printing First characterprint("\nFirst character of String is: ")print(String[0]) # Printing Last characterprint("\nLast character of String is: ")print(String[-1]) Creating String: Welcome to GeeksForGeeks First character of String is: W Last character of String is: s Python dictionary is an unordered collection of data that stores data in the format of key:value pair. It is like hash tables in any other language with the time complexity of O(1). Indexing of Python Dictionary is done with the help of keys. These are of any hashable type i.e. an object whose can never change like strings, numbers, tuples, etc. We can create a dictionary by using curly braces ({}) or dictionary comprehension. Python3 # Creating a DictionaryDict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}print("Creating Dictionary: ")print(Dict) # accessing a element using keyprint("Accessing a element using key:")print(Dict['Name']) # accessing a element using get()# methodprint("Accessing a element using get:")print(Dict.get(1)) # creation using Dictionary comprehensionmyDict = {x: x**2 for x in [1,2,3,4,5]}print(myDict) Creating Dictionary: {'Name': 'Geeks', 1: [1, 2, 3, 4]} Accessing a element using key: Geeks Accessing a element using get: [1, 2, 3, 4] {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} A matrix is a 2D array where each element is of strictly the same size. To create a matrix we will be using the NumPy package. Python3 import numpy as np a = np.array([[1,2,3,4],[4,55,1,2], [8,3,20,19],[11,2,22,21]])m = np.reshape(a,(4, 4))print(m) # Accessing elementprint("\nAccessing Elements")print(a[1])print(a[2][0]) # Adding Elementm = np.append(m,[[1, 15,13,11]],0)print("\nAdding Element")print(m) # Deleting Elementm = np.delete(m,[1],0)print("\nDeleting Element")print(m) Output [[ 1 2 3 4] [ 4 55 1 2] [ 8 3 20 19] [11 2 22 21]] Accessing Elements [ 4 55 1 2] 8 Adding Element [[ 1 2 3 4] [ 4 55 1 2] [ 8 3 20 19] [11 2 22 21] [ 1 15 13 11]] Deleting Element [[ 1 2 3 4] [ 8 3 20 19] [11 2 22 21] [ 1 15 13 11]] Python Bytearray gives a mutable sequence of integers in the range 0 <= x < 256. Python3 # Creating bytearraya = bytearray((12, 8, 25, 2))print("Creating Bytearray:")print(a) # accessing elementsprint("\nAccessing Elements:", a[1]) # modifying elementsa[1] = 3print("\nAfter Modifying:")print(a) # Appending elementsa.append(30)print("\nAfter Adding Elements:")print(a) Creating Bytearray: bytearray(b'\x0c\x08\x19\x02') Accessing Elements: 8 After Modifying: bytearray(b'\x0c\x03\x19\x02') After Adding Elements: bytearray(b'\x0c\x03\x19\x02\x1e') A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image: A linked list is represented by a pointer to the first node of the linked list. The first node is called the head. If the linked list is empty, then the value of the head is NULL. Each node in a list consists of at least two parts: Data Pointer (Or Reference) to the next node Python3 # Node classclass Node: # Function to initialize the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize # next as null # Linked List classclass LinkedList: # Function to initialize the Linked # List object def __init__(self): self.head = None Let us create a simple linked list with 3 nodes. Python3 # A simple Python program to introduce a linked list # Node classclass Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node objectclass LinkedList: # Function to initialize head def __init__(self): self.head = None # Code execution starts hereif __name__=='__main__': # Start with the empty list llist = LinkedList() llist.head = Node(1) second = Node(2) third = Node(3) ''' Three nodes have been created. We have references to these three blocks as head, second and third llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | None | | 2 | None | | 3 | None | +----+------+ +----+------+ +----+------+ ''' llist.head.next = second; # Link first node with second ''' Now next of first Node refers to second. So they both are linked. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | null | | 3 | null | +----+------+ +----+------+ +----+------+ ''' second.next = third; # Link second node with the third node ''' Now next of second Node refers to third. So all three nodes are linked. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | o-------->| 3 | null | +----+------+ +----+------+ +----+------+ ''' In the previous program, we have created a simple linked list with three nodes. Let us traverse the created list and print the data of each node. For traversal, let us write a general-purpose function printList() that prints any given list. Python3 # A simple Python program for traversal of a linked list # Node classclass Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node objectclass LinkedList: # Function to initialize head def __init__(self): self.head = None # This function prints contents of linked list # starting from head def printList(self): temp = self.head while (temp): print (temp.data) temp = temp.next # Code execution starts hereif __name__=='__main__': # Start with the empty list llist = LinkedList() llist.head = Node(1) second = Node(2) third = Node(3) llist.head.next = second; # Link first node with second second.next = third; # Link second node with the third node llist.printList() 1 2 3 Linked List Insertion Linked List Deletion (Deleting a given key) Linked List Deletion (Deleting a key at given position) Find Length of a Linked List (Iterative and Recursive) Search an element in a Linked List (Iterative and Recursive) Nth node from the end of a Linked List Reverse a linked list >>> More A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop. The functions associated with stack are: empty() – Returns whether the stack is empty – Time Complexity: O(1) size() – Returns the size of the stack – Time Complexity: O(1) top() – Returns a reference to the topmost element of the stack – Time Complexity: O(1) push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1) pop() – Deletes the topmost element of the stack – Time Complexity: O(1) Python3 stack = [] # append() function to push# element in the stackstack.append('g')stack.append('f')stack.append('g') print('Initial stack')print(stack) # pop() function to pop# element from stack in# LIFO orderprint('\nElements popped from stack:')print(stack.pop())print(stack.pop())print(stack.pop()) print('\nStack after elements are popped:')print(stack) # uncommenting print(stack.pop())# will cause an IndexError# as the stack is now empty Initial stack ['g', 'f', 'g'] Elements popped from stack: g f g Stack after elements are popped: [] Infix to Postfix Conversion using Stack Prefix to Infix Conversion Prefix to Postfix Conversion Postfix to Prefix Conversion Postfix to Infix Check for balanced parentheses in an expression Evaluation of Postfix Expression >>> More As a stack, the queue is a linear data structure that stores items in a First In First Out (FIFO) manner. With a queue, the least recently added item is removed first. A good example of the queue is any queue of consumers for a resource where the consumer that came first is served first. Operations associated with queue are: Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition – Time Complexity: O(1) Dequeue: Removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition – Time Complexity: O(1) Front: Get the front item from queue – Time Complexity: O(1) Rear: Get the last item from queue – Time Complexity: O(1) Python3 # Initializing a queuequeue = [] # Adding elements to the queuequeue.append('g')queue.append('f')queue.append('g') print("Initial queue")print(queue) # Removing elements from the queueprint("\nElements dequeued from queue")print(queue.pop(0))print(queue.pop(0))print(queue.pop(0)) print("\nQueue after removing elements")print(queue) # Uncommenting print(queue.pop(0))# will raise and IndexError# as the queue is now empty Initial queue ['g', 'f', 'g'] Elements dequeued from queue g f g Queue after removing elements [] Implement Queue using Stacks Implement Stack using Queues Implement a stack using single queue Priority Queues are abstract data structures where each data/value in the queue has a certain priority. For example, In airlines, baggage with the title “Business” or “First-class” arrives earlier than the rest. Priority Queue is an extension of the queue with the following properties. An element with high priority is dequeued before an element with low priority. If two elements have the same priority, they are served according to their order in the queue. Python3 # A simple implementation of Priority Queue# using Queue.class PriorityQueue(object): def __init__(self): self.queue = [] def __str__(self): return ' '.join([str(i) for i in self.queue]) # for checking if the queue is empty def isEmpty(self): return len(self.queue) == 0 # for inserting an element in the queue def insert(self, data): self.queue.append(data) # for popping an element based on Priority def delete(self): try: max = 0 for i in range(len(self.queue)): if self.queue[i] > self.queue[max]: max = i item = self.queue[max] del self.queue[max] return item except IndexError: print() exit() if __name__ == '__main__': myQueue = PriorityQueue() myQueue.insert(12) myQueue.insert(1) myQueue.insert(14) myQueue.insert(7) print(myQueue) while not myQueue.isEmpty(): print(myQueue.delete()) 12 1 14 7 14 12 7 1 heapq module in Python provides the heap data structure that is mainly used to represent a priority queue. The property of this data structure is that it always gives the smallest element (min heap) whenever the element is popped. Whenever elements are pushed or popped, heap structure is maintained. The heap[0] element also returns the smallest element each time. It supports the extraction and insertion of the smallest element in the O(log n) times. Generally, Heaps can be of two types: Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of it’s children. The same property must be recursively true for all sub-trees in that Binary Tree. Min-Heap: In a Min-Heap the key present at the root node must be minimum among the keys present at all of it’s children. The same property must be recursively true for all sub-trees in that Binary Tree. Python3 # importing "heapq" to implement heap queueimport heapq # initializing listli = [5, 7, 9, 1, 3] # using heapify to convert list into heapheapq.heapify(li) # printing created heapprint ("The created heap is : ",end="")print (list(li)) # using heappush() to push elements into heap# pushes 4heapq.heappush(li,4) # printing modified heapprint ("The modified heap after push is : ",end="")print (list(li)) # using heappop() to pop smallest elementprint ("The popped and smallest element is : ",end="")print (heapq.heappop(li)) The created heap is : [1, 3, 9, 7, 5] The modified heap after push is : [1, 3, 4, 7, 5, 9] The popped and smallest element is : 1 Binary Heap K’th Largest Element in an array K’th Smallest/Largest Element in Unsorted Array Sort an almost sorted array K-th Largest Sum Contiguous Subarray Minimum sum of two numbers formed from digits of an array >>> More A tree is a hierarchical data structure that looks like the below figure – tree ---- j <-- root / \ f k / \ \ a h z <-- leaves The topmost node of the tree is called the root whereas the bottommost nodes or the nodes with no children are called the leaf nodes. The nodes that are directly under a node are called its children and the nodes that are directly above something are called its parent. A binary tree is a tree whose elements can have almost two children. Since each element in a binary tree can have only 2 children, we typically name them the left and right children. A Binary Tree node contains the following parts. Data Pointer to left child Pointer to the right child Python3 # A Python class that represents an individual node# in a Binary Treeclass Node: def __init__(self,key): self.left = None self.right = None self.val = key Now let’s create a tree with 4 nodes in Python. Let’s assume the tree structure looks like below – tree ---- 1 <-- root / \ 2 3 / 4 Python3 # Python program to introduce Binary Tree # A class that represents an individual node in a# Binary Treeclass Node: def __init__(self,key): self.left = None self.right = None self.val = key # create rootroot = Node(1)''' following is the tree after above statement 1 / \ None None''' root.left = Node(2);root.right = Node(3); ''' 2 and 3 become left and right children of 1 1 / \ 2 3 / \ / \None None None None''' root.left.left = Node(4);'''4 becomes left child of 2 1 / \ 2 3 / \ / \4 None None None/ \None None''' Trees can be traversed in different ways. Following are the generally used ways for traversing trees. Let us consider the below tree – tree ---- 1 <-- root / \ 2 3 / \ 4 5 Depth First Traversals: Inorder (Left, Root, Right) : 4 2 5 1 3 Preorder (Root, Left, Right) : 1 2 4 5 3 Postorder (Left, Right, Root) : 4 5 2 3 1 Algorithm Inorder(tree) Traverse the left subtree, i.e., call Inorder(left-subtree) Visit the root. Traverse the right subtree, i.e., call Inorder(right-subtree) Algorithm Preorder(tree) Visit the root. Traverse the left subtree, i.e., call Preorder(left-subtree) Traverse the right subtree, i.e., call Preorder(right-subtree) Algorithm Postorder(tree) Traverse the left subtree, i.e., call Postorder(left-subtree) Traverse the right subtree, i.e., call Postorder(right-subtree) Visit the root. Python3 # Python program to for tree traversals # A class that represents an individual node in a# Binary Treeclass Node: def __init__(self, key): self.left = None self.right = None self.val = key # A function to do inorder tree traversaldef printInorder(root): if root: # First recur on left child printInorder(root.left) # then print the data of node print(root.val), # now recur on right child printInorder(root.right) # A function to do postorder tree traversaldef printPostorder(root): if root: # First recur on left child printPostorder(root.left) # the recur on right child printPostorder(root.right) # now print the data of node print(root.val), # A function to do preorder tree traversaldef printPreorder(root): if root: # First print the data of node print(root.val), # Then recur on left child printPreorder(root.left) # Finally recur on right child printPreorder(root.right) # Driver coderoot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)print("Preorder traversal of binary tree is")printPreorder(root) print("\nInorder traversal of binary tree is")printInorder(root) print("\nPostorder traversal of binary tree is")printPostorder(root) Preorder traversal of binary tree is 1 2 4 5 3 Inorder traversal of binary tree is 4 2 5 1 3 Postorder traversal of binary tree is 4 5 2 3 1 Time Complexity – O(n) Breadth-First or Level Order Traversal Level order traversal of a tree is breadth-first traversal for the tree. The level order traversal of the above tree is 1 2 3 4 5. For each node, first, the node is visited and then its child nodes are put in a FIFO queue. Below is the algorithm for the same – Create an empty queue q temp_node = root /*start from root*/ Loop while temp_node is not NULLprint temp_node->data.Enqueue temp_node’s children (first left then right children) to qDequeue a node from q print temp_node->data. Enqueue temp_node’s children (first left then right children) to q Dequeue a node from q Python3 # Python program to print level# order traversal using Queue # A node structureclass Node: # A utility function to create a new node def __init__(self ,key): self.data = key self.left = None self.right = None # Iterative Method to print the# height of a binary treedef printLevelOrder(root): # Base Case if root is None: return # Create an empty queue # for level order traversal queue = [] # Enqueue Root and initialize height queue.append(root) while(len(queue) > 0): # Print front of queue and # remove it from queue print (queue[0].data) node = queue.pop(0) # Enqueue left child if node.left is not None: queue.append(node.left) # Enqueue right child if node.right is not None: queue.append(node.right) # Driver Program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5) print ("Level Order Traversal of binary tree is -")printLevelOrder(root) Level Order Traversal of binary tree is - 1 2 3 4 5 Time Complexity: O(n) Insertion in a Binary Tree Deletion in a Binary Tree Inorder Tree Traversal without Recursion Inorder Tree Traversal without recursion and without stack! Print Postorder traversal from given Inorder and Preorder traversals Find postorder traversal of BST from preorder traversal >>> More Binary Search Tree is a node-based binary tree data structure that has the following properties: The left subtree of a node contains only nodes with keys lesser than the node’s key. The right subtree of a node contains only nodes with keys greater than the node’s key. The left and right subtree each must also be a binary search tree. The above properties of the Binary Search Tree provide an ordering among keys so that the operations like search, minimum and maximum can be done fast. If there is no order, then we may have to compare every key to search for a given key. Start from the root. Compare the searching element with root, if less than root, then recurse for left, else recurse for right. If the element to search is found anywhere, return true, else return false. Python3 # A utility function to search a given key in BSTdef search(root,key): # Base Cases: root is null or key is present at root if root is None or root.val == key: return root # Key is greater than root's key if root.val < key: return search(root.right,key) # Key is smaller than root's key return search(root.left,key) Start from the root. Compare the inserting element with root, if less than root, then recurse for left, else recurse for right. After reaching the end, just insert that node at left(if less than current) else right. Python3 # Python program to demonstrate# insert operation in binary search tree # A utility class that represents# an individual node in a BSTclass Node: def __init__(self, key): self.left = None self.right = None self.val = key # A utility function to insert# a new node with the given keydef insert(root, key): if root is None: return Node(key) else: if root.val == key: return root elif root.val < key: root.right = insert(root.right, key) else: root.left = insert(root.left, key) return root # A utility function to do inorder tree traversaldef inorder(root): if root: inorder(root.left) print(root.val) inorder(root.right) # Driver program to test the above functions# Let us create the following BST# 50# / \# 30 70# / \ / \# 20 40 60 80 r = Node(50)r = insert(r, 30)r = insert(r, 20)r = insert(r, 40)r = insert(r, 70)r = insert(r, 60)r = insert(r, 80) # Print inorder traversal of the BSTinorder(r) 20 30 40 50 60 70 80 Binary Search Tree – Delete Key Construct BST from given preorder traversal | Set 1 Binary Tree to Binary Search Tree Conversion Find the node with minimum value in a Binary Search Tree A program to check if a binary tree is BST or not >>> More A graph is a nonlinear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph can be defined as a Graph consisting of a finite set of vertices(or nodes) and a set of edges that connect a pair of nodes. In the above Graph, the set of vertices V = {0,1,2,3,4} and the set of edges E = {01, 12, 23, 34, 04, 14, 13}. The following two are the most commonly used representations of a graph. Adjacency Matrix Adjacency List Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j. The adjacency matrix for an undirected graph is always symmetric. Adjacency Matrix is also used to represent weighted graphs. If adj[i][j] = w, then there is an edge from vertex i to vertex j with weight w. Python3 # A simple representation of graph using Adjacency Matrixclass Graph: def __init__(self,numvertex): self.adjMatrix = [[-1]*numvertex for x in range(numvertex)] self.numvertex = numvertex self.vertices = {} self.verticeslist =[0]*numvertex def set_vertex(self,vtx,id): if 0<=vtx<=self.numvertex: self.vertices[id] = vtx self.verticeslist[vtx] = id def set_edge(self,frm,to,cost=0): frm = self.vertices[frm] to = self.vertices[to] self.adjMatrix[frm][to] = cost # for directed graph do not add this self.adjMatrix[to][frm] = cost def get_vertex(self): return self.verticeslist def get_edges(self): edges=[] for i in range (self.numvertex): for j in range (self.numvertex): if (self.adjMatrix[i][j]!=-1): edges.append((self.verticeslist[i],self.verticeslist[j],self.adjMatrix[i][j])) return edges def get_matrix(self): return self.adjMatrix G =Graph(6)G.set_vertex(0,'a')G.set_vertex(1,'b')G.set_vertex(2,'c')G.set_vertex(3,'d')G.set_vertex(4,'e')G.set_vertex(5,'f')G.set_edge('a','e',10)G.set_edge('a','c',20)G.set_edge('c','b',30)G.set_edge('b','e',40)G.set_edge('e','d',50)G.set_edge('f','e',60) print("Vertices of Graph")print(G.get_vertex()) print("Edges of Graph")print(G.get_edges()) print("Adjacency Matrix of Graph")print(G.get_matrix()) Output Vertices of Graph [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’] Edges of Graph [(‘a’, ‘c’, 20), (‘a’, ‘e’, 10), (‘b’, ‘c’, 30), (‘b’, ‘e’, 40), (‘c’, ‘a’, 20), (‘c’, ‘b’, 30), (‘d’, ‘e’, 50), (‘e’, ‘a’, 10), (‘e’, ‘b’, 40), (‘e’, ‘d’, 50), (‘e’, ‘f’, 60), (‘f’, ‘e’, 60)] Adjacency Matrix of Graph [[-1, -1, 20, -1, 10, -1], [-1, -1, 30, -1, 40, -1], [20, 30, -1, -1, -1, -1], [-1, -1, -1, -1, 50, -1], [10, 40, -1, 50, -1, 60], [-1, -1, -1, -1, 60, -1]] An array of lists is used. The size of the array is equal to the number of vertices. Let the array be an array[]. An entry array[i] represents the list of vertices adjacent to the ith vertex. This representation can also be used to represent a weighted graph. The weights of edges can be represented as lists of pairs. Following is the adjacency list representation of the above graph. Python3 # A class to represent the adjacency list of the nodeclass AdjNode: def __init__(self, data): self.vertex = data self.next = None # A class to represent a graph. A graph# is the list of the adjacency lists.# Size of the array will be the no. of the# vertices "V"class Graph: def __init__(self, vertices): self.V = vertices self.graph = [None] * self.V # Function to add an edge in an undirected graph def add_edge(self, src, dest): # Adding the node to the source node node = AdjNode(dest) node.next = self.graph[src] self.graph[src] = node # Adding the source node to the destination as # it is the undirected graph node = AdjNode(src) node.next = self.graph[dest] self.graph[dest] = node # Function to print the graph def print_graph(self): for i in range(self.V): print("Adjacency list of vertex {}\n head".format(i), end="") temp = self.graph[i] while temp: print(" -> {}".format(temp.vertex), end="") temp = temp.next print(" \n") # Driver program to the above graph classif __name__ == "__main__": V = 5 graph = Graph(V) graph.add_edge(0, 1) graph.add_edge(0, 4) graph.add_edge(1, 2) graph.add_edge(1, 3) graph.add_edge(1, 4) graph.add_edge(2, 3) graph.add_edge(3, 4) graph.print_graph() Adjacency list of vertex 0 head -> 4 -> 1 Adjacency list of vertex 1 head -> 4 -> 3 -> 2 -> 0 Adjacency list of vertex 2 head -> 3 -> 1 Adjacency list of vertex 3 head -> 4 -> 2 -> 1 Adjacency list of vertex 4 head -> 3 -> 1 -> 0 Breadth-First Traversal for a graph is similar to Breadth-First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array. For simplicity, it is assumed that all vertices are reachable from the starting vertex. For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. A Breadth-First Traversal of the following graph is 2, 0, 3, 1. Python3 # Python3 Program to print BFS traversal# from a given source vertex. BFS(int s)# traverses vertices reachable from s.from collections import defaultdict # This class represents a directed graph# using adjacency list representationclass Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # Function to print a BFS of graph def BFS(self, s): # Mark all the vertices as not visited visited = [False] * (max(self.graph) + 1) # Create a queue for BFS queue = [] # Mark the source node as # visited and enqueue it queue.append(s) visited[s] = True while queue: # Dequeue a vertex from # queue and print it s = queue.pop(0) print (s, end = " ") # Get all adjacent vertices of the # dequeued vertex s. If a adjacent # has not been visited, then mark it # visited and enqueue it for i in self.graph[s]: if visited[i] == False: queue.append(i) visited[i] = True # Driver code # Create a graph given in# the above diagramg = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) print ("Following is Breadth First Traversal" " (starting from vertex 2)")g.BFS(2) Following is Breadth First Traversal (starting from vertex 2) 2 0 3 1 Time Complexity: O(V+E) where V is the number of vertices in the graph and E is the number of edges in the graph. Depth First Traversal for a graph is similar to Depth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, a node may be visited twice. To avoid processing a node more than once, use a boolean visited array. Algorithm: Create a recursive function that takes the index of the node and a visited array. Mark the current node as visited and print the node. Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node. Python3 # Python3 program to print DFS traversal# from a given graphfrom collections import defaultdict # This class represents a directed graph using# adjacency list representationclass Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A function used by DFS def DFSUtil(self, v, visited): # Mark the current node as visited # and print it visited.add(v) print(v, end=' ') # Recur for all the vertices # adjacent to this vertex for neighbour in self.graph[v]: if neighbour not in visited: self.DFSUtil(neighbour, visited) # The function to do DFS traversal. It uses # recursive DFSUtil() def DFS(self, v): # Create a set to store visited vertices visited = set() # Call the recursive helper function # to print DFS traversal self.DFSUtil(v, visited) # Driver code # Create a graph given# in the above diagramg = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) print("Following is DFS from (starting from vertex 2)")g.DFS(2) Following is DFS from (starting from vertex 2) 2 0 1 3 Graph representations using set and hash Find Mother Vertex in a Graph Iterative Depth First Search Count the number of nodes at given level in a tree using BFS Count all possible paths between two vertices >>> More The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using the recursive algorithms, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc. In the recursive program, the solution to the base case is provided and the solution of the bigger problem is expressed in terms of smaller problems. def fact(n): # base case if (n < = 1) return 1 else return n*fact(n-1) In the above example, base case for n < = 1 is defined and larger value of number can be solved by converting to smaller one till base case is reached. When any function is called from main(), the memory is allocated to it on the stack. A recursive function calls itself, the memory for a called function is allocated on top of memory allocated to the calling function and a different copy of local variables is created for each function call. When the base case is reached, the function returns its value to the function by whom it is called and memory is de-allocated and the process continues. Let us take the example of how recursion works by taking a simple function. Python3 # A Python 3 program to# demonstrate working of# recursion def printFun(test): if (test < 1): return else: print(test, end=" ") printFun(test-1) # statement 2 print(test, end=" ") return # Driver Codetest = 3printFun(test) 3 2 1 1 2 3 The memory stack has been shown in below diagram. Recursion Recursion in Python Practice Questions for Recursion | Set 1 Practice Questions for Recursion | Set 2 Practice Questions for Recursion | Set 3 Practice Questions for Recursion | Set 4 Practice Questions for Recursion | Set 5 Practice Questions for Recursion | Set 6 Practice Questions for Recursion | Set 7 >>> More Dynamic Programming is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of subproblems, so that we do not have to re-compute them when needed later. This simple optimization reduces time complexities from exponential to polynomial. For example, if we write simple recursive solution for Fibonacci Numbers, we get exponential time complexity and if we optimize it by storing solutions of subproblems, time complexity reduces to linear. There are two different ways to store the values so that the values of a sub-problem can be reused. Here, will discuss two patterns of solving dynamic programming (DP) problem: Tabulation: Bottom Up Memoization: Top Down As the name itself suggests starting from the bottom and accumulating answers to the top. Let’s discuss in terms of state transition. Let’s describe a state for our DP problem to be dp[x] with dp[0] as base state and dp[n] as our destination state. So, we need to find the value of destination state i.e dp[n]. If we start our transition from our base state i.e dp[0] and follow our state transition relation to reach our destination state dp[n], we call it the Bottom-Up approach as it is quite clear that we started our transition from the bottom base state and reached the topmost desired state. Now, Why do we call it tabulation method? To know this let’s first write some code to calculate the factorial of a number using bottom up approach. Once, again as our general procedure to solve a DP we first define a state. In this case, we define a state as dp[x], where dp[x] is to find the factorial of x. Now, it is quite obvious that dp[x+1] = dp[x] * (x+1) # Tabulated version to find factorial x. dp = [0]*MAXN # base case dp[0] = 1; for i in range(n+1): dp[i] = dp[i-1] * i Once, again let’s describe it in terms of state transition. If we need to find the value for some state say dp[n] and instead of starting from the base state that i.e dp[0] we ask our answer from the states that can reach the destination state dp[n] following the state transition relation, then it is the top-down fashion of DP. Here, we start our journey from the top most destination state and compute its answer by taking in count the values of states that can reach the destination state, till we reach the bottom-most base state. Once again, let’s write the code for the factorial problem in the top-down fashion # Memoized version to find factorial x. # To speed up we store the values # of calculated states # initialized to -1 dp[0]*MAXN # return fact x! def solve(x): if (x==0) return 1 if (dp[x]!=-1) return dp[x] return (dp[x] = x * solve(x-1)) Optimal Substructure Property Overlapping Subproblems Property Fibonacci numbers Subset with sum divisible by m Maximum Sum Increasing Subsequence Longest Common Substring >>> More Start from the leftmost element of arr[] and one by one compare x with each element of arr[] If x matches with an element, return the index. If x doesn’t match with any of the elements, return -1. Python3 # Python3 code to linearly search x in arr[].# If x is present then return its location,# otherwise return -1 def search(arr, n, x): for i in range(0, n): if (arr[i] == x): return i return -1 # Driver Codearr = [2, 3, 4, 10, 40]x = 10n = len(arr) # Function callresult = search(arr, n, x)if(result == -1): print("Element is not present in array")else: print("Element is present at index", result) Element is present at index 3 The time complexity of the above algorithm is O(n). For more information, refer to Linear Search. Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Repeatedly check until the value is found or the interval is empty. Python3 # Python3 Program for recursive binary search. # Returns index of x in arr if present, else -1def binarySearch (arr, l, r, x): # Check base case if r >= l: mid = l + (r - l) // 2 # If element is present at the middle itself if arr[mid] == x: return mid # If element is smaller than mid, then it # can only be present in left subarray elif arr[mid] > x: return binarySearch(arr, l, mid-1, x) # Else the element can only be present # in right subarray else: return binarySearch(arr, mid + 1, r, x) else: # Element is not present in the array return -1 # Driver Codearr = [ 2, 3, 4, 10, 40 ]x = 10 # Function callresult = binarySearch(arr, 0, len(arr)-1, x) if result != -1: print ("Element is present at index % d" % result)else: print ("Element is not present in array") Element is present at index 3 The time complexity of the above algorithm is O(log(n)). For more information, refer to Binary Search. The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. Python3 # Python program for implementation of Selection# Sortimport sys A = [64, 25, 12, 22, 11] # Traverse through all array elementsfor i in range(len(A)): # Find the minimum element in remaining # unsorted array min_idx = i for j in range(i+1, len(A)): if A[min_idx] > A[j]: min_idx = j # Swap the found minimum element with # the first element A[i], A[min_idx] = A[min_idx], A[i] # Driver code to test aboveprint ("Sorted array")for i in range(len(A)): print("%d" %A[i]), Sorted array 11 12 22 25 64 Time Complexity: O(n2) as there are two nested loops. Auxiliary Space: O(1) Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. Illustration : Python3 # Python program for implementation of Bubble Sort def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in place for j in range(0, n-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] # Driver code to test abovearr = [64, 34, 25, 12, 22, 11, 90] bubbleSort(arr) print ("Sorted array is:")for i in range(len(arr)): print ("%d" %arr[i]), Sorted array is: 11 12 22 25 34 64 90 Time Complexity: O(n2) To sort an array of size n in ascending order using insertion sort: 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. Illustration: Python3 # 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]) 5 6 11 12 13 Time Complexity: O(n2)) Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides the input array into two halves, calls itself for the two halves, and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is a key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one. MergeSort(arr[], l, r) If r > l 1. Find the middle point to divide the array into two halves: middle m = l+ (r-l)/2 2. Call mergeSort for first half: Call mergeSort(arr, l, m) 3. Call mergeSort for second half: Call mergeSort(arr, m+1, r) 4. Merge the two halves sorted in step 2 and 3: Call merge(arr, l, m, r) Python3 # Python program for implementation of MergeSortdef mergeSort(arr): if len(arr) > 1: # Finding the mid of the array mid = len(arr)//2 # Dividing the array elements L = arr[:mid] # into 2 halves R = arr[mid:] # Sorting the first half mergeSort(L) # Sorting the second half mergeSort(R) i = j = k = 0 # Copy data to temp arrays L[] and R[] while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # Checking if any element was left while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1 # Code to print the list def printList(arr): for i in range(len(arr)): print(arr[i], end=" ") print() # Driver Codeif __name__ == '__main__': arr = [12, 11, 13, 5, 6, 7] print("Given array is", end="\n") printList(arr) mergeSort(arr) print("Sorted array is: ", end="\n") printList(arr) Given array is 12 11 13 5 6 7 Sorted array is: 5 6 7 11 12 13 Time Complexity: O(n(logn)) Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways. Always pick first element as pivot. Always pick last element as pivot (implemented below) Pick a random element as pivot. Pick median as pivot. The key process in quickSort is partition(). Target of partitions is, given an array and an element x of array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x. All this should be done in linear time. /* low --> Starting index, high --> Ending index */ quickSort(arr[], low, high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ pi = partition(arr, low, high); quickSort(arr, low, pi - 1); // Before pi quickSort(arr, pi + 1, high); // After pi } } Partition Algorithm There can be many ways to do partition, following pseudo code adopts the method given in CLRS book. The logic is simple, we start from the leftmost element and keep track of index of smaller (or equal to) elements as i. While traversing, if we find a smaller element, we swap current element with arr[i]. Otherwise we ignore current element. /* low --> Starting index, high --> Ending index */ quickSort(arr[], low, high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ pi = partition(arr, low, high); quickSort(arr, low, pi - 1); // Before pi quickSort(arr, pi + 1, high); // After pi } } Python3 # Python3 implementation of QuickSort # This Function handles sorting part of quick sort# start and end points to first and last element of# an array respectivelydef partition(start, end, array): # Initializing pivot's index to start pivot_index = start pivot = array[pivot_index] # This loop runs till start pointer crosses # end pointer, and when it does we swap the # pivot with element on end pointer while start < end: # Increment the start pointer till it finds an # element greater than pivot while start < len(array) and array[start] <= pivot: start += 1 # Decrement the end pointer till it finds an # element less than pivot while array[end] > pivot: end -= 1 # If start and end have not crossed each other, # swap the numbers on start and end if(start < end): array[start], array[end] = array[end], array[start] # Swap pivot element with element on end pointer. # This puts pivot on its correct sorted place. array[end], array[pivot_index] = array[pivot_index], array[end] # Returning end pointer to divide the array into 2 return end # The main function that implements QuickSortdef quick_sort(start, end, array): if (start < end): # p is partitioning index, array[p] # is at right place p = partition(start, end, array) # Sort elements before partition # and after partition quick_sort(start, p - 1, array) quick_sort(p + 1, end, array) # Driver codearray = [ 10, 7, 8, 9, 1, 5 ]quick_sort(0, len(array) - 1, array) print(f'Sorted array: {array}') Sorted array: [1, 5, 7, 8, 9, 10] Time Complexity: O(n(logn)) ShellSort is mainly a variation of Insertion Sort. In insertion sort, we move elements only one position ahead. When an element has to be moved far ahead, many movements are involved. The idea of shellSort is to allow the exchange of far items. In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every hth element is sorted. Python3 # Python3 program for implementation of Shell Sort def shellSort(arr): gap = len(arr) // 2 # initialize the gap while gap > 0: i = 0 j = gap # check the array in from left to right # till the last possible index of j while j < len(arr): if arr[i] >arr[j]: arr[i],arr[j] = arr[j],arr[i] i += 1 j += 1 # now, we look back from ith index to the left # we swap the values which are not in the right order. k = i while k - gap > -1: if arr[k - gap] > arr[k]: arr[k-gap],arr[k] = arr[k],arr[k-gap] k -= 1 gap //= 2 # driver to check the codearr2 = [12, 34, 54, 2, 3]print("input array:",arr2) shellSort(arr2)print("sorted array",arr2) input array: [12, 34, 54, 2, 3] sorted array [2, 3, 12, 34, 54] Time Complexity: O(n2). simranarora5sos sagartomar9927 as5853535 Python-Data-Structures 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 Convert integer to string in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 469, "s": 52, "text": "This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc, and some user-defined data structures such as linked lists, trees, graphs, etc, and traversal as well as searching and sorting algorithms with the help of good and well-explained examples and practice questions." }, { "code": null, "e": 959, "s": 469, "text": "Python Lists are ordered collections of data just like arrays in other programming languages. It allows different types of elements in the list. The implementation of Python List is similar to Vectors in C++ or ArrayList in JAVA. The costly operation is inserting or deleting the element from the beginning of the List as all the elements are needed to be shifted. Insertion and deletion at the end of the list can also become costly in the case where the preallocated memory becomes full." }, { "code": null, "e": 967, "s": 959, "text": "Python3" }, { "code": "List = [1, 2, 3, \"GFG\", 2.3]print(List)", "e": 1007, "s": 967, "text": null }, { "code": null, "e": 1029, "s": 1007, "text": "[1, 2, 3, 'GFG', 2.3]" }, { "code": null, "e": 1191, "s": 1029, "text": "List elements can be accessed by the assigned index. In python starting index of the list, a sequence is 0 and the ending index is (if N elements are there) N-1." }, { "code": null, "e": 1199, "s": 1191, "text": "Python3" }, { "code": "# Creating a List with# the use of multiple valuesList = [\"Geeks\", \"For\", \"Geeks\"]print(\"\\nList containing multiple values: \")print(List) # Creating a Multi-Dimensional List# (By Nesting a list inside a List)List2 = [['Geeks', 'For'], ['Geeks']]print(\"\\nMulti-Dimensional List: \")print(List2) # accessing a element from the# list using index numberprint(\"Accessing element from the list\")print(List[0])print(List[2]) # accessing a element using# negative indexingprint(\"Accessing element using negative indexing\") # print the last element of listprint(List[-1]) # print the third last element of listprint(List[-3])", "e": 1828, "s": 1199, "text": null }, { "code": null, "e": 2042, "s": 1828, "text": "List containing multiple values: \n['Geeks', 'For', 'Geeks']\n\nMulti-Dimensional List: \n[['Geeks', 'For'], ['Geeks']]\nAccessing element from the list\nGeeks\nGeeks\nAccessing element using negative indexing\nGeeks\nGeeks" }, { "code": null, "e": 2223, "s": 2042, "text": "Python tuples are similar to lists but Tuples are immutable in nature i.e. once created it cannot be modified. Just like a List, a Tuple can also contain elements of various types." }, { "code": null, "e": 2381, "s": 2223, "text": "In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of the data sequence. " }, { "code": null, "e": 2519, "s": 2381, "text": "Note: To create a tuple of one element there must be a trailing comma. For example, (8,) will create a tuple containing 8 as the element." }, { "code": null, "e": 2527, "s": 2519, "text": "Python3" }, { "code": "# Creating a Tuple with# the use of StringsTuple = ('Geeks', 'For')print(\"\\nTuple with the use of String: \")print(Tuple) # Creating a Tuple with# the use of listlist1 = [1, 2, 4, 5, 6]print(\"\\nTuple using List: \")Tuple = tuple(list1) # Accessing element using indexingprint(\"First element of tuple\")print(Tuple[0]) # Accessing element from last# negative indexingprint(\"\\nLast element of tuple\")print(Tuple[-1]) print(\"\\nThird last element of tuple\")print(Tuple[-3])", "e": 3002, "s": 2527, "text": null }, { "code": null, "e": 3151, "s": 3002, "text": "Tuple with the use of String: \n('Geeks', 'For')\n\nTuple using List: \nFirst element of tuple\n1\n\nLast element of tuple\n6\n\nThird last element of tuple\n4" }, { "code": null, "e": 3451, "s": 3151, "text": "Python set is a mutable collection of data that does not allow any duplication. Sets are basically used to include membership testing and eliminating duplicate entries. The data structure used in this is Hashing, a popular technique to perform insertion, deletion, and traversal in O(1) on average. " }, { "code": null, "e": 3742, "s": 3451, "text": "If Multiple values are present at the same index position, then the value is appended to that index position, to form a Linked List. In, CPython Sets are implemented using a dictionary with dummy variables, where key beings the members set with greater optimizations to the time complexity." }, { "code": null, "e": 3762, "s": 3742, "text": "Set Implementation:" }, { "code": null, "e": 3815, "s": 3762, "text": "Sets with Numerous operations on a single HashTable:" }, { "code": null, "e": 3823, "s": 3815, "text": "Python3" }, { "code": "# Creating a Set with# a mixed type of values# (Having numbers and strings)Set = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])print(\"\\nSet with the use of Mixed Values\")print(Set) # Accessing element using# for loopprint(\"\\nElements of set: \")for i in Set: print(i, end =\" \")print() # Checking the element# using in keywordprint(\"Geeks\" in Set)", "e": 4170, "s": 3823, "text": null }, { "code": null, "e": 4275, "s": 4170, "text": "Set with the use of Mixed Values\n{1, 2, 4, 6, 'For', 'Geeks'}\n\nElements of set: \n1 2 4 6 For Geeks \nTrue" }, { "code": null, "e": 4561, "s": 4275, "text": "Frozen sets in Python are immutable objects that only support methods and operators that produce a result without affecting the frozen set or sets to which they are applied. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation." }, { "code": null, "e": 4569, "s": 4561, "text": "Python3" }, { "code": "# Same as {\"a\", \"b\",\"c\"}normal_set = set([\"a\", \"b\",\"c\"]) print(\"Normal Set\")print(normal_set) # A frozen setfrozen_set = frozenset([\"e\", \"f\", \"g\"]) print(\"\\nFrozen Set\")print(frozen_set) # Uncommenting below line would cause error as# we are trying to add element to a frozen set# frozen_set.add(\"h\")", "e": 4874, "s": 4569, "text": null }, { "code": null, "e": 4940, "s": 4874, "text": "Normal Set\n{'a', 'b', 'c'}\n\nFrozen Set\nfrozenset({'f', 'g', 'e'})" }, { "code": null, "e": 5122, "s": 4940, "text": "Python Strings is the immutable array of bytes representing Unicode characters. Python does not have a character data type, a single character is simply a string with a length of 1." }, { "code": null, "e": 5209, "s": 5122, "text": "Note: As strings are immutable, modifying a string will result in creating a new copy." }, { "code": null, "e": 5217, "s": 5209, "text": "Python3" }, { "code": "String = \"Welcome to GeeksForGeeks\"print(\"Creating String: \")print(String) # Printing First characterprint(\"\\nFirst character of String is: \")print(String[0]) # Printing Last characterprint(\"\\nLast character of String is: \")print(String[-1])", "e": 5469, "s": 5217, "text": null }, { "code": null, "e": 5579, "s": 5469, "text": "Creating String: \nWelcome to GeeksForGeeks\n\nFirst character of String is: \nW\n\nLast character of String is: \ns" }, { "code": null, "e": 6010, "s": 5579, "text": "Python dictionary is an unordered collection of data that stores data in the format of key:value pair. It is like hash tables in any other language with the time complexity of O(1). Indexing of Python Dictionary is done with the help of keys. These are of any hashable type i.e. an object whose can never change like strings, numbers, tuples, etc. We can create a dictionary by using curly braces ({}) or dictionary comprehension." }, { "code": null, "e": 6018, "s": 6010, "text": "Python3" }, { "code": "# Creating a DictionaryDict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}print(\"Creating Dictionary: \")print(Dict) # accessing a element using keyprint(\"Accessing a element using key:\")print(Dict['Name']) # accessing a element using get()# methodprint(\"Accessing a element using get:\")print(Dict.get(1)) # creation using Dictionary comprehensionmyDict = {x: x**2 for x in [1,2,3,4,5]}print(myDict)", "e": 6410, "s": 6018, "text": null }, { "code": null, "e": 6581, "s": 6410, "text": "Creating Dictionary: \n{'Name': 'Geeks', 1: [1, 2, 3, 4]}\nAccessing a element using key:\nGeeks\nAccessing a element using get:\n[1, 2, 3, 4]\n{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}" }, { "code": null, "e": 6708, "s": 6581, "text": "A matrix is a 2D array where each element is of strictly the same size. To create a matrix we will be using the NumPy package." }, { "code": null, "e": 6716, "s": 6708, "text": "Python3" }, { "code": "import numpy as np a = np.array([[1,2,3,4],[4,55,1,2], [8,3,20,19],[11,2,22,21]])m = np.reshape(a,(4, 4))print(m) # Accessing elementprint(\"\\nAccessing Elements\")print(a[1])print(a[2][0]) # Adding Elementm = np.append(m,[[1, 15,13,11]],0)print(\"\\nAdding Element\")print(m) # Deleting Elementm = np.delete(m,[1],0)print(\"\\nDeleting Element\")print(m)", "e": 7081, "s": 6716, "text": null }, { "code": null, "e": 7088, "s": 7081, "text": "Output" }, { "code": null, "e": 7356, "s": 7088, "text": "[[ 1 2 3 4]\n [ 4 55 1 2]\n [ 8 3 20 19]\n [11 2 22 21]]\n\nAccessing Elements\n[ 4 55 1 2]\n8\n\nAdding Element\n[[ 1 2 3 4]\n [ 4 55 1 2]\n [ 8 3 20 19]\n [11 2 22 21]\n [ 1 15 13 11]]\n\nDeleting Element\n[[ 1 2 3 4]\n [ 8 3 20 19]\n [11 2 22 21]\n [ 1 15 13 11]]" }, { "code": null, "e": 7437, "s": 7356, "text": "Python Bytearray gives a mutable sequence of integers in the range 0 <= x < 256." }, { "code": null, "e": 7445, "s": 7437, "text": "Python3" }, { "code": "# Creating bytearraya = bytearray((12, 8, 25, 2))print(\"Creating Bytearray:\")print(a) # accessing elementsprint(\"\\nAccessing Elements:\", a[1]) # modifying elementsa[1] = 3print(\"\\nAfter Modifying:\")print(a) # Appending elementsa.append(30)print(\"\\nAfter Adding Elements:\")print(a)", "e": 7729, "s": 7445, "text": null }, { "code": null, "e": 7911, "s": 7729, "text": "Creating Bytearray:\nbytearray(b'\\x0c\\x08\\x19\\x02')\n\nAccessing Elements: 8\n\nAfter Modifying:\nbytearray(b'\\x0c\\x03\\x19\\x02')\n\nAfter Adding Elements:\nbytearray(b'\\x0c\\x03\\x19\\x02\\x1e')" }, { "code": null, "e": 8107, "s": 7911, "text": "A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image:" }, { "code": null, "e": 8339, "s": 8107, "text": "A linked list is represented by a pointer to the first node of the linked list. The first node is called the head. If the linked list is empty, then the value of the head is NULL. Each node in a list consists of at least two parts:" }, { "code": null, "e": 8344, "s": 8339, "text": "Data" }, { "code": null, "e": 8384, "s": 8344, "text": "Pointer (Or Reference) to the next node" }, { "code": null, "e": 8392, "s": 8384, "text": "Python3" }, { "code": "# Node classclass Node: # Function to initialize the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize # next as null # Linked List classclass LinkedList: # Function to initialize the Linked # List object def __init__(self): self.head = None", "e": 8751, "s": 8392, "text": null }, { "code": null, "e": 8800, "s": 8751, "text": "Let us create a simple linked list with 3 nodes." }, { "code": null, "e": 8808, "s": 8800, "text": "Python3" }, { "code": "# A simple Python program to introduce a linked list # Node classclass Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node objectclass LinkedList: # Function to initialize head def __init__(self): self.head = None # Code execution starts hereif __name__=='__main__': # Start with the empty list llist = LinkedList() llist.head = Node(1) second = Node(2) third = Node(3) ''' Three nodes have been created. We have references to these three blocks as head, second and third llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | None | | 2 | None | | 3 | None | +----+------+ +----+------+ +----+------+ ''' llist.head.next = second; # Link first node with second ''' Now next of first Node refers to second. So they both are linked. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | null | | 3 | null | +----+------+ +----+------+ +----+------+ ''' second.next = third; # Link second node with the third node ''' Now next of second Node refers to third. So all three nodes are linked. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | o-------->| 3 | null | +----+------+ +----+------+ +----+------+ '''", "e": 10649, "s": 8808, "text": null }, { "code": null, "e": 10890, "s": 10649, "text": "In the previous program, we have created a simple linked list with three nodes. Let us traverse the created list and print the data of each node. For traversal, let us write a general-purpose function printList() that prints any given list." }, { "code": null, "e": 10898, "s": 10890, "text": "Python3" }, { "code": "# A simple Python program for traversal of a linked list # Node classclass Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node objectclass LinkedList: # Function to initialize head def __init__(self): self.head = None # This function prints contents of linked list # starting from head def printList(self): temp = self.head while (temp): print (temp.data) temp = temp.next # Code execution starts hereif __name__=='__main__': # Start with the empty list llist = LinkedList() llist.head = Node(1) second = Node(2) third = Node(3) llist.head.next = second; # Link first node with second second.next = third; # Link second node with the third node llist.printList()", "e": 11815, "s": 10898, "text": null }, { "code": null, "e": 11821, "s": 11815, "text": "1\n2\n3" }, { "code": null, "e": 11843, "s": 11821, "text": "Linked List Insertion" }, { "code": null, "e": 11887, "s": 11843, "text": "Linked List Deletion (Deleting a given key)" }, { "code": null, "e": 11943, "s": 11887, "text": "Linked List Deletion (Deleting a key at given position)" }, { "code": null, "e": 11998, "s": 11943, "text": "Find Length of a Linked List (Iterative and Recursive)" }, { "code": null, "e": 12059, "s": 11998, "text": "Search an element in a Linked List (Iterative and Recursive)" }, { "code": null, "e": 12098, "s": 12059, "text": "Nth node from the end of a Linked List" }, { "code": null, "e": 12120, "s": 12098, "text": "Reverse a linked list" }, { "code": null, "e": 12129, "s": 12120, "text": ">>> More" }, { "code": null, "e": 12402, "s": 12129, "text": "A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop." }, { "code": null, "e": 12443, "s": 12402, "text": "The functions associated with stack are:" }, { "code": null, "e": 12512, "s": 12443, "text": "empty() – Returns whether the stack is empty – Time Complexity: O(1)" }, { "code": null, "e": 12575, "s": 12512, "text": "size() – Returns the size of the stack – Time Complexity: O(1)" }, { "code": null, "e": 12663, "s": 12575, "text": "top() – Returns a reference to the topmost element of the stack – Time Complexity: O(1)" }, { "code": null, "e": 12745, "s": 12663, "text": "push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)" }, { "code": null, "e": 12818, "s": 12745, "text": "pop() – Deletes the topmost element of the stack – Time Complexity: O(1)" }, { "code": null, "e": 12826, "s": 12818, "text": "Python3" }, { "code": "stack = [] # append() function to push# element in the stackstack.append('g')stack.append('f')stack.append('g') print('Initial stack')print(stack) # pop() function to pop# element from stack in# LIFO orderprint('\\nElements popped from stack:')print(stack.pop())print(stack.pop())print(stack.pop()) print('\\nStack after elements are popped:')print(stack) # uncommenting print(stack.pop())# will cause an IndexError# as the stack is now empty", "e": 13272, "s": 12826, "text": null }, { "code": null, "e": 13374, "s": 13272, "text": "Initial stack\n['g', 'f', 'g']\n\nElements popped from stack:\ng\nf\ng\n\nStack after elements are popped:\n[]" }, { "code": null, "e": 13414, "s": 13374, "text": "Infix to Postfix Conversion using Stack" }, { "code": null, "e": 13441, "s": 13414, "text": "Prefix to Infix Conversion" }, { "code": null, "e": 13470, "s": 13441, "text": "Prefix to Postfix Conversion" }, { "code": null, "e": 13499, "s": 13470, "text": "Postfix to Prefix Conversion" }, { "code": null, "e": 13516, "s": 13499, "text": "Postfix to Infix" }, { "code": null, "e": 13564, "s": 13516, "text": "Check for balanced parentheses in an expression" }, { "code": null, "e": 13597, "s": 13564, "text": "Evaluation of Postfix Expression" }, { "code": null, "e": 13606, "s": 13597, "text": ">>> More" }, { "code": null, "e": 13895, "s": 13606, "text": "As a stack, the queue is a linear data structure that stores items in a First In First Out (FIFO) manner. With a queue, the least recently added item is removed first. A good example of the queue is any queue of consumers for a resource where the consumer that came first is served first." }, { "code": null, "e": 13933, "s": 13895, "text": "Operations associated with queue are:" }, { "code": null, "e": 14059, "s": 13933, "text": "Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition – Time Complexity: O(1)" }, { "code": null, "e": 14257, "s": 14059, "text": "Dequeue: Removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition – Time Complexity: O(1)" }, { "code": null, "e": 14318, "s": 14257, "text": "Front: Get the front item from queue – Time Complexity: O(1)" }, { "code": null, "e": 14377, "s": 14318, "text": "Rear: Get the last item from queue – Time Complexity: O(1)" }, { "code": null, "e": 14385, "s": 14377, "text": "Python3" }, { "code": "# Initializing a queuequeue = [] # Adding elements to the queuequeue.append('g')queue.append('f')queue.append('g') print(\"Initial queue\")print(queue) # Removing elements from the queueprint(\"\\nElements dequeued from queue\")print(queue.pop(0))print(queue.pop(0))print(queue.pop(0)) print(\"\\nQueue after removing elements\")print(queue) # Uncommenting print(queue.pop(0))# will raise and IndexError# as the queue is now empty", "e": 14813, "s": 14385, "text": null }, { "code": null, "e": 14913, "s": 14813, "text": "Initial queue\n['g', 'f', 'g']\n\nElements dequeued from queue\ng\nf\ng\n\nQueue after removing elements\n[]" }, { "code": null, "e": 14942, "s": 14913, "text": "Implement Queue using Stacks" }, { "code": null, "e": 14971, "s": 14942, "text": "Implement Stack using Queues" }, { "code": null, "e": 15008, "s": 14971, "text": "Implement a stack using single queue" }, { "code": null, "e": 15295, "s": 15008, "text": "Priority Queues are abstract data structures where each data/value in the queue has a certain priority. For example, In airlines, baggage with the title “Business” or “First-class” arrives earlier than the rest. Priority Queue is an extension of the queue with the following properties." }, { "code": null, "e": 15374, "s": 15295, "text": "An element with high priority is dequeued before an element with low priority." }, { "code": null, "e": 15469, "s": 15374, "text": "If two elements have the same priority, they are served according to their order in the queue." }, { "code": null, "e": 15477, "s": 15469, "text": "Python3" }, { "code": "# A simple implementation of Priority Queue# using Queue.class PriorityQueue(object): def __init__(self): self.queue = [] def __str__(self): return ' '.join([str(i) for i in self.queue]) # for checking if the queue is empty def isEmpty(self): return len(self.queue) == 0 # for inserting an element in the queue def insert(self, data): self.queue.append(data) # for popping an element based on Priority def delete(self): try: max = 0 for i in range(len(self.queue)): if self.queue[i] > self.queue[max]: max = i item = self.queue[max] del self.queue[max] return item except IndexError: print() exit() if __name__ == '__main__': myQueue = PriorityQueue() myQueue.insert(12) myQueue.insert(1) myQueue.insert(14) myQueue.insert(7) print(myQueue) while not myQueue.isEmpty(): print(myQueue.delete())", "e": 16493, "s": 15477, "text": null }, { "code": null, "e": 16513, "s": 16493, "text": "12 1 14 7\n14\n12\n7\n1" }, { "code": null, "e": 16967, "s": 16513, "text": "heapq module in Python provides the heap data structure that is mainly used to represent a priority queue. The property of this data structure is that it always gives the smallest element (min heap) whenever the element is popped. Whenever elements are pushed or popped, heap structure is maintained. The heap[0] element also returns the smallest element each time. It supports the extraction and insertion of the smallest element in the O(log n) times." }, { "code": null, "e": 17005, "s": 16967, "text": "Generally, Heaps can be of two types:" }, { "code": null, "e": 17209, "s": 17005, "text": "Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of it’s children. The same property must be recursively true for all sub-trees in that Binary Tree." }, { "code": null, "e": 17412, "s": 17209, "text": "Min-Heap: In a Min-Heap the key present at the root node must be minimum among the keys present at all of it’s children. The same property must be recursively true for all sub-trees in that Binary Tree." }, { "code": null, "e": 17422, "s": 17414, "text": "Python3" }, { "code": "# importing \"heapq\" to implement heap queueimport heapq # initializing listli = [5, 7, 9, 1, 3] # using heapify to convert list into heapheapq.heapify(li) # printing created heapprint (\"The created heap is : \",end=\"\")print (list(li)) # using heappush() to push elements into heap# pushes 4heapq.heappush(li,4) # printing modified heapprint (\"The modified heap after push is : \",end=\"\")print (list(li)) # using heappop() to pop smallest elementprint (\"The popped and smallest element is : \",end=\"\")print (heapq.heappop(li))", "e": 17951, "s": 17422, "text": null }, { "code": null, "e": 18081, "s": 17951, "text": "The created heap is : [1, 3, 9, 7, 5]\nThe modified heap after push is : [1, 3, 4, 7, 5, 9]\nThe popped and smallest element is : 1" }, { "code": null, "e": 18093, "s": 18081, "text": "Binary Heap" }, { "code": null, "e": 18126, "s": 18093, "text": "K’th Largest Element in an array" }, { "code": null, "e": 18174, "s": 18126, "text": "K’th Smallest/Largest Element in Unsorted Array" }, { "code": null, "e": 18202, "s": 18174, "text": "Sort an almost sorted array" }, { "code": null, "e": 18239, "s": 18202, "text": "K-th Largest Sum Contiguous Subarray" }, { "code": null, "e": 18297, "s": 18239, "text": "Minimum sum of two numbers formed from digits of an array" }, { "code": null, "e": 18306, "s": 18297, "text": ">>> More" }, { "code": null, "e": 18382, "s": 18306, "text": "A tree is a hierarchical data structure that looks like the below figure –" }, { "code": null, "e": 18484, "s": 18382, "text": " tree\n ----\n j <-- root\n / \\\n f k \n/ \\ \\\na h z <-- leaves" }, { "code": null, "e": 18754, "s": 18484, "text": "The topmost node of the tree is called the root whereas the bottommost nodes or the nodes with no children are called the leaf nodes. The nodes that are directly under a node are called its children and the nodes that are directly above something are called its parent." }, { "code": null, "e": 18986, "s": 18754, "text": "A binary tree is a tree whose elements can have almost two children. Since each element in a binary tree can have only 2 children, we typically name them the left and right children. A Binary Tree node contains the following parts." }, { "code": null, "e": 18991, "s": 18986, "text": "Data" }, { "code": null, "e": 19013, "s": 18991, "text": "Pointer to left child" }, { "code": null, "e": 19040, "s": 19013, "text": "Pointer to the right child" }, { "code": null, "e": 19048, "s": 19040, "text": "Python3" }, { "code": "# A Python class that represents an individual node# in a Binary Treeclass Node: def __init__(self,key): self.left = None self.right = None self.val = key", "e": 19227, "s": 19048, "text": null }, { "code": null, "e": 19326, "s": 19227, "text": "Now let’s create a tree with 4 nodes in Python. Let’s assume the tree structure looks like below –" }, { "code": null, "e": 19392, "s": 19326, "text": " tree\n ----\n 1 <-- root\n / \\\n 2 3 \n / \n4" }, { "code": null, "e": 19400, "s": 19392, "text": "Python3" }, { "code": "# Python program to introduce Binary Tree # A class that represents an individual node in a# Binary Treeclass Node: def __init__(self,key): self.left = None self.right = None self.val = key # create rootroot = Node(1)''' following is the tree after above statement 1 / \\ None None''' root.left = Node(2);root.right = Node(3); ''' 2 and 3 become left and right children of 1 1 / \\ 2 3 / \\ / \\None None None None''' root.left.left = Node(4);'''4 becomes left child of 2 1 / \\ 2 3 / \\ / \\4 None None None/ \\None None'''", "e": 20031, "s": 19400, "text": null }, { "code": null, "e": 20166, "s": 20031, "text": "Trees can be traversed in different ways. Following are the generally used ways for traversing trees. Let us consider the below tree –" }, { "code": null, "e": 20236, "s": 20166, "text": " tree\n ----\n 1 <-- root\n / \\\n 2 3 \n / \\\n4 5" }, { "code": null, "e": 20260, "s": 20236, "text": "Depth First Traversals:" }, { "code": null, "e": 20300, "s": 20260, "text": "Inorder (Left, Root, Right) : 4 2 5 1 3" }, { "code": null, "e": 20341, "s": 20300, "text": "Preorder (Root, Left, Right) : 1 2 4 5 3" }, { "code": null, "e": 20383, "s": 20341, "text": "Postorder (Left, Right, Root) : 4 5 2 3 1" }, { "code": null, "e": 20407, "s": 20383, "text": "Algorithm Inorder(tree)" }, { "code": null, "e": 20467, "s": 20407, "text": "Traverse the left subtree, i.e., call Inorder(left-subtree)" }, { "code": null, "e": 20483, "s": 20467, "text": "Visit the root." }, { "code": null, "e": 20545, "s": 20483, "text": "Traverse the right subtree, i.e., call Inorder(right-subtree)" }, { "code": null, "e": 20570, "s": 20545, "text": "Algorithm Preorder(tree)" }, { "code": null, "e": 20586, "s": 20570, "text": "Visit the root." }, { "code": null, "e": 20647, "s": 20586, "text": "Traverse the left subtree, i.e., call Preorder(left-subtree)" }, { "code": null, "e": 20710, "s": 20647, "text": "Traverse the right subtree, i.e., call Preorder(right-subtree)" }, { "code": null, "e": 20736, "s": 20710, "text": "Algorithm Postorder(tree)" }, { "code": null, "e": 20798, "s": 20736, "text": "Traverse the left subtree, i.e., call Postorder(left-subtree)" }, { "code": null, "e": 20862, "s": 20798, "text": "Traverse the right subtree, i.e., call Postorder(right-subtree)" }, { "code": null, "e": 20878, "s": 20862, "text": "Visit the root." }, { "code": null, "e": 20886, "s": 20878, "text": "Python3" }, { "code": "# Python program to for tree traversals # A class that represents an individual node in a# Binary Treeclass Node: def __init__(self, key): self.left = None self.right = None self.val = key # A function to do inorder tree traversaldef printInorder(root): if root: # First recur on left child printInorder(root.left) # then print the data of node print(root.val), # now recur on right child printInorder(root.right) # A function to do postorder tree traversaldef printPostorder(root): if root: # First recur on left child printPostorder(root.left) # the recur on right child printPostorder(root.right) # now print the data of node print(root.val), # A function to do preorder tree traversaldef printPreorder(root): if root: # First print the data of node print(root.val), # Then recur on left child printPreorder(root.left) # Finally recur on right child printPreorder(root.right) # Driver coderoot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)print(\"Preorder traversal of binary tree is\")printPreorder(root) print(\"\\nInorder traversal of binary tree is\")printInorder(root) print(\"\\nPostorder traversal of binary tree is\")printPostorder(root)", "e": 22277, "s": 20886, "text": null }, { "code": null, "e": 22420, "s": 22277, "text": "Preorder traversal of binary tree is\n1\n2\n4\n5\n3\n\nInorder traversal of binary tree is\n4\n2\n5\n1\n3\n\nPostorder traversal of binary tree is\n4\n5\n2\n3\n1" }, { "code": null, "e": 22444, "s": 22420, "text": "Time Complexity – O(n)" }, { "code": null, "e": 22483, "s": 22444, "text": "Breadth-First or Level Order Traversal" }, { "code": null, "e": 22614, "s": 22483, "text": "Level order traversal of a tree is breadth-first traversal for the tree. The level order traversal of the above tree is 1 2 3 4 5." }, { "code": null, "e": 22744, "s": 22614, "text": "For each node, first, the node is visited and then its child nodes are put in a FIFO queue. Below is the algorithm for the same –" }, { "code": null, "e": 22768, "s": 22744, "text": "Create an empty queue q" }, { "code": null, "e": 22805, "s": 22768, "text": "temp_node = root /*start from root*/" }, { "code": null, "e": 22947, "s": 22805, "text": "Loop while temp_node is not NULLprint temp_node->data.Enqueue temp_node’s children (first left then right children) to qDequeue a node from q" }, { "code": null, "e": 22970, "s": 22947, "text": "print temp_node->data." }, { "code": null, "e": 23037, "s": 22970, "text": "Enqueue temp_node’s children (first left then right children) to q" }, { "code": null, "e": 23059, "s": 23037, "text": "Dequeue a node from q" }, { "code": null, "e": 23067, "s": 23059, "text": "Python3" }, { "code": "# Python program to print level# order traversal using Queue # A node structureclass Node: # A utility function to create a new node def __init__(self ,key): self.data = key self.left = None self.right = None # Iterative Method to print the# height of a binary treedef printLevelOrder(root): # Base Case if root is None: return # Create an empty queue # for level order traversal queue = [] # Enqueue Root and initialize height queue.append(root) while(len(queue) > 0): # Print front of queue and # remove it from queue print (queue[0].data) node = queue.pop(0) # Enqueue left child if node.left is not None: queue.append(node.left) # Enqueue right child if node.right is not None: queue.append(node.right) # Driver Program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5) print (\"Level Order Traversal of binary tree is -\")printLevelOrder(root)", "e": 24153, "s": 23067, "text": null }, { "code": null, "e": 24205, "s": 24153, "text": "Level Order Traversal of binary tree is -\n1\n2\n3\n4\n5" }, { "code": null, "e": 24228, "s": 24205, "text": "Time Complexity: O(n) " }, { "code": null, "e": 24255, "s": 24228, "text": "Insertion in a Binary Tree" }, { "code": null, "e": 24281, "s": 24255, "text": "Deletion in a Binary Tree" }, { "code": null, "e": 24322, "s": 24281, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 24382, "s": 24322, "text": "Inorder Tree Traversal without recursion and without stack!" }, { "code": null, "e": 24451, "s": 24382, "text": "Print Postorder traversal from given Inorder and Preorder traversals" }, { "code": null, "e": 24507, "s": 24451, "text": "Find postorder traversal of BST from preorder traversal" }, { "code": null, "e": 24516, "s": 24507, "text": ">>> More" }, { "code": null, "e": 24613, "s": 24516, "text": "Binary Search Tree is a node-based binary tree data structure that has the following properties:" }, { "code": null, "e": 24698, "s": 24613, "text": "The left subtree of a node contains only nodes with keys lesser than the node’s key." }, { "code": null, "e": 24785, "s": 24698, "text": "The right subtree of a node contains only nodes with keys greater than the node’s key." }, { "code": null, "e": 24852, "s": 24785, "text": "The left and right subtree each must also be a binary search tree." }, { "code": null, "e": 25091, "s": 24852, "text": "The above properties of the Binary Search Tree provide an ordering among keys so that the operations like search, minimum and maximum can be done fast. If there is no order, then we may have to compare every key to search for a given key." }, { "code": null, "e": 25112, "s": 25091, "text": "Start from the root." }, { "code": null, "e": 25219, "s": 25112, "text": "Compare the searching element with root, if less than root, then recurse for left, else recurse for right." }, { "code": null, "e": 25295, "s": 25219, "text": "If the element to search is found anywhere, return true, else return false." }, { "code": null, "e": 25303, "s": 25295, "text": "Python3" }, { "code": "# A utility function to search a given key in BSTdef search(root,key): # Base Cases: root is null or key is present at root if root is None or root.val == key: return root # Key is greater than root's key if root.val < key: return search(root.right,key) # Key is smaller than root's key return search(root.left,key)", "e": 25661, "s": 25303, "text": null }, { "code": null, "e": 25682, "s": 25661, "text": "Start from the root." }, { "code": null, "e": 25789, "s": 25682, "text": "Compare the inserting element with root, if less than root, then recurse for left, else recurse for right." }, { "code": null, "e": 25877, "s": 25789, "text": "After reaching the end, just insert that node at left(if less than current) else right." }, { "code": null, "e": 25885, "s": 25877, "text": "Python3" }, { "code": "# Python program to demonstrate# insert operation in binary search tree # A utility class that represents# an individual node in a BSTclass Node: def __init__(self, key): self.left = None self.right = None self.val = key # A utility function to insert# a new node with the given keydef insert(root, key): if root is None: return Node(key) else: if root.val == key: return root elif root.val < key: root.right = insert(root.right, key) else: root.left = insert(root.left, key) return root # A utility function to do inorder tree traversaldef inorder(root): if root: inorder(root.left) print(root.val) inorder(root.right) # Driver program to test the above functions# Let us create the following BST# 50# / \\# 30 70# / \\ / \\# 20 40 60 80 r = Node(50)r = insert(r, 30)r = insert(r, 20)r = insert(r, 40)r = insert(r, 70)r = insert(r, 60)r = insert(r, 80) # Print inorder traversal of the BSTinorder(r)", "e": 26917, "s": 25885, "text": null }, { "code": null, "e": 26938, "s": 26917, "text": "20\n30\n40\n50\n60\n70\n80" }, { "code": null, "e": 26970, "s": 26938, "text": "Binary Search Tree – Delete Key" }, { "code": null, "e": 27022, "s": 26970, "text": "Construct BST from given preorder traversal | Set 1" }, { "code": null, "e": 27067, "s": 27022, "text": "Binary Tree to Binary Search Tree Conversion" }, { "code": null, "e": 27124, "s": 27067, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 27174, "s": 27124, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 27183, "s": 27174, "text": ">>> More" }, { "code": null, "e": 27524, "s": 27183, "text": "A graph is a nonlinear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph can be defined as a Graph consisting of a finite set of vertices(or nodes) and a set of edges that connect a pair of nodes." }, { "code": null, "e": 27708, "s": 27524, "text": "In the above Graph, the set of vertices V = {0,1,2,3,4} and the set of edges E = {01, 12, 23, 34, 04, 14, 13}. The following two are the most commonly used representations of a graph." }, { "code": null, "e": 27725, "s": 27708, "text": "Adjacency Matrix" }, { "code": null, "e": 27740, "s": 27725, "text": "Adjacency List" }, { "code": null, "e": 28148, "s": 27740, "text": "Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j. The adjacency matrix for an undirected graph is always symmetric. Adjacency Matrix is also used to represent weighted graphs. If adj[i][j] = w, then there is an edge from vertex i to vertex j with weight w. " }, { "code": null, "e": 28156, "s": 28148, "text": "Python3" }, { "code": "# A simple representation of graph using Adjacency Matrixclass Graph: def __init__(self,numvertex): self.adjMatrix = [[-1]*numvertex for x in range(numvertex)] self.numvertex = numvertex self.vertices = {} self.verticeslist =[0]*numvertex def set_vertex(self,vtx,id): if 0<=vtx<=self.numvertex: self.vertices[id] = vtx self.verticeslist[vtx] = id def set_edge(self,frm,to,cost=0): frm = self.vertices[frm] to = self.vertices[to] self.adjMatrix[frm][to] = cost # for directed graph do not add this self.adjMatrix[to][frm] = cost def get_vertex(self): return self.verticeslist def get_edges(self): edges=[] for i in range (self.numvertex): for j in range (self.numvertex): if (self.adjMatrix[i][j]!=-1): edges.append((self.verticeslist[i],self.verticeslist[j],self.adjMatrix[i][j])) return edges def get_matrix(self): return self.adjMatrix G =Graph(6)G.set_vertex(0,'a')G.set_vertex(1,'b')G.set_vertex(2,'c')G.set_vertex(3,'d')G.set_vertex(4,'e')G.set_vertex(5,'f')G.set_edge('a','e',10)G.set_edge('a','c',20)G.set_edge('c','b',30)G.set_edge('b','e',40)G.set_edge('e','d',50)G.set_edge('f','e',60) print(\"Vertices of Graph\")print(G.get_vertex()) print(\"Edges of Graph\")print(G.get_edges()) print(\"Adjacency Matrix of Graph\")print(G.get_matrix())", "e": 29622, "s": 28156, "text": null }, { "code": null, "e": 29629, "s": 29622, "text": "Output" }, { "code": null, "e": 29647, "s": 29629, "text": "Vertices of Graph" }, { "code": null, "e": 29678, "s": 29647, "text": "[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]" }, { "code": null, "e": 29693, "s": 29678, "text": "Edges of Graph" }, { "code": null, "e": 29886, "s": 29693, "text": "[(‘a’, ‘c’, 20), (‘a’, ‘e’, 10), (‘b’, ‘c’, 30), (‘b’, ‘e’, 40), (‘c’, ‘a’, 20), (‘c’, ‘b’, 30), (‘d’, ‘e’, 50), (‘e’, ‘a’, 10), (‘e’, ‘b’, 40), (‘e’, ‘d’, 50), (‘e’, ‘f’, 60), (‘f’, ‘e’, 60)]" }, { "code": null, "e": 29912, "s": 29886, "text": "Adjacency Matrix of Graph" }, { "code": null, "e": 30069, "s": 29912, "text": "[[-1, -1, 20, -1, 10, -1], [-1, -1, 30, -1, 40, -1], [20, 30, -1, -1, -1, -1], [-1, -1, -1, -1, 50, -1], [10, 40, -1, 50, -1, 60], [-1, -1, -1, -1, 60, -1]]" }, { "code": null, "e": 30456, "s": 30069, "text": "An array of lists is used. The size of the array is equal to the number of vertices. Let the array be an array[]. An entry array[i] represents the list of vertices adjacent to the ith vertex. This representation can also be used to represent a weighted graph. The weights of edges can be represented as lists of pairs. Following is the adjacency list representation of the above graph. " }, { "code": null, "e": 30466, "s": 30458, "text": "Python3" }, { "code": "# A class to represent the adjacency list of the nodeclass AdjNode: def __init__(self, data): self.vertex = data self.next = None # A class to represent a graph. A graph# is the list of the adjacency lists.# Size of the array will be the no. of the# vertices \"V\"class Graph: def __init__(self, vertices): self.V = vertices self.graph = [None] * self.V # Function to add an edge in an undirected graph def add_edge(self, src, dest): # Adding the node to the source node node = AdjNode(dest) node.next = self.graph[src] self.graph[src] = node # Adding the source node to the destination as # it is the undirected graph node = AdjNode(src) node.next = self.graph[dest] self.graph[dest] = node # Function to print the graph def print_graph(self): for i in range(self.V): print(\"Adjacency list of vertex {}\\n head\".format(i), end=\"\") temp = self.graph[i] while temp: print(\" -> {}\".format(temp.vertex), end=\"\") temp = temp.next print(\" \\n\") # Driver program to the above graph classif __name__ == \"__main__\": V = 5 graph = Graph(V) graph.add_edge(0, 1) graph.add_edge(0, 4) graph.add_edge(1, 2) graph.add_edge(1, 3) graph.add_edge(1, 4) graph.add_edge(2, 3) graph.add_edge(3, 4) graph.print_graph()", "e": 31900, "s": 30466, "text": null }, { "code": null, "e": 32144, "s": 31900, "text": "Adjacency list of vertex 0\n head -> 4 -> 1 \n\nAdjacency list of vertex 1\n head -> 4 -> 3 -> 2 -> 0 \n\nAdjacency list of vertex 2\n head -> 3 -> 1 \n\nAdjacency list of vertex 3\n head -> 4 -> 2 -> 1 \n\nAdjacency list of vertex 4\n head -> 3 -> 1 -> 0 " }, { "code": null, "e": 32496, "s": 32144, "text": "Breadth-First Traversal for a graph is similar to Breadth-First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array. For simplicity, it is assumed that all vertices are reachable from the starting vertex." }, { "code": null, "e": 32845, "s": 32496, "text": "For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. A Breadth-First Traversal of the following graph is 2, 0, 3, 1." }, { "code": null, "e": 32855, "s": 32847, "text": "Python3" }, { "code": "# Python3 Program to print BFS traversal# from a given source vertex. BFS(int s)# traverses vertices reachable from s.from collections import defaultdict # This class represents a directed graph# using adjacency list representationclass Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # Function to print a BFS of graph def BFS(self, s): # Mark all the vertices as not visited visited = [False] * (max(self.graph) + 1) # Create a queue for BFS queue = [] # Mark the source node as # visited and enqueue it queue.append(s) visited[s] = True while queue: # Dequeue a vertex from # queue and print it s = queue.pop(0) print (s, end = \" \") # Get all adjacent vertices of the # dequeued vertex s. If a adjacent # has not been visited, then mark it # visited and enqueue it for i in self.graph[s]: if visited[i] == False: queue.append(i) visited[i] = True # Driver code # Create a graph given in# the above diagramg = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) print (\"Following is Breadth First Traversal\" \" (starting from vertex 2)\")g.BFS(2)", "e": 34383, "s": 32855, "text": null }, { "code": null, "e": 34454, "s": 34383, "text": "Following is Breadth First Traversal (starting from vertex 2)\n2 0 3 1 " }, { "code": null, "e": 34568, "s": 34454, "text": "Time Complexity: O(V+E) where V is the number of vertices in the graph and E is the number of edges in the graph." }, { "code": null, "e": 34815, "s": 34568, "text": "Depth First Traversal for a graph is similar to Depth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, a node may be visited twice. To avoid processing a node more than once, use a boolean visited array." }, { "code": null, "e": 34826, "s": 34815, "text": "Algorithm:" }, { "code": null, "e": 34908, "s": 34826, "text": "Create a recursive function that takes the index of the node and a visited array." }, { "code": null, "e": 34961, "s": 34908, "text": "Mark the current node as visited and print the node." }, { "code": null, "e": 35075, "s": 34961, "text": "Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node." }, { "code": null, "e": 35083, "s": 35075, "text": "Python3" }, { "code": "# Python3 program to print DFS traversal# from a given graphfrom collections import defaultdict # This class represents a directed graph using# adjacency list representationclass Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A function used by DFS def DFSUtil(self, v, visited): # Mark the current node as visited # and print it visited.add(v) print(v, end=' ') # Recur for all the vertices # adjacent to this vertex for neighbour in self.graph[v]: if neighbour not in visited: self.DFSUtil(neighbour, visited) # The function to do DFS traversal. It uses # recursive DFSUtil() def DFS(self, v): # Create a set to store visited vertices visited = set() # Call the recursive helper function # to print DFS traversal self.DFSUtil(v, visited) # Driver code # Create a graph given# in the above diagramg = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) print(\"Following is DFS from (starting from vertex 2)\")g.DFS(2)", "e": 36375, "s": 35083, "text": null }, { "code": null, "e": 36431, "s": 36375, "text": "Following is DFS from (starting from vertex 2)\n2 0 1 3 " }, { "code": null, "e": 36472, "s": 36431, "text": "Graph representations using set and hash" }, { "code": null, "e": 36502, "s": 36472, "text": "Find Mother Vertex in a Graph" }, { "code": null, "e": 36531, "s": 36502, "text": "Iterative Depth First Search" }, { "code": null, "e": 36592, "s": 36531, "text": "Count the number of nodes at given level in a tree using BFS" }, { "code": null, "e": 36638, "s": 36592, "text": "Count all possible paths between two vertices" }, { "code": null, "e": 36647, "s": 36638, "text": ">>> More" }, { "code": null, "e": 36991, "s": 36647, "text": "The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using the recursive algorithms, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc." }, { "code": null, "e": 37142, "s": 36991, "text": "In the recursive program, the solution to the base case is provided and the solution of the bigger problem is expressed in terms of smaller problems. " }, { "code": null, "e": 37247, "s": 37142, "text": "def fact(n):\n\n # base case\n if (n < = 1) \n return 1\n else \n return n*fact(n-1)" }, { "code": null, "e": 37399, "s": 37247, "text": "In the above example, base case for n < = 1 is defined and larger value of number can be solved by converting to smaller one till base case is reached." }, { "code": null, "e": 37844, "s": 37399, "text": "When any function is called from main(), the memory is allocated to it on the stack. A recursive function calls itself, the memory for a called function is allocated on top of memory allocated to the calling function and a different copy of local variables is created for each function call. When the base case is reached, the function returns its value to the function by whom it is called and memory is de-allocated and the process continues." }, { "code": null, "e": 37921, "s": 37844, "text": "Let us take the example of how recursion works by taking a simple function. " }, { "code": null, "e": 37929, "s": 37921, "text": "Python3" }, { "code": "# A Python 3 program to# demonstrate working of# recursion def printFun(test): if (test < 1): return else: print(test, end=\" \") printFun(test-1) # statement 2 print(test, end=\" \") return # Driver Codetest = 3printFun(test)", "e": 38200, "s": 37929, "text": null }, { "code": null, "e": 38213, "s": 38200, "text": "3 2 1 1 2 3 " }, { "code": null, "e": 38263, "s": 38213, "text": "The memory stack has been shown in below diagram." }, { "code": null, "e": 38273, "s": 38263, "text": "Recursion" }, { "code": null, "e": 38293, "s": 38273, "text": "Recursion in Python" }, { "code": null, "e": 38334, "s": 38293, "text": "Practice Questions for Recursion | Set 1" }, { "code": null, "e": 38375, "s": 38334, "text": "Practice Questions for Recursion | Set 2" }, { "code": null, "e": 38416, "s": 38375, "text": "Practice Questions for Recursion | Set 3" }, { "code": null, "e": 38457, "s": 38416, "text": "Practice Questions for Recursion | Set 4" }, { "code": null, "e": 38498, "s": 38457, "text": "Practice Questions for Recursion | Set 5" }, { "code": null, "e": 38539, "s": 38498, "text": "Practice Questions for Recursion | Set 6" }, { "code": null, "e": 38580, "s": 38539, "text": "Practice Questions for Recursion | Set 7" }, { "code": null, "e": 38589, "s": 38580, "text": ">>> More" }, { "code": null, "e": 39184, "s": 38589, "text": "Dynamic Programming is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of subproblems, so that we do not have to re-compute them when needed later. This simple optimization reduces time complexities from exponential to polynomial. For example, if we write simple recursive solution for Fibonacci Numbers, we get exponential time complexity and if we optimize it by storing solutions of subproblems, time complexity reduces to linear." }, { "code": null, "e": 39362, "s": 39184, "text": "There are two different ways to store the values so that the values of a sub-problem can be reused. Here, will discuss two patterns of solving dynamic programming (DP) problem: " }, { "code": null, "e": 39384, "s": 39362, "text": "Tabulation: Bottom Up" }, { "code": null, "e": 39406, "s": 39384, "text": "Memoization: Top Down" }, { "code": null, "e": 39540, "s": 39406, "text": "As the name itself suggests starting from the bottom and accumulating answers to the top. Let’s discuss in terms of state transition." }, { "code": null, "e": 39718, "s": 39540, "text": "Let’s describe a state for our DP problem to be dp[x] with dp[0] as base state and dp[n] as our destination state. So, we need to find the value of destination state i.e dp[n]." }, { "code": null, "e": 40006, "s": 39718, "text": "If we start our transition from our base state i.e dp[0] and follow our state transition relation to reach our destination state dp[n], we call it the Bottom-Up approach as it is quite clear that we started our transition from the bottom base state and reached the topmost desired state." }, { "code": null, "e": 40048, "s": 40006, "text": "Now, Why do we call it tabulation method?" }, { "code": null, "e": 40315, "s": 40048, "text": "To know this let’s first write some code to calculate the factorial of a number using bottom up approach. Once, again as our general procedure to solve a DP we first define a state. In this case, we define a state as dp[x], where dp[x] is to find the factorial of x." }, { "code": null, "e": 40369, "s": 40315, "text": "Now, it is quite obvious that dp[x+1] = dp[x] * (x+1)" }, { "code": null, "e": 40492, "s": 40369, "text": "# Tabulated version to find factorial x.\ndp = [0]*MAXN\n\n# base case\ndp[0] = 1;\nfor i in range(n+1):\n dp[i] = dp[i-1] * i" }, { "code": null, "e": 40822, "s": 40492, "text": "Once, again let’s describe it in terms of state transition. If we need to find the value for some state say dp[n] and instead of starting from the base state that i.e dp[0] we ask our answer from the states that can reach the destination state dp[n] following the state transition relation, then it is the top-down fashion of DP." }, { "code": null, "e": 41028, "s": 40822, "text": "Here, we start our journey from the top most destination state and compute its answer by taking in count the values of states that can reach the destination state, till we reach the bottom-most base state." }, { "code": null, "e": 41111, "s": 41028, "text": "Once again, let’s write the code for the factorial problem in the top-down fashion" }, { "code": null, "e": 41375, "s": 41111, "text": "# Memoized version to find factorial x.\n# To speed up we store the values\n# of calculated states\n\n# initialized to -1\ndp[0]*MAXN\n\n# return fact x!\ndef solve(x):\n if (x==0)\n return 1\n if (dp[x]!=-1)\n return dp[x]\n return (dp[x] = x * solve(x-1))" }, { "code": null, "e": 41405, "s": 41375, "text": "Optimal Substructure Property" }, { "code": null, "e": 41438, "s": 41405, "text": "Overlapping Subproblems Property" }, { "code": null, "e": 41456, "s": 41438, "text": "Fibonacci numbers" }, { "code": null, "e": 41487, "s": 41456, "text": "Subset with sum divisible by m" }, { "code": null, "e": 41522, "s": 41487, "text": "Maximum Sum Increasing Subsequence" }, { "code": null, "e": 41547, "s": 41522, "text": "Longest Common Substring" }, { "code": null, "e": 41556, "s": 41547, "text": ">>> More" }, { "code": null, "e": 41649, "s": 41556, "text": "Start from the leftmost element of arr[] and one by one compare x with each element of arr[]" }, { "code": null, "e": 41697, "s": 41649, "text": "If x matches with an element, return the index." }, { "code": null, "e": 41753, "s": 41697, "text": "If x doesn’t match with any of the elements, return -1." }, { "code": null, "e": 41763, "s": 41755, "text": "Python3" }, { "code": "# Python3 code to linearly search x in arr[].# If x is present then return its location,# otherwise return -1 def search(arr, n, x): for i in range(0, n): if (arr[i] == x): return i return -1 # Driver Codearr = [2, 3, 4, 10, 40]x = 10n = len(arr) # Function callresult = search(arr, n, x)if(result == -1): print(\"Element is not present in array\")else: print(\"Element is present at index\", result)", "e": 42199, "s": 41763, "text": null }, { "code": null, "e": 42229, "s": 42199, "text": "Element is present at index 3" }, { "code": null, "e": 42282, "s": 42229, "text": "The time complexity of the above algorithm is O(n). " }, { "code": null, "e": 42328, "s": 42282, "text": "For more information, refer to Linear Search." }, { "code": null, "e": 42682, "s": 42328, "text": "Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Repeatedly check until the value is found or the interval is empty." }, { "code": null, "e": 42692, "s": 42684, "text": "Python3" }, { "code": "# Python3 Program for recursive binary search. # Returns index of x in arr if present, else -1def binarySearch (arr, l, r, x): # Check base case if r >= l: mid = l + (r - l) // 2 # If element is present at the middle itself if arr[mid] == x: return mid # If element is smaller than mid, then it # can only be present in left subarray elif arr[mid] > x: return binarySearch(arr, l, mid-1, x) # Else the element can only be present # in right subarray else: return binarySearch(arr, mid + 1, r, x) else: # Element is not present in the array return -1 # Driver Codearr = [ 2, 3, 4, 10, 40 ]x = 10 # Function callresult = binarySearch(arr, 0, len(arr)-1, x) if result != -1: print (\"Element is present at index % d\" % result)else: print (\"Element is not present in array\")", "e": 43611, "s": 42692, "text": null }, { "code": null, "e": 43642, "s": 43611, "text": "Element is present at index 3" }, { "code": null, "e": 43700, "s": 43642, "text": "The time complexity of the above algorithm is O(log(n)). " }, { "code": null, "e": 43746, "s": 43700, "text": "For more information, refer to Binary Search." }, { "code": null, "e": 44074, "s": 43746, "text": "The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. " }, { "code": null, "e": 44084, "s": 44076, "text": "Python3" }, { "code": "# Python program for implementation of Selection# Sortimport sys A = [64, 25, 12, 22, 11] # Traverse through all array elementsfor i in range(len(A)): # Find the minimum element in remaining # unsorted array min_idx = i for j in range(i+1, len(A)): if A[min_idx] > A[j]: min_idx = j # Swap the found minimum element with # the first element A[i], A[min_idx] = A[min_idx], A[i] # Driver code to test aboveprint (\"Sorted array\")for i in range(len(A)): print(\"%d\" %A[i]),", "e": 44624, "s": 44084, "text": null }, { "code": null, "e": 44652, "s": 44624, "text": "Sorted array\n11\n12\n22\n25\n64" }, { "code": null, "e": 44706, "s": 44652, "text": "Time Complexity: O(n2) as there are two nested loops." }, { "code": null, "e": 44729, "s": 44706, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 44859, "s": 44729, "text": "Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order." }, { "code": null, "e": 44875, "s": 44859, "text": "Illustration : " }, { "code": null, "e": 44885, "s": 44877, "text": "Python3" }, { "code": "# Python program for implementation of Bubble Sort def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in place for j in range(0, n-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] # Driver code to test abovearr = [64, 34, 25, 12, 22, 11, 90] bubbleSort(arr) print (\"Sorted array is:\")for i in range(len(arr)): print (\"%d\" %arr[i]),", "e": 45498, "s": 44885, "text": null }, { "code": null, "e": 45536, "s": 45498, "text": "Sorted array is:\n11\n12\n22\n25\n34\n64\n90" }, { "code": null, "e": 45559, "s": 45536, "text": "Time Complexity: O(n2)" }, { "code": null, "e": 45627, "s": 45559, "text": "To sort an array of size n in ascending order using insertion sort:" }, { "code": null, "e": 45673, "s": 45627, "text": "Iterate from arr[1] to arr[n] over the array." }, { "code": null, "e": 45727, "s": 45673, "text": "Compare the current element (key) to its predecessor." }, { "code": null, "e": 45895, "s": 45727, "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": 45909, "s": 45895, "text": "Illustration:" }, { "code": null, "e": 45919, "s": 45911, "text": "Python3" }, { "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])", "e": 46514, "s": 45919, "text": null }, { "code": null, "e": 46532, "s": 46514, "text": " 5\n 6\n 11\n 12\n 13" }, { "code": null, "e": 46556, "s": 46532, "text": "Time Complexity: O(n2))" }, { "code": null, "e": 46931, "s": 46556, "text": "Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides the input array into two halves, calls itself for the two halves, and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is a key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one. " }, { "code": null, "e": 47321, "s": 46931, "text": "MergeSort(arr[], l, r)\nIf r > l\n 1. Find the middle point to divide the array into two halves: \n middle m = l+ (r-l)/2\n 2. Call mergeSort for first half: \n Call mergeSort(arr, l, m)\n 3. Call mergeSort for second half:\n Call mergeSort(arr, m+1, r)\n 4. Merge the two halves sorted in step 2 and 3:\n Call merge(arr, l, m, r)" }, { "code": null, "e": 47331, "s": 47323, "text": "Python3" }, { "code": "# Python program for implementation of MergeSortdef mergeSort(arr): if len(arr) > 1: # Finding the mid of the array mid = len(arr)//2 # Dividing the array elements L = arr[:mid] # into 2 halves R = arr[mid:] # Sorting the first half mergeSort(L) # Sorting the second half mergeSort(R) i = j = k = 0 # Copy data to temp arrays L[] and R[] while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # Checking if any element was left while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1 # Code to print the list def printList(arr): for i in range(len(arr)): print(arr[i], end=\" \") print() # Driver Codeif __name__ == '__main__': arr = [12, 11, 13, 5, 6, 7] print(\"Given array is\", end=\"\\n\") printList(arr) mergeSort(arr) print(\"Sorted array is: \", end=\"\\n\") printList(arr)", "e": 48516, "s": 47331, "text": null }, { "code": null, "e": 48581, "s": 48516, "text": "Given array is\n12 11 13 5 6 7 \nSorted array is: \n5 6 7 11 12 13 " }, { "code": null, "e": 48609, "s": 48581, "text": "Time Complexity: O(n(logn))" }, { "code": null, "e": 48838, "s": 48609, "text": "Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways." }, { "code": null, "e": 48874, "s": 48838, "text": "Always pick first element as pivot." }, { "code": null, "e": 48928, "s": 48874, "text": "Always pick last element as pivot (implemented below)" }, { "code": null, "e": 48960, "s": 48928, "text": "Pick a random element as pivot." }, { "code": null, "e": 48982, "s": 48960, "text": "Pick median as pivot." }, { "code": null, "e": 49300, "s": 48982, "text": "The key process in quickSort is partition(). Target of partitions is, given an array and an element x of array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x. All this should be done in linear time." }, { "code": null, "e": 49642, "s": 49300, "text": "/* low --> Starting index, high --> Ending index */\nquickSort(arr[], low, high)\n{\n if (low < high)\n {\n /* pi is partitioning index, arr[pi] is now\n at right place */\n pi = partition(arr, low, high);\n\n quickSort(arr, low, pi - 1); // Before pi\n quickSort(arr, pi + 1, high); // After pi\n }\n}" }, { "code": null, "e": 49662, "s": 49642, "text": "Partition Algorithm" }, { "code": null, "e": 50005, "s": 49662, "text": "There can be many ways to do partition, following pseudo code adopts the method given in CLRS book. The logic is simple, we start from the leftmost element and keep track of index of smaller (or equal to) elements as i. While traversing, if we find a smaller element, we swap current element with arr[i]. Otherwise we ignore current element. " }, { "code": null, "e": 50347, "s": 50005, "text": "/* low --> Starting index, high --> Ending index */\nquickSort(arr[], low, high)\n{\n if (low < high)\n {\n /* pi is partitioning index, arr[pi] is now\n at right place */\n pi = partition(arr, low, high);\n\n quickSort(arr, low, pi - 1); // Before pi\n quickSort(arr, pi + 1, high); // After pi\n }\n}" }, { "code": null, "e": 50355, "s": 50347, "text": "Python3" }, { "code": "# Python3 implementation of QuickSort # This Function handles sorting part of quick sort# start and end points to first and last element of# an array respectivelydef partition(start, end, array): # Initializing pivot's index to start pivot_index = start pivot = array[pivot_index] # This loop runs till start pointer crosses # end pointer, and when it does we swap the # pivot with element on end pointer while start < end: # Increment the start pointer till it finds an # element greater than pivot while start < len(array) and array[start] <= pivot: start += 1 # Decrement the end pointer till it finds an # element less than pivot while array[end] > pivot: end -= 1 # If start and end have not crossed each other, # swap the numbers on start and end if(start < end): array[start], array[end] = array[end], array[start] # Swap pivot element with element on end pointer. # This puts pivot on its correct sorted place. array[end], array[pivot_index] = array[pivot_index], array[end] # Returning end pointer to divide the array into 2 return end # The main function that implements QuickSortdef quick_sort(start, end, array): if (start < end): # p is partitioning index, array[p] # is at right place p = partition(start, end, array) # Sort elements before partition # and after partition quick_sort(start, p - 1, array) quick_sort(p + 1, end, array) # Driver codearray = [ 10, 7, 8, 9, 1, 5 ]quick_sort(0, len(array) - 1, array) print(f'Sorted array: {array}')", "e": 52099, "s": 50355, "text": null }, { "code": null, "e": 52133, "s": 52099, "text": "Sorted array: [1, 5, 7, 8, 9, 10]" }, { "code": null, "e": 52161, "s": 52133, "text": "Time Complexity: O(n(logn))" }, { "code": null, "e": 52603, "s": 52161, "text": "ShellSort is mainly a variation of Insertion Sort. In insertion sort, we move elements only one position ahead. When an element has to be moved far ahead, many movements are involved. The idea of shellSort is to allow the exchange of far items. In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every hth element is sorted." }, { "code": null, "e": 52611, "s": 52603, "text": "Python3" }, { "code": "# Python3 program for implementation of Shell Sort def shellSort(arr): gap = len(arr) // 2 # initialize the gap while gap > 0: i = 0 j = gap # check the array in from left to right # till the last possible index of j while j < len(arr): if arr[i] >arr[j]: arr[i],arr[j] = arr[j],arr[i] i += 1 j += 1 # now, we look back from ith index to the left # we swap the values which are not in the right order. k = i while k - gap > -1: if arr[k - gap] > arr[k]: arr[k-gap],arr[k] = arr[k],arr[k-gap] k -= 1 gap //= 2 # driver to check the codearr2 = [12, 34, 54, 2, 3]print(\"input array:\",arr2) shellSort(arr2)print(\"sorted array\",arr2)", "e": 53480, "s": 52611, "text": null }, { "code": null, "e": 53544, "s": 53480, "text": "input array: [12, 34, 54, 2, 3]\nsorted array [2, 3, 12, 34, 54]" }, { "code": null, "e": 53570, "s": 53544, "text": "Time Complexity: O(n2). " }, { "code": null, "e": 53586, "s": 53570, "text": "simranarora5sos" }, { "code": null, "e": 53601, "s": 53586, "text": "sagartomar9927" }, { "code": null, "e": 53611, "s": 53601, "text": "as5853535" }, { "code": null, "e": 53634, "s": 53611, "text": "Python-Data-Structures" }, { "code": null, "e": 53641, "s": 53634, "text": "Python" }, { "code": null, "e": 53739, "s": 53641, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 53757, "s": 53739, "text": "Python Dictionary" }, { "code": null, "e": 53799, "s": 53757, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 53821, "s": 53799, "text": "Enumerate() in Python" }, { "code": null, "e": 53856, "s": 53821, "text": "Read a file line by line in Python" }, { "code": null, "e": 53882, "s": 53856, "text": "Python String | replace()" }, { "code": null, "e": 53914, "s": 53882, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 53943, "s": 53914, "text": "*args and **kwargs in Python" }, { "code": null, "e": 53970, "s": 53943, "text": "Python Classes and Objects" }, { "code": null, "e": 54000, "s": 53970, "text": "Iterate over a list in Python" } ]
Python | Fetch your gmail emails from a particular user
15 Sep, 2021 If you are ever curious to know how we can fetch Gmail e-mails using Python then this article is for you.As we know Python is a multi-utility language which can be used to do a wide range of tasks. Fetching Gmail emails though is a tedious task but with Python, many things can be done if you are well versed with its usage. Gmail provides IMAP access to clients who want to access Gmail without manually logging in the browser. In setting page, enable this before running script. Implementation: The libraries used in this implementation includes imaplib, email. You have to manually go and make IMAP access enabled by going into your Gmail account settings. After this only you could access your Gmail account without logging in browser. Three functions are defined in the implementation which is used to get email body, search for emails from a particular user and get all emails under a label. For showing results I have sent email to my id from my another Gmail account. Now I will be fetching emails from my Gmail account which is received from my another Gmail account. The process begins from making Gmail connection with the help of imaplib library and proving our Gmail login credentials to it. After logging we are selecting emails under the label: Inbox which is a default labeled section for all users. However, you can create your own labels also. Then we are calling get emails function and provide it the parameter from search function result i.e “from user” In get emails function we are putting all emails in an array named “msgs” Now print to see the msgs array Now we can easily iterate over this array. We are iterating it in the order the emails arrived. Then we are searching for the index from where our content begins. This indexing part will be different for different emails/users and the user can manually change the indexes to print only that part which they require. We have our results printed out. Below is the Python implementation – Python3 # Importing librariesimport imaplib, email user = 'USER_EMAIL_ADDRESS'password = 'USER_PASSWORD'imap_url = 'imap.gmail.com' # Function to get email content part i.e its body partdef get_body(msg): if msg.is_multipart(): return get_body(msg.get_payload(0)) else: return msg.get_payload(None, True) # Function to search for a key value pairdef search(key, value, con): result, data = con.search(None, key, '"{}"'.format(value)) return data # Function to get the list of emails under this labeldef get_emails(result_bytes): msgs = [] # all the email data are pushed inside an array for num in result_bytes[0].split(): typ, data = con.fetch(num, '(RFC822)') msgs.append(data) return msgs # this is done to make SSL connection with GMAILcon = imaplib.IMAP4_SSL(imap_url) # logging the user incon.login(user, password) # calling function to check for email under this labelcon.select('Inbox') # fetching emails from this user "tu**h*****[email protected]"msgs = get_emails(search('FROM', 'MY_ANOTHER_GMAIL_ADDRESS', con)) # Uncomment this to see what actually comes as data# print(msgs) # Finding the required content from our msgs# User can make custom changes in this part to# fetch the required content he / she needs # printing them by the order they are displayed in your gmailfor msg in msgs[::-1]: for sent in msg: if type(sent) is tuple: # encoding set as utf-8 content = str(sent[1], 'utf-8') data = str(content) # Handling errors related to unicodenecode try: indexstart = data.find("ltr") data2 = data[indexstart + 5: len(data)] indexend = data2.find("</div>") # printtng the required content which we need # to extract from our email i.e our body print(data2[0: indexend]) except UnicodeEncodeError as e: pass Output: Akanksha_Rai sweetyty Marketing python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Convert integer to string in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Sep, 2021" }, { "code": null, "e": 483, "s": 54, "text": "If you are ever curious to know how we can fetch Gmail e-mails using Python then this article is for you.As we know Python is a multi-utility language which can be used to do a wide range of tasks. Fetching Gmail emails though is a tedious task but with Python, many things can be done if you are well versed with its usage. Gmail provides IMAP access to clients who want to access Gmail without manually logging in the browser." }, { "code": null, "e": 536, "s": 483, "text": "In setting page, enable this before running script. " }, { "code": null, "e": 796, "s": 536, "text": "Implementation: The libraries used in this implementation includes imaplib, email. You have to manually go and make IMAP access enabled by going into your Gmail account settings. After this only you could access your Gmail account without logging in browser. " }, { "code": null, "e": 954, "s": 796, "text": "Three functions are defined in the implementation which is used to get email body, search for emails from a particular user and get all emails under a label." }, { "code": null, "e": 1133, "s": 954, "text": "For showing results I have sent email to my id from my another Gmail account. Now I will be fetching emails from my Gmail account which is received from my another Gmail account." }, { "code": null, "e": 1261, "s": 1133, "text": "The process begins from making Gmail connection with the help of imaplib library and proving our Gmail login credentials to it." }, { "code": null, "e": 1418, "s": 1261, "text": "After logging we are selecting emails under the label: Inbox which is a default labeled section for all users. However, you can create your own labels also." }, { "code": null, "e": 1531, "s": 1418, "text": "Then we are calling get emails function and provide it the parameter from search function result i.e “from user”" }, { "code": null, "e": 1605, "s": 1531, "text": "In get emails function we are putting all emails in an array named “msgs”" }, { "code": null, "e": 1637, "s": 1605, "text": "Now print to see the msgs array" }, { "code": null, "e": 1953, "s": 1637, "text": "Now we can easily iterate over this array. We are iterating it in the order the emails arrived. Then we are searching for the index from where our content begins. This indexing part will be different for different emails/users and the user can manually change the indexes to print only that part which they require." }, { "code": null, "e": 1986, "s": 1953, "text": "We have our results printed out." }, { "code": null, "e": 2025, "s": 1986, "text": "Below is the Python implementation – " }, { "code": null, "e": 2033, "s": 2025, "text": "Python3" }, { "code": "# Importing librariesimport imaplib, email user = 'USER_EMAIL_ADDRESS'password = 'USER_PASSWORD'imap_url = 'imap.gmail.com' # Function to get email content part i.e its body partdef get_body(msg): if msg.is_multipart(): return get_body(msg.get_payload(0)) else: return msg.get_payload(None, True) # Function to search for a key value pairdef search(key, value, con): result, data = con.search(None, key, '\"{}\"'.format(value)) return data # Function to get the list of emails under this labeldef get_emails(result_bytes): msgs = [] # all the email data are pushed inside an array for num in result_bytes[0].split(): typ, data = con.fetch(num, '(RFC822)') msgs.append(data) return msgs # this is done to make SSL connection with GMAILcon = imaplib.IMAP4_SSL(imap_url) # logging the user incon.login(user, password) # calling function to check for email under this labelcon.select('Inbox') # fetching emails from this user \"tu**h*****[email protected]\"msgs = get_emails(search('FROM', 'MY_ANOTHER_GMAIL_ADDRESS', con)) # Uncomment this to see what actually comes as data# print(msgs) # Finding the required content from our msgs# User can make custom changes in this part to# fetch the required content he / she needs # printing them by the order they are displayed in your gmailfor msg in msgs[::-1]: for sent in msg: if type(sent) is tuple: # encoding set as utf-8 content = str(sent[1], 'utf-8') data = str(content) # Handling errors related to unicodenecode try: indexstart = data.find(\"ltr\") data2 = data[indexstart + 5: len(data)] indexend = data2.find(\"</div>\") # printtng the required content which we need # to extract from our email i.e our body print(data2[0: indexend]) except UnicodeEncodeError as e: pass", "e": 3980, "s": 2033, "text": null }, { "code": null, "e": 3989, "s": 3980, "text": "Output: " }, { "code": null, "e": 4004, "s": 3991, "text": "Akanksha_Rai" }, { "code": null, "e": 4013, "s": 4004, "text": "sweetyty" }, { "code": null, "e": 4023, "s": 4013, "text": "Marketing" }, { "code": null, "e": 4038, "s": 4023, "text": "python-utility" }, { "code": null, "e": 4045, "s": 4038, "text": "Python" }, { "code": null, "e": 4143, "s": 4045, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4161, "s": 4143, "text": "Python Dictionary" }, { "code": null, "e": 4203, "s": 4161, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4225, "s": 4203, "text": "Enumerate() in Python" }, { "code": null, "e": 4251, "s": 4225, "text": "Python String | replace()" }, { "code": null, "e": 4283, "s": 4251, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4312, "s": 4283, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4339, "s": 4312, "text": "Python Classes and Objects" }, { "code": null, "e": 4360, "s": 4339, "text": "Python OOPs Concepts" }, { "code": null, "e": 4383, "s": 4360, "text": "Introduction To PYTHON" } ]
Flask – (Creating first simple application)
20 Jun, 2022 There are many modules or frameworks which allow building your webpage using python like a bottle, Django, Flask, etc. But the real popular ones are Flask and Django. Django is easy to use as compared to Flask but Flask provides you with the versatility to program with.To understand what Flask is you have to understand a few general terms. WSGI Web Server Gateway Interface (WSGI) has been adopted as a standard for Python web application development. WSGI is a specification for a universal interface between the web server and the web applications. Werkzeug It is a WSGI toolkit, which implements requests, response objects, and other utility functions. This enables building a web framework on top of it. The Flask framework uses Werkzeug as one of its bases.jinja2 jinja2 is a popular templating engine for Python. A web templating system combines a template with a certain data source to render dynamic web pages. WSGI Web Server Gateway Interface (WSGI) has been adopted as a standard for Python web application development. WSGI is a specification for a universal interface between the web server and the web applications. Werkzeug It is a WSGI toolkit, which implements requests, response objects, and other utility functions. This enables building a web framework on top of it. The Flask framework uses Werkzeug as one of its bases. jinja2 jinja2 is a popular templating engine for Python. A web templating system combines a template with a certain data source to render dynamic web pages. Flask is a web application framework written in Python. Flask is based on the Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects. Installation: We will require two packages to set up your environment. virtualenv for a user to create multiple Python environments side-by-side. Thereby, it can avoid compatibility issues between the different versions of the libraries and the next will be Flask itself. virtualenv pip install virtualenv Create Python virtual environment virtualenv venv Activate virtual environment windows > venv\Scripts\activate linux > source ./venv/bin/activate Flask pip install Flask After completing the installation of the package, let’s get our hands on the code. Python3 # Importing flask module in the project is mandatory# An object of Flask class is our WSGI application.from flask import Flask # Flask constructor takes the name of# current module (__name__) as argument.app = Flask(__name__) # The route() function of the Flask class is a decorator,# which tells the application which URL should call# the associated [email protected]('/')# ‘/’ URL is bound with hello_world() function.def hello_world(): return 'Hello World' # main driver functionif __name__ == '__main__': # run() method of Flask class runs the application # on the local development server. app.run() Save it in a file and then run the script we will be getting an output like this. Then go to the URL given there you will see your first webpage displaying hello world there on your local server.Digging further into the context, the route() decorator in Flask is used to bind a URL to a function. Now to extend this functionality our small web app is also equipped with another method add_url_rule() which is a function of an application object that is also available to bind a URL with a function as in the above example, route() is used. Example: def gfg(): return ‘geeksforgeeks’ app.add_url_rule(‘/’, ‘g2g’, gfg) Output: geeksforgeeks You can also add variables in your web app, well you might be thinking about how it’ll help you, it’ll help you to build a URL dynamically. So let’s figure it out with an example. Python3 from flask import Flaskapp = Flask(__name__) @app.route('/hello/<name>')def hello_name(name): return 'Hello %s!' % name if __name__ == '__main__': app.run() And go to the URL http://127.0.0.1:5000/hello/geeksforgeeks it’ll give you the following output. We can also use HTTP methods in Flask let’s see how to do thatThe HTTP protocol is the foundation of data communication on the world wide web. Different methods of data retrieval from specified URL are defined in this protocol. The methods are described down below. GET : Sends data in simple or unencrypted form to the server.HEAD : Sends data in simple or unencrypted form to the server without body. HEAD : Sends form data to the server. Data is not cached.PUT : Replaces target resource with the updated content.DELETE : Deletes target resource provided as URL. By default, the Flask route responds to the GET requests. However, this preference can be altered by providing methods argument to route() decorator. In order to demonstrate the use of the POST method in URL routing, first, let us create an HTML form and use the POST method to send form data to a URL. Now let’s create an HTML login page. Below is the source code of the file: HTML <html> <body> <form action = "http://localhost:5000/login" method = "post"> <p>Enter Name:</p> <p><input type = "text" name = "nm" /></p> <p><input type = "submit" value = "submit" /></p> </form> </body></html> Now save this file HTML and try this python script to create the server. Python3 from flask import Flask, redirect, url_for, requestapp = Flask(__name__) @app.route('/success/<name>')def success(name): return 'welcome %s' % name @app.route('/login', methods=['POST', 'GET'])def login(): if request.method == 'POST': user = request.form['nm'] return redirect(url_for('success', name=user)) else: user = request.args.get('nm') return redirect(url_for('success', name=user)) if __name__ == '__main__': app.run(debug=True) After the development server starts running, open login.html in the browser, enter your name in the text field and click submit button. The output would be the following. The result will be something like this And there’s much more to Flask than this. If you are interested in this web framework of Python you can dig into the links provided down below for further information. This article is contributed by Subhajit Saha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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. eshaangupta101 spoojary614 Python Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jun, 2022" }, { "code": null, "e": 395, "s": 52, "text": "There are many modules or frameworks which allow building your webpage using python like a bottle, Django, Flask, etc. But the real popular ones are Flask and Django. Django is easy to use as compared to Flask but Flask provides you with the versatility to program with.To understand what Flask is you have to understand a few general terms. " }, { "code": null, "e": 975, "s": 395, "text": "WSGI Web Server Gateway Interface (WSGI) has been adopted as a standard for Python web application development. WSGI is a specification for a universal interface between the web server and the web applications. Werkzeug It is a WSGI toolkit, which implements requests, response objects, and other utility functions. This enables building a web framework on top of it. The Flask framework uses Werkzeug as one of its bases.jinja2 jinja2 is a popular templating engine for Python. A web templating system combines a template with a certain data source to render dynamic web pages. " }, { "code": null, "e": 1187, "s": 975, "text": "WSGI Web Server Gateway Interface (WSGI) has been adopted as a standard for Python web application development. WSGI is a specification for a universal interface between the web server and the web applications. " }, { "code": null, "e": 1399, "s": 1187, "text": "Werkzeug It is a WSGI toolkit, which implements requests, response objects, and other utility functions. This enables building a web framework on top of it. The Flask framework uses Werkzeug as one of its bases." }, { "code": null, "e": 1557, "s": 1399, "text": "jinja2 jinja2 is a popular templating engine for Python. A web templating system combines a template with a certain data source to render dynamic web pages. " }, { "code": null, "e": 1710, "s": 1557, "text": "Flask is a web application framework written in Python. Flask is based on the Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects." }, { "code": null, "e": 1724, "s": 1710, "text": "Installation:" }, { "code": null, "e": 1983, "s": 1724, "text": "We will require two packages to set up your environment. virtualenv for a user to create multiple Python environments side-by-side. Thereby, it can avoid compatibility issues between the different versions of the libraries and the next will be Flask itself. " }, { "code": null, "e": 1995, "s": 1983, "text": "virtualenv " }, { "code": null, "e": 2018, "s": 1995, "text": "pip install virtualenv" }, { "code": null, "e": 2052, "s": 2018, "text": "Create Python virtual environment" }, { "code": null, "e": 2068, "s": 2052, "text": "virtualenv venv" }, { "code": null, "e": 2097, "s": 2068, "text": "Activate virtual environment" }, { "code": null, "e": 2164, "s": 2097, "text": "windows > venv\\Scripts\\activate\nlinux > source ./venv/bin/activate" }, { "code": null, "e": 2171, "s": 2164, "text": "Flask " }, { "code": null, "e": 2189, "s": 2171, "text": "pip install Flask" }, { "code": null, "e": 2272, "s": 2189, "text": "After completing the installation of the package, let’s get our hands on the code." }, { "code": null, "e": 2280, "s": 2272, "text": "Python3" }, { "code": "# Importing flask module in the project is mandatory# An object of Flask class is our WSGI application.from flask import Flask # Flask constructor takes the name of# current module (__name__) as argument.app = Flask(__name__) # The route() function of the Flask class is a decorator,# which tells the application which URL should call# the associated [email protected]('/')# ‘/’ URL is bound with hello_world() function.def hello_world(): return 'Hello World' # main driver functionif __name__ == '__main__': # run() method of Flask class runs the application # on the local development server. app.run()", "e": 2900, "s": 2280, "text": null }, { "code": null, "e": 2982, "s": 2900, "text": "Save it in a file and then run the script we will be getting an output like this." }, { "code": null, "e": 3441, "s": 2982, "text": "Then go to the URL given there you will see your first webpage displaying hello world there on your local server.Digging further into the context, the route() decorator in Flask is used to bind a URL to a function. Now to extend this functionality our small web app is also equipped with another method add_url_rule() which is a function of an application object that is also available to bind a URL with a function as in the above example, route() is used. " }, { "code": null, "e": 3451, "s": 3441, "text": "Example: " }, { "code": null, "e": 3522, "s": 3451, "text": "def gfg():\n return ‘geeksforgeeks’\napp.add_url_rule(‘/’, ‘g2g’, gfg)" }, { "code": null, "e": 3531, "s": 3522, "text": "Output: " }, { "code": null, "e": 3545, "s": 3531, "text": "geeksforgeeks" }, { "code": null, "e": 3725, "s": 3545, "text": "You can also add variables in your web app, well you might be thinking about how it’ll help you, it’ll help you to build a URL dynamically. So let’s figure it out with an example." }, { "code": null, "e": 3733, "s": 3725, "text": "Python3" }, { "code": "from flask import Flaskapp = Flask(__name__) @app.route('/hello/<name>')def hello_name(name): return 'Hello %s!' % name if __name__ == '__main__': app.run()", "e": 3894, "s": 3733, "text": null }, { "code": null, "e": 3991, "s": 3894, "text": "And go to the URL http://127.0.0.1:5000/hello/geeksforgeeks it’ll give you the following output." }, { "code": null, "e": 4257, "s": 3991, "text": "We can also use HTTP methods in Flask let’s see how to do thatThe HTTP protocol is the foundation of data communication on the world wide web. Different methods of data retrieval from specified URL are defined in this protocol. The methods are described down below." }, { "code": null, "e": 4557, "s": 4257, "text": "GET : Sends data in simple or unencrypted form to the server.HEAD : Sends data in simple or unencrypted form to the server without body. HEAD : Sends form data to the server. Data is not cached.PUT : Replaces target resource with the updated content.DELETE : Deletes target resource provided as URL." }, { "code": null, "e": 4897, "s": 4557, "text": "By default, the Flask route responds to the GET requests. However, this preference can be altered by providing methods argument to route() decorator. In order to demonstrate the use of the POST method in URL routing, first, let us create an HTML form and use the POST method to send form data to a URL. Now let’s create an HTML login page." }, { "code": null, "e": 4936, "s": 4897, "text": "Below is the source code of the file: " }, { "code": null, "e": 4941, "s": 4936, "text": "HTML" }, { "code": "<html> <body> <form action = \"http://localhost:5000/login\" method = \"post\"> <p>Enter Name:</p> <p><input type = \"text\" name = \"nm\" /></p> <p><input type = \"submit\" value = \"submit\" /></p> </form> </body></html>", "e": 5212, "s": 4941, "text": null }, { "code": null, "e": 5285, "s": 5212, "text": "Now save this file HTML and try this python script to create the server." }, { "code": null, "e": 5293, "s": 5285, "text": "Python3" }, { "code": "from flask import Flask, redirect, url_for, requestapp = Flask(__name__) @app.route('/success/<name>')def success(name): return 'welcome %s' % name @app.route('/login', methods=['POST', 'GET'])def login(): if request.method == 'POST': user = request.form['nm'] return redirect(url_for('success', name=user)) else: user = request.args.get('nm') return redirect(url_for('success', name=user)) if __name__ == '__main__': app.run(debug=True)", "e": 5774, "s": 5293, "text": null }, { "code": null, "e": 5945, "s": 5774, "text": "After the development server starts running, open login.html in the browser, enter your name in the text field and click submit button. The output would be the following." }, { "code": null, "e": 5984, "s": 5945, "text": "The result will be something like this" }, { "code": null, "e": 6152, "s": 5984, "text": "And there’s much more to Flask than this. If you are interested in this web framework of Python you can dig into the links provided down below for further information." }, { "code": null, "e": 6576, "s": 6152, "text": "This article is contributed by Subhajit Saha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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": 6591, "s": 6576, "text": "eshaangupta101" }, { "code": null, "e": 6603, "s": 6591, "text": "spoojary614" }, { "code": null, "e": 6610, "s": 6603, "text": "Python" }, { "code": null, "e": 6627, "s": 6610, "text": "Web Technologies" } ]
How to Install Flex on Windows?
21 Dec, 2021 Flex stands for fast lexical analyzer generator, it is a computer application that is used to generate lexical analyzers for the programs written in lex language. The main work of the lexical analyzer is to convert the program into a sequence of tokens. It is developed by Vern Paxson. It is free software written in C language and can be run on different platforms like Linux, Unix, windows, mac, etc. Its initial release was in 1987 and its first stable release was in 2017. Flex has a limitation to generating code for C and C++ only. YACC stands for yet another compiler, it is a parser generator that is used with lex to generate parsers of lex files. It uses LALR(1) parsing technique, LALR means to look ahead left to right and 1 shows that rightmost derivation is used with 1 lookahead token. There are 3 main components of a lex file : Definition Section: The first section is the definition section, this section is used to include libraries and header files for the program. This section is able to accept code written in C. Example of Definition Section: %{ #include <stdio.h> #include<conio.h> %} Rule Section: The second section is the rule section, the main work of this section is to match patterns by using regular expressions written in this section. Example of Rule Section: %% [a-zA-Z] this pattern will search for alphabets in lower and upper case %% Code Section: This is the last section that is used to write all the logic, functions, and statements for the program. This code is written in C language. The program will have all the functionalities of a C program. Example of Code Section: int main() { yylex(); return 0; } Follow the below steps to install Flex on Windows: Step 1: Visit this URL using any web browser. Step 2: On this page, all the features and minimum requirement of the system to install flex is given. Here the download link of the flex program for Windows XP, 7, 8, etc is given. Click on the download link, downloading of the executable file will start shortly. It is a small 30.19 MB file that will hardly take a minute. Step 3: Now check for the executable file in downloads in your system and run it. Step 4: It will prompt confirmation to make changes to your system. Click on Yes. Step 5: Setup screen will appear, click on Next. Step 6: The next screen will be of License Agreement, click on I Agree. Step 7: The next screen will be of installing location so choose the drive which will have sufficient memory space for installation. It needed only a memory space of 176.7 MB. Step 8: Next screen will be of choosing the Start menu folder so don’t do anything just click on the Next Button. Step 9: After this installation process will start and will hardly take a minute to complete the installation. Step 10: Click on Finish after the installation process is complete. Keep the tick mark on the checkbox if you want to run Flex now if not then uncheck it. Step 11: Flex Windows is successfully installed on the system and an icon is created on the desktop Step 12: Run the software and see the interface. Congratulations!! At this point, you have successfully installed Flex on your windows system. sagartomar9927 how-to-install Compiler Design How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Dec, 2021" }, { "code": null, "e": 567, "s": 28, "text": "Flex stands for fast lexical analyzer generator, it is a computer application that is used to generate lexical analyzers for the programs written in lex language. The main work of the lexical analyzer is to convert the program into a sequence of tokens. It is developed by Vern Paxson. It is free software written in C language and can be run on different platforms like Linux, Unix, windows, mac, etc. Its initial release was in 1987 and its first stable release was in 2017. Flex has a limitation to generating code for C and C++ only. " }, { "code": null, "e": 830, "s": 567, "text": "YACC stands for yet another compiler, it is a parser generator that is used with lex to generate parsers of lex files. It uses LALR(1) parsing technique, LALR means to look ahead left to right and 1 shows that rightmost derivation is used with 1 lookahead token." }, { "code": null, "e": 874, "s": 830, "text": "There are 3 main components of a lex file :" }, { "code": null, "e": 1065, "s": 874, "text": "Definition Section: The first section is the definition section, this section is used to include libraries and header files for the program. This section is able to accept code written in C." }, { "code": null, "e": 1097, "s": 1065, "text": "Example of Definition Section: " }, { "code": null, "e": 1140, "s": 1097, "text": "%{\n#include <stdio.h>\n#include<conio.h>\n%}" }, { "code": null, "e": 1299, "s": 1140, "text": "Rule Section: The second section is the rule section, the main work of this section is to match patterns by using regular expressions written in this section." }, { "code": null, "e": 1324, "s": 1299, "text": "Example of Rule Section:" }, { "code": null, "e": 1405, "s": 1324, "text": "%%\n[a-zA-Z] this pattern will search for alphabets in lower and upper case\n%%" }, { "code": null, "e": 1622, "s": 1405, "text": "Code Section: This is the last section that is used to write all the logic, functions, and statements for the program. This code is written in C language. The program will have all the functionalities of a C program." }, { "code": null, "e": 1647, "s": 1622, "text": "Example of Code Section:" }, { "code": null, "e": 1681, "s": 1647, "text": "int main()\n{\nyylex();\nreturn 0;\n}" }, { "code": null, "e": 1732, "s": 1681, "text": "Follow the below steps to install Flex on Windows:" }, { "code": null, "e": 1778, "s": 1732, "text": "Step 1: Visit this URL using any web browser." }, { "code": null, "e": 2103, "s": 1778, "text": "Step 2: On this page, all the features and minimum requirement of the system to install flex is given. Here the download link of the flex program for Windows XP, 7, 8, etc is given. Click on the download link, downloading of the executable file will start shortly. It is a small 30.19 MB file that will hardly take a minute." }, { "code": null, "e": 2185, "s": 2103, "text": "Step 3: Now check for the executable file in downloads in your system and run it." }, { "code": null, "e": 2267, "s": 2185, "text": "Step 4: It will prompt confirmation to make changes to your system. Click on Yes." }, { "code": null, "e": 2316, "s": 2267, "text": "Step 5: Setup screen will appear, click on Next." }, { "code": null, "e": 2388, "s": 2316, "text": "Step 6: The next screen will be of License Agreement, click on I Agree." }, { "code": null, "e": 2564, "s": 2388, "text": "Step 7: The next screen will be of installing location so choose the drive which will have sufficient memory space for installation. It needed only a memory space of 176.7 MB." }, { "code": null, "e": 2678, "s": 2564, "text": "Step 8: Next screen will be of choosing the Start menu folder so don’t do anything just click on the Next Button." }, { "code": null, "e": 2789, "s": 2678, "text": "Step 9: After this installation process will start and will hardly take a minute to complete the installation." }, { "code": null, "e": 2945, "s": 2789, "text": "Step 10: Click on Finish after the installation process is complete. Keep the tick mark on the checkbox if you want to run Flex now if not then uncheck it." }, { "code": null, "e": 3045, "s": 2945, "text": "Step 11: Flex Windows is successfully installed on the system and an icon is created on the desktop" }, { "code": null, "e": 3094, "s": 3045, "text": "Step 12: Run the software and see the interface." }, { "code": null, "e": 3188, "s": 3094, "text": "Congratulations!! At this point, you have successfully installed Flex on your windows system." }, { "code": null, "e": 3203, "s": 3188, "text": "sagartomar9927" }, { "code": null, "e": 3218, "s": 3203, "text": "how-to-install" }, { "code": null, "e": 3234, "s": 3218, "text": "Compiler Design" }, { "code": null, "e": 3241, "s": 3234, "text": "How To" }, { "code": null, "e": 3260, "s": 3241, "text": "Installation Guide" } ]
Split string into three palindromic substrings with earliest possible cuts
24 Nov, 2021 Given string str, the task is to check if it is possible to split the given string S into three palindromic substrings or not. If multiple answers are possible, then print the one where the cuts are made the least indices. If no such possible partition exists, then print “-1”. Examples: Input: str = “aabbcdc”Output: aa bb cdcExplanation:Only one possible partition exists {“aa”, “bb”, “cdc”}. Input: str = “ababbcb”Output: a bab bcb Explanation: Possible splits are {“aba”, “b”, “bcb”} and {“a”, “bab”, “bcb”}. Since, {“a”, “bab”, “bcb”} has splits at earlier indices, it is the required answer. Approach: Follow the steps below to solve the problem: Generate all possible substrings of the string and check whether the given substring is palindromic or not.If any substring is present then store the last index of a substring in a vector startPal, where startPal will store the first palindrome starting from 0 indexes and ending at stored value.Similar to the first step, generate all the substring from the last index of the given string str and check whether the given substring is palindrome or not. If any substring is present as a substring then store the last index of a substring in the vector lastPal, where lastPal will store the third palindrome starting from stored value and ending at (N – 1)th index of the given string str.Reverse the vector lastPal to get the earliest cut.Now, iterate two nested loop, the outer loop picks the first palindrome ending index from the startPal and the inner loop picks the third palindrome starting index from the lastPal. If the value of startPal is lesser than the lastPal value then store it in the middlePal vector in form of pairs.Now traverse over the vector middlePal and check if the substring between the ending index of the first palindrome and starting index of the third palindrome is palindrome or not. If found to be true then the first palindrome = s.substr(0, middlePal[i].first), third palindrome = s.substr(middlePal[i].second, N – middlePal[i].second) and rest string will be third string.If all the three palindromic strings are present then print that string Otherwise print “-1”. Generate all possible substrings of the string and check whether the given substring is palindromic or not. If any substring is present then store the last index of a substring in a vector startPal, where startPal will store the first palindrome starting from 0 indexes and ending at stored value. Similar to the first step, generate all the substring from the last index of the given string str and check whether the given substring is palindrome or not. If any substring is present as a substring then store the last index of a substring in the vector lastPal, where lastPal will store the third palindrome starting from stored value and ending at (N – 1)th index of the given string str. Reverse the vector lastPal to get the earliest cut. Now, iterate two nested loop, the outer loop picks the first palindrome ending index from the startPal and the inner loop picks the third palindrome starting index from the lastPal. If the value of startPal is lesser than the lastPal value then store it in the middlePal vector in form of pairs. Now traverse over the vector middlePal and check if the substring between the ending index of the first palindrome and starting index of the third palindrome is palindrome or not. If found to be true then the first palindrome = s.substr(0, middlePal[i].first), third palindrome = s.substr(middlePal[i].second, N – middlePal[i].second) and rest string will be third string. If all the three palindromic strings are present then print that string Otherwise print “-1”. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to check if a string// is palindrome or notbool isPalindrome(string x){ // Copy the string x to y string y = x; // Reverse the string y reverse(y.begin(), y.end()); if (x == y) { // If string x equals y return true; } return false;} // Function to find three palindromes// from the given string with earliest// possible cutsvoid Palindromes(string S, int N){ // Stores index of palindrome // starting from left & right vector<int> startPal, lastPal; string start; // Store the indices for possible // palindromes from left for (int i = 0; i < S.length() - 2; i++) { // Push the current character start.push_back(S[i]); // Check for palindrome if (isPalindrome(start)) { // Insert the current index startPal.push_back(i); } } string last; // Stores the indexes for possible // palindromes from right for (int j = S.length() - 1; j >= 2; j--) { // Push the current character last.push_back(S[j]); // Check palindromic if (isPalindrome(last)) { // Insert the current index lastPal.push_back(j); } } // Sort the indexes for palindromes // from right in ascending order reverse(lastPal.begin(), lastPal.end()); vector<pair<int, int> > middlePal; for (int i = 0; i < startPal.size(); i++) { for (int j = 0; j < lastPal.size(); j++) { // If the value of startPal // < lastPal value then // store it in middlePal if (startPal[i] < lastPal[j]) { // Insert the current pair middlePal.push_back( { startPal[i], lastPal[j] }); } } } string res1, res2, res3; int flag = 0; // Traverse over the middlePal for (int i = 0; i < middlePal.size(); i++) { int x = middlePal[i].first; int y = middlePal[i].second; string middle; for (int k = x + 1; k < y; k++) { middle.push_back(S[k]); } // Check if the middle part // is palindrome if (isPalindrome(middle)) { flag = 1; res1 = S.substr(0, x + 1); res2 = middle; res3 = S.substr(y, N - y); break; } } // Print the three palindromic if (flag == 1) { cout << res1 << " " << res2 << " " << res3; } // Otherwise else cout << "-1";} // Driver Codeint main(){ // Given string str string str = "ababbcb"; int N = str.length(); // Function Call Palindromes(str, N); return 0;} // Java program for the// above approachimport java.util.*;class GFG{ static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} static String reverse(String input){ char[] a = input.toCharArray(); int l, r = a.length - 1; for (l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a);} // Function to check if a String// is palindrome or notstatic boolean isPalindrome(String x){ // Copy the String x to y String y = x; // Reverse the String y y = reverse(y); if (x.equals(y)) { // If String x equals y return true; } return false;} // Function to find three palindromes// from the given String with earliest// possible cutsstatic void Palindromes(String S, int N){ // Stores index of palindrome // starting from left & right Vector<Integer> startPal = new Vector<>(); Vector<Integer> lastPal = new Vector<>(); String start = ""; // Store the indices for possible // palindromes from left for (int i = 0; i < S.length() - 2; i++) { // Push the current character start += S.charAt(i); // Check for palindrome if (isPalindrome(start)) { // Insert the current index startPal.add(i); } } String last = ""; // Stores the indexes for possible // palindromes from right for (int j = S.length() - 1; j >= 2; j--) { // Push the current character last += S.charAt(j); // Check palindromic if (isPalindrome(last)) { // Insert the current index lastPal.add(j); } } // Sort the indexes for palindromes // from right in ascending order Collections.reverse(lastPal); Vector<pair> middlePal = new Vector<>(); for (int i = 0; i < startPal.size(); i++) { for (int j = 0; j < lastPal.size(); j++) { // If the value of startPal // < lastPal value then // store it in middlePal if (startPal.get(i) < lastPal.get(j)) { // Insert the current pair middlePal.add(new pair(startPal.get(i), lastPal.get(j))); } } } String res1 = "", res2 = "", res3 = ""; int flag = 0; // Traverse over the middlePal for (int i = 0; i < middlePal.size(); i++) { int x = middlePal.get(i).first; int y = middlePal.get(i).second; String middle = ""; for (int k = x + 1; k < y; k++) { middle += S.charAt(k); } // Check if the middle part // is palindrome if (isPalindrome(middle)) { flag = 1; res1 = S.substring(0, x + 1); res2 = middle; res3 = S.substring(y, N); break; } } // Print the three palindromic if (flag == 1) { System.out.print(res1 + " " + res2 + " " + res3); } // Otherwise else System.out.print("-1");} // Driver Codepublic static void main(String[] args){ // Given String str String str = "ababbcb"; int N = str.length(); // Function Call Palindromes(str, N);}} // This code is contributed by shikhasingrajput # Python3 program for the above approach # Function to check if a string# is palindrome or notdef isPalindrome(x): # Copy the x to y y = x # Reverse the y y = y[::-1] if (x == y): # If x equals y return True return False # Function to find three palindromes# from the given with earliest# possible cutsdef Palindromes(S, N): # Stores index of palindrome # starting from left & right startPal, lastPal = [], [] start = [] # Store the indices for possible # palindromes from left for i in range(len(S) - 2): # Push the current character start.append(S[i]) # Check for palindrome if (isPalindrome(start)): # Insert the current index startPal.append(i) last = [] # Stores the indexes for possible # palindromes from right for j in range(len(S) - 1, 1, -1): # Push the current character last.append(S[j]) # Check palindromic if (isPalindrome(last)): # Insert the current index lastPal.append(j) # Sort the indexes for palindromes # from right in ascending order lastPal = lastPal[::-1] middlePal = [] for i in range(len(startPal)): for j in range(len(lastPal)): # If the value of startPal # < lastPal value then # store it in middlePal if (startPal[i] < lastPal[j]): # Insert the current pair middlePal.append([startPal[i], lastPal[j]]) res1, res2, res3 = "", "", "" flag = 0 # Traverse over the middlePal for i in range(len(middlePal)): x = middlePal[i][0] y = middlePal[i][1] #print(x,y) middle = "" for k in range(x + 1, y): middle += (S[k]) # Check if the middle part # is palindrome if (isPalindrome(middle)): flag = 1 res1 = S[0 : x + 1] res2 = middle res3 = S[y : N] #print(S,x,y,N) break # Print the three palindromic if (flag == 1): print(res1, res2, res3) # Otherwise else: print("-1") # Driver Codeif __name__ == '__main__': # Given strr strr = "ababbcb" N = len(strr) # Function call Palindromes(strr, N) # This code is contributed by mohit kumar 29 // C# program for the// above approachusing System;using System.Collections.Generic; class GFG{ public class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} static String reverse(String input){ char[] a = input.ToCharArray(); int l, r = a.Length - 1; for(l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.Join("",a);} // Function to check if a String// is palindrome or notstatic bool isPalindrome(String x){ // Copy the String x to y String y = x; // Reverse the String y y = reverse(y); if (x.Equals(y)) { // If String x equals y return true; } return false;} // Function to find three palindromes// from the given String with earliest// possible cutsstatic void Palindromes(String S, int N){ // Stores index of palindrome // starting from left & right List<int> startPal = new List<int>(); List<int> lastPal = new List<int>(); String start = ""; // Store the indices for possible // palindromes from left for(int i = 0; i < S.Length - 2; i++) { // Push the current character start += S[i]; // Check for palindrome if (isPalindrome(start)) { // Insert the current index startPal.Add(i); } } String last = ""; // Stores the indexes for possible // palindromes from right for(int j = S.Length - 1; j >= 2; j--) { // Push the current character last += S[j]; // Check palindromic if (isPalindrome(last)) { // Insert the current index lastPal.Add(j); } } // Sort the indexes for palindromes // from right in ascending order lastPal.Reverse(); List<pair> middlePal = new List<pair>(); for(int i = 0; i < startPal.Count; i++) { for(int j = 0; j < lastPal.Count; j++) { // If the value of startPal // < lastPal value then // store it in middlePal if (startPal[i] < lastPal[j]) { // Insert the current pair middlePal.Add(new pair(startPal[i], lastPal[j])); } } } String res1 = "", res2 = "", res3 = ""; int flag = 0; // Traverse over the middlePal for(int i = 0; i < middlePal.Count; i++) { int x = middlePal[i].first; int y = middlePal[i].second; String middle = ""; for(int k = x + 1; k < y; k++) { middle += S[k]; } // Check if the middle part // is palindrome if (isPalindrome(middle)) { flag = 1; res1 = S.Substring(0, x + 1); res2 = middle; res3 = S.Substring(y); break; } } // Print the three palindromic if (flag == 1) { Console.Write(res1 + " " + res2 + " " + res3); } // Otherwise else Console.Write("-1");} // Driver Codepublic static void Main(String[] args){ // Given String str String str = "ababbcb"; int N = str.Length; // Function Call Palindromes(str, N);}} // This code is contributed by Amit Katiyar <script> // Function to check if a String // is palindrome or not function isPalindrome(x) { // Copy the String x to y var y = x; // Reverse the String y y = y.split("").reverse().join(""); if (x === y) { // If String x equals y return true; } return false; } // Function to find three palindromes // from the given String with earliest // possible cuts function Palindromes(S, N) { // Stores index of palindrome // starting from left & right var startPal = []; var lastPal = []; var start = ""; // Store the indices for possible // palindromes from left for (var i = 0; i < S.length - 2; i++) { // Push the current character start += S[i]; // Check for palindrome if (isPalindrome(start)) { // Insert the current index startPal.push(i); } } var last = ""; // Stores the indexes for possible // palindromes from right for (var j = S.length - 1; j >= 2; j--) { // Push the current character last += S[j]; // Check palindromic if (isPalindrome(last)) { // Insert the current index lastPal.push(j); } } // Sort the indexes for palindromes // from right in ascending order lastPal.sort(); var middlePal = []; for (var i = 0; i < startPal.length; i++) { for (var j = 0; j < lastPal.length; j++) { // If the value of startPal // < lastPal value then // store it in middlePal if (startPal[i] < lastPal[j]) { // Insert the current pair middlePal.push([startPal[i], lastPal[j]]); } } } var res1 = "", res2 = "", res3 = ""; var flag = 0; // Traverse over the middlePal for (var i = 0; i < middlePal.length; i++) { var x = middlePal[i][0]; var y = middlePal[i][1]; var middle = ""; for (var k = x + 1; k < y; k++) { middle += S[k]; } // Check if the middle part // is palindrome if (isPalindrome(middle)) { flag = 1; res1 = S.substring(0, x + 1); res2 = middle; res3 = S.substring(y, N); break; } } // Print the three palindromic if (flag === 1) { document.write(res1 + " " + res2 + " " + res3); } // Otherwise else document.write("-1"); } // Driver Code // Given String str var str = "ababbcb"; var N = str.length; // Function Call Palindromes(str, N);</script> a bab bcb Time Complexity: O(N2)Auxiliary Space: O(N) mohit kumar 29 shikhasingrajput amit143katiyar akshaysingh98088 rdtank rs1686740 palindrome Reverse substring Searching Strings Searching Strings palindrome Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Search an element in a sorted and rotated array Search, insert and delete in an unsorted array Median of two sorted arrays of different sizes Program to find largest element in an array k largest(or smallest) elements in an array Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Different Methods to Reverse a String in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Nov, 2021" }, { "code": null, "e": 332, "s": 54, "text": "Given string str, the task is to check if it is possible to split the given string S into three palindromic substrings or not. If multiple answers are possible, then print the one where the cuts are made the least indices. If no such possible partition exists, then print “-1”." }, { "code": null, "e": 342, "s": 332, "text": "Examples:" }, { "code": null, "e": 449, "s": 342, "text": "Input: str = “aabbcdc”Output: aa bb cdcExplanation:Only one possible partition exists {“aa”, “bb”, “cdc”}." }, { "code": null, "e": 652, "s": 449, "text": "Input: str = “ababbcb”Output: a bab bcb Explanation: Possible splits are {“aba”, “b”, “bcb”} and {“a”, “bab”, “bcb”}. Since, {“a”, “bab”, “bcb”} has splits at earlier indices, it is the required answer." }, { "code": null, "e": 707, "s": 652, "text": "Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 2207, "s": 707, "text": "Generate all possible substrings of the string and check whether the given substring is palindromic or not.If any substring is present then store the last index of a substring in a vector startPal, where startPal will store the first palindrome starting from 0 indexes and ending at stored value.Similar to the first step, generate all the substring from the last index of the given string str and check whether the given substring is palindrome or not. If any substring is present as a substring then store the last index of a substring in the vector lastPal, where lastPal will store the third palindrome starting from stored value and ending at (N – 1)th index of the given string str.Reverse the vector lastPal to get the earliest cut.Now, iterate two nested loop, the outer loop picks the first palindrome ending index from the startPal and the inner loop picks the third palindrome starting index from the lastPal. If the value of startPal is lesser than the lastPal value then store it in the middlePal vector in form of pairs.Now traverse over the vector middlePal and check if the substring between the ending index of the first palindrome and starting index of the third palindrome is palindrome or not. If found to be true then the first palindrome = s.substr(0, middlePal[i].first), third palindrome = s.substr(middlePal[i].second, N – middlePal[i].second) and rest string will be third string.If all the three palindromic strings are present then print that string Otherwise print “-1”." }, { "code": null, "e": 2315, "s": 2207, "text": "Generate all possible substrings of the string and check whether the given substring is palindromic or not." }, { "code": null, "e": 2505, "s": 2315, "text": "If any substring is present then store the last index of a substring in a vector startPal, where startPal will store the first palindrome starting from 0 indexes and ending at stored value." }, { "code": null, "e": 2898, "s": 2505, "text": "Similar to the first step, generate all the substring from the last index of the given string str and check whether the given substring is palindrome or not. If any substring is present as a substring then store the last index of a substring in the vector lastPal, where lastPal will store the third palindrome starting from stored value and ending at (N – 1)th index of the given string str." }, { "code": null, "e": 2950, "s": 2898, "text": "Reverse the vector lastPal to get the earliest cut." }, { "code": null, "e": 3246, "s": 2950, "text": "Now, iterate two nested loop, the outer loop picks the first palindrome ending index from the startPal and the inner loop picks the third palindrome starting index from the lastPal. If the value of startPal is lesser than the lastPal value then store it in the middlePal vector in form of pairs." }, { "code": null, "e": 3619, "s": 3246, "text": "Now traverse over the vector middlePal and check if the substring between the ending index of the first palindrome and starting index of the third palindrome is palindrome or not. If found to be true then the first palindrome = s.substr(0, middlePal[i].first), third palindrome = s.substr(middlePal[i].second, N – middlePal[i].second) and rest string will be third string." }, { "code": null, "e": 3713, "s": 3619, "text": "If all the three palindromic strings are present then print that string Otherwise print “-1”." }, { "code": null, "e": 3764, "s": 3713, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 3768, "s": 3764, "text": "C++" }, { "code": null, "e": 3773, "s": 3768, "text": "Java" }, { "code": null, "e": 3781, "s": 3773, "text": "Python3" }, { "code": null, "e": 3784, "s": 3781, "text": "C#" }, { "code": null, "e": 3795, "s": 3784, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to check if a string// is palindrome or notbool isPalindrome(string x){ // Copy the string x to y string y = x; // Reverse the string y reverse(y.begin(), y.end()); if (x == y) { // If string x equals y return true; } return false;} // Function to find three palindromes// from the given string with earliest// possible cutsvoid Palindromes(string S, int N){ // Stores index of palindrome // starting from left & right vector<int> startPal, lastPal; string start; // Store the indices for possible // palindromes from left for (int i = 0; i < S.length() - 2; i++) { // Push the current character start.push_back(S[i]); // Check for palindrome if (isPalindrome(start)) { // Insert the current index startPal.push_back(i); } } string last; // Stores the indexes for possible // palindromes from right for (int j = S.length() - 1; j >= 2; j--) { // Push the current character last.push_back(S[j]); // Check palindromic if (isPalindrome(last)) { // Insert the current index lastPal.push_back(j); } } // Sort the indexes for palindromes // from right in ascending order reverse(lastPal.begin(), lastPal.end()); vector<pair<int, int> > middlePal; for (int i = 0; i < startPal.size(); i++) { for (int j = 0; j < lastPal.size(); j++) { // If the value of startPal // < lastPal value then // store it in middlePal if (startPal[i] < lastPal[j]) { // Insert the current pair middlePal.push_back( { startPal[i], lastPal[j] }); } } } string res1, res2, res3; int flag = 0; // Traverse over the middlePal for (int i = 0; i < middlePal.size(); i++) { int x = middlePal[i].first; int y = middlePal[i].second; string middle; for (int k = x + 1; k < y; k++) { middle.push_back(S[k]); } // Check if the middle part // is palindrome if (isPalindrome(middle)) { flag = 1; res1 = S.substr(0, x + 1); res2 = middle; res3 = S.substr(y, N - y); break; } } // Print the three palindromic if (flag == 1) { cout << res1 << \" \" << res2 << \" \" << res3; } // Otherwise else cout << \"-1\";} // Driver Codeint main(){ // Given string str string str = \"ababbcb\"; int N = str.length(); // Function Call Palindromes(str, N); return 0;}", "e": 6635, "s": 3795, "text": null }, { "code": "// Java program for the// above approachimport java.util.*;class GFG{ static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} static String reverse(String input){ char[] a = input.toCharArray(); int l, r = a.length - 1; for (l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a);} // Function to check if a String// is palindrome or notstatic boolean isPalindrome(String x){ // Copy the String x to y String y = x; // Reverse the String y y = reverse(y); if (x.equals(y)) { // If String x equals y return true; } return false;} // Function to find three palindromes// from the given String with earliest// possible cutsstatic void Palindromes(String S, int N){ // Stores index of palindrome // starting from left & right Vector<Integer> startPal = new Vector<>(); Vector<Integer> lastPal = new Vector<>(); String start = \"\"; // Store the indices for possible // palindromes from left for (int i = 0; i < S.length() - 2; i++) { // Push the current character start += S.charAt(i); // Check for palindrome if (isPalindrome(start)) { // Insert the current index startPal.add(i); } } String last = \"\"; // Stores the indexes for possible // palindromes from right for (int j = S.length() - 1; j >= 2; j--) { // Push the current character last += S.charAt(j); // Check palindromic if (isPalindrome(last)) { // Insert the current index lastPal.add(j); } } // Sort the indexes for palindromes // from right in ascending order Collections.reverse(lastPal); Vector<pair> middlePal = new Vector<>(); for (int i = 0; i < startPal.size(); i++) { for (int j = 0; j < lastPal.size(); j++) { // If the value of startPal // < lastPal value then // store it in middlePal if (startPal.get(i) < lastPal.get(j)) { // Insert the current pair middlePal.add(new pair(startPal.get(i), lastPal.get(j))); } } } String res1 = \"\", res2 = \"\", res3 = \"\"; int flag = 0; // Traverse over the middlePal for (int i = 0; i < middlePal.size(); i++) { int x = middlePal.get(i).first; int y = middlePal.get(i).second; String middle = \"\"; for (int k = x + 1; k < y; k++) { middle += S.charAt(k); } // Check if the middle part // is palindrome if (isPalindrome(middle)) { flag = 1; res1 = S.substring(0, x + 1); res2 = middle; res3 = S.substring(y, N); break; } } // Print the three palindromic if (flag == 1) { System.out.print(res1 + \" \" + res2 + \" \" + res3); } // Otherwise else System.out.print(\"-1\");} // Driver Codepublic static void main(String[] args){ // Given String str String str = \"ababbcb\"; int N = str.length(); // Function Call Palindromes(str, N);}} // This code is contributed by shikhasingrajput", "e": 9782, "s": 6635, "text": null }, { "code": "# Python3 program for the above approach # Function to check if a string# is palindrome or notdef isPalindrome(x): # Copy the x to y y = x # Reverse the y y = y[::-1] if (x == y): # If x equals y return True return False # Function to find three palindromes# from the given with earliest# possible cutsdef Palindromes(S, N): # Stores index of palindrome # starting from left & right startPal, lastPal = [], [] start = [] # Store the indices for possible # palindromes from left for i in range(len(S) - 2): # Push the current character start.append(S[i]) # Check for palindrome if (isPalindrome(start)): # Insert the current index startPal.append(i) last = [] # Stores the indexes for possible # palindromes from right for j in range(len(S) - 1, 1, -1): # Push the current character last.append(S[j]) # Check palindromic if (isPalindrome(last)): # Insert the current index lastPal.append(j) # Sort the indexes for palindromes # from right in ascending order lastPal = lastPal[::-1] middlePal = [] for i in range(len(startPal)): for j in range(len(lastPal)): # If the value of startPal # < lastPal value then # store it in middlePal if (startPal[i] < lastPal[j]): # Insert the current pair middlePal.append([startPal[i], lastPal[j]]) res1, res2, res3 = \"\", \"\", \"\" flag = 0 # Traverse over the middlePal for i in range(len(middlePal)): x = middlePal[i][0] y = middlePal[i][1] #print(x,y) middle = \"\" for k in range(x + 1, y): middle += (S[k]) # Check if the middle part # is palindrome if (isPalindrome(middle)): flag = 1 res1 = S[0 : x + 1] res2 = middle res3 = S[y : N] #print(S,x,y,N) break # Print the three palindromic if (flag == 1): print(res1, res2, res3) # Otherwise else: print(\"-1\") # Driver Codeif __name__ == '__main__': # Given strr strr = \"ababbcb\" N = len(strr) # Function call Palindromes(strr, N) # This code is contributed by mohit kumar 29", "e": 12171, "s": 9782, "text": null }, { "code": "// C# program for the// above approachusing System;using System.Collections.Generic; class GFG{ public class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} static String reverse(String input){ char[] a = input.ToCharArray(); int l, r = a.Length - 1; for(l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.Join(\"\",a);} // Function to check if a String// is palindrome or notstatic bool isPalindrome(String x){ // Copy the String x to y String y = x; // Reverse the String y y = reverse(y); if (x.Equals(y)) { // If String x equals y return true; } return false;} // Function to find three palindromes// from the given String with earliest// possible cutsstatic void Palindromes(String S, int N){ // Stores index of palindrome // starting from left & right List<int> startPal = new List<int>(); List<int> lastPal = new List<int>(); String start = \"\"; // Store the indices for possible // palindromes from left for(int i = 0; i < S.Length - 2; i++) { // Push the current character start += S[i]; // Check for palindrome if (isPalindrome(start)) { // Insert the current index startPal.Add(i); } } String last = \"\"; // Stores the indexes for possible // palindromes from right for(int j = S.Length - 1; j >= 2; j--) { // Push the current character last += S[j]; // Check palindromic if (isPalindrome(last)) { // Insert the current index lastPal.Add(j); } } // Sort the indexes for palindromes // from right in ascending order lastPal.Reverse(); List<pair> middlePal = new List<pair>(); for(int i = 0; i < startPal.Count; i++) { for(int j = 0; j < lastPal.Count; j++) { // If the value of startPal // < lastPal value then // store it in middlePal if (startPal[i] < lastPal[j]) { // Insert the current pair middlePal.Add(new pair(startPal[i], lastPal[j])); } } } String res1 = \"\", res2 = \"\", res3 = \"\"; int flag = 0; // Traverse over the middlePal for(int i = 0; i < middlePal.Count; i++) { int x = middlePal[i].first; int y = middlePal[i].second; String middle = \"\"; for(int k = x + 1; k < y; k++) { middle += S[k]; } // Check if the middle part // is palindrome if (isPalindrome(middle)) { flag = 1; res1 = S.Substring(0, x + 1); res2 = middle; res3 = S.Substring(y); break; } } // Print the three palindromic if (flag == 1) { Console.Write(res1 + \" \" + res2 + \" \" + res3); } // Otherwise else Console.Write(\"-1\");} // Driver Codepublic static void Main(String[] args){ // Given String str String str = \"ababbcb\"; int N = str.Length; // Function Call Palindromes(str, N);}} // This code is contributed by Amit Katiyar", "e": 15264, "s": 12171, "text": null }, { "code": "<script> // Function to check if a String // is palindrome or not function isPalindrome(x) { // Copy the String x to y var y = x; // Reverse the String y y = y.split(\"\").reverse().join(\"\"); if (x === y) { // If String x equals y return true; } return false; } // Function to find three palindromes // from the given String with earliest // possible cuts function Palindromes(S, N) { // Stores index of palindrome // starting from left & right var startPal = []; var lastPal = []; var start = \"\"; // Store the indices for possible // palindromes from left for (var i = 0; i < S.length - 2; i++) { // Push the current character start += S[i]; // Check for palindrome if (isPalindrome(start)) { // Insert the current index startPal.push(i); } } var last = \"\"; // Stores the indexes for possible // palindromes from right for (var j = S.length - 1; j >= 2; j--) { // Push the current character last += S[j]; // Check palindromic if (isPalindrome(last)) { // Insert the current index lastPal.push(j); } } // Sort the indexes for palindromes // from right in ascending order lastPal.sort(); var middlePal = []; for (var i = 0; i < startPal.length; i++) { for (var j = 0; j < lastPal.length; j++) { // If the value of startPal // < lastPal value then // store it in middlePal if (startPal[i] < lastPal[j]) { // Insert the current pair middlePal.push([startPal[i], lastPal[j]]); } } } var res1 = \"\", res2 = \"\", res3 = \"\"; var flag = 0; // Traverse over the middlePal for (var i = 0; i < middlePal.length; i++) { var x = middlePal[i][0]; var y = middlePal[i][1]; var middle = \"\"; for (var k = x + 1; k < y; k++) { middle += S[k]; } // Check if the middle part // is palindrome if (isPalindrome(middle)) { flag = 1; res1 = S.substring(0, x + 1); res2 = middle; res3 = S.substring(y, N); break; } } // Print the three palindromic if (flag === 1) { document.write(res1 + \" \" + res2 + \" \" + res3); } // Otherwise else document.write(\"-1\"); } // Driver Code // Given String str var str = \"ababbcb\"; var N = str.length; // Function Call Palindromes(str, N);</script>", "e": 18096, "s": 15264, "text": null }, { "code": null, "e": 18106, "s": 18096, "text": "a bab bcb" }, { "code": null, "e": 18152, "s": 18108, "text": "Time Complexity: O(N2)Auxiliary Space: O(N)" }, { "code": null, "e": 18167, "s": 18152, "text": "mohit kumar 29" }, { "code": null, "e": 18184, "s": 18167, "text": "shikhasingrajput" }, { "code": null, "e": 18199, "s": 18184, "text": "amit143katiyar" }, { "code": null, "e": 18216, "s": 18199, "text": "akshaysingh98088" }, { "code": null, "e": 18223, "s": 18216, "text": "rdtank" }, { "code": null, "e": 18233, "s": 18223, "text": "rs1686740" }, { "code": null, "e": 18244, "s": 18233, "text": "palindrome" }, { "code": null, "e": 18252, "s": 18244, "text": "Reverse" }, { "code": null, "e": 18262, "s": 18252, "text": "substring" }, { "code": null, "e": 18272, "s": 18262, "text": "Searching" }, { "code": null, "e": 18280, "s": 18272, "text": "Strings" }, { "code": null, "e": 18290, "s": 18280, "text": "Searching" }, { "code": null, "e": 18298, "s": 18290, "text": "Strings" }, { "code": null, "e": 18309, "s": 18298, "text": "palindrome" }, { "code": null, "e": 18317, "s": 18309, "text": "Reverse" }, { "code": null, "e": 18415, "s": 18317, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 18463, "s": 18415, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 18510, "s": 18463, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 18557, "s": 18510, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 18601, "s": 18557, "text": "Program to find largest element in an array" }, { "code": null, "e": 18645, "s": 18601, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 18691, "s": 18645, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 18716, "s": 18691, "text": "Reverse a string in Java" }, { "code": null, "e": 18776, "s": 18716, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 18791, "s": 18776, "text": "C++ Data Types" } ]
Unbounded Binary Search Example (Find the point where a monotonically increasing function becomes positive first time)
23 Feb, 2022 Given a function ‘int f(unsigned int x)’ which takes a non-negative integer ‘x’ as input and returns an integer as output. The function is monotonically increasing with respect to the value of x, i.e., the value of f(x+1) is greater than f(x) for every input x. Find the value ‘n’ where f() becomes positive for the first time. Since f() is monotonically increasing, values of f(n+1), f(n+2),... must be positive and values of f(n-2), f(n-3), ... must be negative. Find n in O(logn) time, you may assume that f(x) can be evaluated in O(1) time for any input x. A simple solution is to start from i equals to 0 and one by one calculate the value of f(i) for 1, 2, 3, 4 ... etc until we find a positive f(i). This works but takes O(n) time.Can we apply Binary Search to find n in O(Logn) time? We can’t directly apply Binary Search as we don’t have an upper limit or high index. The idea is to do repeated doubling until we find a positive value, i.e., check values of f() for following values until f(i) becomes positive. f(0) f(1) f(2) f(4) f(8) f(16) f(32) .... .... f(high) Let 'high' be the value of i when f() becomes positive for first time. Can we apply Binary Search to find n after finding ‘high’? We can apply Binary Search now, we can use ‘high/2’ as low and ‘high’ as high indexes in binary search. The result n must lie between ‘high/2’ and ‘high’.The number of steps for finding ‘high’ is O(Logn). So we can find ‘high’ in O(Logn) time. What about the time taken by Binary Search between high/2 and high? The value of ‘high’ must be less than 2*n. The number of elements between high/2 and high must be O(n). Therefore, the time complexity of Binary Search is O(Logn) and the overall time complexity is 2*O(Logn) which is O(Logn). C++ C Java Python3 C# PHP Javascript // C++ code for binary search#include<bits/stdc++.h>using namespace std; int binarySearch(int low, int high); // prototype // Let's take an example function// as f(x) = x^2 - 10*x - 20 Note that// f(x) can be any monotonically increasing functionint f(int x) { return (x*x - 10*x - 20); } // Returns the value x where above// function f() becomes positive// first time.int findFirstPositive(){ // When first value itself is positive if (f(0) > 0) return 0; // Find 'high' for binary search by repeated doubling int i = 1; while (f(i) <= 0) i = i*2; // Call binary search return binarySearch(i/2, i);} // Searches first positive value// of f(i) where low <= i <= highint binarySearch(int low, int high){ if (high >= low) { int mid = low + (high - low)/2; /* mid = (low + high)/2 */ // If f(mid) is greater than 0 and // one of the following two // conditions is true: // a) mid is equal to low // b) f(mid-1) is negative if (f(mid) > 0 && (mid == low || f(mid-1) <= 0)) return mid; // If f(mid) is smaller than or equal to 0 if (f(mid) <= 0) return binarySearch((mid + 1), high); else // f(mid) > 0 return binarySearch(low, (mid -1)); } /* Return -1 if there is no positive value in given range */ return -1;} /* Driver code */int main(){ cout<<"The value n where f() becomes" << "positive first is "<< findFirstPositive(); return 0;} // This code is contributed by rathbhupendra #include <stdio.h>int binarySearch(int low, int high); // prototype // Let's take an example function as f(x) = x^2 - 10*x - 20// Note that f(x) can be any monotonically increasing functionint f(int x) { return (x*x - 10*x - 20); } // Returns the value x where above function f() becomes positive// first time.int findFirstPositive(){ // When first value itself is positive if (f(0) > 0) return 0; // Find 'high' for binary search by repeated doubling int i = 1; while (f(i) <= 0) i = i*2; // Call binary search return binarySearch(i/2, i);} // Searches first positive value of f(i) where low <= i <= highint binarySearch(int low, int high){ if (high >= low) { int mid = low + (high - low)/2; /* mid = (low + high)/2 */ // If f(mid) is greater than 0 and one of the following two // conditions is true: // a) mid is equal to low // b) f(mid-1) is negative if (f(mid) > 0 && (mid == low || f(mid-1) <= 0)) return mid; // If f(mid) is smaller than or equal to 0 if (f(mid) <= 0) return binarySearch((mid + 1), high); else // f(mid) > 0 return binarySearch(low, (mid -1)); } /* Return -1 if there is no positive value in given range */ return -1;} /* Driver program to check above functions */int main(){ printf("The value n where f() becomes positive first is %d", findFirstPositive()); return 0;} // Java program for Binary Searchimport java.util.*; class Binary{ public static int f(int x) { return (x*x - 10*x - 20); } // Returns the value x where above // function f() becomes positive // first time. public static int findFirstPositive() { // When first value itself is positive if (f(0) > 0) return 0; // Find 'high' for binary search // by repeated doubling int i = 1; while (f(i) <= 0) i = i * 2; // Call binary search return binarySearch(i / 2, i); } // Searches first positive value of // f(i) where low <= i <= high public static int binarySearch(int low, int high) { if (high >= low) { /* mid = (low + high)/2 */ int mid = low + (high - low)/2; // If f(mid) is greater than 0 and // one of the following two // conditions is true: // a) mid is equal to low // b) f(mid-1) is negative if (f(mid) > 0 && (mid == low || f(mid-1) <= 0)) return mid; // If f(mid) is smaller than or equal to 0 if (f(mid) <= 0) return binarySearch((mid + 1), high); else // f(mid) > 0 return binarySearch(low, (mid -1)); } /* Return -1 if there is no positive value in given range */ return -1; } // driver code public static void main(String[] args) { System.out.print ("The value n where f() "+ "becomes positive first is "+ findFirstPositive()); }} // This code is contributed by rishabh_jain # Python3 program for Unbound Binary search. # Let's take an example function as# f(x) = x^2 - 10*x - 20# Note that f(x) can be any monotonically# increasing functiondef f(x): return (x * x - 10 * x - 20) # Returns the value x where above function# f() becomes positive first time.def findFirstPositive() : # When first value itself is positive if (f(0) > 0): return 0 # Find 'high' for binary search # by repeated doubling i = 1 while (f(i) <= 0) : i = i * 2 # Call binary search return binarySearch(i/2, i) # Searches first positive value of# f(i) where low <= i <= highdef binarySearch(low, high): if (high >= low) : # mid = (low + high)/2 mid = low + (high - low)/2; # If f(mid) is greater than 0 # and one of the following two # conditions is true: # a) mid is equal to low # b) f(mid-1) is negative if (f(mid) > 0 and (mid == low or f(mid-1) <= 0)) : return mid; # If f(mid) is smaller than or equal to 0 if (f(mid) <= 0) : return binarySearch((mid + 1), high) else : # f(mid) > 0 return binarySearch(low, (mid -1)) # Return -1 if there is no positive # value in given range return -1; # Driver Codeprint ("The value n where f() becomes "+ "positive first is ", findFirstPositive()); # This code is contributed by rishabh_jain // C# program for Binary Searchusing System; class Binary{ public static int f(int x) { return (x*x - 10*x - 20); } // Returns the value x where above // function f() becomes positive // first time. public static int findFirstPositive() { // When first value itself is positive if (f(0) > 0) return 0; // Find 'high' for binary search // by repeated doubling int i = 1; while (f(i) <= 0) i = i * 2; // Call binary search return binarySearch(i / 2, i); } // Searches first positive value of // f(i) where low <= i <= high public static int binarySearch(int low, int high) { if (high >= low) { /* mid = (low + high)/2 */ int mid = low + (high - low)/2; // If f(mid) is greater than 0 and // one of the following two // conditions is true: // a) mid is equal to low // b) f(mid-1) is negative if (f(mid) > 0 && (mid == low || f(mid-1) <= 0)) return mid; // If f(mid) is smaller than or equal to 0 if (f(mid) <= 0) return binarySearch((mid + 1), high); else // f(mid) > 0 return binarySearch(low, (mid -1)); } /* Return -1 if there is no positive value in given range */ return -1; } // Driver code public static void Main() { Console.Write ("The value n where f() " + "becomes positive first is " + findFirstPositive()); }} // This code is contributed by nitin mittal <?php// PHP program for Binary Search // Let's take an example function// as f(x) = x^2 - 10*x - 20// Note that f(x) can be any// monotonically increasing functionfunction f($x){ return ($x * $x - 10 * $x - 20);} // Returns the value x where above// function f() becomes positive// first time.function findFirstPositive(){ // When first value // itself is positive if (f(0) > 0) return 0; // Find 'high' for binary // search by repeated doubling $i = 1; while (f($i) <= 0) $i = $i * 2; // Call binary search return binarySearch(intval($i / 2), $i);} // Searches first positive value// of f(i) where low <= i <= highfunction binarySearch($low, $high){ if ($high >= $low) { /* mid = (low + high)/2 */ $mid = $low + intval(($high - $low) / 2); // If f(mid) is greater than 0 // and one of the following two // conditions is true: // a) mid is equal to low // b) f(mid-1) is negative if (f($mid) > 0 && ($mid == $low || f($mid - 1) <= 0)) return $mid; // If f(mid) is smaller // than or equal to 0 if (f($mid) <= 0) return binarySearch(($mid + 1), $high); else // f(mid) > 0 return binarySearch($low, ($mid - 1)); } /* Return -1 if there is no positive value in given range */ return -1;} // Driver Codeecho "The value n where f() becomes ". "positive first is ". findFirstPositive() ; // This code is contributed by Sam007?> <script> // Javascript program for Binary Search function f(x) { return (x*x - 10*x - 20); } // Returns the value x where above // function f() becomes positive // first time. function findFirstPositive() { // When first value itself is positive if (f(0) > 0) return 0; // Find 'high' for binary search // by repeated doubling let i = 1; while (f(i) <= 0) i = i * 2; // Call binary search return binarySearch(parseInt(i / 2, 10), i); } // Searches first positive value of // f(i) where low <= i <= high function binarySearch(low, high) { if (high >= low) { /* mid = (low + high)/2 */ let mid = low + parseInt((high - low)/2, 10); // If f(mid) is greater than 0 and // one of the following two // conditions is true: // a) mid is equal to low // b) f(mid-1) is negative if (f(mid) > 0 && (mid == low || f(mid-1) <= 0)) return mid; // If f(mid) is smaller than or equal to 0 if (f(mid) <= 0) return binarySearch((mid + 1), high); else // f(mid) > 0 return binarySearch(low, (mid -1)); } /* Return -1 if there is no positive value in given range */ return -1; } document.write ("The value n where f() " + "becomes positive first is " + findFirstPositive()); </script> Output : The value n where f() becomes positive first is 12 nitin mittal Sam007 rathbhupendra vaibhavrabadiya117 simmytarika5 Binary Search Divide and Conquer Searching Searching Divide and Conquer Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Feb, 2022" }, { "code": null, "e": 614, "s": 52, "text": "Given a function ‘int f(unsigned int x)’ which takes a non-negative integer ‘x’ as input and returns an integer as output. The function is monotonically increasing with respect to the value of x, i.e., the value of f(x+1) is greater than f(x) for every input x. Find the value ‘n’ where f() becomes positive for the first time. Since f() is monotonically increasing, values of f(n+1), f(n+2),... must be positive and values of f(n-2), f(n-3), ... must be negative. Find n in O(logn) time, you may assume that f(x) can be evaluated in O(1) time for any input x. " }, { "code": null, "e": 1074, "s": 614, "text": "A simple solution is to start from i equals to 0 and one by one calculate the value of f(i) for 1, 2, 3, 4 ... etc until we find a positive f(i). This works but takes O(n) time.Can we apply Binary Search to find n in O(Logn) time? We can’t directly apply Binary Search as we don’t have an upper limit or high index. The idea is to do repeated doubling until we find a positive value, i.e., check values of f() for following values until f(i) becomes positive." }, { "code": null, "e": 1221, "s": 1074, "text": " f(0) \n f(1)\n f(2)\n f(4)\n f(8)\n f(16)\n f(32)\n ....\n ....\n f(high)\nLet 'high' be the value of i when f() becomes positive for first time." }, { "code": null, "e": 1820, "s": 1221, "text": "Can we apply Binary Search to find n after finding ‘high’? We can apply Binary Search now, we can use ‘high/2’ as low and ‘high’ as high indexes in binary search. The result n must lie between ‘high/2’ and ‘high’.The number of steps for finding ‘high’ is O(Logn). So we can find ‘high’ in O(Logn) time. What about the time taken by Binary Search between high/2 and high? The value of ‘high’ must be less than 2*n. The number of elements between high/2 and high must be O(n). Therefore, the time complexity of Binary Search is O(Logn) and the overall time complexity is 2*O(Logn) which is O(Logn). " }, { "code": null, "e": 1824, "s": 1820, "text": "C++" }, { "code": null, "e": 1826, "s": 1824, "text": "C" }, { "code": null, "e": 1831, "s": 1826, "text": "Java" }, { "code": null, "e": 1839, "s": 1831, "text": "Python3" }, { "code": null, "e": 1842, "s": 1839, "text": "C#" }, { "code": null, "e": 1846, "s": 1842, "text": "PHP" }, { "code": null, "e": 1857, "s": 1846, "text": "Javascript" }, { "code": "// C++ code for binary search#include<bits/stdc++.h>using namespace std; int binarySearch(int low, int high); // prototype // Let's take an example function// as f(x) = x^2 - 10*x - 20 Note that// f(x) can be any monotonically increasing functionint f(int x) { return (x*x - 10*x - 20); } // Returns the value x where above// function f() becomes positive// first time.int findFirstPositive(){ // When first value itself is positive if (f(0) > 0) return 0; // Find 'high' for binary search by repeated doubling int i = 1; while (f(i) <= 0) i = i*2; // Call binary search return binarySearch(i/2, i);} // Searches first positive value// of f(i) where low <= i <= highint binarySearch(int low, int high){ if (high >= low) { int mid = low + (high - low)/2; /* mid = (low + high)/2 */ // If f(mid) is greater than 0 and // one of the following two // conditions is true: // a) mid is equal to low // b) f(mid-1) is negative if (f(mid) > 0 && (mid == low || f(mid-1) <= 0)) return mid; // If f(mid) is smaller than or equal to 0 if (f(mid) <= 0) return binarySearch((mid + 1), high); else // f(mid) > 0 return binarySearch(low, (mid -1)); } /* Return -1 if there is no positive value in given range */ return -1;} /* Driver code */int main(){ cout<<\"The value n where f() becomes\" << \"positive first is \"<< findFirstPositive(); return 0;} // This code is contributed by rathbhupendra", "e": 3410, "s": 1857, "text": null }, { "code": "#include <stdio.h>int binarySearch(int low, int high); // prototype // Let's take an example function as f(x) = x^2 - 10*x - 20// Note that f(x) can be any monotonically increasing functionint f(int x) { return (x*x - 10*x - 20); } // Returns the value x where above function f() becomes positive// first time.int findFirstPositive(){ // When first value itself is positive if (f(0) > 0) return 0; // Find 'high' for binary search by repeated doubling int i = 1; while (f(i) <= 0) i = i*2; // Call binary search return binarySearch(i/2, i);} // Searches first positive value of f(i) where low <= i <= highint binarySearch(int low, int high){ if (high >= low) { int mid = low + (high - low)/2; /* mid = (low + high)/2 */ // If f(mid) is greater than 0 and one of the following two // conditions is true: // a) mid is equal to low // b) f(mid-1) is negative if (f(mid) > 0 && (mid == low || f(mid-1) <= 0)) return mid; // If f(mid) is smaller than or equal to 0 if (f(mid) <= 0) return binarySearch((mid + 1), high); else // f(mid) > 0 return binarySearch(low, (mid -1)); } /* Return -1 if there is no positive value in given range */ return -1;} /* Driver program to check above functions */int main(){ printf(\"The value n where f() becomes positive first is %d\", findFirstPositive()); return 0;}", "e": 4874, "s": 3410, "text": null }, { "code": "// Java program for Binary Searchimport java.util.*; class Binary{ public static int f(int x) { return (x*x - 10*x - 20); } // Returns the value x where above // function f() becomes positive // first time. public static int findFirstPositive() { // When first value itself is positive if (f(0) > 0) return 0; // Find 'high' for binary search // by repeated doubling int i = 1; while (f(i) <= 0) i = i * 2; // Call binary search return binarySearch(i / 2, i); } // Searches first positive value of // f(i) where low <= i <= high public static int binarySearch(int low, int high) { if (high >= low) { /* mid = (low + high)/2 */ int mid = low + (high - low)/2; // If f(mid) is greater than 0 and // one of the following two // conditions is true: // a) mid is equal to low // b) f(mid-1) is negative if (f(mid) > 0 && (mid == low || f(mid-1) <= 0)) return mid; // If f(mid) is smaller than or equal to 0 if (f(mid) <= 0) return binarySearch((mid + 1), high); else // f(mid) > 0 return binarySearch(low, (mid -1)); } /* Return -1 if there is no positive value in given range */ return -1; } // driver code public static void main(String[] args) { System.out.print (\"The value n where f() \"+ \"becomes positive first is \"+ findFirstPositive()); }} // This code is contributed by rishabh_jain", "e": 6567, "s": 4874, "text": null }, { "code": "# Python3 program for Unbound Binary search. # Let's take an example function as# f(x) = x^2 - 10*x - 20# Note that f(x) can be any monotonically# increasing functiondef f(x): return (x * x - 10 * x - 20) # Returns the value x where above function# f() becomes positive first time.def findFirstPositive() : # When first value itself is positive if (f(0) > 0): return 0 # Find 'high' for binary search # by repeated doubling i = 1 while (f(i) <= 0) : i = i * 2 # Call binary search return binarySearch(i/2, i) # Searches first positive value of# f(i) where low <= i <= highdef binarySearch(low, high): if (high >= low) : # mid = (low + high)/2 mid = low + (high - low)/2; # If f(mid) is greater than 0 # and one of the following two # conditions is true: # a) mid is equal to low # b) f(mid-1) is negative if (f(mid) > 0 and (mid == low or f(mid-1) <= 0)) : return mid; # If f(mid) is smaller than or equal to 0 if (f(mid) <= 0) : return binarySearch((mid + 1), high) else : # f(mid) > 0 return binarySearch(low, (mid -1)) # Return -1 if there is no positive # value in given range return -1; # Driver Codeprint (\"The value n where f() becomes \"+ \"positive first is \", findFirstPositive()); # This code is contributed by rishabh_jain", "e": 7992, "s": 6567, "text": null }, { "code": "// C# program for Binary Searchusing System; class Binary{ public static int f(int x) { return (x*x - 10*x - 20); } // Returns the value x where above // function f() becomes positive // first time. public static int findFirstPositive() { // When first value itself is positive if (f(0) > 0) return 0; // Find 'high' for binary search // by repeated doubling int i = 1; while (f(i) <= 0) i = i * 2; // Call binary search return binarySearch(i / 2, i); } // Searches first positive value of // f(i) where low <= i <= high public static int binarySearch(int low, int high) { if (high >= low) { /* mid = (low + high)/2 */ int mid = low + (high - low)/2; // If f(mid) is greater than 0 and // one of the following two // conditions is true: // a) mid is equal to low // b) f(mid-1) is negative if (f(mid) > 0 && (mid == low || f(mid-1) <= 0)) return mid; // If f(mid) is smaller than or equal to 0 if (f(mid) <= 0) return binarySearch((mid + 1), high); else // f(mid) > 0 return binarySearch(low, (mid -1)); } /* Return -1 if there is no positive value in given range */ return -1; } // Driver code public static void Main() { Console.Write (\"The value n where f() \" + \"becomes positive first is \" + findFirstPositive()); }} // This code is contributed by nitin mittal", "e": 9721, "s": 7992, "text": null }, { "code": "<?php// PHP program for Binary Search // Let's take an example function// as f(x) = x^2 - 10*x - 20// Note that f(x) can be any// monotonically increasing functionfunction f($x){ return ($x * $x - 10 * $x - 20);} // Returns the value x where above// function f() becomes positive// first time.function findFirstPositive(){ // When first value // itself is positive if (f(0) > 0) return 0; // Find 'high' for binary // search by repeated doubling $i = 1; while (f($i) <= 0) $i = $i * 2; // Call binary search return binarySearch(intval($i / 2), $i);} // Searches first positive value// of f(i) where low <= i <= highfunction binarySearch($low, $high){ if ($high >= $low) { /* mid = (low + high)/2 */ $mid = $low + intval(($high - $low) / 2); // If f(mid) is greater than 0 // and one of the following two // conditions is true: // a) mid is equal to low // b) f(mid-1) is negative if (f($mid) > 0 && ($mid == $low || f($mid - 1) <= 0)) return $mid; // If f(mid) is smaller // than or equal to 0 if (f($mid) <= 0) return binarySearch(($mid + 1), $high); else // f(mid) > 0 return binarySearch($low, ($mid - 1)); } /* Return -1 if there is no positive value in given range */ return -1;} // Driver Codeecho \"The value n where f() becomes \". \"positive first is \". findFirstPositive() ; // This code is contributed by Sam007?>", "e": 11313, "s": 9721, "text": null }, { "code": "<script> // Javascript program for Binary Search function f(x) { return (x*x - 10*x - 20); } // Returns the value x where above // function f() becomes positive // first time. function findFirstPositive() { // When first value itself is positive if (f(0) > 0) return 0; // Find 'high' for binary search // by repeated doubling let i = 1; while (f(i) <= 0) i = i * 2; // Call binary search return binarySearch(parseInt(i / 2, 10), i); } // Searches first positive value of // f(i) where low <= i <= high function binarySearch(low, high) { if (high >= low) { /* mid = (low + high)/2 */ let mid = low + parseInt((high - low)/2, 10); // If f(mid) is greater than 0 and // one of the following two // conditions is true: // a) mid is equal to low // b) f(mid-1) is negative if (f(mid) > 0 && (mid == low || f(mid-1) <= 0)) return mid; // If f(mid) is smaller than or equal to 0 if (f(mid) <= 0) return binarySearch((mid + 1), high); else // f(mid) > 0 return binarySearch(low, (mid -1)); } /* Return -1 if there is no positive value in given range */ return -1; } document.write (\"The value n where f() \" + \"becomes positive first is \" + findFirstPositive()); </script>", "e": 12951, "s": 11313, "text": null }, { "code": null, "e": 12961, "s": 12951, "text": "Output : " }, { "code": null, "e": 13012, "s": 12961, "text": "The value n where f() becomes positive first is 12" }, { "code": null, "e": 13027, "s": 13014, "text": "nitin mittal" }, { "code": null, "e": 13034, "s": 13027, "text": "Sam007" }, { "code": null, "e": 13048, "s": 13034, "text": "rathbhupendra" }, { "code": null, "e": 13067, "s": 13048, "text": "vaibhavrabadiya117" }, { "code": null, "e": 13080, "s": 13067, "text": "simmytarika5" }, { "code": null, "e": 13094, "s": 13080, "text": "Binary Search" }, { "code": null, "e": 13113, "s": 13094, "text": "Divide and Conquer" }, { "code": null, "e": 13123, "s": 13113, "text": "Searching" }, { "code": null, "e": 13133, "s": 13123, "text": "Searching" }, { "code": null, "e": 13152, "s": 13133, "text": "Divide and Conquer" }, { "code": null, "e": 13166, "s": 13152, "text": "Binary Search" } ]
TreeMap get() Method in Java
28 Jun, 2018 The java.util.TreeMap.get() method of TreeMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key. Syntax: Tree_Map.get(Object key_element) Parameter: The method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched. Return Value: The method returns the value associated with the key_element in the parameter. Below programs illustrates the working of java.util.TreeMap.get() method:Program 1: Mapping String Values to Integer Keys. // Java code to illustrate the get() methodimport java.util.*; public class Tree_Map_Demo { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(); // Mapping string values to int keys tree_map.put(10, "Geeks"); tree_map.put(15, "4"); tree_map.put(20, "Geeks"); tree_map.put(25, "Welcomes"); tree_map.put(30, "You"); // Displaying the TreeMap System.out.println("Initial Mappings are: " + tree_map); // Getting the value of 25 System.out.println("The Value is: " + tree_map.get(25)); // Getting the value of 10 System.out.println("The Value is: " + tree_map.get(10)); }} Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You} The Value is: Welcomes The Value is: Geeks Program 2: Mapping Integer Values to String Keys. // Java code to illustrate the get() methodimport java.util.*; public class Tree_Map_Demo { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<String, Integer> tree_map = new TreeMap<String, Integer>(); // Mapping int values to string keys tree_map.put("Geeks", 10); tree_map.put("4", 15); tree_map.put("Geeks", 20); tree_map.put("Welcomes", 25); tree_map.put("You", 30); // Displaying the TreeMap System.out.println("Initial Mappings are: " + tree_map); // Getting the value of "Geeks" System.out.println("The Value is: " + tree_map.get("Geeks")); // Getting the value of "You" System.out.println("The Value is: " + tree_map.get("You")); }} Initial Mappings are: {4=15, Geeks=20, Welcomes=25, You=30} The Value is: 20 The Value is: 30 Note: The same operation can be performed with any type of Mappings with variation and combination of different data types. Java - util package Java-Collections java-TreeMap Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Queue Interface In Java How to add an element to an Array in Java? Multidimensional Arrays in Java Math pow() method in Java with Example PriorityQueue in Java Stack Class in Java List Interface in Java with Examples ArrayList in Java Different ways of Reading a text file in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2018" }, { "code": null, "e": 265, "s": 52, "text": "The java.util.TreeMap.get() method of TreeMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key." }, { "code": null, "e": 273, "s": 265, "text": "Syntax:" }, { "code": null, "e": 306, "s": 273, "text": "Tree_Map.get(Object key_element)" }, { "code": null, "e": 447, "s": 306, "text": "Parameter: The method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched." }, { "code": null, "e": 540, "s": 447, "text": "Return Value: The method returns the value associated with the key_element in the parameter." }, { "code": null, "e": 663, "s": 540, "text": "Below programs illustrates the working of java.util.TreeMap.get() method:Program 1: Mapping String Values to Integer Keys." }, { "code": "// Java code to illustrate the get() methodimport java.util.*; public class Tree_Map_Demo { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(); // Mapping string values to int keys tree_map.put(10, \"Geeks\"); tree_map.put(15, \"4\"); tree_map.put(20, \"Geeks\"); tree_map.put(25, \"Welcomes\"); tree_map.put(30, \"You\"); // Displaying the TreeMap System.out.println(\"Initial Mappings are: \" + tree_map); // Getting the value of 25 System.out.println(\"The Value is: \" + tree_map.get(25)); // Getting the value of 10 System.out.println(\"The Value is: \" + tree_map.get(10)); }}", "e": 1434, "s": 663, "text": null }, { "code": null, "e": 1548, "s": 1434, "text": "Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}\nThe Value is: Welcomes\nThe Value is: Geeks\n" }, { "code": null, "e": 1598, "s": 1548, "text": "Program 2: Mapping Integer Values to String Keys." }, { "code": "// Java code to illustrate the get() methodimport java.util.*; public class Tree_Map_Demo { public static void main(String[] args) { // Creating an empty TreeMap TreeMap<String, Integer> tree_map = new TreeMap<String, Integer>(); // Mapping int values to string keys tree_map.put(\"Geeks\", 10); tree_map.put(\"4\", 15); tree_map.put(\"Geeks\", 20); tree_map.put(\"Welcomes\", 25); tree_map.put(\"You\", 30); // Displaying the TreeMap System.out.println(\"Initial Mappings are: \" + tree_map); // Getting the value of \"Geeks\" System.out.println(\"The Value is: \" + tree_map.get(\"Geeks\")); // Getting the value of \"You\" System.out.println(\"The Value is: \" + tree_map.get(\"You\")); }}", "e": 2385, "s": 1598, "text": null }, { "code": null, "e": 2480, "s": 2385, "text": "Initial Mappings are: {4=15, Geeks=20, Welcomes=25, You=30}\nThe Value is: 20\nThe Value is: 30\n" }, { "code": null, "e": 2604, "s": 2480, "text": "Note: The same operation can be performed with any type of Mappings with variation and combination of different data types." }, { "code": null, "e": 2624, "s": 2604, "text": "Java - util package" }, { "code": null, "e": 2641, "s": 2624, "text": "Java-Collections" }, { "code": null, "e": 2654, "s": 2641, "text": "java-TreeMap" }, { "code": null, "e": 2659, "s": 2654, "text": "Java" }, { "code": null, "e": 2664, "s": 2659, "text": "Java" }, { "code": null, "e": 2681, "s": 2664, "text": "Java-Collections" }, { "code": null, "e": 2779, "s": 2681, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2798, "s": 2779, "text": "Interfaces in Java" }, { "code": null, "e": 2822, "s": 2798, "text": "Queue Interface In Java" }, { "code": null, "e": 2865, "s": 2822, "text": "How to add an element to an Array in Java?" }, { "code": null, "e": 2897, "s": 2865, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 2936, "s": 2897, "text": "Math pow() method in Java with Example" }, { "code": null, "e": 2958, "s": 2936, "text": "PriorityQueue in Java" }, { "code": null, "e": 2978, "s": 2958, "text": "Stack Class in Java" }, { "code": null, "e": 3015, "s": 2978, "text": "List Interface in Java with Examples" }, { "code": null, "e": 3033, "s": 3015, "text": "ArrayList in Java" } ]
Longest subarray whose elements can be made equal by maximum K increments
22 Jun, 2022 Given an array arr[] of positive integers of size N and a positive integer K, the task is to find the maximum possible length of a subarray which can be made equal by adding some integer value to each element of the sub-array such that the sum of the added elements does not exceed K. Examples: Input: N = 5, arr[] = {1, 4, 9, 3, 6}, K = 9 Output: 3 Explanation: {1, 4} : {1+3, 4} = {4, 4} {4, 9} : {4+5, 9} = {9, 9} {3, 6} : {3+3, 6} = {6, 6} {9, 3, 6} : {9, 3+6, 6+3} = {9, 9, 9} Hence, the maximum length of such a subarray is 3. Input: N = 6, arr[] = {2, 4, 7, 3, 8, 5}, K = 10 Output: 4 Approach: This problem can be solved by using dynamic programming. Initialize: dp[]: Stores the sum of elements that are added to the subarray.deque: Stores the indices of the maximum element for each subarray.pos: Index of the current position of the subarray.ans: Length of the maximum subarray.mx: Maximum element of a subarraypre: Previous index of the current subarray. dp[]: Stores the sum of elements that are added to the subarray. deque: Stores the indices of the maximum element for each subarray. pos: Index of the current position of the subarray. ans: Length of the maximum subarray. mx: Maximum element of a subarray pre: Previous index of the current subarray. Traverse the array and check if the deque is empty or not. If yes, then update the maximum element and the index of the maximum element along with the indices of pre and pos. Check if the currently added element is greater than K. If yes, then remove it from dp[] array and update the indices of pos and pre. Finally, update the maximum length of the valid sub-array. Below is the implementation of the above approach: C++ Java Python3 Javascript C# // C++ code for the above approach #include <bits/stdc++.h>using namespace std; // Function to find maximum// possible length of subarrayint validSubArrLength(int arr[], int N, int K){ // Stores the sum of elements // that needs to be added to // the sub array int dp[N + 1]; // Stores the index of the // current position of subarray int pos = 0; // Stores the maximum // length of subarray. int ans = 0; // Maximum element from // each subarray length int mx = 0; // Previous index of the // current subarray of // maximum length int pre = 0; // Deque to store the indices // of maximum element of // each sub array deque<int> q; // For each array element, // find the maximum length of // required subarray for (int i = 0; i < N; i++) { // Traverse the deque and // update the index of // maximum element. while (!q.empty() && arr[q.back()] < arr[i]) q.pop_back(); q.push_back(i); // If it is first element // then update maximum // and dp[] if (i == 0) { mx = arr[i]; dp[i] = arr[i]; } // Else check if current // element exceeds max else if (mx <= arr[i]) { // Update max and dp[] dp[i] = dp[i - 1] + arr[i]; mx = arr[i]; } else { dp[i] = dp[i - 1] + arr[i]; } // Update the index of the // current maximum length // subarray if (pre == 0) pos = 0; else pos = pre - 1; // While current element // being added to dp[] array // exceeds K while ((i - pre + 1) * mx - (dp[i] - dp[pos]) > K && pre < i) { // Update index of // current position and // the previous position pos = pre; pre++; // Remove elements // from deque and // update the // maximum element while (!q.empty() && q.front() < pre && pre < i) { q.pop_front(); mx = arr[q.front()]; } } // Update the maximum length // of the required subarray. ans = max(ans, i - pre + 1); } return ans;} // Driver Programint main(){ int N = 6; int K = 8; int arr[] = { 2, 7, 1, 3, 4, 5 }; cout << validSubArrLength(arr, N, K); return 0;} // Java code for the above approachimport java.util.*; class GFG{ // Function to find maximum// possible length of subarraystatic int validSubArrLength(int arr[], int N, int K){ // Stores the sum of elements // that needs to be added to // the sub array int []dp = new int[N + 1]; // Stores the index of the // current position of subarray int pos = 0; // Stores the maximum // length of subarray. int ans = 0; // Maximum element from // each subarray length int mx = 0; // Previous index of the // current subarray of // maximum length int pre = 0; // Deque to store the indices // of maximum element of // each sub array Deque<Integer> q = new LinkedList<>(); // For each array element, // find the maximum length of // required subarray for(int i = 0; i < N; i++) { // Traverse the deque and // update the index of // maximum element. while (!q.isEmpty() && arr[q.getLast()] < arr[i]) q.removeLast(); q.add(i); // If it is first element // then update maximum // and dp[] if (i == 0) { mx = arr[i]; dp[i] = arr[i]; } // Else check if current // element exceeds max else if (mx <= arr[i]) { // Update max and dp[] dp[i] = dp[i - 1] + arr[i]; mx = arr[i]; } else { dp[i] = dp[i - 1] + arr[i]; } // Update the index of the // current maximum length // subarray if (pre == 0) pos = 0; else pos = pre - 1; // While current element // being added to dp[] array // exceeds K while ((i - pre + 1) * mx - (dp[i] - dp[pos]) > K && pre < i) { // Update index of // current position and // the previous position pos = pre; pre++; // Remove elements from // deque and update the // maximum element while (!q.isEmpty() && q.peek() < pre && pre < i) { q.removeFirst(); mx = arr[q.peek()]; } } // Update the maximum length // of the required subarray. ans = Math.max(ans, i - pre + 1); } return ans;} // Driver codepublic static void main(String[] args){ int N = 6; int K = 8; int arr[] = { 2, 7, 1, 3, 4, 5 }; System.out.print(validSubArrLength(arr, N, K));}} // This code is contributed by amal kumar choubey # Python3 code for the above approach # Function to find maximum# possible length of subarraydef validSubArrLength(arr, N, K): # Stores the sum of elements # that needs to be added to # the sub array dp = [0 for i in range(N + 1)] # Stores the index of the # current position of subarray pos = 0 # Stores the maximum # length of subarray. ans = 0 # Maximum element from # each subarray length mx = 0 # Previous index of the # current subarray of # maximum length pre = 0 # Deque to store the indices # of maximum element of # each sub array q = [] # For each array element, # find the maximum length of # required subarray for i in range(N): # Traverse the deque and # update the index of # maximum element. while (len(q) and arr[len(q) - 1] < arr[i]): q.remove(q[len(q) - 1]) q.append(i) # If it is first element # then update maximum # and dp[] if (i == 0): mx = arr[i] dp[i] = arr[i] # Else check if current # element exceeds max elif (mx <= arr[i]): # Update max and dp[] dp[i] = dp[i - 1] + arr[i] mx = arr[i] else: dp[i] = dp[i - 1] + arr[i] # Update the index of the # current maximum length # subarray if (pre == 0): pos = 0 else: pos = pre - 1 # While current element # being added to dp[] array # exceeds K while ((i - pre + 1) * mx - (dp[i] - dp[pos]) > K and pre < i): # Update index of # current position and # the previous position pos = pre pre += 1 # Remove elements # from deque and # update the # maximum element while (len(q) and q[0] < pre and pre < i): q.remove(q[0]) mx = arr[q[0]] # Update the maximum length # of the required subarray. ans = max(ans, i - pre + 1) return ans # Driver codeif __name__ == '__main__': N = 6 K = 8 arr = [ 2, 7, 1, 3, 4, 5 ] print(validSubArrLength(arr, N, K)) # This code is contributed by ipg2016107 <script> // Javascript code for the above approach // Function to find maximum// possible length of subarrayfunction validSubArrLength(arr, N, K){ // Stores the sum of elements // that needs to be added to // the sub array var dp = Array(N+1); // Stores the index of the // current position of subarray var pos = 0; // Stores the maximum // length of subarray. var ans = 0; // Maximum element from // each subarray length var mx = 0; // Previous index of the // current subarray of // maximum length var pre = 0; // Deque to store the indices // of maximum element of // each sub array var q = []; // For each array element, // find the maximum length of // required subarray for (var i = 0; i < N; i++) { // Traverse the deque and // update the index of // maximum element. while (q.length!=0 && arr[q[q.length-1]] < arr[i]) q.pop(); q.push(i); // If it is first element // then update maximum // and dp[] if (i == 0) { mx = arr[i]; dp[i] = arr[i]; } // Else check if current // element exceeds max else if (mx <= arr[i]) { // Update max and dp[] dp[i] = dp[i - 1] + arr[i]; mx = arr[i]; } else { dp[i] = dp[i - 1] + arr[i]; } // Update the index of the // current maximum length // subarray if (pre == 0) pos = 0; else pos = pre - 1; // While current element // being added to dp[] array // exceeds K while ((i - pre + 1) * mx - (dp[i] - dp[pos]) > K && pre < i) { // Update index of // current position and // the previous position pos = pre; pre++; // Remove elements // from deque and // update the // maximum element while (q.length!=0 && q[0] < pre && pre < i) { q.shift(); mx = arr[q[0]]; } } // Update the maximum length // of the required subarray. ans = Math.max(ans, i - pre + 1); } return ans;} // Driver Programvar N = 6;var K = 8;var arr = [2, 7, 1, 3, 4, 5];document.write( validSubArrLength(arr, N, K)); </script> // C# program to implement above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to find maximum // possible length of subarray static int validSubArrLength(int[] arr, int N, int K) { // Stores the sum of elements // that needs to be added to // the sub array int[] dp = new int[N + 1]; // Stores the index of the // current position of subarray int pos = 0; // Stores the maximum // length of subarray. int ans = 0; // Maximum element from // each subarray length int mx = 0; // Previous index of the // current subarray of // maximum length int pre = 0; // Deque to store the indices // of maximum element of // each sub array List<int> q = new List<int>(); // For each array element, // find the maximum length of // required subarray for(int i = 0 ; i < N ; i++) { // Traverse the deque and // update the index of // maximum element. while (q.Count > 0 && arr[q[q.Count - 1]] < arr[i]){ q.RemoveAt(q.Count - 1); } q.Add(i); // If it is first element // then update maximum // and dp[] if (i == 0) { mx = arr[i]; dp[i] = arr[i]; } // Else check if current // element exceeds max else if (mx <= arr[i]) { // Update max and dp[] dp[i] = dp[i - 1] + arr[i]; mx = arr[i]; } else { dp[i] = dp[i - 1] + arr[i]; } // Update the index of the // current maximum length // subarray if (pre == 0) pos = 0; else pos = pre - 1; // While current element // being added to dp[] array // exceeds K while ((i - pre + 1) * mx - (dp[i] - dp[pos]) > K && pre < i) { // Update index of // current position and // the previous position pos = pre; pre++; // Remove elements from // deque and update the // maximum element while (q.Count > 0 && q[0] < pre && pre < i) { q.RemoveAt(0); mx = arr[q[0]]; } } // Update the maximum length // of the required subarray. ans = Math.Max(ans, i - pre + 1); } return ans; } // Driver code public static void Main(string[] args){ int N = 6; int K = 8; int[] arr = new int[]{ 2, 7, 1, 3, 4, 5 }; Console.WriteLine(validSubArrLength(arr, N, K)); }} 4 Time Complexity: O(N2) Auxiliary Space Complexity: O(N) Amal Kumar Choubey nidhi_biet ipg2016107 importantly subhamgoyal2014 subarray Algorithms Arrays Competitive Programming Data Structures Dynamic Programming Queue Data Structures Arrays Dynamic Programming Queue Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 337, "s": 52, "text": "Given an array arr[] of positive integers of size N and a positive integer K, the task is to find the maximum possible length of a subarray which can be made equal by adding some integer value to each element of the sub-array such that the sum of the added elements does not exceed K." }, { "code": null, "e": 348, "s": 337, "text": "Examples: " }, { "code": null, "e": 586, "s": 348, "text": "Input: N = 5, arr[] = {1, 4, 9, 3, 6}, K = 9 Output: 3 Explanation: {1, 4} : {1+3, 4} = {4, 4} {4, 9} : {4+5, 9} = {9, 9} {3, 6} : {3+3, 6} = {6, 6} {9, 3, 6} : {9, 3+6, 6+3} = {9, 9, 9} Hence, the maximum length of such a subarray is 3." }, { "code": null, "e": 646, "s": 586, "text": "Input: N = 6, arr[] = {2, 4, 7, 3, 8, 5}, K = 10 Output: 4 " }, { "code": null, "e": 714, "s": 646, "text": "Approach: This problem can be solved by using dynamic programming. " }, { "code": null, "e": 1022, "s": 714, "text": "Initialize: dp[]: Stores the sum of elements that are added to the subarray.deque: Stores the indices of the maximum element for each subarray.pos: Index of the current position of the subarray.ans: Length of the maximum subarray.mx: Maximum element of a subarraypre: Previous index of the current subarray." }, { "code": null, "e": 1087, "s": 1022, "text": "dp[]: Stores the sum of elements that are added to the subarray." }, { "code": null, "e": 1155, "s": 1087, "text": "deque: Stores the indices of the maximum element for each subarray." }, { "code": null, "e": 1207, "s": 1155, "text": "pos: Index of the current position of the subarray." }, { "code": null, "e": 1244, "s": 1207, "text": "ans: Length of the maximum subarray." }, { "code": null, "e": 1278, "s": 1244, "text": "mx: Maximum element of a subarray" }, { "code": null, "e": 1323, "s": 1278, "text": "pre: Previous index of the current subarray." }, { "code": null, "e": 1498, "s": 1323, "text": "Traverse the array and check if the deque is empty or not. If yes, then update the maximum element and the index of the maximum element along with the indices of pre and pos." }, { "code": null, "e": 1632, "s": 1498, "text": "Check if the currently added element is greater than K. If yes, then remove it from dp[] array and update the indices of pos and pre." }, { "code": null, "e": 1691, "s": 1632, "text": "Finally, update the maximum length of the valid sub-array." }, { "code": null, "e": 1743, "s": 1691, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1747, "s": 1743, "text": "C++" }, { "code": null, "e": 1752, "s": 1747, "text": "Java" }, { "code": null, "e": 1760, "s": 1752, "text": "Python3" }, { "code": null, "e": 1771, "s": 1760, "text": "Javascript" }, { "code": null, "e": 1774, "s": 1771, "text": "C#" }, { "code": "// C++ code for the above approach #include <bits/stdc++.h>using namespace std; // Function to find maximum// possible length of subarrayint validSubArrLength(int arr[], int N, int K){ // Stores the sum of elements // that needs to be added to // the sub array int dp[N + 1]; // Stores the index of the // current position of subarray int pos = 0; // Stores the maximum // length of subarray. int ans = 0; // Maximum element from // each subarray length int mx = 0; // Previous index of the // current subarray of // maximum length int pre = 0; // Deque to store the indices // of maximum element of // each sub array deque<int> q; // For each array element, // find the maximum length of // required subarray for (int i = 0; i < N; i++) { // Traverse the deque and // update the index of // maximum element. while (!q.empty() && arr[q.back()] < arr[i]) q.pop_back(); q.push_back(i); // If it is first element // then update maximum // and dp[] if (i == 0) { mx = arr[i]; dp[i] = arr[i]; } // Else check if current // element exceeds max else if (mx <= arr[i]) { // Update max and dp[] dp[i] = dp[i - 1] + arr[i]; mx = arr[i]; } else { dp[i] = dp[i - 1] + arr[i]; } // Update the index of the // current maximum length // subarray if (pre == 0) pos = 0; else pos = pre - 1; // While current element // being added to dp[] array // exceeds K while ((i - pre + 1) * mx - (dp[i] - dp[pos]) > K && pre < i) { // Update index of // current position and // the previous position pos = pre; pre++; // Remove elements // from deque and // update the // maximum element while (!q.empty() && q.front() < pre && pre < i) { q.pop_front(); mx = arr[q.front()]; } } // Update the maximum length // of the required subarray. ans = max(ans, i - pre + 1); } return ans;} // Driver Programint main(){ int N = 6; int K = 8; int arr[] = { 2, 7, 1, 3, 4, 5 }; cout << validSubArrLength(arr, N, K); return 0;}", "e": 4353, "s": 1774, "text": null }, { "code": "// Java code for the above approachimport java.util.*; class GFG{ // Function to find maximum// possible length of subarraystatic int validSubArrLength(int arr[], int N, int K){ // Stores the sum of elements // that needs to be added to // the sub array int []dp = new int[N + 1]; // Stores the index of the // current position of subarray int pos = 0; // Stores the maximum // length of subarray. int ans = 0; // Maximum element from // each subarray length int mx = 0; // Previous index of the // current subarray of // maximum length int pre = 0; // Deque to store the indices // of maximum element of // each sub array Deque<Integer> q = new LinkedList<>(); // For each array element, // find the maximum length of // required subarray for(int i = 0; i < N; i++) { // Traverse the deque and // update the index of // maximum element. while (!q.isEmpty() && arr[q.getLast()] < arr[i]) q.removeLast(); q.add(i); // If it is first element // then update maximum // and dp[] if (i == 0) { mx = arr[i]; dp[i] = arr[i]; } // Else check if current // element exceeds max else if (mx <= arr[i]) { // Update max and dp[] dp[i] = dp[i - 1] + arr[i]; mx = arr[i]; } else { dp[i] = dp[i - 1] + arr[i]; } // Update the index of the // current maximum length // subarray if (pre == 0) pos = 0; else pos = pre - 1; // While current element // being added to dp[] array // exceeds K while ((i - pre + 1) * mx - (dp[i] - dp[pos]) > K && pre < i) { // Update index of // current position and // the previous position pos = pre; pre++; // Remove elements from // deque and update the // maximum element while (!q.isEmpty() && q.peek() < pre && pre < i) { q.removeFirst(); mx = arr[q.peek()]; } } // Update the maximum length // of the required subarray. ans = Math.max(ans, i - pre + 1); } return ans;} // Driver codepublic static void main(String[] args){ int N = 6; int K = 8; int arr[] = { 2, 7, 1, 3, 4, 5 }; System.out.print(validSubArrLength(arr, N, K));}} // This code is contributed by amal kumar choubey", "e": 7038, "s": 4353, "text": null }, { "code": "# Python3 code for the above approach # Function to find maximum# possible length of subarraydef validSubArrLength(arr, N, K): # Stores the sum of elements # that needs to be added to # the sub array dp = [0 for i in range(N + 1)] # Stores the index of the # current position of subarray pos = 0 # Stores the maximum # length of subarray. ans = 0 # Maximum element from # each subarray length mx = 0 # Previous index of the # current subarray of # maximum length pre = 0 # Deque to store the indices # of maximum element of # each sub array q = [] # For each array element, # find the maximum length of # required subarray for i in range(N): # Traverse the deque and # update the index of # maximum element. while (len(q) and arr[len(q) - 1] < arr[i]): q.remove(q[len(q) - 1]) q.append(i) # If it is first element # then update maximum # and dp[] if (i == 0): mx = arr[i] dp[i] = arr[i] # Else check if current # element exceeds max elif (mx <= arr[i]): # Update max and dp[] dp[i] = dp[i - 1] + arr[i] mx = arr[i] else: dp[i] = dp[i - 1] + arr[i] # Update the index of the # current maximum length # subarray if (pre == 0): pos = 0 else: pos = pre - 1 # While current element # being added to dp[] array # exceeds K while ((i - pre + 1) * mx - (dp[i] - dp[pos]) > K and pre < i): # Update index of # current position and # the previous position pos = pre pre += 1 # Remove elements # from deque and # update the # maximum element while (len(q) and q[0] < pre and pre < i): q.remove(q[0]) mx = arr[q[0]] # Update the maximum length # of the required subarray. ans = max(ans, i - pre + 1) return ans # Driver codeif __name__ == '__main__': N = 6 K = 8 arr = [ 2, 7, 1, 3, 4, 5 ] print(validSubArrLength(arr, N, K)) # This code is contributed by ipg2016107", "e": 9445, "s": 7038, "text": null }, { "code": "<script> // Javascript code for the above approach // Function to find maximum// possible length of subarrayfunction validSubArrLength(arr, N, K){ // Stores the sum of elements // that needs to be added to // the sub array var dp = Array(N+1); // Stores the index of the // current position of subarray var pos = 0; // Stores the maximum // length of subarray. var ans = 0; // Maximum element from // each subarray length var mx = 0; // Previous index of the // current subarray of // maximum length var pre = 0; // Deque to store the indices // of maximum element of // each sub array var q = []; // For each array element, // find the maximum length of // required subarray for (var i = 0; i < N; i++) { // Traverse the deque and // update the index of // maximum element. while (q.length!=0 && arr[q[q.length-1]] < arr[i]) q.pop(); q.push(i); // If it is first element // then update maximum // and dp[] if (i == 0) { mx = arr[i]; dp[i] = arr[i]; } // Else check if current // element exceeds max else if (mx <= arr[i]) { // Update max and dp[] dp[i] = dp[i - 1] + arr[i]; mx = arr[i]; } else { dp[i] = dp[i - 1] + arr[i]; } // Update the index of the // current maximum length // subarray if (pre == 0) pos = 0; else pos = pre - 1; // While current element // being added to dp[] array // exceeds K while ((i - pre + 1) * mx - (dp[i] - dp[pos]) > K && pre < i) { // Update index of // current position and // the previous position pos = pre; pre++; // Remove elements // from deque and // update the // maximum element while (q.length!=0 && q[0] < pre && pre < i) { q.shift(); mx = arr[q[0]]; } } // Update the maximum length // of the required subarray. ans = Math.max(ans, i - pre + 1); } return ans;} // Driver Programvar N = 6;var K = 8;var arr = [2, 7, 1, 3, 4, 5];document.write( validSubArrLength(arr, N, K)); </script>", "e": 11932, "s": 9445, "text": null }, { "code": "// C# program to implement above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to find maximum // possible length of subarray static int validSubArrLength(int[] arr, int N, int K) { // Stores the sum of elements // that needs to be added to // the sub array int[] dp = new int[N + 1]; // Stores the index of the // current position of subarray int pos = 0; // Stores the maximum // length of subarray. int ans = 0; // Maximum element from // each subarray length int mx = 0; // Previous index of the // current subarray of // maximum length int pre = 0; // Deque to store the indices // of maximum element of // each sub array List<int> q = new List<int>(); // For each array element, // find the maximum length of // required subarray for(int i = 0 ; i < N ; i++) { // Traverse the deque and // update the index of // maximum element. while (q.Count > 0 && arr[q[q.Count - 1]] < arr[i]){ q.RemoveAt(q.Count - 1); } q.Add(i); // If it is first element // then update maximum // and dp[] if (i == 0) { mx = arr[i]; dp[i] = arr[i]; } // Else check if current // element exceeds max else if (mx <= arr[i]) { // Update max and dp[] dp[i] = dp[i - 1] + arr[i]; mx = arr[i]; } else { dp[i] = dp[i - 1] + arr[i]; } // Update the index of the // current maximum length // subarray if (pre == 0) pos = 0; else pos = pre - 1; // While current element // being added to dp[] array // exceeds K while ((i - pre + 1) * mx - (dp[i] - dp[pos]) > K && pre < i) { // Update index of // current position and // the previous position pos = pre; pre++; // Remove elements from // deque and update the // maximum element while (q.Count > 0 && q[0] < pre && pre < i) { q.RemoveAt(0); mx = arr[q[0]]; } } // Update the maximum length // of the required subarray. ans = Math.Max(ans, i - pre + 1); } return ans; } // Driver code public static void Main(string[] args){ int N = 6; int K = 8; int[] arr = new int[]{ 2, 7, 1, 3, 4, 5 }; Console.WriteLine(validSubArrLength(arr, N, K)); }}", "e": 15091, "s": 11932, "text": null }, { "code": null, "e": 15093, "s": 15091, "text": "4" }, { "code": null, "e": 15153, "s": 15095, "text": "Time Complexity: O(N2) Auxiliary Space Complexity: O(N) " }, { "code": null, "e": 15172, "s": 15153, "text": "Amal Kumar Choubey" }, { "code": null, "e": 15183, "s": 15172, "text": "nidhi_biet" }, { "code": null, "e": 15194, "s": 15183, "text": "ipg2016107" }, { "code": null, "e": 15206, "s": 15194, "text": "importantly" }, { "code": null, "e": 15222, "s": 15206, "text": "subhamgoyal2014" }, { "code": null, "e": 15231, "s": 15222, "text": "subarray" }, { "code": null, "e": 15242, "s": 15231, "text": "Algorithms" }, { "code": null, "e": 15249, "s": 15242, "text": "Arrays" }, { "code": null, "e": 15273, "s": 15249, "text": "Competitive Programming" }, { "code": null, "e": 15289, "s": 15273, "text": "Data Structures" }, { "code": null, "e": 15309, "s": 15289, "text": "Dynamic Programming" }, { "code": null, "e": 15315, "s": 15309, "text": "Queue" }, { "code": null, "e": 15331, "s": 15315, "text": "Data Structures" }, { "code": null, "e": 15338, "s": 15331, "text": "Arrays" }, { "code": null, "e": 15358, "s": 15338, "text": "Dynamic Programming" }, { "code": null, "e": 15364, "s": 15358, "text": "Queue" }, { "code": null, "e": 15375, "s": 15364, "text": "Algorithms" } ]
C++ Switch Case Statement | Practice | GeeksforGeeks
Given a number N, if the number is between 1 and 10 both inclusive then return the number in words (Lower case English Alphabets) otherwise return "not in range". Example 1: Input: 5 Output: five Example 2: Input: 11 Output: not in range Your Task: You don't need to read input or print anything. Your task is to complete the function isInRange() which takes an integer and if the number is between 1 and 10 both inclusive then return the number in words otherwise return "not in range". Expected Time Complexity: O(1) Expected Auxiliary Space: O(1) Constraints: 1<=N<=10000 0 yaminishegajqd73 hours ago switch(N){ case 1:{ cout<<"one"; break; } case 2:{ cout<<"Two"; break; } case 3:{ cout<<"Three"; break; } case 4:{ cout<<"Four"; break; } case 5:{ cout<<"Five"; break; } case 6:{ cout<<"Six"; break; } case 7:{ cout<<"Seven"; break; } case 8:{ cout<<"Eight"; break; } case 9:{ cout<<"Nine"; break; } case 10:{ cout<<"Ten"; break; } default:{ cout<<"not in range"; break; } } }}; 0 analgesik117 hours ago switch(N) { case 1: cout<<"one"; break; case 2: cout<<"two"; break; case 3: cout<<"three"; break; case 4: cout<<"four"; break; case 5: cout<<"five"; break; case 6: cout<<"six"; break; case 7: cout<<"seven"; break; case 8: cout<<"eight"; break; case 9: cout<<"nine"; break; case 10: cout<<"ten"; break; default : cout<<"not in range"; break; } 0 singh112002muskan6 days ago class Solution{ public: string isInRange(int N){ // code here switch(N) { case 1: cout<<"one"; break; case 2: cout<<"two"; break; case 3: cout<< "three"; break; case 4: cout<< "four"; break; case 5: cout<<"five"; break; case 6: cout<<"six"; break; case 7: cout<<"seven"; break; case 8: cout<<"eight"; break; case 9: cout<<"nine"; break; case 10: cout<<"ten"; break; default: cout<<"not in range"; } 0 pranjalrasq3sa1 week ago ---------c++------------------ #include <iostream> using namespace std; int main() { int a; cout << "enter a number" << endl; cin >> a; switch (a) { case 1: cout << "one" << endl; break; case 2: cout << "two" << endl; break; case 3: cout << "three" << endl; break; case 4: cout << "four" << endl; break; case 5: cout << "five" << endl; break; case 6: cout << "six" << endl; break; case 7: cout << "seven" << endl; break; case 8: cout << "eight" << endl; break; case 9: cout << "nine" << endl; break; case 10: cout << "ten" << endl; break; default: cout << "not in range" << endl; } } 0 prashant123singh1233 weeks ago ***********NEED HELP************ ************C++*************** string isInRange(int N){ // code here string a[] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}; if(N>0 && N<=10){ return a[N-1]; } else cout<<"not in range"; } for 33rd test case i.e, 47 it is giving wrong output but when I give 47 as custom input it's giving correct answer. WHY? 0 rumi1w8ry3 weeks ago class Solution: def isInRange (ob,N): # code here switcher = { 1 : "one", 2 : "two", 3 : "three", 4 : "four", 5 : "five", 6 : "six", 7 : "seven", 8 : "eight", 9 : "nine", 10 : "ten", } return switcher.get(N, "not in range") 0 adityashrivastava29032 months ago //Program for the same output but easier and less messy. #include<iostream> using namespace std; int main(){string a[] = {"one", "two", "three", "four", "five", "six", "seven", "eight", “nine”, “ten”}; int n;cin>>n; if(n>10){ cout<<"Not in range!"; } cout<<a[n-1]; } 0 avicode4243 months ago class Solution{ static String isInRange(int N){ // code here String str = ""; switch(N) { case 1: str = "one"; break; case 2: str = "two"; break; case 3: str = "three"; break; case 4: str = "four"; break; case 5: str = "five"; break; case 6: str = "six"; break; case 7: str = "seven"; break; case 8: str = "eight"; break; case 9: str = "nine"; break; case 10: str = "ten"; break; default: str = "not in range"; } return str; }} 0 anushavennapoosa20023 months ago // JAVA SOLUTION class Solution{ static String isInRange(int N){ // code here switch(N){ case 1: return "one"; case 2: return "two"; case 3: return "three"; case 4: return "four"; case 5: return "five"; case 6: return "six"; case 7: return "seven"; case 8: return "eight"; case 9: return "nine"; case 10: return "ten"; default: return "not in range"; } }} 0 shorouqehab0763 months ago #include<iostream> using namespace std;int main(){ int x; cin >> x; switch (x) { case 1: cout << "one"; break; case 2: cout << "two"; break; case 3: cout << "three"; break; case 4: cout << "four"; break; case 5: cout << "five"; break; case 6: cout << "six"; break; case 7: cout << "seven"; break; case 8: cout << "eight"; break; case 9: cout << "nine"; break; case 10: cout << "ten"; break; default: cout << "not in range"; } return 0;} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 401, "s": 238, "text": "Given a number N, if the number is between 1 and 10 both inclusive then return the number in words (Lower case English Alphabets) otherwise return \"not in range\"." }, { "code": null, "e": 414, "s": 403, "text": "Example 1:" }, { "code": null, "e": 436, "s": 414, "text": "Input:\n5\nOutput:\nfive" }, { "code": null, "e": 449, "s": 438, "text": "Example 2:" }, { "code": null, "e": 480, "s": 449, "text": "Input:\n11\nOutput:\nnot in range" }, { "code": null, "e": 495, "s": 484, "text": "Your Task:" }, { "code": null, "e": 734, "s": 495, "text": "You don't need to read input or print anything. Your task is to complete the function isInRange() which takes an integer and if the number is between 1 and 10 both inclusive then return the number in words otherwise return \"not in range\"." }, { "code": null, "e": 798, "s": 736, "text": "Expected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 812, "s": 798, "text": "\nConstraints:" }, { "code": null, "e": 824, "s": 812, "text": "1<=N<=10000" }, { "code": null, "e": 828, "s": 826, "text": "0" }, { "code": null, "e": 855, "s": 828, "text": "yaminishegajqd73 hours ago" }, { "code": null, "e": 1726, "s": 855, "text": " switch(N){ case 1:{ cout<<\"one\"; break; } case 2:{ cout<<\"Two\"; break; } case 3:{ cout<<\"Three\"; break; } case 4:{ cout<<\"Four\"; break; } case 5:{ cout<<\"Five\"; break; } case 6:{ cout<<\"Six\"; break; } case 7:{ cout<<\"Seven\"; break; } case 8:{ cout<<\"Eight\"; break; } case 9:{ cout<<\"Nine\"; break; } case 10:{ cout<<\"Ten\"; break; } default:{ cout<<\"not in range\";" }, { "code": null, "e": 1792, "s": 1726, "text": " break; } } }};" }, { "code": null, "e": 1794, "s": 1792, "text": "0" }, { "code": null, "e": 1817, "s": 1794, "text": "analgesik117 hours ago" }, { "code": null, "e": 2289, "s": 1817, "text": "switch(N) { case 1: cout<<\"one\"; break; case 2: cout<<\"two\"; break; case 3: cout<<\"three\"; break; case 4: cout<<\"four\"; break; case 5: cout<<\"five\"; break; case 6: cout<<\"six\"; break; case 7: cout<<\"seven\"; break; case 8: cout<<\"eight\"; break; case 9: cout<<\"nine\"; break; case 10: cout<<\"ten\"; break; default : cout<<\"not in range\"; break; }" }, { "code": null, "e": 2291, "s": 2289, "text": "0" }, { "code": null, "e": 2319, "s": 2291, "text": "singh112002muskan6 days ago" }, { "code": null, "e": 2391, "s": 2319, "text": "class Solution{ public: string isInRange(int N){ // code here" }, { "code": null, "e": 2996, "s": 2391, "text": " switch(N) { case 1: cout<<\"one\"; break; case 2: cout<<\"two\"; break; case 3: cout<< \"three\"; break; case 4: cout<< \"four\"; break; case 5: cout<<\"five\"; break; case 6: cout<<\"six\"; break; case 7: cout<<\"seven\"; break; case 8: cout<<\"eight\"; break; case 9: cout<<\"nine\"; break;" }, { "code": null, "e": 3126, "s": 2996, "text": " case 10: cout<<\"ten\"; break; default: cout<<\"not in range\"; } " }, { "code": null, "e": 3128, "s": 3126, "text": "0" }, { "code": null, "e": 3153, "s": 3128, "text": "pranjalrasq3sa1 week ago" }, { "code": null, "e": 3184, "s": 3153, "text": "---------c++------------------" }, { "code": null, "e": 3206, "s": 3186, "text": "#include <iostream>" }, { "code": null, "e": 3227, "s": 3206, "text": "using namespace std;" }, { "code": null, "e": 3240, "s": 3229, "text": "int main()" }, { "code": null, "e": 3242, "s": 3240, "text": "{" }, { "code": null, "e": 3251, "s": 3242, "text": " int a;" }, { "code": null, "e": 3287, "s": 3251, "text": " cout << \"enter a number\" << endl;" }, { "code": null, "e": 3299, "s": 3287, "text": " cin >> a;" }, { "code": null, "e": 3312, "s": 3299, "text": " switch (a)" }, { "code": null, "e": 3316, "s": 3312, "text": " {" }, { "code": null, "e": 3326, "s": 3316, "text": " case 1:" }, { "code": null, "e": 3353, "s": 3326, "text": " cout << \"one\" << endl;" }, { "code": null, "e": 3364, "s": 3353, "text": " break;" }, { "code": null, "e": 3380, "s": 3368, "text": " case 2:" }, { "code": null, "e": 3407, "s": 3380, "text": " cout << \"two\" << endl;" }, { "code": null, "e": 3418, "s": 3407, "text": " break;" }, { "code": null, "e": 3430, "s": 3420, "text": " case 3:" }, { "code": null, "e": 3459, "s": 3430, "text": " cout << \"three\" << endl;" }, { "code": null, "e": 3470, "s": 3459, "text": " break;" }, { "code": null, "e": 3484, "s": 3472, "text": " case 4:" }, { "code": null, "e": 3512, "s": 3484, "text": " cout << \"four\" << endl;" }, { "code": null, "e": 3523, "s": 3512, "text": " break;" }, { "code": null, "e": 3539, "s": 3526, "text": " case 5:" }, { "code": null, "e": 3569, "s": 3539, "text": " cout << \"five\" << endl;" }, { "code": null, "e": 3582, "s": 3569, "text": " break;" }, { "code": null, "e": 3596, "s": 3584, "text": " case 6:" }, { "code": null, "e": 3623, "s": 3596, "text": " cout << \"six\" << endl;" }, { "code": null, "e": 3634, "s": 3623, "text": " break;" }, { "code": null, "e": 3651, "s": 3638, "text": " case 7:" }, { "code": null, "e": 3680, "s": 3651, "text": " cout << \"seven\" << endl;" }, { "code": null, "e": 3692, "s": 3680, "text": " break;" }, { "code": null, "e": 3707, "s": 3694, "text": " case 8:" }, { "code": null, "e": 3736, "s": 3707, "text": " cout << \"eight\" << endl;" }, { "code": null, "e": 3747, "s": 3736, "text": " break;" }, { "code": null, "e": 3762, "s": 3749, "text": " case 9:" }, { "code": null, "e": 3790, "s": 3762, "text": " cout << \"nine\" << endl;" }, { "code": null, "e": 3801, "s": 3790, "text": " break;" }, { "code": null, "e": 3816, "s": 3803, "text": " case 10:" }, { "code": null, "e": 3843, "s": 3816, "text": " cout << \"ten\" << endl;" }, { "code": null, "e": 3854, "s": 3843, "text": " break;" }, { "code": null, "e": 3869, "s": 3856, "text": " default:" }, { "code": null, "e": 3905, "s": 3869, "text": " cout << \"not in range\" << endl;" }, { "code": null, "e": 3913, "s": 3909, "text": " }" }, { "code": null, "e": 3915, "s": 3913, "text": "}" }, { "code": null, "e": 3919, "s": 3917, "text": "0" }, { "code": null, "e": 3950, "s": 3919, "text": "prashant123singh1233 weeks ago" }, { "code": null, "e": 3983, "s": 3950, "text": "***********NEED HELP************" }, { "code": null, "e": 4016, "s": 3985, "text": "************C++***************" }, { "code": null, "e": 4267, "s": 4018, "text": "string isInRange(int N){ // code here string a[] = {\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"}; if(N>0 && N<=10){ return a[N-1]; } else cout<<\"not in range\"; }" }, { "code": null, "e": 4390, "s": 4269, "text": "for 33rd test case i.e, 47 it is giving wrong output but when I give 47 as custom input it's giving correct answer. WHY?" }, { "code": null, "e": 4394, "s": 4392, "text": "0" }, { "code": null, "e": 4415, "s": 4394, "text": "rumi1w8ry3 weeks ago" }, { "code": null, "e": 4771, "s": 4415, "text": "class Solution: def isInRange (ob,N): # code here switcher = { 1 : \"one\", 2 : \"two\", 3 : \"three\", 4 : \"four\", 5 : \"five\", 6 : \"six\", 7 : \"seven\", 8 : \"eight\", 9 : \"nine\", 10 : \"ten\", } return switcher.get(N, \"not in range\")" }, { "code": null, "e": 4773, "s": 4771, "text": "0" }, { "code": null, "e": 4807, "s": 4773, "text": "adityashrivastava29032 months ago" }, { "code": null, "e": 4864, "s": 4807, "text": "//Program for the same output but easier and less messy." }, { "code": null, "e": 4885, "s": 4866, "text": "#include<iostream>" }, { "code": null, "e": 4908, "s": 4887, "text": "using namespace std;" }, { "code": null, "e": 5015, "s": 4910, "text": "int main(){string a[] = {\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", “nine”, “ten”};" }, { "code": null, "e": 5029, "s": 5015, "text": "int n;cin>>n;" }, { "code": null, "e": 5041, "s": 5031, "text": "if(n>10){" }, { "code": null, "e": 5064, "s": 5041, "text": "cout<<\"Not in range!\";" }, { "code": null, "e": 5066, "s": 5064, "text": "}" }, { "code": null, "e": 5080, "s": 5066, "text": "cout<<a[n-1];" }, { "code": null, "e": 5082, "s": 5080, "text": "}" }, { "code": null, "e": 5084, "s": 5082, "text": "0" }, { "code": null, "e": 5107, "s": 5084, "text": "avicode4243 months ago" }, { "code": null, "e": 5986, "s": 5107, "text": "class Solution{ static String isInRange(int N){ // code here String str = \"\"; switch(N) { case 1: str = \"one\"; break; case 2: str = \"two\"; break; case 3: str = \"three\"; break; case 4: str = \"four\"; break; case 5: str = \"five\"; break; case 6: str = \"six\"; break; case 7: str = \"seven\"; break; case 8: str = \"eight\"; break; case 9: str = \"nine\"; break; case 10: str = \"ten\"; break; default: str = \"not in range\"; } return str; }}" }, { "code": null, "e": 5988, "s": 5986, "text": "0" }, { "code": null, "e": 6021, "s": 5988, "text": "anushavennapoosa20023 months ago" }, { "code": null, "e": 6038, "s": 6021, "text": "// JAVA SOLUTION" }, { "code": null, "e": 6107, "s": 6038, "text": "class Solution{ static String isInRange(int N){ // code here" }, { "code": null, "e": 6150, "s": 6107, "text": " switch(N){ case 1: return \"one\";" }, { "code": null, "e": 6178, "s": 6150, "text": " case 2: return \"two\";" }, { "code": null, "e": 6208, "s": 6178, "text": " case 3: return \"three\";" }, { "code": null, "e": 6237, "s": 6208, "text": " case 4: return \"four\";" }, { "code": null, "e": 6266, "s": 6237, "text": " case 5: return \"five\";" }, { "code": null, "e": 6294, "s": 6266, "text": " case 6: return \"six\";" }, { "code": null, "e": 6324, "s": 6294, "text": " case 7: return \"seven\";" }, { "code": null, "e": 6354, "s": 6324, "text": " case 8: return \"eight\";" }, { "code": null, "e": 6383, "s": 6354, "text": " case 9: return \"nine\";" }, { "code": null, "e": 6412, "s": 6383, "text": " case 10: return \"ten\";" }, { "code": null, "e": 6453, "s": 6412, "text": " default: return \"not in range\"; }" }, { "code": null, "e": 6459, "s": 6453, "text": " }}" }, { "code": null, "e": 6461, "s": 6459, "text": "0" }, { "code": null, "e": 6488, "s": 6461, "text": "shorouqehab0763 months ago" }, { "code": null, "e": 6507, "s": 6488, "text": "#include<iostream>" }, { "code": null, "e": 7037, "s": 6507, "text": "using namespace std;int main(){ int x; cin >> x; switch (x) { case 1: cout << \"one\"; break; case 2: cout << \"two\"; break; case 3: cout << \"three\"; break; case 4: cout << \"four\"; break; case 5: cout << \"five\"; break; case 6: cout << \"six\"; break; case 7: cout << \"seven\"; break; case 8: cout << \"eight\"; break; case 9: cout << \"nine\"; break; case 10: cout << \"ten\"; break; default: cout << \"not in range\"; } return 0;}" }, { "code": null, "e": 7183, "s": 7037, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 7219, "s": 7183, "text": " Login to access your submissions. " }, { "code": null, "e": 7229, "s": 7219, "text": "\nProblem\n" }, { "code": null, "e": 7239, "s": 7229, "text": "\nContest\n" }, { "code": null, "e": 7302, "s": 7239, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7487, "s": 7302, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7771, "s": 7487, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 7917, "s": 7771, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 7994, "s": 7917, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 8035, "s": 7994, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 8063, "s": 8035, "text": "Disable browser extensions." }, { "code": null, "e": 8134, "s": 8063, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 8321, "s": 8134, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
HTML Cleaning and Entity Conversion | Python
02 Aug, 2019 The very important and always ignored task on web is the cleaning of text. Whenever one thinks to parse HTML, embedded Javascript and CSS is always avoided. The users are only interested in tags and text present on the webserver. lxml installation –It is a Python binding for C libraries – libxslt and libxml2. So maintaining a Python base, it is very fast HTML parsing and XML library. To let it work – C libraries also need to be installed. The link – http://lxml.de/installation.html will provide all the installation instructions. sudo apt-get install python-lxml or pip install lxml Cleaning task is performed using clean_html() function present in the lxml.html.clean module. This function removes the unnecessary HTML tags. In the code below, clean_html() function in the lxml.html.clean module is used to remove unnecessary HTML tags and embedded JavaScript from an HTML string. import lxml.html.cleanlxml.html.clean.clean_html('<html><head></head> <bodyonload = loadfunc()>my text</body></html>') Output : '<div><body>my text</body></div>' As you can see that the results are much easier and cleaner. Thus, makes our job easy to deal with the HTML. The lxml.html.clean_html() function iterates over the string as it parses the HTML string into a tree. It then removes all nodes that don’t hold much importance. Using embedded JavaScript, the function also cleans nodes of unnecessary attributes like embedded JavaScript using regex (regular expression) substitution and matching. This function defines a default Cleaner class that’s used clean_html() method is called. By creating self instance, the class behavior can be customized. Strings such as “&” or “<” are HTML entities. These are normal ASCII character encoding having special uses in HTML. “<” is the entity for “<" because "<" is present within HTML tags and it is the beginning character for an HTML tag. So, to escape it "<" entity is defined. "&" is entity code for "&".To process the text within an HTML document, convert these entities back to their normal characters so as to recognize them and use them appropriately. Requirement :1) install BeautifulSoup2) sudo easy_install beautifulsoup4 or sudo pip install beautifulsoup4 It is an HTML parser library used for entity conversion. It simply creates an instance of BeautifulSoup given a string containing HTML entities. And then it retrieves the string attribute: Code – # importing BeautifulSoupfrom bs4 import BeautifulSoup print (BeautifulSoup('<').string) print (BeautifulSoup('&').string) Output : '<' '&' But the reverse for it is not possible i.e. for ‘<' in BeautifulSoup, a None result is obtained as it is invalid in HTML. BeautifulSoup looks for tokens that look similar to an entity and in order to convert the HTML entities, it replaces them with their corresponding value in the htmlentitydefs.name2codepoint dictionary which is there in the python standard library. Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Aug, 2019" }, { "code": null, "e": 258, "s": 28, "text": "The very important and always ignored task on web is the cleaning of text. Whenever one thinks to parse HTML, embedded Javascript and CSS is always avoided. The users are only interested in tags and text present on the webserver." }, { "code": null, "e": 563, "s": 258, "text": "lxml installation –It is a Python binding for C libraries – libxslt and libxml2. So maintaining a Python base, it is very fast HTML parsing and XML library. To let it work – C libraries also need to be installed. The link – http://lxml.de/installation.html will provide all the installation instructions." }, { "code": null, "e": 616, "s": 563, "text": "sudo apt-get install python-lxml or\npip install lxml" }, { "code": null, "e": 915, "s": 616, "text": "Cleaning task is performed using clean_html() function present in the lxml.html.clean module. This function removes the unnecessary HTML tags. In the code below, clean_html() function in the lxml.html.clean module is used to remove unnecessary HTML tags and embedded JavaScript from an HTML string." }, { "code": "import lxml.html.cleanlxml.html.clean.clean_html('<html><head></head> <bodyonload = loadfunc()>my text</body></html>')", "e": 1060, "s": 915, "text": null }, { "code": null, "e": 1069, "s": 1060, "text": "Output :" }, { "code": null, "e": 1104, "s": 1069, "text": "'<div><body>my text</body></div>'\n" }, { "code": null, "e": 1213, "s": 1104, "text": "As you can see that the results are much easier and cleaner. Thus, makes our job easy to deal with the HTML." }, { "code": null, "e": 1698, "s": 1213, "text": "The lxml.html.clean_html() function iterates over the string as it parses the HTML string into a tree. It then removes all nodes that don’t hold much importance. Using embedded JavaScript, the function also cleans nodes of unnecessary attributes like embedded JavaScript using regex (regular expression) substitution and matching. This function defines a default Cleaner class that’s used clean_html() method is called. By creating self instance, the class behavior can be customized." }, { "code": null, "e": 2151, "s": 1698, "text": "Strings such as “&” or “<” are HTML entities. These are normal ASCII character encoding having special uses in HTML. “<” is the entity for “<\" because \"<\" is present within HTML tags and it is the beginning character for an HTML tag. So, to escape it \"<\" entity is defined. \"&\" is entity code for \"&\".To process the text within an HTML document, convert these entities back to their normal characters so as to recognize them and use them appropriately." }, { "code": null, "e": 2259, "s": 2151, "text": "Requirement :1) install BeautifulSoup2) sudo easy_install beautifulsoup4 or sudo pip install beautifulsoup4" }, { "code": null, "e": 2448, "s": 2259, "text": "It is an HTML parser library used for entity conversion. It simply creates an instance of BeautifulSoup given a string containing HTML entities. And then it retrieves the string attribute:" }, { "code": null, "e": 2455, "s": 2448, "text": "Code –" }, { "code": "# importing BeautifulSoupfrom bs4 import BeautifulSoup print (BeautifulSoup('<').string) print (BeautifulSoup('&').string)", "e": 2580, "s": 2455, "text": null }, { "code": null, "e": 2589, "s": 2580, "text": "Output :" }, { "code": null, "e": 2598, "s": 2589, "text": "'<'\n'&'\n" }, { "code": null, "e": 2968, "s": 2598, "text": "But the reverse for it is not possible i.e. for ‘<' in BeautifulSoup, a None result is obtained as it is invalid in HTML. BeautifulSoup looks for tokens that look similar to an entity and in order to convert the HTML entities, it replaces them with their corresponding value in the htmlentitydefs.name2codepoint dictionary which is there in the python standard library." }, { "code": null, "e": 2975, "s": 2968, "text": "Python" }, { "code": null, "e": 3073, "s": 2975, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3105, "s": 3073, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3132, "s": 3105, "text": "Python Classes and Objects" }, { "code": null, "e": 3153, "s": 3132, "text": "Python OOPs Concepts" }, { "code": null, "e": 3176, "s": 3153, "text": "Introduction To PYTHON" }, { "code": null, "e": 3207, "s": 3176, "text": "Python | os.path.join() method" }, { "code": null, "e": 3263, "s": 3207, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3305, "s": 3263, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3347, "s": 3305, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3386, "s": 3347, "text": "Python | Get unique values from a list" } ]
Python – Interleave two lists of different length
16 May, 2021 Given two lists of different lengths, the task is to write a Python program to get their elements alternatively and repeat the list elements of the smaller list till the larger list elements get exhausted. Examples: Input : test_list1 = [‘a’, ‘b’, ‘c’], test_list2 = [5, 7, 3, 0, 1, 8, 4] Output : [‘a’, 5, ‘b’, 7, ‘c’, 3, ‘a’, 0, ‘b’, 1, ‘c’, 8, ‘a’, 4] Explanation : Alternate elements from 1st list are printed in cyclic manner once it gets exhausted. Then after exhaustion, again 1st list starts from ‘a’, with elements left in 2nd list. Input : test_list1 = [3, 8, 7], test_list2 = [5, 7, 3, 0, 1, 8] Output : [3, 5, 8, 7, 7, 3, 3, 0, 8, 1, 7, 8] Explanation : Alternate elements from 1st list are printed in cyclic manner once it gets exhausted. 3, 5, 8, 7, 7, 3.. Then after exhaustion, again 1st list starts from 3, with elements left in 2nd list Method #1 : Using zip() + cycle() + list comprehension In this, repetition of elements in smaller list is handled using cycle(), joining is done using zip(). List comprehension performs task of interleaving simultaneously. Python3 # Python3 code to demonstrate working of# Repetitive Interleave 2 lists# Using zip() + cycle() + list comprehension from itertools import cycle # initializing liststest_list1 = list('abc')test_list2 = [5, 7, 3, 0, 1, 8, 4] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # zip() combining list, after Repetitiveness using cycle()res = [ele for comb in zip(cycle(test_list1), test_list2) for ele in comb] # printing resultprint("The interleaved list : " + str(res)) Output: The original list 1 is : [‘a’, ‘b’, ‘c’] The original list 2 is : [5, 7, 3, 0, 1, 8, 4] The interleaved list : [‘a’, 5, ‘b’, 7, ‘c’, 3, ‘a’, 0, ‘b’, 1, ‘c’, 8, ‘a’, 4] Method #2 : Using chain() + zip() + cycle() Most operations as above method, only difference being interleaving task is perform using chain(). Python3 # Python3 code to demonstrate working of# Repetitive Interleave 2 lists# Using chain() + zip() + cycle()from itertools import cycle, chain # initializing liststest_list1 = list('abc')test_list2 = [5, 7, 3, 0, 1, 8, 4] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # zip() combining list, after Repetitiveness using cycle()# chain() gets interleaved doneres = list(chain(*zip(cycle(test_list1), test_list2))) # printing resultprint("The interleaved list : " + str(res)) Output: The original list 1 is : [‘a’, ‘b’, ‘c’] The original list 2 is : [5, 7, 3, 0, 1, 8, 4] The interleaved list : [‘a’, 5, ‘b’, 7, ‘c’, 3, ‘a’, 0, ‘b’, 1, ‘c’, 8, ‘a’, 4] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method 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": "\n16 May, 2021" }, { "code": null, "e": 234, "s": 28, "text": "Given two lists of different lengths, the task is to write a Python program to get their elements alternatively and repeat the list elements of the smaller list till the larger list elements get exhausted." }, { "code": null, "e": 244, "s": 234, "text": "Examples:" }, { "code": null, "e": 317, "s": 244, "text": "Input : test_list1 = [‘a’, ‘b’, ‘c’], test_list2 = [5, 7, 3, 0, 1, 8, 4]" }, { "code": null, "e": 383, "s": 317, "text": "Output : [‘a’, 5, ‘b’, 7, ‘c’, 3, ‘a’, 0, ‘b’, 1, ‘c’, 8, ‘a’, 4]" }, { "code": null, "e": 570, "s": 383, "text": "Explanation : Alternate elements from 1st list are printed in cyclic manner once it gets exhausted. Then after exhaustion, again 1st list starts from ‘a’, with elements left in 2nd list." }, { "code": null, "e": 634, "s": 570, "text": "Input : test_list1 = [3, 8, 7], test_list2 = [5, 7, 3, 0, 1, 8]" }, { "code": null, "e": 680, "s": 634, "text": "Output : [3, 5, 8, 7, 7, 3, 3, 0, 8, 1, 7, 8]" }, { "code": null, "e": 883, "s": 680, "text": "Explanation : Alternate elements from 1st list are printed in cyclic manner once it gets exhausted. 3, 5, 8, 7, 7, 3.. Then after exhaustion, again 1st list starts from 3, with elements left in 2nd list" }, { "code": null, "e": 939, "s": 883, "text": "Method #1 : Using zip() + cycle() + list comprehension " }, { "code": null, "e": 1107, "s": 939, "text": "In this, repetition of elements in smaller list is handled using cycle(), joining is done using zip(). List comprehension performs task of interleaving simultaneously." }, { "code": null, "e": 1115, "s": 1107, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Repetitive Interleave 2 lists# Using zip() + cycle() + list comprehension from itertools import cycle # initializing liststest_list1 = list('abc')test_list2 = [5, 7, 3, 0, 1, 8, 4] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # zip() combining list, after Repetitiveness using cycle()res = [ele for comb in zip(cycle(test_list1), test_list2) for ele in comb] # printing resultprint(\"The interleaved list : \" + str(res))", "e": 1666, "s": 1115, "text": null }, { "code": null, "e": 1674, "s": 1666, "text": "Output:" }, { "code": null, "e": 1715, "s": 1674, "text": "The original list 1 is : [‘a’, ‘b’, ‘c’]" }, { "code": null, "e": 1762, "s": 1715, "text": "The original list 2 is : [5, 7, 3, 0, 1, 8, 4]" }, { "code": null, "e": 1842, "s": 1762, "text": "The interleaved list : [‘a’, 5, ‘b’, 7, ‘c’, 3, ‘a’, 0, ‘b’, 1, ‘c’, 8, ‘a’, 4]" }, { "code": null, "e": 1886, "s": 1842, "text": "Method #2 : Using chain() + zip() + cycle()" }, { "code": null, "e": 1985, "s": 1886, "text": "Most operations as above method, only difference being interleaving task is perform using chain()." }, { "code": null, "e": 1993, "s": 1985, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Repetitive Interleave 2 lists# Using chain() + zip() + cycle()from itertools import cycle, chain # initializing liststest_list1 = list('abc')test_list2 = [5, 7, 3, 0, 1, 8, 4] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # zip() combining list, after Repetitiveness using cycle()# chain() gets interleaved doneres = list(chain(*zip(cycle(test_list1), test_list2))) # printing resultprint(\"The interleaved list : \" + str(res))", "e": 2550, "s": 1993, "text": null }, { "code": null, "e": 2558, "s": 2550, "text": "Output:" }, { "code": null, "e": 2599, "s": 2558, "text": "The original list 1 is : [‘a’, ‘b’, ‘c’]" }, { "code": null, "e": 2646, "s": 2599, "text": "The original list 2 is : [5, 7, 3, 0, 1, 8, 4]" }, { "code": null, "e": 2726, "s": 2646, "text": "The interleaved list : [‘a’, 5, ‘b’, 7, ‘c’, 3, ‘a’, 0, ‘b’, 1, ‘c’, 8, ‘a’, 4]" }, { "code": null, "e": 2747, "s": 2726, "text": "Python list-programs" }, { "code": null, "e": 2754, "s": 2747, "text": "Python" }, { "code": null, "e": 2770, "s": 2754, "text": "Python Programs" }, { "code": null, "e": 2868, "s": 2770, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2900, "s": 2868, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2927, "s": 2900, "text": "Python Classes and Objects" }, { "code": null, "e": 2948, "s": 2927, "text": "Python OOPs Concepts" }, { "code": null, "e": 2971, "s": 2948, "text": "Introduction To PYTHON" }, { "code": null, "e": 3002, "s": 2971, "text": "Python | os.path.join() method" }, { "code": null, "e": 3024, "s": 3002, "text": "Defaultdict in Python" }, { "code": null, "e": 3063, "s": 3024, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3101, "s": 3063, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3150, "s": 3101, "text": "Python | Convert string dictionary to dictionary" } ]
GATE | GATE-CS-2015 (Set 2) | Question 27
28 Jun, 2021 Consider a complete binary tree where the left and the right subtrees of the root are max-heaps. The lower bound for the number of operations to convert the tree to a heap is(A) Ω(logn)(B) Ω(n)(C) Ω(nlogn)(D) Ω(n2)Answer: (A)Explanation: The answer to this question is simply max-heapify function. Time complexity of max-heapify is O(Log n) as it recurses at most through height of heap. // A recursive method to heapify a subtree with root at given index // This method assumes that the subtrees are already heapified void MinHeap::MaxHeapify(int i) { int l = left(i); int r = right(i); int largest = i; if (l < heap_size && harr[l] < harr[i]) largest = l; if (r < heap_size && harr[r] < harr[smallest]) largest = r; if (largest != i) { swap(&harr[i], &harr[largest]); MinHeapify(largest); } } See Binary Heap for details.Quiz of this Question GATE-CS-2015 (Set 2) GATE-GATE-CS-2015 (Set 2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Jun, 2021" }, { "code": null, "e": 441, "s": 53, "text": "Consider a complete binary tree where the left and the right subtrees of the root are max-heaps. The lower bound for the number of operations to convert the tree to a heap is(A) Ω(logn)(B) Ω(n)(C) Ω(nlogn)(D) Ω(n2)Answer: (A)Explanation: The answer to this question is simply max-heapify function. Time complexity of max-heapify is O(Log n) as it recurses at most through height of heap." }, { "code": null, "e": 912, "s": 441, "text": "// A recursive method to heapify a subtree with root at given index\n// This method assumes that the subtrees are already heapified\nvoid MinHeap::MaxHeapify(int i)\n{\n int l = left(i);\n int r = right(i);\n int largest = i;\n if (l < heap_size && harr[l] < harr[i])\n largest = l;\n if (r < heap_size && harr[r] < harr[smallest])\n largest = r;\n if (largest != i)\n {\n swap(&harr[i], &harr[largest]);\n MinHeapify(largest);\n }\n}" }, { "code": null, "e": 962, "s": 912, "text": "See Binary Heap for details.Quiz of this Question" }, { "code": null, "e": 983, "s": 962, "text": "GATE-CS-2015 (Set 2)" }, { "code": null, "e": 1009, "s": 983, "text": "GATE-GATE-CS-2015 (Set 2)" }, { "code": null, "e": 1014, "s": 1009, "text": "GATE" } ]
Python | Print list after removing element at given index
31 Mar, 2020 Given an index, remove the element at that index from the list and print the new list.Examples: Input : list = [10, 20, 30, 40, 50] index = 2 Output : [10, 20, 40, 50] Input : list = [10, 20, 40, 50] index = 0 Output : [20, 40, 50] Method 1: Traversal of list Using traversal in the list, append all the index values except the given index to a new list and then print the new list. For this we will require a new list where we can append all the values except the given index value. Below is the Python3 implementation of the above approach # Python3 program to remove the index # element from the list # using traversal def remove(list1, pos): newlist = [] # traverse in the list for x in range(len(list1)): # if index not equal to pos if x != pos: newlist.append(list1[x]) print(*newlist) # driver codelist1 = [10, 20, 30, 40, 50]pos = 2remove(list1, pos) Output: 10 20 40 50 Method 2: pop() pop() function helps us to pop the value at any desired position that is passed in the parameter, if nothing is passed in the parameter, then it removes the last index value. Below is the Python3 implementation of the above approach: # Python3 program to remove the index # element from the list # using pop() def remove(list1, pos): # pop the element at index = pos list1.pop(pos) print(*list1) # driver codelist1 = [10, 20, 30, 40, 50]pos = 2remove(list1, pos) Output: 10 20 40 50 Method 3: del function del function can be used to remove any element at any given position. If -1 or -2 is given in the [] brackets, then it deletes the last and second last element respectively. Below is the Python3 implementation of the above approach: # Python3 program to remove the index element# from the list using del def remove(list1, pos): # delete the element at index = pos del list1[pos] print(*list1) # driver codelist1 = [10, 20, 30, 40, 50]pos = 2remove(list1, pos) Output: 10 20 40 50 SagarUtekar Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python 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 How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 53, "s": 25, "text": "\n31 Mar, 2020" }, { "code": null, "e": 149, "s": 53, "text": "Given an index, remove the element at that index from the list and print the new list.Examples:" }, { "code": null, "e": 308, "s": 149, "text": "Input : list = [10, 20, 30, 40, 50] \n index = 2\nOutput : [10, 20, 40, 50] \n\nInput : list = [10, 20, 40, 50] \n index = 0 \nOutput : [20, 40, 50] \n" }, { "code": null, "e": 336, "s": 308, "text": "Method 1: Traversal of list" }, { "code": null, "e": 560, "s": 336, "text": "Using traversal in the list, append all the index values except the given index to a new list and then print the new list. For this we will require a new list where we can append all the values except the given index value." }, { "code": null, "e": 618, "s": 560, "text": "Below is the Python3 implementation of the above approach" }, { "code": "# Python3 program to remove the index # element from the list # using traversal def remove(list1, pos): newlist = [] # traverse in the list for x in range(len(list1)): # if index not equal to pos if x != pos: newlist.append(list1[x]) print(*newlist) # driver codelist1 = [10, 20, 30, 40, 50]pos = 2remove(list1, pos)", "e": 990, "s": 618, "text": null }, { "code": null, "e": 998, "s": 990, "text": "Output:" }, { "code": null, "e": 1011, "s": 998, "text": "10 20 40 50\n" }, { "code": null, "e": 1027, "s": 1011, "text": "Method 2: pop()" }, { "code": null, "e": 1202, "s": 1027, "text": "pop() function helps us to pop the value at any desired position that is passed in the parameter, if nothing is passed in the parameter, then it removes the last index value." }, { "code": null, "e": 1261, "s": 1202, "text": "Below is the Python3 implementation of the above approach:" }, { "code": "# Python3 program to remove the index # element from the list # using pop() def remove(list1, pos): # pop the element at index = pos list1.pop(pos) print(*list1) # driver codelist1 = [10, 20, 30, 40, 50]pos = 2remove(list1, pos)", "e": 1514, "s": 1261, "text": null }, { "code": null, "e": 1522, "s": 1514, "text": "Output:" }, { "code": null, "e": 1535, "s": 1522, "text": "10 20 40 50\n" }, { "code": null, "e": 1558, "s": 1535, "text": "Method 3: del function" }, { "code": null, "e": 1732, "s": 1558, "text": "del function can be used to remove any element at any given position. If -1 or -2 is given in the [] brackets, then it deletes the last and second last element respectively." }, { "code": null, "e": 1791, "s": 1732, "text": "Below is the Python3 implementation of the above approach:" }, { "code": "# Python3 program to remove the index element# from the list using del def remove(list1, pos): # delete the element at index = pos del list1[pos] print(*list1) # driver codelist1 = [10, 20, 30, 40, 50]pos = 2remove(list1, pos)", "e": 2042, "s": 1791, "text": null }, { "code": null, "e": 2050, "s": 2042, "text": "Output:" }, { "code": null, "e": 2063, "s": 2050, "text": "10 20 40 50\n" }, { "code": null, "e": 2075, "s": 2063, "text": "SagarUtekar" }, { "code": null, "e": 2096, "s": 2075, "text": "Python list-programs" }, { "code": null, "e": 2108, "s": 2096, "text": "python-list" }, { "code": null, "e": 2115, "s": 2108, "text": "Python" }, { "code": null, "e": 2127, "s": 2115, "text": "python-list" }, { "code": null, "e": 2225, "s": 2127, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2267, "s": 2225, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2289, "s": 2267, "text": "Enumerate() in Python" }, { "code": null, "e": 2315, "s": 2289, "text": "Python String | replace()" }, { "code": null, "e": 2347, "s": 2315, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2376, "s": 2347, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2403, "s": 2376, "text": "Python Classes and Objects" }, { "code": null, "e": 2424, "s": 2403, "text": "Python OOPs Concepts" }, { "code": null, "e": 2460, "s": 2424, "text": "Convert integer to string in Python" }, { "code": null, "e": 2483, "s": 2460, "text": "Introduction To PYTHON" } ]
Python | Lemmatization with TextBlob
24 Sep, 2021 Lemmatization is the process of grouping together the different inflected forms of a word so they can be analyzed as a single item. Lemmatization is similar to stemming but it brings context to the words. So it links words with similar meanings to one word.Text preprocessing includes both Stemming as well as Lemmatization. Many times people find these two terms confusing. Some treat these two as the same. Actually, lemmatization is preferred over Stemming because lemmatization does morphological analysis of the words.Applications of lemmatization are: Used in comprehensive retrieval systems like search engines. Used in compact indexing. Examples of lemmatization : -> rocks : rock -> corpora : corpus -> better : good One major difference with stemming is that lemmatize takes a part of speech parameter, “pos” If not supplied, the default is “noun.”Below is the implementation of lemmatization words using TextBlob: Python3 # from textblob lib import Word methodfrom textblob import Word # create a Word object.u = Word("rocks") # apply lemmatization.print("rocks :", u.lemmatize()) # create a Word object.v = Word("corpora") # apply lemmatization.print("corpora :", v.lemmatize()) # create a Word object.w = Word("better") # apply lemmatization with# parameter "a", "a" denotes adjective.print("better :", w.lemmatize("a")) Output : rocks : rock corpora : corpus better : good 23620uday2021 Technical Scripter 2018 Machine Learning Python 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": "\n24 Sep, 2021" }, { "code": null, "e": 614, "s": 54, "text": "Lemmatization is the process of grouping together the different inflected forms of a word so they can be analyzed as a single item. Lemmatization is similar to stemming but it brings context to the words. So it links words with similar meanings to one word.Text preprocessing includes both Stemming as well as Lemmatization. Many times people find these two terms confusing. Some treat these two as the same. Actually, lemmatization is preferred over Stemming because lemmatization does morphological analysis of the words.Applications of lemmatization are: " }, { "code": null, "e": 675, "s": 614, "text": "Used in comprehensive retrieval systems like search engines." }, { "code": null, "e": 701, "s": 675, "text": "Used in compact indexing." }, { "code": null, "e": 785, "s": 703, "text": "Examples of lemmatization :\n\n-> rocks : rock\n-> corpora : corpus\n-> better : good" }, { "code": null, "e": 986, "s": 785, "text": "One major difference with stemming is that lemmatize takes a part of speech parameter, “pos” If not supplied, the default is “noun.”Below is the implementation of lemmatization words using TextBlob: " }, { "code": null, "e": 994, "s": 986, "text": "Python3" }, { "code": "# from textblob lib import Word methodfrom textblob import Word # create a Word object.u = Word(\"rocks\") # apply lemmatization.print(\"rocks :\", u.lemmatize()) # create a Word object.v = Word(\"corpora\") # apply lemmatization.print(\"corpora :\", v.lemmatize()) # create a Word object.w = Word(\"better\") # apply lemmatization with# parameter \"a\", \"a\" denotes adjective.print(\"better :\", w.lemmatize(\"a\"))", "e": 1396, "s": 994, "text": null }, { "code": null, "e": 1407, "s": 1396, "text": "Output : " }, { "code": null, "e": 1451, "s": 1407, "text": "rocks : rock\ncorpora : corpus\nbetter : good" }, { "code": null, "e": 1467, "s": 1453, "text": "23620uday2021" }, { "code": null, "e": 1491, "s": 1467, "text": "Technical Scripter 2018" }, { "code": null, "e": 1508, "s": 1491, "text": "Machine Learning" }, { "code": null, "e": 1515, "s": 1508, "text": "Python" }, { "code": null, "e": 1534, "s": 1515, "text": "Technical Scripter" }, { "code": null, "e": 1551, "s": 1534, "text": "Machine Learning" } ]
PostgreSQL – Show Databases
28 Aug, 2020 In PostgreSQL, there are couple of ways to list all the databases present on the server. In this article, we will explore them. To list all the database present in the current database server use one of the following commands: Syntax: \l or \l+ Example: First log into the PostgreSQL server using the pSQL shell: Now use the below command to list all databases using a superuser such as postgres: \l This will lead to the following: Alternatively one can use the below command: \l+ Output: The SELECT statement can also be used to list all the database present on the server: Syntax: SELECT datname FROM pg_database; Example: Below is the simple use of the SELECT statement to list all database present on the server: SELECT datname FROM pg_database; Output: postgreSQL-managing-database PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Aug, 2020" }, { "code": null, "e": 157, "s": 28, "text": "In PostgreSQL, there are couple of ways to list all the databases present on the server. In this article, we will explore them." }, { "code": null, "e": 256, "s": 157, "text": "To list all the database present in the current database server use one of the following commands:" }, { "code": null, "e": 274, "s": 256, "text": "Syntax: \\l or \\l+" }, { "code": null, "e": 283, "s": 274, "text": "Example:" }, { "code": null, "e": 342, "s": 283, "text": "First log into the PostgreSQL server using the pSQL shell:" }, { "code": null, "e": 426, "s": 342, "text": "Now use the below command to list all databases using a superuser such as postgres:" }, { "code": null, "e": 429, "s": 426, "text": "\\l" }, { "code": null, "e": 462, "s": 429, "text": "This will lead to the following:" }, { "code": null, "e": 507, "s": 462, "text": "Alternatively one can use the below command:" }, { "code": null, "e": 511, "s": 507, "text": "\\l+" }, { "code": null, "e": 519, "s": 511, "text": "Output:" }, { "code": null, "e": 605, "s": 519, "text": "The SELECT statement can also be used to list all the database present on the server:" }, { "code": null, "e": 646, "s": 605, "text": "Syntax: SELECT datname FROM pg_database;" }, { "code": null, "e": 655, "s": 646, "text": "Example:" }, { "code": null, "e": 747, "s": 655, "text": "Below is the simple use of the SELECT statement to list all database present on the server:" }, { "code": null, "e": 780, "s": 747, "text": "SELECT datname FROM pg_database;" }, { "code": null, "e": 788, "s": 780, "text": "Output:" }, { "code": null, "e": 817, "s": 788, "text": "postgreSQL-managing-database" }, { "code": null, "e": 828, "s": 817, "text": "PostgreSQL" } ]
Python program to check if a number is Prime or not
In this, we’ll write a program that will test if the given number which is greater than 1 is prime or not. A prime number is a positive integer greater than 1 and which has only two factors 1 & the number itself for example number: 2, 3, 5, 7... etc are prime numbers as they have only two factors .i.e. 1 & the number itself. # Python program to check if the input number is prime or not #Take input from the user num = int(input("Please enter the number: ")) #Check if the given number is greater than 1 if num > 1: # Iterate through 2 to num/2. for i in range(2,num//2): #Select if the number is divisible by any number between 2 and num/2. if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) break else: #If given number is not fully divisible by any number between 1 and num/2, then its prime. print(num,"is a prime number") # Also, if the number is less than 1, its also not a prime number. else: print(num,"is not a prime number") Please enter the number: 47 47 is a prime number >>> ================= RESTART: C:/Python/Python361/primeNum1.py ================= Please enter the number: -2 -2 is not a prime number >>> ================= RESTART: C:/Python/Python361/primeNum1.py ================= Please enter the number: 3333 3333 is not a prime number 3 times 1111 is 3333 User-Input 1: num: 47 Output: Number(47) is a prime number User-Input 2: num = -2 Output: Number(-2) is not a prime number User-Input 3: num = 3333 Output: Number(3333) is not a prime number In the above program, we check if the user input number is prime or not. Because numbers less than or equal to 1 are not prime numbers, therefore we only consider user-input greater than 1. Then we check if the user-input is exactly divisible by any number between 2 to user-input/2. If we find a factor in that range, the number is not a prime number else, it’s a prime number.
[ { "code": null, "e": 1169, "s": 1062, "text": "In this, we’ll write a program that will test if the given number which is greater than 1 is prime or not." }, { "code": null, "e": 1389, "s": 1169, "text": "A prime number is a positive integer greater than 1 and which has only two factors 1 & the number itself for example number: 2, 3, 5, 7... etc are prime numbers as they have only two factors .i.e. 1 & the number itself." }, { "code": null, "e": 2107, "s": 1389, "text": "# Python program to check if the input number is prime or not\n#Take input from the user\nnum = int(input(\"Please enter the number: \"))\n#Check if the given number is greater than 1\nif num > 1:\n # Iterate through 2 to num/2.\n for i in range(2,num//2):\n #Select if the number is divisible by any number between 2 and num/2.\n if (num % i) == 0:\n print(num,\"is not a prime number\")\n print(i,\"times\",num//i,\"is\",num)\n break\n else:\n #If given number is not fully divisible by any number between 1 and num/2, then its prime.\n print(num,\"is a prime number\")\n# Also, if the number is less than 1, its also not a prime number.\nelse:\n print(num,\"is not a prime number\")" }, { "code": null, "e": 2451, "s": 2107, "text": "Please enter the number: 47\n47 is a prime number\n>>>\n================= RESTART: C:/Python/Python361/primeNum1.py =================\nPlease enter the number: -2\n-2 is not a prime number\n>>>\n================= RESTART: C:/Python/Python361/primeNum1.py =================\nPlease enter the number: 3333\n3333 is not a prime number\n3 times 1111 is 3333" }, { "code": null, "e": 2473, "s": 2451, "text": "User-Input 1: num: 47" }, { "code": null, "e": 2510, "s": 2473, "text": "Output: Number(47) is a prime number" }, { "code": null, "e": 2533, "s": 2510, "text": "User-Input 2: num = -2" }, { "code": null, "e": 2574, "s": 2533, "text": "Output: Number(-2) is not a prime number" }, { "code": null, "e": 2599, "s": 2574, "text": "User-Input 3: num = 3333" }, { "code": null, "e": 2642, "s": 2599, "text": "Output: Number(3333) is not a prime number" }, { "code": null, "e": 2832, "s": 2642, "text": "In the above program, we check if the user input number is prime or not. Because numbers less than or equal to 1 are not prime numbers, therefore we only consider user-input greater than 1." }, { "code": null, "e": 3021, "s": 2832, "text": "Then we check if the user-input is exactly divisible by any number between 2 to user-input/2. If we find a factor in that range, the number is not a prime number else, it’s a prime number." } ]
Tryit Editor v3.7
Tryit: HTML table - colgroup
[]
Binary Search Tree - Search and Insertion Operations in C++
Binary search tree (BST) is a special type of tree which follows the following rules − left child node’s value is always less than the parent Note right child node has a greater value than the parent node. all the nodes individually form a binary search tree. Example of a binary search tree (BST) − A binary search tree is created in order to reduce the complexity of operations like search, find minimum and maximum. Performing a search in a binary search tree, We need to search for a key in the tree. For this, We will compare the key with the root node of the tree. If key equals to root node, the key is found. If the value of the key is greater than the root node, take the right subtree and search for the key. If the value of the key is less than the root node, take left subtree and search for the key. Live Demo #include<stdio.h> #include<stdlib.h> struct node{ int key; struct node *left, *right; }; struct node *newNode(int item){ struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; return temp; } void traversetree(struct node *root){ if (root != NULL){ traversetree(root->left); printf("%d \t", root->key); traversetree(root->right); } } struct node* search(struct node* root, int key){ if (root == NULL || root->key == key) return root; if (root->key < key) return search(root->right, key); return search(root->left, key); } struct node* insert(struct node* node, int key){ if (node == NULL) return newNode(key); if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); return node; } int main(){ struct node *root = NULL; root = insert(root, 23); insert(root, 15); insert(root, 12); insert(root, 17); insert(root, 32); insert(root, 29); insert(root, 45); printf("The tree is :\n"); traversetree(root); printf("\nSearching for 12 in this tree "); if(search(root , 12)) printf("\nelement found"); else printf("\nelement not found"); return 0; } The tree is : 12 15 17 23 29 32 45 Searching for 12 in this tree element found Insertion operation in a BST takes place at the leaf node of the tree for insertion we will start the comparison of the node with the root node and find the correct position of the node and then place it. The following example will make it more clear to you. Inserting 12 to this BST. We will compare 12 with root node 12 > 5, it belongs to the right subtree. Compare 12 with the right child node 12 > 8, it belongs to the right of the right sub child. Compare 12 with the right sub child of right subtree 12 >10, its position is the right of this node. The new tree formed will be, Live Demo #include<stdio.h> #include<stdlib.h> struct node{ int key; struct node *left, *right; }; struct node *newNode(int item){ struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; return temp; } void traversetree(struct node *root){ if (root != NULL){ traversetree(root->left); printf("%d \t", root->key); traversetree(root->right); } } struct node* insert(struct node* node, int key){ if (node == NULL) return newNode(key); if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); return node; } int main(){ struct node *root = NULL; root = insert(root, 23); insert(root, 15); insert(root, 12); insert(root, 17); insert(root, 32); insert(root, 29); printf("The tree is :\n"); traversetree(root); printf("\nInseting 45 to the tree\n"); insert(root, 45); printf("Tree after insertion is :\n"); traversetree(root); return 0; } The tree is : 12 15 17 23 29 32 Inserting 45 to the tree Tree after insertion is : 12 15 17 23 29 32 45
[ { "code": null, "e": 1149, "s": 1062, "text": "Binary search tree (BST) is a special type of tree which follows the following rules −" }, { "code": null, "e": 1209, "s": 1149, "text": "left child node’s value is always less than the parent Note" }, { "code": null, "e": 1268, "s": 1209, "text": "right child node has a greater value than the parent node." }, { "code": null, "e": 1322, "s": 1268, "text": "all the nodes individually form a binary search tree." }, { "code": null, "e": 1362, "s": 1322, "text": "Example of a binary search tree (BST) −" }, { "code": null, "e": 1481, "s": 1362, "text": "A binary search tree is created in order to reduce the complexity of operations like search, find minimum and maximum." }, { "code": null, "e": 1526, "s": 1481, "text": "Performing a search in a binary search tree," }, { "code": null, "e": 1633, "s": 1526, "text": "We need to search for a key in the tree. For this, We will compare the key with the root node of the tree." }, { "code": null, "e": 1679, "s": 1633, "text": "If key equals to root node, the key is found." }, { "code": null, "e": 1781, "s": 1679, "text": "If the value of the key is greater than the root node, take the right subtree and search for the key." }, { "code": null, "e": 1875, "s": 1781, "text": "If the value of the key is less than the root node, take left subtree and search for the key." }, { "code": null, "e": 1886, "s": 1875, "text": " Live Demo" }, { "code": null, "e": 3207, "s": 1886, "text": "#include<stdio.h>\n#include<stdlib.h>\nstruct node{\n int key;\n struct node *left, *right;\n};\nstruct node *newNode(int item){\n struct node *temp = (struct node *)malloc(sizeof(struct node));\n temp->key = item;\n temp->left = temp->right = NULL;\n return temp;\n}\nvoid traversetree(struct node *root){\n if (root != NULL){\n traversetree(root->left);\n printf(\"%d \\t\", root->key);\n traversetree(root->right);\n }\n}\nstruct node* search(struct node* root, int key){\n if (root == NULL || root->key == key)\n return root;\n if (root->key < key)\n return search(root->right, key);\n return search(root->left, key);\n}\nstruct node* insert(struct node* node, int key){\n if (node == NULL) return newNode(key);\n if (key < node->key)\n node->left = insert(node->left, key);\n else if (key > node->key)\n node->right = insert(node->right, key);\n return node;\n}\nint main(){\n struct node *root = NULL;\n root = insert(root, 23);\n insert(root, 15);\n insert(root, 12);\n insert(root, 17);\n insert(root, 32);\n insert(root, 29);\n insert(root, 45);\n printf(\"The tree is :\\n\");\n traversetree(root);\n printf(\"\\nSearching for 12 in this tree \");\n if(search(root , 12))\n printf(\"\\nelement found\");\n else\n printf(\"\\nelement not found\");\n return 0;\n}" }, { "code": null, "e": 3286, "s": 3207, "text": "The tree is :\n12 15 17 23 29 32 45\nSearching for 12 in this tree\nelement found" }, { "code": null, "e": 3545, "s": 3286, "text": "Insertion operation in a BST takes place at the leaf node of the tree for insertion we will start the comparison of the node with the root node and find the correct position of the node and then place it. The following example will make it more clear to you." }, { "code": null, "e": 3571, "s": 3545, "text": "Inserting 12 to this BST." }, { "code": null, "e": 3646, "s": 3571, "text": "We will compare 12 with root node 12 > 5, it belongs to the right subtree." }, { "code": null, "e": 3739, "s": 3646, "text": "Compare 12 with the right child node 12 > 8, it belongs to the right of the right sub child." }, { "code": null, "e": 3840, "s": 3739, "text": "Compare 12 with the right sub child of right subtree 12 >10, its position is the right of this node." }, { "code": null, "e": 3869, "s": 3840, "text": "The new tree formed will be," }, { "code": null, "e": 3880, "s": 3869, "text": " Live Demo" }, { "code": null, "e": 4949, "s": 3880, "text": "#include<stdio.h>\n#include<stdlib.h>\nstruct node{\n int key;\n struct node *left, *right;\n};\nstruct node *newNode(int item){\n struct node *temp = (struct node *)malloc(sizeof(struct node));\n temp->key = item;\n temp->left = temp->right = NULL;\n return temp;\n}\nvoid traversetree(struct node *root){\n if (root != NULL){\n traversetree(root->left);\n printf(\"%d \\t\", root->key);\n traversetree(root->right);\n }\n}\nstruct node* insert(struct node* node, int key){\n if (node == NULL) return newNode(key);\n if (key < node->key)\n node->left = insert(node->left, key);\n else if (key > node->key)\n node->right = insert(node->right, key);\n return node;\n}\nint main(){\n struct node *root = NULL;\n root = insert(root, 23);\n insert(root, 15);\n insert(root, 12);\n insert(root, 17);\n insert(root, 32);\n insert(root, 29);\n printf(\"The tree is :\\n\");\n traversetree(root);\n printf(\"\\nInseting 45 to the tree\\n\");\n insert(root, 45);\n printf(\"Tree after insertion is :\\n\");\n traversetree(root);\n return 0;\n}" }, { "code": null, "e": 5053, "s": 4949, "text": "The tree is :\n12 15 17 23 29 32\nInserting 45 to the tree\nTree after insertion is :\n12 15 17 23 29 32 45" } ]
How to load JSON data using jQuery?
To load JSON data using jQuery, use the getJSON() and ajax() method. The jQuery.getJSON( ) method loads JSON data from the server using a GET HTTP request. Here is the description of all the parameters used by this method − url − A string containing the URL to which the request is sent data − This optional parameter represents key/value pairs that will be sent to the server. callback − This optional parameter represents a function to be executed whenever the data is loaded successfully. Add your JSON content in result.json file − { "name": "Amit", "age" : "27", "sex": "male" } The following is a code snippet showing the usage of this method. It links the above created result.json file, <head> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> $(document).ready(function() { $("#driver").click(function(event){ $.getJSON('result.json', function(jd) { $('#stage').html('<p> Name: ' + jd.name + '</p>'); $('#stage').append('<p>Age : ' + jd.age+ '</p>'); $('#stage').append('<p> Sex: ' + jd.sex+ '</p>'); }); }); }); </script> </head> <body> <p>Click on the button to load result.html file:</p> <div id = "stage" style = "background-color:#cc0;"> STAGE </div> <input type = "button" id = "driver" value = "Load Data" /> </body>
[ { "code": null, "e": 1218, "s": 1062, "text": "To load JSON data using jQuery, use the getJSON() and ajax() method. The jQuery.getJSON( ) method loads JSON data from the server using a GET HTTP request." }, { "code": null, "e": 1286, "s": 1218, "text": "Here is the description of all the parameters used by this method −" }, { "code": null, "e": 1349, "s": 1286, "text": "url − A string containing the URL to which the request is sent" }, { "code": null, "e": 1440, "s": 1349, "text": "data − This optional parameter represents key/value pairs that will be sent to the server." }, { "code": null, "e": 1554, "s": 1440, "text": "callback − This optional parameter represents a function to be executed whenever the data is loaded successfully." }, { "code": null, "e": 1598, "s": 1554, "text": "Add your JSON content in result.json file −" }, { "code": null, "e": 1646, "s": 1598, "text": "{\n\"name\": \"Amit\",\n\"age\" : \"27\",\n\"sex\": \"male\"\n}" }, { "code": null, "e": 1757, "s": 1646, "text": "The following is a code snippet showing the usage of this method. It links the above created result.json file," }, { "code": null, "e": 2600, "s": 1757, "text": " <head> \n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() {\n \n $(\"#driver\").click(function(event){\n $.getJSON('result.json', function(jd) {\n $('#stage').html('<p> Name: ' + jd.name + '</p>');\n $('#stage').append('<p>Age : ' + jd.age+ '</p>');\n $('#stage').append('<p> Sex: ' + jd.sex+ '</p>');\n });\n });\n \n });\n </script>\n </head>\n \n <body>\n \n <p>Click on the button to load result.html file:</p>\n \n <div id = \"stage\" style = \"background-color:#cc0;\">\n STAGE\n </div>\n \n <input type = \"button\" id = \"driver\" value = \"Load Data\" />\n \n </body>" } ]
Output of C++ programs | Set 39 (Pointers) - GeeksforGeeks
26 Aug, 2017 Prerequisite: Pointers in C/C++ QUE.1 What would be printed from the following C++ program? #include <iostream>#include <stdlib.h>using namespace std;int main(){ float x = 5.999; float* y, *z; y = &x; z = y; cout << x << ", " << *(&x) << ", " << *y << ", " << *z << "\n"; return 0;} a) 5.999, 5.999, 5.999, 5.999b) 5.999, 5.9, 5.000, 5.900c) Address of the elementsd) compilation error Answer: a Explanation: The reason for this is x gives the value stored in the variable x. *(&x) gives the data value stored in the address &x i.e., the data value of x. Since y points to x (..y=&x), *y gives the value of x. And because z has the same address as that of y, *z also gives the value of x i.e., 5.999 QUE.2 What would be printed from the following C++ program? #include <iostream>using namespace std; int main(){ int track[] = { 10, 20, 30, 40 }, *striker; striker = track; track[1] += 30; cout << "Striker>" << *striker << " "; *striker -= 10; striker++; cout << "Next@" << *striker << " "; striker += 2; cout << "Last@" << *striker << " "; cout << "Reset To" << track[0] << " "; return 0;} a) 10, 20, 30, 40b) Striker>10 Next@50 Last@40 Reset To0c) Striker>10 Next@40 Last@50 Reset To0d) Striker> Next@ Last@ Reset To Answer: b Explanation: The array track contains 4 elements {10, 20, 30, 40} and the pointer striker holds the base address of the array track i.e, address of track[0].1) *striker holds the data value of track[0] i.e, 10. Decrement in *striker by 10 makes the track[0]=0.2) Incrementing pointer striker gives the next location of track i.e., 1. Now *striker gives the data value of track[1].3) Again by incrementing by 2, striker reaches to the 4 address of the array track i.e, track[4].4) At last print the value at track[0], which is 0 (see step 1) QUE.3 What would be printed from the following C++ program? #include <iostream>using namespace std; int main(){ int a = 32, *ptr = &a; char ch = 'A', &cho = ch; cho += a; *ptr += ch; cout << a << ", " << ch << endl; return 0;} OPTIONa) 97, Ab) 128, Ac) 97, ad) 129, a Answer: d Explanation: ptr is a pointer which holds the address of a while *ptr returns the data value of a. Cho is a reference variable which hold the reference of ch. Now, incrementing the value of cho by 32 (ASCII value), reflect to cho and ch makes it equal to “a” (alphabet). In last step, data value of *ptr incremented by ch i. e., “a” gives a = 129. QUE.4 What is the output of the following C++ program? #include <iostream>using namespace std; int main(){ const int i = 20; const int* const ptr = &i; (*ptr)++; int j = 15; ptr = &j; return 0;} a) Address of the elementsb) run time errorc) Compilation errord) none of this Answer:c Explanation: ptr is a constant pointer to constant integer, which means neither the pointer nor its contents will be modified, thus lines 6 and 8 are invalid as they are trying to modify the contents and pointer respectively. QUE.5 What is the output of the following C++ program? #include <iostream>using namespace std;#include <stdio.h>int main(){ char* str[] = { "AAAAA", "BBBBB", "CCCCC", "DDDDD" }; char** sptr[] = { str + 3, str + 2, str + 1, str }; char*** pp; pp = sptr; ++pp; printf("%s", **++pp + 2); return 0;} a) BBBBBb) CCCCCc) BBBd) Error Answer: c Explanation: *str is a array pointer of string, **sptr is array pointer(double pointer) that is pointing to str strings in reverse order. ***pp also a pointer that is pointing sptr base address. ++pp will point to 1st index of sptr that contain str+2 (“CCCCC”). in printf(“%s”, **++pp+2); ++pp will point to str+1, and **++pp, value stored @ str+1 (“BBBBB). and (**++pp)+2 will point the 2nd index of “BBBBB”, hence BBB will be printed. This article is contributed by Ajay Puri(ajay0007). 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. CPP-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to copy a string in C/C++ Output of Python Program | Set 1 Runtime Errors Output of Java Program | Set 3 Output of Java Program | Set 2 unsigned specifier (%u) in C with Examples Output of C++ Program | Set 1 Output of C Programs | Set 3 Output of C++ programs | Set 50 Output of Java program | Set 5
[ { "code": null, "e": 24396, "s": 24368, "text": "\n26 Aug, 2017" }, { "code": null, "e": 24428, "s": 24396, "text": "Prerequisite: Pointers in C/C++" }, { "code": null, "e": 24488, "s": 24428, "text": "QUE.1 What would be printed from the following C++ program?" }, { "code": "#include <iostream>#include <stdlib.h>using namespace std;int main(){ float x = 5.999; float* y, *z; y = &x; z = y; cout << x << \", \" << *(&x) << \", \" << *y << \", \" << *z << \"\\n\"; return 0;}", "e": 24697, "s": 24488, "text": null }, { "code": null, "e": 24800, "s": 24697, "text": "a) 5.999, 5.999, 5.999, 5.999b) 5.999, 5.9, 5.000, 5.900c) Address of the elementsd) compilation error" }, { "code": null, "e": 24811, "s": 24800, "text": " Answer: a" }, { "code": null, "e": 25115, "s": 24811, "text": "Explanation: The reason for this is x gives the value stored in the variable x. *(&x) gives the data value stored in the address &x i.e., the data value of x. Since y points to x (..y=&x), *y gives the value of x. And because z has the same address as that of y, *z also gives the value of x i.e., 5.999" }, { "code": null, "e": 25175, "s": 25115, "text": "QUE.2 What would be printed from the following C++ program?" }, { "code": "#include <iostream>using namespace std; int main(){ int track[] = { 10, 20, 30, 40 }, *striker; striker = track; track[1] += 30; cout << \"Striker>\" << *striker << \" \"; *striker -= 10; striker++; cout << \"Next@\" << *striker << \" \"; striker += 2; cout << \"Last@\" << *striker << \" \"; cout << \"Reset To\" << track[0] << \" \"; return 0;}", "e": 25544, "s": 25175, "text": null }, { "code": null, "e": 25672, "s": 25544, "text": "a) 10, 20, 30, 40b) Striker>10 Next@50 Last@40 Reset To0c) Striker>10 Next@40 Last@50 Reset To0d) Striker> Next@ Last@ Reset To" }, { "code": null, "e": 25683, "s": 25672, "text": " Answer: b" }, { "code": null, "e": 26224, "s": 25683, "text": "Explanation: The array track contains 4 elements {10, 20, 30, 40} and the pointer striker holds the base address of the array track i.e, address of track[0].1) *striker holds the data value of track[0] i.e, 10. Decrement in *striker by 10 makes the track[0]=0.2) Incrementing pointer striker gives the next location of track i.e., 1. Now *striker gives the data value of track[1].3) Again by incrementing by 2, striker reaches to the 4 address of the array track i.e, track[4].4) At last print the value at track[0], which is 0 (see step 1)" }, { "code": null, "e": 26284, "s": 26224, "text": "QUE.3 What would be printed from the following C++ program?" }, { "code": "#include <iostream>using namespace std; int main(){ int a = 32, *ptr = &a; char ch = 'A', &cho = ch; cho += a; *ptr += ch; cout << a << \", \" << ch << endl; return 0;}", "e": 26472, "s": 26284, "text": null }, { "code": null, "e": 26513, "s": 26472, "text": "OPTIONa) 97, Ab) 128, Ac) 97, ad) 129, a" }, { "code": null, "e": 26523, "s": 26513, "text": "Answer: d" }, { "code": null, "e": 26871, "s": 26523, "text": "Explanation: ptr is a pointer which holds the address of a while *ptr returns the data value of a. Cho is a reference variable which hold the reference of ch. Now, incrementing the value of cho by 32 (ASCII value), reflect to cho and ch makes it equal to “a” (alphabet). In last step, data value of *ptr incremented by ch i. e., “a” gives a = 129." }, { "code": null, "e": 26926, "s": 26871, "text": "QUE.4 What is the output of the following C++ program?" }, { "code": "#include <iostream>using namespace std; int main(){ const int i = 20; const int* const ptr = &i; (*ptr)++; int j = 15; ptr = &j; return 0;}", "e": 27085, "s": 26926, "text": null }, { "code": null, "e": 27164, "s": 27085, "text": "a) Address of the elementsb) run time errorc) Compilation errord) none of this" }, { "code": null, "e": 27173, "s": 27164, "text": "Answer:c" }, { "code": null, "e": 27399, "s": 27173, "text": "Explanation: ptr is a constant pointer to constant integer, which means neither the pointer nor its contents will be modified, thus lines 6 and 8 are invalid as they are trying to modify the contents and pointer respectively." }, { "code": null, "e": 27454, "s": 27399, "text": "QUE.5 What is the output of the following C++ program?" }, { "code": "#include <iostream>using namespace std;#include <stdio.h>int main(){ char* str[] = { \"AAAAA\", \"BBBBB\", \"CCCCC\", \"DDDDD\" }; char** sptr[] = { str + 3, str + 2, str + 1, str }; char*** pp; pp = sptr; ++pp; printf(\"%s\", **++pp + 2); return 0;}", "e": 27718, "s": 27454, "text": null }, { "code": null, "e": 27749, "s": 27718, "text": "a) BBBBBb) CCCCCc) BBBd) Error" }, { "code": null, "e": 27759, "s": 27749, "text": "Answer: c" }, { "code": null, "e": 28196, "s": 27759, "text": "Explanation: *str is a array pointer of string, **sptr is array pointer(double pointer) that is pointing to str strings in reverse order. ***pp also a pointer that is pointing sptr base address. ++pp will point to 1st index of sptr that contain str+2 (“CCCCC”). in printf(“%s”, **++pp+2); ++pp will point to str+1, and **++pp, value stored @ str+1 (“BBBBB). and (**++pp)+2 will point the 2nd index of “BBBBB”, hence BBB will be printed." }, { "code": null, "e": 28503, "s": 28196, "text": "This article is contributed by Ajay Puri(ajay0007). 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": 28628, "s": 28503, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28639, "s": 28628, "text": "CPP-Output" }, { "code": null, "e": 28654, "s": 28639, "text": "Program Output" }, { "code": null, "e": 28752, "s": 28654, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28793, "s": 28752, "text": "Different ways to copy a string in C/C++" }, { "code": null, "e": 28826, "s": 28793, "text": "Output of Python Program | Set 1" }, { "code": null, "e": 28841, "s": 28826, "text": "Runtime Errors" }, { "code": null, "e": 28872, "s": 28841, "text": "Output of Java Program | Set 3" }, { "code": null, "e": 28903, "s": 28872, "text": "Output of Java Program | Set 2" }, { "code": null, "e": 28946, "s": 28903, "text": "unsigned specifier (%u) in C with Examples" }, { "code": null, "e": 28976, "s": 28946, "text": "Output of C++ Program | Set 1" }, { "code": null, "e": 29005, "s": 28976, "text": "Output of C Programs | Set 3" }, { "code": null, "e": 29037, "s": 29005, "text": "Output of C++ programs | Set 50" } ]
Foreach loop with two arrays and if-condition evaluation to find matching values PHP?
Let’s say we have the following two arrays $firstArray=array(10,20,30,40,50); $secondArray=array(100,80,30,40,90); We need to find the matching i.e. the output should be 30 40 The PHP code is as follows Live Demo <!DOCTYPE html> <html> <body> <?php $firstArray=array(10,20,30,40,50); $secondArray=array(100,80,30,40,90); foreach($firstArray as $f){ foreach($secondArray as $s){ if($f==$s){ echo "The matching result is=",$f,"<br>"; } } } ?> </body> </html> This will produce the following output The matching result is=30 The matching result is=40
[ { "code": null, "e": 1106, "s": 1062, "text": "Let’s say we have the following two arrays " }, { "code": null, "e": 1178, "s": 1106, "text": "$firstArray=array(10,20,30,40,50);\n$secondArray=array(100,80,30,40,90);" }, { "code": null, "e": 1234, "s": 1178, "text": "We need to find the matching i.e. the output should be " }, { "code": null, "e": 1240, "s": 1234, "text": "30\n40" }, { "code": null, "e": 1267, "s": 1240, "text": "The PHP code is as follows" }, { "code": null, "e": 1278, "s": 1267, "text": " Live Demo" }, { "code": null, "e": 1549, "s": 1278, "text": "<!DOCTYPE html>\n<html>\n<body>\n<?php\n$firstArray=array(10,20,30,40,50);\n$secondArray=array(100,80,30,40,90);\nforeach($firstArray as $f){\n foreach($secondArray as $s){\n if($f==$s){\n echo \"The matching result is=\",$f,\"<br>\";\n }\n }\n}\n?>\n</body>\n</html>" }, { "code": null, "e": 1589, "s": 1549, "text": "This will produce the following output " }, { "code": null, "e": 1641, "s": 1589, "text": "The matching result is=30\nThe matching result is=40" } ]
Creating a Hybrid Content-Collaborative Movie Recommender Using Deep Learning | by Adam Lineberry | Towards Data Science
Written by Adam Lineberry and Claire Longo In this post we’ll describe how we used deep learning models to create a hybrid recommender system that leverages both content and collaborative data. This approach tackles the content and collaborative data separately at first, then combines the efforts to produce a system with the best of both worlds. Using the MovieLens 20M Dataset, we developed an item-to-item (movie-to-movie) recommender system that recommends movies similar to a given input movie. To create the hybrid model, we ensembled the results of an autoencoder which learns content-based movie embeddings from tag data, and a deep entity embedding neural network which learns collaborative-based movie embeddings from ratings data. We provide a brief summary of content and collaborative recommender systems, and discuss the benefits of a hybrid model. We’ll be tracking how the different systems perform on one of our favorite movies: The Lord of the Rings: The Fellowship of the Ring. The deep learning work was performed on a Paperspace GPU machine using PyTorch 0.4.1. The code for this project can be found in this GitHub repository. Collaborative recommenders rely on data generated by users as they interact with items. Examples of this include: Users rating movies on a scale of 1–5Users purchasing or even viewing items on an online retail siteUsers reacting with “thumbs up” or “thumbs down” to songs on an online music streaming serviceSwiping left or right on a dating site Users rating movies on a scale of 1–5 Users purchasing or even viewing items on an online retail site Users reacting with “thumbs up” or “thumbs down” to songs on an online music streaming service Swiping left or right on a dating site In the context of a movie recommender, collaborative filters find trends in how similar users rate movies based on rating profiles. The ratings data can be decomposed or otherwise processed using a variety of techniques to ultimately find user and movie embeddings in a shared latent space. The movie embeddings, which describe their location in the latent space, can then be used to make movie-to-movie recommendations. One benefit of collaborative data is that it is always “self-generating” — users create the data for you naturally as they interact with items. This can be a valuable data source, especially in cases where high-quality item features are not available or difficult to obtain. Another benefit of collaborative filters is that it helps users discover new items that are outside the subspace defined by their historical profile. However, there are some drawbacks to collaborative filters such as the well-known cold start problem. It is also difficult for collaborative filters to accurately recommend novel or niche items because these items typically do not have enough user-item interaction data. Content recommenders rely on item features to make recommendations. Examples of this include: User generated tags on moviesItem colorText description or user review of an item User generated tags on movies Item color Text description or user review of an item Content filters tend to be more robust against popularity bias and the cold start problem. They can easily recommend new or novel items based on niche tastes. However, in an item-to-item recommender, content filters can only recommend items with features similar to the original item. This limits the scope of recommendations, and can also result in surfacing items with low ratings. In the context of a movie-to-movie recommender, a collaborative filter answers the question: “What movies have a similar user-rating profile?”, and a content filter answers the question: “What movies have similar features?”. By creating a hybrid recommender we’ve attempted to create a system that recommends movies that other users rated in a similar manner, while still making on-topic recommendations based on the features of that movie. Embeddings are a popular topic in several areas of machine learning, such as natural language processing, predictive models with categorical features and recommender systems. There are many ways to compute embeddings, but the end goal is to map “things” to a latent space with complex and meaningful dimensions. In a movie recommender, you can imagine latent dimensions measuring genres such as “sci-fi” and “romance” and other concepts such as “dialogue-driven versus action-packed”. Users and movies are mapped to this space by how strongly associated they are with each of the dimensions. In the famous word2vec example, learned word embeddings were able to complete the analogy “man is to woman as king is to ___.” As seen in the [very simplified] figure below, the words have been mapped into a shared latent space such that the meaning of the word is represented geometrically. There are cases in machine learning and deep learning where one can choose between using a one-hot encoding (OHE) or a learned embedding to perform a particular task. OHE representations of data have the potentially undesirable trait that every item is orthogonal (therefore quantitatively entirely dissimilar) to all other items. When thinking of words as an example, this can be a weak representation of the data because the similarity/exchangeability of similar words such as “alien” and “extraterrestrial” is completely lost due to the orthogonality. For this reason, the use of word embeddings can extend the capabilities of some models. We used cosine similarity to quantify the similarities between movies. Cosine similarity ranges from -1 to 1 and is calculated as the dot product between two vectors divided by their magnitudes. In a nutshell, movie embedding vectors pointing in the same direction will receive high cosine similarity scores. The idea is that directions through the latent concept space capture the essence of movies. A simple example to help visualize this: if “sci-fi” and “romance” are dimensions in the latent space, then movies with similar ratios of sci-fi-ness to romance-ness will point in the same direction and thus receive high cosine similarity scores. This code constructs the cosine similarity matrix from the movie embeddings and outputs the top n most similar movies for a given input movie. Included in the MovieLens data is a set of around 500k user-generated movie tags. According to the MovieLens README: “Each tag is typically a single word or short phrase. The meaning, value, and purpose of a particular tag is determined by each user.” This data is grouped by movie and the tags are concatenated to produce a corpus of documents. In this corpus, documents are the combination of all tags for a particular movie. An excerpt of the tag document for “Lord of the Rings: The Fellowship of the Ring” is shown below. As you can see, words/phrases like “adventure”, “fantasy” and “based on a book” appear frequently. This data also includes the names of actors and the book author. adventure characters epic fantasy world fighting photography Action adventure atmospheric based on a book based on book beautifully filmed ensemble cast fantasy fantasy world high fantasy imdb top 250 magic music nature nothing at all Oscar (Best Cinematography) Oscar (Best Effects - Visual Effects) scenic stylized Tolkien wizards adventure atmospheric ensemble cast fantasy fantasy world magic stylized wizards Watched adapted from:book author:J. R. R. Tolkein based on book epic fantasy middle earth faithful to book fantasy good versus evil high fantasy joseph campbell's study of mythology influenced magic atmospheric boring high fantasy Action adventure atmospheric based on a book beautifully filmed fantasy high fantasy magic music mythology romance stylized time travel Viggo Mortensen wizards Peter Jackson Peter Jackson music must see Tolkien high fantasy Myth Tolkien wizards Ian McKellen bast background universe Next, we transformed the tag documents into a Term Frequency — Inverse Document Frequency (TF-IDF) representation. TF-IDF tokenizes unstructured text data into numeric features that can be more easily processed by machine learning algorithms. Roughly speaking, the frequency of each term in a document is scaled by the number of documents containing that term. As a result, words that differentiate movies (e.g., “alien”, “fantasy”) will be weighted higher than words used to describe all movies (e.g. “movie”, “cast”). The TF-IDF vectorizer in sci-kit learn allows you to select the range of ngrams to consider. For this project, we found that unigrams were sufficient while still keeping our number of features manageable. In TF-IDF space, each dimension represents how important a certain word is to a movie. This representation is less than ideal because the encoding of a single concept (e.g., alien/extraterrestrial) is fragmented and scattered across multiple dimensions. We would like to compress the TF-IDF data into a lower dimensional space where concepts are consolidated into shared dimensions. In the compressed space, the hope is that each dimension will represent complex and robust concepts. To perform the compression we chose to use an autoencoder. Autoencoders are neural networks where the outputs are identical to the inputs. In our architecture (shown in the figure below), the high-dimensional TF-IDF input is gradually compressed into a 100 dimensional central hidden layer. This first half of the network is the “encoder”. The second half of the network, the “decoder”, attempts to reconstruct the original input. By setting a mean-squared error loss function and performing backpropagation, the network (particularly the encoder) learns a function which maps data into lower dimensional space in such a way that most of the information is preserved. Let’s start off by defining the encoder and decoder networks. They are defined separately to make it easy to encode the data once the network is trained. Next, let’s define a PyTorch Dataset class. Notice in the __getitem__ method that x and y are equivalent — this is the fundamental concept of an autoencoder. With these building blocks in-hand, let’s define a wrapper class that instantiates everything, handles the training loop, and performs the data encoding. From here, it’s straightforward to train the autoencoder and encode/compress the data: Below is a plot of the train and validation losses over time. As you can see, the model is not over- or under-fitting and eventually the losses converges to a very low value (on the order of 1e-4). Using the content-based movie embeddings learned by the autoencoder, the top 20 most similar movies to “Lord of the Rings: The Fellowship of the Ring” as defined by cosine similarity are shown below. A fully connected neural network is used to find movie and user embeddings. In this architecture, a user embedding matrix of size (n_users, n_factors) and a movie embedding matrix of size (n_movies, n_factors) are randomly initialized and subsequently learned via gradient descent. Each training data point is a user index, movie index and a rating (on a scale of 1–5). The user and movie indices are used to lookup the embedding vectors (which are rows of the embedding matrices). These vectors are then concatenated and passed in as the input to the neural net. This is similar to the technique taught by Jeremy Howard in the fast.ai MOOC, and we used the fastai library as well. Let’s read in the data, create a validation set, and construct a fastai ColumnarModelData object which is essentially a handy wrapper around PyTorch’s Dataset and DataLoader classes. Next, let’s define the neural net. Since the output of the network is constrained to be within 1–5, a scaled sigmoid activation function is used at the output layer. Passing the linear activation though a sigmoid gives the model a bit more flexibility and thus makes it easier to train. For example, if the model is trying to output a 5, instead of forcing it to output a value very near 5 from the linear calculation, using a sigmoid allows it to output any high value (because inputs ~6 or greater all get mapped to ~1.0 by the sigmoid function). An alternative would be to stop short of the sigmoid and let the model learn to output the correct rating directly from the linear output. The fastai library makes it very simple to fit the model. The fit function used here takes care of the training loop and provides a nice animated status bar with time remaining and loss values for each minibatch. This model took a while to train due to the large size of the training data (20 million). At various points throughout training we adjusted the dropout levels to combat over- or under-fitting. The learning rate was also regularly tweaked using information from the learning rate finder tool included in the fastai library: In the learning rate finder procedure, the learning rate is initially set to a very small value (1e-5) and is iteratively increased throughout the course of one epoch, up to a high ceiling value (10). At each stage, the loss is recorded so that a plot such as the one below may be produced. Interpreting this plot is a heuristic process that is explained in more detail in the fastai course, but the takeaway is this: select a learning rate where the loss is still decreasing quickly and has not leveled off yet. In this case, selecting 1e-2 would be a reasonable choice. With a dataset of this size (and the associated long training times), it is likely that you will need the ability to persist and depersist your trained model such that you can continue training at a later time. Once finished, you will also need to save your learned embeddings to disk for post-processing. The following code will take care of these items. Once the net is satisfactorily trained, you will have robust movie and user embeddings ready to use for a variety of practical tasks. Using the collaborative-based movie embeddings learned by this neural net, the top 20 most similar movies to “Lord of the Rings: The Fellowship of the Ring” as defined by cosine similarity are shown below. As seen above, the collaborative recommendations for Lord of the Rings appear to be primarily popular and highly rated blockbuster movies with strong action and adventure themes. The content recommendations appear to be less influenced by popularity and may include some hidden gems in the fantasy genre. To ensemble the results from the content and the collaborative models we simply averaged the cosine similarities. By ensembling collaborative and content-based results we are able to make recommendations that can hopefully draw from the strengths of both methods. The following are the ensembled recommendations for Lord of the Rings. In this post we developed a movie-to-movie hybrid content-collaborative recommender system. We discussed and illustrated the pros and cons of content and collaborative-based methods. We also showed how to develop recommender systems using deep learning instead of traditional matrix factorization methods. In our observations the collaborative filter was good at spanning gaps across genres and consistently recommending movies with high ratings. The content filter was good at identifying very similar styles (e.g., magical realms set in a medieval time) and lesser-viewed, potentially hidden gem movies. The aim of the hybrid approach is to combine the strengths of both systems. We also found some movies we want to see! If you would like to see recommendations for a particular movie of your choice, feel free to reach out on Twitter, LinkedIn or email. Adam is a data scientist in Denver, CO with interests in deep learning, big data, Formula 1 racing and skiing. Claire is a data scientist in Denver, CO working in the fashion industry. Her research interests are in recommender systems.
[ { "code": null, "e": 215, "s": 172, "text": "Written by Adam Lineberry and Claire Longo" }, { "code": null, "e": 520, "s": 215, "text": "In this post we’ll describe how we used deep learning models to create a hybrid recommender system that leverages both content and collaborative data. This approach tackles the content and collaborative data separately at first, then combines the efforts to produce a system with the best of both worlds." }, { "code": null, "e": 915, "s": 520, "text": "Using the MovieLens 20M Dataset, we developed an item-to-item (movie-to-movie) recommender system that recommends movies similar to a given input movie. To create the hybrid model, we ensembled the results of an autoencoder which learns content-based movie embeddings from tag data, and a deep entity embedding neural network which learns collaborative-based movie embeddings from ratings data." }, { "code": null, "e": 1170, "s": 915, "text": "We provide a brief summary of content and collaborative recommender systems, and discuss the benefits of a hybrid model. We’ll be tracking how the different systems perform on one of our favorite movies: The Lord of the Rings: The Fellowship of the Ring." }, { "code": null, "e": 1322, "s": 1170, "text": "The deep learning work was performed on a Paperspace GPU machine using PyTorch 0.4.1. The code for this project can be found in this GitHub repository." }, { "code": null, "e": 1436, "s": 1322, "text": "Collaborative recommenders rely on data generated by users as they interact with items. Examples of this include:" }, { "code": null, "e": 1669, "s": 1436, "text": "Users rating movies on a scale of 1–5Users purchasing or even viewing items on an online retail siteUsers reacting with “thumbs up” or “thumbs down” to songs on an online music streaming serviceSwiping left or right on a dating site" }, { "code": null, "e": 1707, "s": 1669, "text": "Users rating movies on a scale of 1–5" }, { "code": null, "e": 1771, "s": 1707, "text": "Users purchasing or even viewing items on an online retail site" }, { "code": null, "e": 1866, "s": 1771, "text": "Users reacting with “thumbs up” or “thumbs down” to songs on an online music streaming service" }, { "code": null, "e": 1905, "s": 1866, "text": "Swiping left or right on a dating site" }, { "code": null, "e": 2326, "s": 1905, "text": "In the context of a movie recommender, collaborative filters find trends in how similar users rate movies based on rating profiles. The ratings data can be decomposed or otherwise processed using a variety of techniques to ultimately find user and movie embeddings in a shared latent space. The movie embeddings, which describe their location in the latent space, can then be used to make movie-to-movie recommendations." }, { "code": null, "e": 2751, "s": 2326, "text": "One benefit of collaborative data is that it is always “self-generating” — users create the data for you naturally as they interact with items. This can be a valuable data source, especially in cases where high-quality item features are not available or difficult to obtain. Another benefit of collaborative filters is that it helps users discover new items that are outside the subspace defined by their historical profile." }, { "code": null, "e": 3022, "s": 2751, "text": "However, there are some drawbacks to collaborative filters such as the well-known cold start problem. It is also difficult for collaborative filters to accurately recommend novel or niche items because these items typically do not have enough user-item interaction data." }, { "code": null, "e": 3116, "s": 3022, "text": "Content recommenders rely on item features to make recommendations. Examples of this include:" }, { "code": null, "e": 3198, "s": 3116, "text": "User generated tags on moviesItem colorText description or user review of an item" }, { "code": null, "e": 3228, "s": 3198, "text": "User generated tags on movies" }, { "code": null, "e": 3239, "s": 3228, "text": "Item color" }, { "code": null, "e": 3282, "s": 3239, "text": "Text description or user review of an item" }, { "code": null, "e": 3666, "s": 3282, "text": "Content filters tend to be more robust against popularity bias and the cold start problem. They can easily recommend new or novel items based on niche tastes. However, in an item-to-item recommender, content filters can only recommend items with features similar to the original item. This limits the scope of recommendations, and can also result in surfacing items with low ratings." }, { "code": null, "e": 4107, "s": 3666, "text": "In the context of a movie-to-movie recommender, a collaborative filter answers the question: “What movies have a similar user-rating profile?”, and a content filter answers the question: “What movies have similar features?”. By creating a hybrid recommender we’ve attempted to create a system that recommends movies that other users rated in a similar manner, while still making on-topic recommendations based on the features of that movie." }, { "code": null, "e": 4699, "s": 4107, "text": "Embeddings are a popular topic in several areas of machine learning, such as natural language processing, predictive models with categorical features and recommender systems. There are many ways to compute embeddings, but the end goal is to map “things” to a latent space with complex and meaningful dimensions. In a movie recommender, you can imagine latent dimensions measuring genres such as “sci-fi” and “romance” and other concepts such as “dialogue-driven versus action-packed”. Users and movies are mapped to this space by how strongly associated they are with each of the dimensions." }, { "code": null, "e": 4991, "s": 4699, "text": "In the famous word2vec example, learned word embeddings were able to complete the analogy “man is to woman as king is to ___.” As seen in the [very simplified] figure below, the words have been mapped into a shared latent space such that the meaning of the word is represented geometrically." }, { "code": null, "e": 5634, "s": 4991, "text": "There are cases in machine learning and deep learning where one can choose between using a one-hot encoding (OHE) or a learned embedding to perform a particular task. OHE representations of data have the potentially undesirable trait that every item is orthogonal (therefore quantitatively entirely dissimilar) to all other items. When thinking of words as an example, this can be a weak representation of the data because the similarity/exchangeability of similar words such as “alien” and “extraterrestrial” is completely lost due to the orthogonality. For this reason, the use of word embeddings can extend the capabilities of some models." }, { "code": null, "e": 5829, "s": 5634, "text": "We used cosine similarity to quantify the similarities between movies. Cosine similarity ranges from -1 to 1 and is calculated as the dot product between two vectors divided by their magnitudes." }, { "code": null, "e": 6282, "s": 5829, "text": "In a nutshell, movie embedding vectors pointing in the same direction will receive high cosine similarity scores. The idea is that directions through the latent concept space capture the essence of movies. A simple example to help visualize this: if “sci-fi” and “romance” are dimensions in the latent space, then movies with similar ratios of sci-fi-ness to romance-ness will point in the same direction and thus receive high cosine similarity scores." }, { "code": null, "e": 6425, "s": 6282, "text": "This code constructs the cosine similarity matrix from the movie embeddings and outputs the top n most similar movies for a given input movie." }, { "code": null, "e": 6677, "s": 6425, "text": "Included in the MovieLens data is a set of around 500k user-generated movie tags. According to the MovieLens README: “Each tag is typically a single word or short phrase. The meaning, value, and purpose of a particular tag is determined by each user.”" }, { "code": null, "e": 7116, "s": 6677, "text": "This data is grouped by movie and the tags are concatenated to produce a corpus of documents. In this corpus, documents are the combination of all tags for a particular movie. An excerpt of the tag document for “Lord of the Rings: The Fellowship of the Ring” is shown below. As you can see, words/phrases like “adventure”, “fantasy” and “based on a book” appear frequently. This data also includes the names of actors and the book author." }, { "code": null, "e": 8044, "s": 7116, "text": "adventure characters epic fantasy world fighting photography Action adventure atmospheric based on a book based on book beautifully filmed ensemble cast fantasy fantasy world high fantasy imdb top 250 magic music nature nothing at all Oscar (Best Cinematography) Oscar (Best Effects - Visual Effects) scenic stylized Tolkien wizards adventure atmospheric ensemble cast fantasy fantasy world magic stylized wizards Watched adapted from:book author:J. R. R. Tolkein based on book epic fantasy middle earth faithful to book fantasy good versus evil high fantasy joseph campbell's study of mythology influenced magic atmospheric boring high fantasy Action adventure atmospheric based on a book beautifully filmed fantasy high fantasy magic music mythology romance stylized time travel Viggo Mortensen wizards Peter Jackson Peter Jackson music must see Tolkien high fantasy Myth Tolkien wizards Ian McKellen bast background universe" }, { "code": null, "e": 8564, "s": 8044, "text": "Next, we transformed the tag documents into a Term Frequency — Inverse Document Frequency (TF-IDF) representation. TF-IDF tokenizes unstructured text data into numeric features that can be more easily processed by machine learning algorithms. Roughly speaking, the frequency of each term in a document is scaled by the number of documents containing that term. As a result, words that differentiate movies (e.g., “alien”, “fantasy”) will be weighted higher than words used to describe all movies (e.g. “movie”, “cast”)." }, { "code": null, "e": 8769, "s": 8564, "text": "The TF-IDF vectorizer in sci-kit learn allows you to select the range of ngrams to consider. For this project, we found that unigrams were sufficient while still keeping our number of features manageable." }, { "code": null, "e": 9253, "s": 8769, "text": "In TF-IDF space, each dimension represents how important a certain word is to a movie. This representation is less than ideal because the encoding of a single concept (e.g., alien/extraterrestrial) is fragmented and scattered across multiple dimensions. We would like to compress the TF-IDF data into a lower dimensional space where concepts are consolidated into shared dimensions. In the compressed space, the hope is that each dimension will represent complex and robust concepts." }, { "code": null, "e": 9921, "s": 9253, "text": "To perform the compression we chose to use an autoencoder. Autoencoders are neural networks where the outputs are identical to the inputs. In our architecture (shown in the figure below), the high-dimensional TF-IDF input is gradually compressed into a 100 dimensional central hidden layer. This first half of the network is the “encoder”. The second half of the network, the “decoder”, attempts to reconstruct the original input. By setting a mean-squared error loss function and performing backpropagation, the network (particularly the encoder) learns a function which maps data into lower dimensional space in such a way that most of the information is preserved." }, { "code": null, "e": 10075, "s": 9921, "text": "Let’s start off by defining the encoder and decoder networks. They are defined separately to make it easy to encode the data once the network is trained." }, { "code": null, "e": 10233, "s": 10075, "text": "Next, let’s define a PyTorch Dataset class. Notice in the __getitem__ method that x and y are equivalent — this is the fundamental concept of an autoencoder." }, { "code": null, "e": 10387, "s": 10233, "text": "With these building blocks in-hand, let’s define a wrapper class that instantiates everything, handles the training loop, and performs the data encoding." }, { "code": null, "e": 10474, "s": 10387, "text": "From here, it’s straightforward to train the autoencoder and encode/compress the data:" }, { "code": null, "e": 10672, "s": 10474, "text": "Below is a plot of the train and validation losses over time. As you can see, the model is not over- or under-fitting and eventually the losses converges to a very low value (on the order of 1e-4)." }, { "code": null, "e": 10872, "s": 10672, "text": "Using the content-based movie embeddings learned by the autoencoder, the top 20 most similar movies to “Lord of the Rings: The Fellowship of the Ring” as defined by cosine similarity are shown below." }, { "code": null, "e": 11436, "s": 10872, "text": "A fully connected neural network is used to find movie and user embeddings. In this architecture, a user embedding matrix of size (n_users, n_factors) and a movie embedding matrix of size (n_movies, n_factors) are randomly initialized and subsequently learned via gradient descent. Each training data point is a user index, movie index and a rating (on a scale of 1–5). The user and movie indices are used to lookup the embedding vectors (which are rows of the embedding matrices). These vectors are then concatenated and passed in as the input to the neural net." }, { "code": null, "e": 11737, "s": 11436, "text": "This is similar to the technique taught by Jeremy Howard in the fast.ai MOOC, and we used the fastai library as well. Let’s read in the data, create a validation set, and construct a fastai ColumnarModelData object which is essentially a handy wrapper around PyTorch’s Dataset and DataLoader classes." }, { "code": null, "e": 12425, "s": 11737, "text": "Next, let’s define the neural net. Since the output of the network is constrained to be within 1–5, a scaled sigmoid activation function is used at the output layer. Passing the linear activation though a sigmoid gives the model a bit more flexibility and thus makes it easier to train. For example, if the model is trying to output a 5, instead of forcing it to output a value very near 5 from the linear calculation, using a sigmoid allows it to output any high value (because inputs ~6 or greater all get mapped to ~1.0 by the sigmoid function). An alternative would be to stop short of the sigmoid and let the model learn to output the correct rating directly from the linear output." }, { "code": null, "e": 12638, "s": 12425, "text": "The fastai library makes it very simple to fit the model. The fit function used here takes care of the training loop and provides a nice animated status bar with time remaining and loss values for each minibatch." }, { "code": null, "e": 12961, "s": 12638, "text": "This model took a while to train due to the large size of the training data (20 million). At various points throughout training we adjusted the dropout levels to combat over- or under-fitting. The learning rate was also regularly tweaked using information from the learning rate finder tool included in the fastai library:" }, { "code": null, "e": 13533, "s": 12961, "text": "In the learning rate finder procedure, the learning rate is initially set to a very small value (1e-5) and is iteratively increased throughout the course of one epoch, up to a high ceiling value (10). At each stage, the loss is recorded so that a plot such as the one below may be produced. Interpreting this plot is a heuristic process that is explained in more detail in the fastai course, but the takeaway is this: select a learning rate where the loss is still decreasing quickly and has not leveled off yet. In this case, selecting 1e-2 would be a reasonable choice." }, { "code": null, "e": 13889, "s": 13533, "text": "With a dataset of this size (and the associated long training times), it is likely that you will need the ability to persist and depersist your trained model such that you can continue training at a later time. Once finished, you will also need to save your learned embeddings to disk for post-processing. The following code will take care of these items." }, { "code": null, "e": 14229, "s": 13889, "text": "Once the net is satisfactorily trained, you will have robust movie and user embeddings ready to use for a variety of practical tasks. Using the collaborative-based movie embeddings learned by this neural net, the top 20 most similar movies to “Lord of the Rings: The Fellowship of the Ring” as defined by cosine similarity are shown below." }, { "code": null, "e": 14534, "s": 14229, "text": "As seen above, the collaborative recommendations for Lord of the Rings appear to be primarily popular and highly rated blockbuster movies with strong action and adventure themes. The content recommendations appear to be less influenced by popularity and may include some hidden gems in the fantasy genre." }, { "code": null, "e": 14869, "s": 14534, "text": "To ensemble the results from the content and the collaborative models we simply averaged the cosine similarities. By ensembling collaborative and content-based results we are able to make recommendations that can hopefully draw from the strengths of both methods. The following are the ensembled recommendations for Lord of the Rings." }, { "code": null, "e": 15175, "s": 14869, "text": "In this post we developed a movie-to-movie hybrid content-collaborative recommender system. We discussed and illustrated the pros and cons of content and collaborative-based methods. We also showed how to develop recommender systems using deep learning instead of traditional matrix factorization methods." }, { "code": null, "e": 15551, "s": 15175, "text": "In our observations the collaborative filter was good at spanning gaps across genres and consistently recommending movies with high ratings. The content filter was good at identifying very similar styles (e.g., magical realms set in a medieval time) and lesser-viewed, potentially hidden gem movies. The aim of the hybrid approach is to combine the strengths of both systems." }, { "code": null, "e": 15727, "s": 15551, "text": "We also found some movies we want to see! If you would like to see recommendations for a particular movie of your choice, feel free to reach out on Twitter, LinkedIn or email." }, { "code": null, "e": 15838, "s": 15727, "text": "Adam is a data scientist in Denver, CO with interests in deep learning, big data, Formula 1 racing and skiing." } ]
PHP - Simple XML
The simple XML parser is used to parse Name, attributes and textual content. The simple XML functions are shown below − This function accepts file path as a first parameter and it is mandatory. simplexml_load_file(($fileName,$class,$options,$ns,$is_prefix) This function accepts the string instead of file reference. simplexml_load_string($XMLData,$class,$options,$ns,$is_prefix) This function accepts DOM formatted XML content and it converts into simple XML. simplexml_load_string($DOMNode,$class) The following example shows, How to parse a xml data file. <?php $data = "<?xml version = '1.0' encoding = 'UTF-8'?> <note> <Course>Android</Course> <Subject>Android</Subject> <Company>TutorialsPoint</Company> <Price>$10</Price> </note>"; $xml = simplexml_load_string($data) or die("Error: Cannot create object"); ?> <html> <head> <body> <?php print_r($xml); ?> </body> </head> </html> It will produce the following result − SimpleXMLElement Object ( [Course] => Android [Subject] => Android [Company] => TutorialsPoint [Price] => $10 ) We can also call a xml data file as shown below and it produces the same result as shown above − <?php $xml = simplexml_load_file("data") or die("Error: Cannot create object"); print_r($xml); ?> 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2834, "s": 2757, "text": "The simple XML parser is used to parse Name, attributes and textual content." }, { "code": null, "e": 2877, "s": 2834, "text": "The simple XML functions are shown below −" }, { "code": null, "e": 2951, "s": 2877, "text": "This function accepts file path as a first parameter and it is mandatory." }, { "code": null, "e": 3015, "s": 2951, "text": "simplexml_load_file(($fileName,$class,$options,$ns,$is_prefix)\n" }, { "code": null, "e": 3075, "s": 3015, "text": "This function accepts the string instead of file reference." }, { "code": null, "e": 3139, "s": 3075, "text": "simplexml_load_string($XMLData,$class,$options,$ns,$is_prefix)\n" }, { "code": null, "e": 3220, "s": 3139, "text": "This function accepts DOM formatted XML content and it converts into simple XML." }, { "code": null, "e": 3260, "s": 3220, "text": "simplexml_load_string($DOMNode,$class)\n" }, { "code": null, "e": 3319, "s": 3260, "text": "The following example shows, How to parse a xml data file." }, { "code": null, "e": 3760, "s": 3319, "text": "<?php\n $data = \"<?xml version = '1.0' encoding = 'UTF-8'?>\n \n <note>\n <Course>Android</Course>\n <Subject>Android</Subject>\n <Company>TutorialsPoint</Company>\n <Price>$10</Price>\n </note>\";\n \n $xml = simplexml_load_string($data) or die(\"Error: Cannot create object\");\n?>\n<html>\n\n <head>\n <body>\n \n <?php\n print_r($xml);\n ?>\n \n </body>\n </head>\n \n</html>" }, { "code": null, "e": 3799, "s": 3760, "text": "It will produce the following result −" }, { "code": null, "e": 3912, "s": 3799, "text": "SimpleXMLElement Object ( [Course] => Android [Subject] => Android [Company] => TutorialsPoint [Price] => $10 )\n" }, { "code": null, "e": 4009, "s": 3912, "text": "We can also call a xml data file as shown below and it produces the same result as shown above −" }, { "code": null, "e": 4113, "s": 4009, "text": "<?php\n $xml = simplexml_load_file(\"data\") or die(\"Error: Cannot create object\");\n print_r($xml);\n?>" }, { "code": null, "e": 4146, "s": 4113, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 4162, "s": 4146, "text": " Malhar Lathkar" }, { "code": null, "e": 4195, "s": 4162, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 4206, "s": 4195, "text": " Syed Raza" }, { "code": null, "e": 4241, "s": 4206, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4258, "s": 4241, "text": " Frahaan Hussain" }, { "code": null, "e": 4291, "s": 4258, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 4306, "s": 4291, "text": " Nivedita Jain" }, { "code": null, "e": 4341, "s": 4306, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 4353, "s": 4341, "text": " Azaz Patel" }, { "code": null, "e": 4388, "s": 4353, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4416, "s": 4388, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 4423, "s": 4416, "text": " Print" }, { "code": null, "e": 4434, "s": 4423, "text": " Add Notes" } ]
Future and FutureTask in java - GeeksforGeeks
25 Jun, 2021 Prerequisite: Future and callable A Future interface provides methods to check if the computation is complete, to wait for its completion and to retrieve the results of the computation. The result is retrieved using Future’s get() method when the computation has completed, and it blocks until it is completed. Future and FutureTask both are available in java.util.concurrent package from Java 1.5. FutureTask implementation Future interface and RunnableFuture Interface, means one can use FutureTask as Runnable and can be submitted to ExecutorService for execution.When one call Future.submit() Callable or Runnable objects then most of time ExecutorService creates FutureTask, and one can create it manually also.FutureTask acts like a latch.Computation represent by FutureTask is implemented with Callable interface.It implements Future or Callable interface.Behaviour of get() method depends on the state of the task. If tasks are not completed get() method waits or blocks till the task is completed. Once task completed, it returns the result or throws an ExecutionException. FutureTask implementation Future interface and RunnableFuture Interface, means one can use FutureTask as Runnable and can be submitted to ExecutorService for execution. When one call Future.submit() Callable or Runnable objects then most of time ExecutorService creates FutureTask, and one can create it manually also. FutureTask acts like a latch. Computation represent by FutureTask is implemented with Callable interface. It implements Future or Callable interface. Behaviour of get() method depends on the state of the task. If tasks are not completed get() method waits or blocks till the task is completed. Once task completed, it returns the result or throws an ExecutionException. An example of using Future is working with Thread pools. When one submit a task to ExecutorService which is take a long running time, then it returns a Future object immediately. This Future object can be used for task completion and getting result of computation. Examples: Create two task. After one is completely executed, then after waiting 2000 millisecond, second task is being executed Note: Online IDE does not work properly on sleep() method. Java // Java program do two FutureTask// using Runnable Interface import java.util.concurrent.*;import java.util.logging.Level;import java.util.logging.Logger; class MyRunnable implements Runnable { private final long waitTime; public MyRunnable(int timeInMillis) { this.waitTime = timeInMillis; } @Override public void run() { try { // sleep for user given millisecond // before checking again Thread.sleep(waitTime); // return current thread name System.out.println(Thread .currentThread() .getName()); } catch (InterruptedException ex) { Logger .getLogger(MyRunnable.class.getName()) .log(Level.SEVERE, null, ex); } }} // Class FutureTaskExample execute two future taskclass FutureTaskExample { public static void main(String[] args) { // create two object of MyRunnable class // for FutureTask and sleep 1000, 2000 // millisecond before checking again MyRunnable myrunnableobject1 = new MyRunnable(1000); MyRunnable myrunnableobject2 = new MyRunnable(2000); FutureTask<String> futureTask1 = new FutureTask<>(myrunnableobject1, "FutureTask1 is complete"); FutureTask<String> futureTask2 = new FutureTask<>(myrunnableobject2, "FutureTask2 is complete"); // create thread pool of 2 size for ExecutorService ExecutorService executor = Executors.newFixedThreadPool(2); // submit futureTask1 to ExecutorService executor.submit(futureTask1); // submit futureTask2 to ExecutorService executor.submit(futureTask2); while (true) { try { // if both future task complete if (futureTask1.isDone() && futureTask2.isDone()) { System.out.println("Both FutureTask Complete"); // shut down executor service executor.shutdown(); return; } if (!futureTask1.isDone()) { // wait indefinitely for future // task to complete System.out.println("FutureTask1 output = " + futureTask1.get()); } System.out.println("Waiting for FutureTask2 to complete"); // Wait if necessary for the computation to complete, // and then retrieves its result String s = futureTask2.get(250, TimeUnit.MILLISECONDS); if (s != null) { System.out.println("FutureTask2 output=" + s); } } catch (Exception e) { Sysmtem.out.println("Exception: " + e); } } }} Output: FutureTask1 output=FutureTask1 is complete Waiting for FutureTask2 to complete Waiting for FutureTask2 to complete Waiting for FutureTask2 to complete Waiting for FutureTask2 to complete FutureTask2 output=FutureTask2 is complete Both FutureTask Complete Reference: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/FutureTask.html Java-Class and Object java-interfaces Technical Scripter 2018 Java Technical Scripter Java-Class and Object Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Interfaces in Java Object Oriented Programming (OOPs) Concept in Java ArrayList in Java Initialize an ArrayList in Java How to iterate any Map in Java Overriding in Java LinkedList in Java Collections in Java Queue Interface In Java
[ { "code": null, "e": 24019, "s": 23991, "text": "\n25 Jun, 2021" }, { "code": null, "e": 24053, "s": 24019, "text": "Prerequisite: Future and callable" }, { "code": null, "e": 24418, "s": 24053, "text": "A Future interface provides methods to check if the computation is complete, to wait for its completion and to retrieve the results of the computation. The result is retrieved using Future’s get() method when the computation has completed, and it blocks until it is completed. Future and FutureTask both are available in java.util.concurrent package from Java 1.5." }, { "code": null, "e": 25102, "s": 24418, "text": "FutureTask implementation Future interface and RunnableFuture Interface, means one can use FutureTask as Runnable and can be submitted to ExecutorService for execution.When one call Future.submit() Callable or Runnable objects then most of time ExecutorService creates FutureTask, and one can create it manually also.FutureTask acts like a latch.Computation represent by FutureTask is implemented with Callable interface.It implements Future or Callable interface.Behaviour of get() method depends on the state of the task. If tasks are not completed get() method waits or blocks till the task is completed. Once task completed, it returns the result or throws an ExecutionException." }, { "code": null, "e": 25271, "s": 25102, "text": "FutureTask implementation Future interface and RunnableFuture Interface, means one can use FutureTask as Runnable and can be submitted to ExecutorService for execution." }, { "code": null, "e": 25421, "s": 25271, "text": "When one call Future.submit() Callable or Runnable objects then most of time ExecutorService creates FutureTask, and one can create it manually also." }, { "code": null, "e": 25451, "s": 25421, "text": "FutureTask acts like a latch." }, { "code": null, "e": 25527, "s": 25451, "text": "Computation represent by FutureTask is implemented with Callable interface." }, { "code": null, "e": 25571, "s": 25527, "text": "It implements Future or Callable interface." }, { "code": null, "e": 25791, "s": 25571, "text": "Behaviour of get() method depends on the state of the task. If tasks are not completed get() method waits or blocks till the task is completed. Once task completed, it returns the result or throws an ExecutionException." }, { "code": null, "e": 26058, "s": 25791, "text": "An example of using Future is working with Thread pools. When one submit a task to ExecutorService which is take a long running time, then it returns a Future object immediately. This Future object can be used for task completion and getting result of computation. " }, { "code": null, "e": 26186, "s": 26058, "text": "Examples: Create two task. After one is completely executed, then after waiting 2000 millisecond, second task is being executed" }, { "code": null, "e": 26246, "s": 26186, "text": "Note: Online IDE does not work properly on sleep() method. " }, { "code": null, "e": 26251, "s": 26246, "text": "Java" }, { "code": "// Java program do two FutureTask// using Runnable Interface import java.util.concurrent.*;import java.util.logging.Level;import java.util.logging.Logger; class MyRunnable implements Runnable { private final long waitTime; public MyRunnable(int timeInMillis) { this.waitTime = timeInMillis; } @Override public void run() { try { // sleep for user given millisecond // before checking again Thread.sleep(waitTime); // return current thread name System.out.println(Thread .currentThread() .getName()); } catch (InterruptedException ex) { Logger .getLogger(MyRunnable.class.getName()) .log(Level.SEVERE, null, ex); } }} // Class FutureTaskExample execute two future taskclass FutureTaskExample { public static void main(String[] args) { // create two object of MyRunnable class // for FutureTask and sleep 1000, 2000 // millisecond before checking again MyRunnable myrunnableobject1 = new MyRunnable(1000); MyRunnable myrunnableobject2 = new MyRunnable(2000); FutureTask<String> futureTask1 = new FutureTask<>(myrunnableobject1, \"FutureTask1 is complete\"); FutureTask<String> futureTask2 = new FutureTask<>(myrunnableobject2, \"FutureTask2 is complete\"); // create thread pool of 2 size for ExecutorService ExecutorService executor = Executors.newFixedThreadPool(2); // submit futureTask1 to ExecutorService executor.submit(futureTask1); // submit futureTask2 to ExecutorService executor.submit(futureTask2); while (true) { try { // if both future task complete if (futureTask1.isDone() && futureTask2.isDone()) { System.out.println(\"Both FutureTask Complete\"); // shut down executor service executor.shutdown(); return; } if (!futureTask1.isDone()) { // wait indefinitely for future // task to complete System.out.println(\"FutureTask1 output = \" + futureTask1.get()); } System.out.println(\"Waiting for FutureTask2 to complete\"); // Wait if necessary for the computation to complete, // and then retrieves its result String s = futureTask2.get(250, TimeUnit.MILLISECONDS); if (s != null) { System.out.println(\"FutureTask2 output=\" + s); } } catch (Exception e) { Sysmtem.out.println(\"Exception: \" + e); } } }}", "e": 29234, "s": 26251, "text": null }, { "code": null, "e": 29243, "s": 29234, "text": "Output: " }, { "code": null, "e": 29498, "s": 29243, "text": "FutureTask1 output=FutureTask1 is complete\nWaiting for FutureTask2 to complete\nWaiting for FutureTask2 to complete\nWaiting for FutureTask2 to complete\nWaiting for FutureTask2 to complete\nFutureTask2 output=FutureTask2 is complete\nBoth FutureTask Complete" }, { "code": null, "e": 29511, "s": 29498, "text": "Reference: " }, { "code": null, "e": 29586, "s": 29511, "text": "https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html" }, { "code": null, "e": 29665, "s": 29586, "text": "https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/FutureTask.html" }, { "code": null, "e": 29689, "s": 29667, "text": "Java-Class and Object" }, { "code": null, "e": 29705, "s": 29689, "text": "java-interfaces" }, { "code": null, "e": 29729, "s": 29705, "text": "Technical Scripter 2018" }, { "code": null, "e": 29734, "s": 29729, "text": "Java" }, { "code": null, "e": 29753, "s": 29734, "text": "Technical Scripter" }, { "code": null, "e": 29775, "s": 29753, "text": "Java-Class and Object" }, { "code": null, "e": 29780, "s": 29775, "text": "Java" }, { "code": null, "e": 29878, "s": 29780, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29887, "s": 29878, "text": "Comments" }, { "code": null, "e": 29900, "s": 29887, "text": "Old Comments" }, { "code": null, "e": 29930, "s": 29900, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29949, "s": 29930, "text": "Interfaces in Java" }, { "code": null, "e": 30000, "s": 29949, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 30018, "s": 30000, "text": "ArrayList in Java" }, { "code": null, "e": 30050, "s": 30018, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 30081, "s": 30050, "text": "How to iterate any Map in Java" }, { "code": null, "e": 30100, "s": 30081, "text": "Overriding in Java" }, { "code": null, "e": 30119, "s": 30100, "text": "LinkedList in Java" }, { "code": null, "e": 30139, "s": 30119, "text": "Collections in Java" } ]
JavaFX - Application
In this chapter, we will discuss the structure of a JavaFX application in detail and also learn to create a JavaFX application with an example. In general, a JavaFX application will have three major components namely Stage, Scene and Nodes as shown in the following diagram. A stage (a window) contains all the objects of a JavaFX application. It is represented by Stage class of the package javafx.stage. The primary stage is created by the platform itself. The created stage object is passed as an argument to the start() method of the Application class (explained in the next section). A stage has two parameters determining its position namely Width and Height. It is divided as Content Area and Decorations (Title Bar and Borders). There are five types of stages available − Decorated Undecorated Transparent Unified Utility You have to call the show() method to display the contents of a stage. A scene represents the physical contents of a JavaFX application. It contains all the contents of a scene graph. The class Scene of the package javafx.scene represents the scene object. At an instance, the scene object is added to only one stage. You can create a scene by instantiating the Scene Class. You can opt for the size of the scene by passing its dimensions (height and width) along with the root node to its constructor. A scene graph is a tree-like data structure (hierarchical) representing the contents of a scene. In contrast, a node is a visual/graphical object of a scene graph. A node may include − Geometrical (Graphical) objects (2D and 3D) such as − Circle, Rectangle, Polygon, etc. Geometrical (Graphical) objects (2D and 3D) such as − Circle, Rectangle, Polygon, etc. UI Controls such as − Button, Checkbox, Choice Box, Text Area, etc. UI Controls such as − Button, Checkbox, Choice Box, Text Area, etc. Containers (Layout Panes) such as Border Pane, Grid Pane, Flow Pane, etc. Containers (Layout Panes) such as Border Pane, Grid Pane, Flow Pane, etc. Media elements such as Audio, Video and Image Objects. Media elements such as Audio, Video and Image Objects. The Node Class of the package javafx.scene represents a node in JavaFX, this class is the super class of all the nodes. As discussed earlier a node is of three types − Root Node − The first Scene Graph is known as the Root node. Root Node − The first Scene Graph is known as the Root node. Branch Node/Parent Node − The node with child nodes are known as branch/parent nodes. The abstract class named Parent of the package javafx.scene is the base class of all the parent nodes, and those parent nodes will be of the following types − Group − A group node is a collective node that contains a list of children nodes. Whenever the group node is rendered, all its child nodes are rendered in order. Any transformation, effect state applied on the group will be applied to all the child nodes. Region − It is the base class of all the JavaFX Node based UI Controls, such as Chart, Pane and Control. WebView − This node manages the web engine and displays its contents. Branch Node/Parent Node − The node with child nodes are known as branch/parent nodes. The abstract class named Parent of the package javafx.scene is the base class of all the parent nodes, and those parent nodes will be of the following types − Group − A group node is a collective node that contains a list of children nodes. Whenever the group node is rendered, all its child nodes are rendered in order. Any transformation, effect state applied on the group will be applied to all the child nodes. Group − A group node is a collective node that contains a list of children nodes. Whenever the group node is rendered, all its child nodes are rendered in order. Any transformation, effect state applied on the group will be applied to all the child nodes. Region − It is the base class of all the JavaFX Node based UI Controls, such as Chart, Pane and Control. Region − It is the base class of all the JavaFX Node based UI Controls, such as Chart, Pane and Control. WebView − This node manages the web engine and displays its contents. WebView − This node manages the web engine and displays its contents. Leaf Node − The node without child nodes is known as the leaf node. For example, Rectangle, Ellipse, Box, ImageView, MediaView are examples of leaf nodes. Leaf Node − The node without child nodes is known as the leaf node. For example, Rectangle, Ellipse, Box, ImageView, MediaView are examples of leaf nodes. It is mandatory to pass the root node to the scene graph. If the Group is passed as root, all the nodes will be clipped to the scene and any alteration in the size of the scene will not affect the layout of the scene. To create a JavaFX application, you need to instantiate the Application class and implement its abstract method start(). In this method, we will write the code for the JavaFX Application. The Application class of the package javafx.application is the entry point of the application in JavaFX. To create a JavaFX application, you need to inherit this class and implement its abstract method start(). In this method, you need to write the entire code for the JavaFX graphics In the main method, you have to launch the application using the launch() method. This method internally calls the start() method of the Application class as shown in the following program. public class JavafxSample extends Application { @Override public void start(Stage primaryStage) throws Exception { /* Code for JavaFX application. (Stage, scene, scene graph) */ } public static void main(String args[]){ launch(args); } } Within the start() method, in order to create a typical JavaFX application, you need to follow the steps given below − Prepare a scene graph with the required nodes. Prepare a scene graph with the required nodes. Prepare a Scene with the required dimensions and add the scene graph (root node of the scene graph) to it. Prepare a Scene with the required dimensions and add the scene graph (root node of the scene graph) to it. Prepare a stage and add the scene to the stage and display the contents of the stage. Prepare a stage and add the scene to the stage and display the contents of the stage. As per your application, you need to prepare a scene graph with required nodes. Since the root node is the first node, you need to create a root node. As a root node, you can choose from the Group, Region or WebView. Group − A Group node is represented by the class named Group which belongs to the package javafx.scene, you can create a Group node by instantiating this class as shown below. Group root = new Group(); The getChildren() method of the Group class gives you an object of the ObservableList class which holds the nodes. We can retrieve this object and add nodes to it as shown below. //Retrieving the observable list object ObservableList list = root.getChildren(); //Setting the text object as a node list.add(NodeObject); We can also add Node objects to the group, just by passing them to the Group class and to its constructor at the time of instantiation, as shown below. Group root = new Group(NodeObject); Region − It is the Base class of all the JavaFX Node-based UI Controls, such as − Chart − This class is the base class of all the charts and it belongs to the package javafx.scene.chart. This class has two sub classes, which are − PieChart and XYChart. These two in turn have subclasses such as AreaChart, BarChart, BubbleChart, etc. used to draw different types of XY-Plane Charts in JavaFX. You can use these classes to embed charts in your application. Chart − This class is the base class of all the charts and it belongs to the package javafx.scene.chart. This class has two sub classes, which are − PieChart and XYChart. These two in turn have subclasses such as AreaChart, BarChart, BubbleChart, etc. used to draw different types of XY-Plane Charts in JavaFX. You can use these classes to embed charts in your application. Pane − A Pane is the base class of all the layout panes such as AnchorPane, BorderPane, DialogPane, etc. This class belong to a package that is called as − javafx.scene.layout. You can use these classes to insert predefined layouts in your application. Pane − A Pane is the base class of all the layout panes such as AnchorPane, BorderPane, DialogPane, etc. This class belong to a package that is called as − javafx.scene.layout. You can use these classes to insert predefined layouts in your application. Control − It is the base class of the User Interface controls such as Accordion, ButtonBar, ChoiceBox, ComboBoxBase, HTMLEditor, etc. This class belongs to the package javafx.scene.control. You can use these classes to insert various UI elements in your application. Control − It is the base class of the User Interface controls such as Accordion, ButtonBar, ChoiceBox, ComboBoxBase, HTMLEditor, etc. This class belongs to the package javafx.scene.control. You can use these classes to insert various UI elements in your application. In a Group, you can instantiate any of the above-mentioned classes and use them as root nodes, as shown in the following program. //Creating a Stack Pane StackPane pane = new StackPane(); //Adding text area to the pane ObservableList list = pane.getChildren(); list.add(NodeObject); WebView − This node manages the web engine and displays its contents. Following is a diagram representing the node class hierarchy of JavaFX. A JavaFX scene is represented by the Scene class of the package javafx.scene. You can create a Scene by instantiating this class as shown in the following cod block. While instantiating, it is mandatory to pass the root object to the constructor of the scene class. Scene scene = new Scene(root); You can also pass two parameters of double type representing the height and width of the scene as shown below. Scene scene = new Scene(root, 600, 300); This is the container of any JavaFX application and it provides a window for the application. It is represented by the Stage class of the package javafx.stage. An object of this class is passed as a parameter of the start() method of the Application class. Using this object, you can perform various operations on the stage. Primarily you can perform the following − Set the title for the stage using the method setTitle(). Set the title for the stage using the method setTitle(). Attach the scene object to the stage using the setScene() method. Attach the scene object to the stage using the setScene() method. Display the contents of the scene using the show() method as shown below. Display the contents of the scene using the show() method as shown below. //Setting the title to Stage. primaryStage.setTitle("Sample application"); //Setting the scene to Stage primaryStage.setScene(scene); //Displaying the stage primaryStage.show(); The JavaFX Application class has three life cycle methods, which are − start() − The entry point method where the JavaFX graphics code is to be written. start() − The entry point method where the JavaFX graphics code is to be written. stop() − An empty method which can be overridden, here you can write the logic to stop the application. stop() − An empty method which can be overridden, here you can write the logic to stop the application. init() − An empty method which can be overridden, but you cannot create stage or scene in this method. init() − An empty method which can be overridden, but you cannot create stage or scene in this method. In addition to these, it provides a static method named launch() to launch JavaFX application. Since the launch() method is static, you need to call it from a static context (main generally). Whenever a JavaFX application is launched, the following actions will be carried out (in the same order). An instance of the application class is created. An instance of the application class is created. Init() method is called. Init() method is called. The start() method is called. The start() method is called. The launcher waits for the application to finish and calls the stop() method. The launcher waits for the application to finish and calls the stop() method. When the last window of the application is closed, the JavaFX application is terminated implicitly. You can turn this behavior off by passing the Boolean value “False” to the static method setImplicitExit() (should be called from a static context). You can terminate a JavaFX application explicitly using the methods Platform.exit() or System.exit(int). This section teaches you how to create a JavaFX sample application which displays an empty window. Following are the steps − Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows. public class JavafxSample extends Application { @Override public void start(Stage primaryStage) throws Exception { } } In the start() method creates a group object by instantiating the class named Group, which belongs to the package javafx.scene, as follows. Group root = new Group(); Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class, pass the Group object (root), created in the previous step. In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows. Scene scene = new Scene(root,600, 300); You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter. Using the primaryStage object, set the title of the scene as Sample Application as shown below. primaryStage.setTitle("Sample Application"); You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as shown below. primaryStage.setScene(scene); Display the contents of the scene using the method named show() of the Stage class as follows. primaryStage.show(); Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows. public static void main(String args[]){ launch(args); } The following program generates an empty JavaFX window. Save this code in a file with the name JavafxSample.java import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; public class JavafxSample extends Application { @Override public void start(Stage primaryStage) throws Exception { //creating a Group object Group group = new Group(); //Creating a Scene by passing the group object, height and width Scene scene = new Scene(group ,600, 300); //setting color to the scene scene.setFill(Color.BROWN); //Setting the title to Stage. primaryStage.setTitle("Sample Application"); //Adding the scene to Stage primaryStage.setScene(scene); //Displaying the contents of the stage primaryStage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac JavafxSample.java java JavafxSample On executing, the above program generates a JavaFX window as shown below. In the previous example, we have seen how to create an empty stage, now in this example let us try to draw a straight line using the JavaFX library. Following are the steps − Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows. public class DrawingLine extends Application { @Override public void start(Stage primaryStage) throws Exception { } } You can create a line in JavaFX by instantiating the class named Line which belongs to a package javafx.scene.shape, instantiate this class as follows. //Creating a line object Line line = new Line(); Specify the coordinates to draw the line on an X-Y plane by setting the properties startX, startY, endX and endY, using their respective setter methods as shown in the following code block. line.setStartX(100.0); line.setStartY(150.0); line.setEndX(500.0); line.setEndY(150.0); In the start() method create a group object by instantiating the class named Group, which belongs to the package javafx.scene. Pass the Line (node) object, created in the previous step, as a parameter to the constructor of the Group class, in order to add it to the group as follows − Group root = new Group(line); Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class, pass the Group object (root) that was created in the previous step. In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows. Scene scene = new Scene(group ,600, 300); You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter. Using the primaryStage object, set the title of the scene as Sample Application as follows. primaryStage.setTitle("Sample Application"); You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as follows. primaryStage.setScene(scene); Display the contents of the scene using the method named show() of the Stage class as follows. primaryStage.show(); Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows. public static void main(String args[]){ launch(args); } The following program shows how to generate a straight line using JavaFX. Save this code in a file with the name JavafxSample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Line; import javafx.stage.Stage; public class DrawingLine extends Application{ @Override public void start(Stage stage) { //Creating a line object Line line = new Line(); //Setting the properties to a line line.setStartX(100.0); line.setStartY(150.0); line.setEndX(500.0); line.setEndY(150.0); //Creating a Group Group root = new Group(line); //Creating a Scene Scene scene = new Scene(root, 600, 300); //Setting title to the scene stage.setTitle("Sample application"); //Adding the scene to the stage stage.setScene(scene); //Displaying the contents of a scene stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac DrawingLine.java java DrawingLine On executing, the above program generates a JavaFX window displaying a straight line as shown below. We can also embed text in JavaFX scene. This example shows how to embed text in JavaFX. Following are the steps − Create a Java Class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows. public class DrawingLine extends Application { @Override public void start(Stage primaryStage) throws Exception { } } You can embed text into a JavaFX scene by instantiating the class named Text which belongs to a package javafx.scene.shape, instantiate this class. You can instantiate this class by passing text to be embedded, in String format Or, you can create text object using the default constructor as shown below. //Creating a Text object Text text = new Text(); You can set font to the text using the setFont() method of the Text class. This method accepts a font object as parameters. Set the font of the given text to 45 as shown below. //Setting font to the text text.setFont(new Font(45)); You can set the position of the text on the X-Y plane by setting the X,Y coordinates using the respective setter methods setX() and setY() as follows. //setting the position of the text text.setX(50); text.setY(150); You can set the text to be added using the setText() method of the Text class. This method accepts a string parameter representing the text to be added. text.setText("Welcome to Tutorialspoint"); In the start() method, create a group object by instantiating the class named Group, which belongs to the package javafx.scene. Pass the Text (node) object, created in the previous step, as a parameter to the constructor of the Group class, in order to add it to the group as follows − Group root = new Group(text) Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class, pass the Group object (root), created in the previous step. In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows. Scene scene = new Scene(group ,600, 300); You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter. Using the primaryStage object, set the title of the scene as Sample Application as shown below. primaryStage.setTitle("Sample Application"); You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as follows. primaryStage.setScene(scene); Display the contents of the scene using the method named show() of the Stage class as follows. primaryStage.show(); Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows. public static void main(String args[]){ launch(args); } Following is the program to display text using JavaFX. Save this code in a file with name DisplayingText.java. import javafx.application.Application; import javafx.collections.ObservableList; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.text.Font; import javafx.scene.text.Text; public class DisplayingText extends Application { @Override public void start(Stage stage) { //Creating a Text object Text text = new Text(); //Setting font to the text text.setFont(new Font(45)); //setting the position of the text text.setX(50); text.setY(150); //Setting the text to be added. text.setText("Welcome to Tutorialspoint"); //Creating a Group object Group root = new Group(); //Retrieving the observable list object ObservableList list = root.getChildren(); //Setting the text object as a node to the group object list.add(text); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle("Sample Application"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac DisplayingText.java java DisplayingText On executing, the above program generates a JavaFX window displaying text as shown below. 33 Lectures 7.5 hours Syed Raza 64 Lectures 12.5 hours Emenwa Global, Ejike IfeanyiChukwu 20 Lectures 4 hours Emenwa Global, Ejike IfeanyiChukwu Print Add Notes Bookmark this page
[ { "code": null, "e": 2044, "s": 1900, "text": "In this chapter, we will discuss the structure of a JavaFX application in detail and also learn to create a JavaFX application with an example." }, { "code": null, "e": 2175, "s": 2044, "text": "In general, a JavaFX application will have three major components namely Stage, Scene and Nodes as shown in the following diagram." }, { "code": null, "e": 2489, "s": 2175, "text": "A stage (a window) contains all the objects of a JavaFX application. It is represented by Stage class of the package javafx.stage. The primary stage is created by the platform itself. The created stage object is passed as an argument to the start() method of the Application class (explained in the next section)." }, { "code": null, "e": 2637, "s": 2489, "text": "A stage has two parameters determining its position namely Width and Height. It is divided as Content Area and Decorations (Title Bar and Borders)." }, { "code": null, "e": 2681, "s": 2637, "text": "There are five types of stages available −" }, { "code": null, "e": 2691, "s": 2681, "text": "Decorated" }, { "code": null, "e": 2703, "s": 2691, "text": "Undecorated" }, { "code": null, "e": 2715, "s": 2703, "text": "Transparent" }, { "code": null, "e": 2723, "s": 2715, "text": "Unified" }, { "code": null, "e": 2731, "s": 2723, "text": "Utility" }, { "code": null, "e": 2802, "s": 2731, "text": "You have to call the show() method to display the contents of a stage." }, { "code": null, "e": 3049, "s": 2802, "text": "A scene represents the physical contents of a JavaFX application. It contains all the contents of a scene graph. The class Scene of the package javafx.scene represents the scene object. At an instance, the scene object is added to only one stage." }, { "code": null, "e": 3234, "s": 3049, "text": "You can create a scene by instantiating the Scene Class. You can opt for the size of the scene by passing its dimensions (height and width) along with the root node to its constructor." }, { "code": null, "e": 3398, "s": 3234, "text": "A scene graph is a tree-like data structure (hierarchical) representing the contents of a scene. In contrast, a node is a visual/graphical object of a scene graph." }, { "code": null, "e": 3419, "s": 3398, "text": "A node may include −" }, { "code": null, "e": 3506, "s": 3419, "text": "Geometrical (Graphical) objects (2D and 3D) such as − Circle, Rectangle, Polygon, etc." }, { "code": null, "e": 3593, "s": 3506, "text": "Geometrical (Graphical) objects (2D and 3D) such as − Circle, Rectangle, Polygon, etc." }, { "code": null, "e": 3661, "s": 3593, "text": "UI Controls such as − Button, Checkbox, Choice Box, Text Area, etc." }, { "code": null, "e": 3729, "s": 3661, "text": "UI Controls such as − Button, Checkbox, Choice Box, Text Area, etc." }, { "code": null, "e": 3803, "s": 3729, "text": "Containers (Layout Panes) such as Border Pane, Grid Pane, Flow Pane, etc." }, { "code": null, "e": 3877, "s": 3803, "text": "Containers (Layout Panes) such as Border Pane, Grid Pane, Flow Pane, etc." }, { "code": null, "e": 3932, "s": 3877, "text": "Media elements such as Audio, Video and Image Objects." }, { "code": null, "e": 3987, "s": 3932, "text": "Media elements such as Audio, Video and Image Objects." }, { "code": null, "e": 4107, "s": 3987, "text": "The Node Class of the package javafx.scene represents a node in JavaFX, this class is the super class of all the nodes." }, { "code": null, "e": 4155, "s": 4107, "text": "As discussed earlier a node is of three types −" }, { "code": null, "e": 4216, "s": 4155, "text": "Root Node − The first Scene Graph is known as the Root node." }, { "code": null, "e": 4277, "s": 4216, "text": "Root Node − The first Scene Graph is known as the Root node." }, { "code": null, "e": 4957, "s": 4277, "text": "Branch Node/Parent Node − The node with child nodes are known as branch/parent nodes. The abstract class named Parent of the package javafx.scene is the base class of all the parent nodes, and those parent nodes will be of the following types −\n\nGroup − A group node is a collective node that contains a list of children nodes. Whenever the group node is rendered, all its child nodes are rendered in order. Any transformation, effect state applied on the group will be applied to all the child nodes.\nRegion − It is the base class of all the JavaFX Node based UI Controls, such as Chart, Pane and Control.\nWebView − This node manages the web engine and displays its contents.\n\n" }, { "code": null, "e": 5202, "s": 4957, "text": "Branch Node/Parent Node − The node with child nodes are known as branch/parent nodes. The abstract class named Parent of the package javafx.scene is the base class of all the parent nodes, and those parent nodes will be of the following types −" }, { "code": null, "e": 5459, "s": 5202, "text": "Group − A group node is a collective node that contains a list of children nodes. Whenever the group node is rendered, all its child nodes are rendered in order. Any transformation, effect state applied on the group will be applied to all the child nodes." }, { "code": null, "e": 5716, "s": 5459, "text": "Group − A group node is a collective node that contains a list of children nodes. Whenever the group node is rendered, all its child nodes are rendered in order. Any transformation, effect state applied on the group will be applied to all the child nodes." }, { "code": null, "e": 5821, "s": 5716, "text": "Region − It is the base class of all the JavaFX Node based UI Controls, such as Chart, Pane and Control." }, { "code": null, "e": 5926, "s": 5821, "text": "Region − It is the base class of all the JavaFX Node based UI Controls, such as Chart, Pane and Control." }, { "code": null, "e": 5996, "s": 5926, "text": "WebView − This node manages the web engine and displays its contents." }, { "code": null, "e": 6066, "s": 5996, "text": "WebView − This node manages the web engine and displays its contents." }, { "code": null, "e": 6221, "s": 6066, "text": "Leaf Node − The node without child nodes is known as the leaf node. For example, Rectangle, Ellipse, Box, ImageView, MediaView are examples of leaf nodes." }, { "code": null, "e": 6376, "s": 6221, "text": "Leaf Node − The node without child nodes is known as the leaf node. For example, Rectangle, Ellipse, Box, ImageView, MediaView are examples of leaf nodes." }, { "code": null, "e": 6594, "s": 6376, "text": "It is mandatory to pass the root node to the scene graph. If the Group is passed as root, all the nodes will be clipped to the scene and any alteration in the size of the scene will not affect the layout of the scene." }, { "code": null, "e": 6782, "s": 6594, "text": "To create a JavaFX application, you need to instantiate the Application class and implement its abstract method start(). In this method, we will write the code for the JavaFX Application." }, { "code": null, "e": 7067, "s": 6782, "text": "The Application class of the package javafx.application is the entry point of the application in JavaFX. To create a JavaFX application, you need to inherit this class and implement its abstract method start(). In this method, you need to write the entire code for the JavaFX graphics" }, { "code": null, "e": 7257, "s": 7067, "text": "In the main method, you have to launch the application using the launch() method. This method internally calls the start() method of the Application class as shown in the following program." }, { "code": null, "e": 7586, "s": 7257, "text": "public class JavafxSample extends Application { \n @Override \n public void start(Stage primaryStage) throws Exception { \n /* \n Code for JavaFX application. \n (Stage, scene, scene graph) \n */ \n } \n public static void main(String args[]){ \n launch(args); \n } \n} " }, { "code": null, "e": 7705, "s": 7586, "text": "Within the start() method, in order to create a typical JavaFX application, you need to follow the steps given below −" }, { "code": null, "e": 7752, "s": 7705, "text": "Prepare a scene graph with the required nodes." }, { "code": null, "e": 7799, "s": 7752, "text": "Prepare a scene graph with the required nodes." }, { "code": null, "e": 7906, "s": 7799, "text": "Prepare a Scene with the required dimensions and add the scene graph (root node of the scene graph) to it." }, { "code": null, "e": 8013, "s": 7906, "text": "Prepare a Scene with the required dimensions and add the scene graph (root node of the scene graph) to it." }, { "code": null, "e": 8099, "s": 8013, "text": "Prepare a stage and add the scene to the stage and display the contents of the stage." }, { "code": null, "e": 8185, "s": 8099, "text": "Prepare a stage and add the scene to the stage and display the contents of the stage." }, { "code": null, "e": 8402, "s": 8185, "text": "As per your application, you need to prepare a scene graph with required nodes. Since the root node is the first node, you need to create a root node. As a root node, you can choose from the Group, Region or WebView." }, { "code": null, "e": 8578, "s": 8402, "text": "Group − A Group node is represented by the class named Group which belongs to the package javafx.scene, you can create a Group node by instantiating this class as shown below." }, { "code": null, "e": 8605, "s": 8578, "text": "Group root = new Group();\n" }, { "code": null, "e": 8784, "s": 8605, "text": "The getChildren() method of the Group class gives you an object of the ObservableList class which holds the nodes. We can retrieve this object and add nodes to it as shown below." }, { "code": null, "e": 8938, "s": 8784, "text": "//Retrieving the observable list object \nObservableList list = root.getChildren(); \n \n//Setting the text object as a node \nlist.add(NodeObject); \n" }, { "code": null, "e": 9090, "s": 8938, "text": "We can also add Node objects to the group, just by passing them to the Group class and to its constructor at the time of instantiation, as shown below." }, { "code": null, "e": 9127, "s": 9090, "text": "Group root = new Group(NodeObject);\n" }, { "code": null, "e": 9209, "s": 9127, "text": "Region − It is the Base class of all the JavaFX Node-based UI Controls, such as −" }, { "code": null, "e": 9584, "s": 9209, "text": "Chart − This class is the base class of all the charts and it belongs to the package javafx.scene.chart.\nThis class has two sub classes, which are − PieChart and XYChart. These two in turn have subclasses such as AreaChart, BarChart, BubbleChart, etc. used to draw different types of XY-Plane Charts in JavaFX.\nYou can use these classes to embed charts in your application.\n" }, { "code": null, "e": 9689, "s": 9584, "text": "Chart − This class is the base class of all the charts and it belongs to the package javafx.scene.chart." }, { "code": null, "e": 9895, "s": 9689, "text": "This class has two sub classes, which are − PieChart and XYChart. These two in turn have subclasses such as AreaChart, BarChart, BubbleChart, etc. used to draw different types of XY-Plane Charts in JavaFX." }, { "code": null, "e": 9958, "s": 9895, "text": "You can use these classes to embed charts in your application." }, { "code": null, "e": 10212, "s": 9958, "text": "Pane − A Pane is the base class of all the layout panes such as AnchorPane, BorderPane, DialogPane, etc. This class belong to a package that is called as − javafx.scene.layout.\nYou can use these classes to insert predefined layouts in your application.\n" }, { "code": null, "e": 10389, "s": 10212, "text": "Pane − A Pane is the base class of all the layout panes such as AnchorPane, BorderPane, DialogPane, etc. This class belong to a package that is called as − javafx.scene.layout." }, { "code": null, "e": 10465, "s": 10389, "text": "You can use these classes to insert predefined layouts in your application." }, { "code": null, "e": 10733, "s": 10465, "text": "Control − It is the base class of the User Interface controls such as Accordion, ButtonBar, ChoiceBox, ComboBoxBase, HTMLEditor, etc. This class belongs to the package javafx.scene.control.\nYou can use these classes to insert various UI elements in your application.\n" }, { "code": null, "e": 10923, "s": 10733, "text": "Control − It is the base class of the User Interface controls such as Accordion, ButtonBar, ChoiceBox, ComboBoxBase, HTMLEditor, etc. This class belongs to the package javafx.scene.control." }, { "code": null, "e": 11000, "s": 10923, "text": "You can use these classes to insert various UI elements in your application." }, { "code": null, "e": 11130, "s": 11000, "text": "In a Group, you can instantiate any of the above-mentioned classes and use them as root nodes, as shown in the following program." }, { "code": null, "e": 11303, "s": 11130, "text": "//Creating a Stack Pane \nStackPane pane = new StackPane(); \n \n//Adding text area to the pane \nObservableList list = pane.getChildren(); \nlist.add(NodeObject);\n" }, { "code": null, "e": 11373, "s": 11303, "text": "WebView − This node manages the web engine and displays its contents." }, { "code": null, "e": 11445, "s": 11373, "text": "Following is a diagram representing the node class hierarchy of JavaFX." }, { "code": null, "e": 11611, "s": 11445, "text": "A JavaFX scene is represented by the Scene class of the package javafx.scene. You can create a Scene by instantiating this class as shown in the following cod block." }, { "code": null, "e": 11711, "s": 11611, "text": "While instantiating, it is mandatory to pass the root object to the constructor of the scene class." }, { "code": null, "e": 11743, "s": 11711, "text": "Scene scene = new Scene(root);\n" }, { "code": null, "e": 11854, "s": 11743, "text": "You can also pass two parameters of double type representing the height and width of the scene as shown below." }, { "code": null, "e": 11896, "s": 11854, "text": "Scene scene = new Scene(root, 600, 300);\n" }, { "code": null, "e": 12153, "s": 11896, "text": "This is the container of any JavaFX application and it provides a window for the application. It is represented by the Stage class of the package javafx.stage. An object of this class is passed as a parameter of the start() method of the Application class." }, { "code": null, "e": 12263, "s": 12153, "text": "Using this object, you can perform various operations on the stage. Primarily you can perform the following −" }, { "code": null, "e": 12320, "s": 12263, "text": "Set the title for the stage using the method setTitle()." }, { "code": null, "e": 12377, "s": 12320, "text": "Set the title for the stage using the method setTitle()." }, { "code": null, "e": 12443, "s": 12377, "text": "Attach the scene object to the stage using the setScene() method." }, { "code": null, "e": 12509, "s": 12443, "text": "Attach the scene object to the stage using the setScene() method." }, { "code": null, "e": 12583, "s": 12509, "text": "Display the contents of the scene using the show() method as shown below." }, { "code": null, "e": 12657, "s": 12583, "text": "Display the contents of the scene using the show() method as shown below." }, { "code": null, "e": 12857, "s": 12657, "text": "//Setting the title to Stage. \nprimaryStage.setTitle(\"Sample application\"); \n \n//Setting the scene to Stage \nprimaryStage.setScene(scene); \n \n//Displaying the stage \nprimaryStage.show();\n" }, { "code": null, "e": 12928, "s": 12857, "text": "The JavaFX Application class has three life cycle methods, which are −" }, { "code": null, "e": 13010, "s": 12928, "text": "start() − The entry point method where the JavaFX graphics code is to be written." }, { "code": null, "e": 13092, "s": 13010, "text": "start() − The entry point method where the JavaFX graphics code is to be written." }, { "code": null, "e": 13196, "s": 13092, "text": "stop() − An empty method which can be overridden, here you can write the logic to stop the application." }, { "code": null, "e": 13300, "s": 13196, "text": "stop() − An empty method which can be overridden, here you can write the logic to stop the application." }, { "code": null, "e": 13403, "s": 13300, "text": "init() − An empty method which can be overridden, but you cannot create stage or scene in this method." }, { "code": null, "e": 13506, "s": 13403, "text": "init() − An empty method which can be overridden, but you cannot create stage or scene in this method." }, { "code": null, "e": 13601, "s": 13506, "text": "In addition to these, it provides a static method named launch() to launch JavaFX application." }, { "code": null, "e": 13804, "s": 13601, "text": "Since the launch() method is static, you need to call it from a static context (main generally). Whenever a JavaFX application is launched, the following actions will be carried out (in the same order)." }, { "code": null, "e": 13853, "s": 13804, "text": "An instance of the application class is created." }, { "code": null, "e": 13902, "s": 13853, "text": "An instance of the application class is created." }, { "code": null, "e": 13927, "s": 13902, "text": "Init() method is called." }, { "code": null, "e": 13952, "s": 13927, "text": "Init() method is called." }, { "code": null, "e": 13982, "s": 13952, "text": "The start() method is called." }, { "code": null, "e": 14012, "s": 13982, "text": "The start() method is called." }, { "code": null, "e": 14090, "s": 14012, "text": "The launcher waits for the application to finish and calls the stop() method." }, { "code": null, "e": 14168, "s": 14090, "text": "The launcher waits for the application to finish and calls the stop() method." }, { "code": null, "e": 14418, "s": 14168, "text": "When the last window of the application is closed, the JavaFX application is terminated implicitly. You can turn this behavior off by passing the Boolean value “False” to the static method setImplicitExit() (should be called from a static context)." }, { "code": null, "e": 14525, "s": 14418, "text": "You can terminate a JavaFX application explicitly using the methods Platform.exit() or System.exit(int)." }, { "code": null, "e": 14650, "s": 14525, "text": "This section teaches you how to create a JavaFX sample application which displays an empty window. Following are the steps −" }, { "code": null, "e": 14797, "s": 14650, "text": "Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows." }, { "code": null, "e": 14943, "s": 14797, "text": "public class JavafxSample extends Application { \n @Override \n public void start(Stage primaryStage) throws Exception { \n } \n} " }, { "code": null, "e": 15083, "s": 14943, "text": "In the start() method creates a group object by instantiating the class named Group, which belongs to the package javafx.scene, as follows." }, { "code": null, "e": 15110, "s": 15083, "text": "Group root = new Group();\n" }, { "code": null, "e": 15282, "s": 15110, "text": "Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class, pass the Group object (root), created in the previous step." }, { "code": null, "e": 15451, "s": 15282, "text": "In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows." }, { "code": null, "e": 15492, "s": 15451, "text": "Scene scene = new Scene(root,600, 300);\n" }, { "code": null, "e": 15682, "s": 15492, "text": "You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter." }, { "code": null, "e": 15778, "s": 15682, "text": "Using the primaryStage object, set the title of the scene as Sample Application as shown below." }, { "code": null, "e": 15824, "s": 15778, "text": "primaryStage.setTitle(\"Sample Application\");\n" }, { "code": null, "e": 16004, "s": 15824, "text": "You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as shown below." }, { "code": null, "e": 16035, "s": 16004, "text": "primaryStage.setScene(scene);\n" }, { "code": null, "e": 16130, "s": 16035, "text": "Display the contents of the scene using the method named show() of the Stage class as follows." }, { "code": null, "e": 16152, "s": 16130, "text": "primaryStage.show();\n" }, { "code": null, "e": 16278, "s": 16152, "text": "Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows." }, { "code": null, "e": 16348, "s": 16278, "text": "public static void main(String args[]){ \n launch(args); \n} " }, { "code": null, "e": 16461, "s": 16348, "text": "The following program generates an empty JavaFX window. Save this code in a file with the name JavafxSample.java" }, { "code": null, "e": 17395, "s": 16461, "text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.scene.paint.Color; \nimport javafx.stage.Stage; \n\npublic class JavafxSample extends Application { \n @Override \n public void start(Stage primaryStage) throws Exception { \n //creating a Group object \n Group group = new Group(); \n \n //Creating a Scene by passing the group object, height and width \n Scene scene = new Scene(group ,600, 300); \n \n //setting color to the scene \n scene.setFill(Color.BROWN); \n \n //Setting the title to Stage. \n primaryStage.setTitle(\"Sample Application\"); \n \n //Adding the scene to Stage \n primaryStage.setScene(scene); \n \n //Displaying the contents of the stage \n primaryStage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n} " }, { "code": null, "e": 17489, "s": 17395, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 17533, "s": 17489, "text": "javac JavafxSample.java \njava JavafxSample\n" }, { "code": null, "e": 17607, "s": 17533, "text": "On executing, the above program generates a JavaFX window as shown below." }, { "code": null, "e": 17756, "s": 17607, "text": "In the previous example, we have seen how to create an empty stage, now in this example let us try to draw a straight line using the JavaFX library." }, { "code": null, "e": 17782, "s": 17756, "text": "Following are the steps −" }, { "code": null, "e": 17929, "s": 17782, "text": "Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows." }, { "code": null, "e": 18071, "s": 17929, "text": "public class DrawingLine extends Application {\n @Override \n public void start(Stage primaryStage) throws Exception { \n } \n} " }, { "code": null, "e": 18223, "s": 18071, "text": "You can create a line in JavaFX by instantiating the class named Line which belongs to a package javafx.scene.shape, instantiate this class as follows." }, { "code": null, "e": 18282, "s": 18223, "text": "//Creating a line object \nLine line = new Line();\n" }, { "code": null, "e": 18472, "s": 18282, "text": "Specify the coordinates to draw the line on an X-Y plane by setting the properties startX, startY, endX and endY, using their respective setter methods as shown in the following code block." }, { "code": null, "e": 18564, "s": 18472, "text": "line.setStartX(100.0); \nline.setStartY(150.0); \nline.setEndX(500.0); \nline.setEndY(150.0);\n" }, { "code": null, "e": 18691, "s": 18564, "text": "In the start() method create a group object by instantiating the class named Group, which belongs to the package javafx.scene." }, { "code": null, "e": 18849, "s": 18691, "text": "Pass the Line (node) object, created in the previous step, as a parameter to the constructor of the Group class, in order to add it to the group as follows −" }, { "code": null, "e": 18880, "s": 18849, "text": "Group root = new Group(line);\n" }, { "code": null, "e": 19060, "s": 18880, "text": "Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class, pass the Group object (root) that was created in the previous step." }, { "code": null, "e": 19229, "s": 19060, "text": "In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows." }, { "code": null, "e": 19272, "s": 19229, "text": "Scene scene = new Scene(group ,600, 300);\n" }, { "code": null, "e": 19462, "s": 19272, "text": "You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter." }, { "code": null, "e": 19554, "s": 19462, "text": "Using the primaryStage object, set the title of the scene as Sample Application as follows." }, { "code": null, "e": 19600, "s": 19554, "text": "primaryStage.setTitle(\"Sample Application\");\n" }, { "code": null, "e": 19776, "s": 19600, "text": "You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as follows." }, { "code": null, "e": 19807, "s": 19776, "text": "primaryStage.setScene(scene);\n" }, { "code": null, "e": 19902, "s": 19807, "text": "Display the contents of the scene using the method named show() of the Stage class as follows." }, { "code": null, "e": 19924, "s": 19902, "text": "primaryStage.show();\n" }, { "code": null, "e": 20050, "s": 19924, "text": "Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows." }, { "code": null, "e": 20119, "s": 20050, "text": "public static void main(String args[]){ \n launch(args); \n} " }, { "code": null, "e": 20251, "s": 20119, "text": "The following program shows how to generate a straight line using JavaFX. Save this code in a file with the name JavafxSample.java." }, { "code": null, "e": 21226, "s": 20251, "text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.scene.shape.Line; \nimport javafx.stage.Stage; \n\npublic class DrawingLine extends Application{ \n @Override \n public void start(Stage stage) { \n //Creating a line object \n Line line = new Line(); \n \n //Setting the properties to a line \n line.setStartX(100.0); \n line.setStartY(150.0); \n line.setEndX(500.0); \n line.setEndY(150.0); \n \n //Creating a Group \n Group root = new Group(line); \n \n //Creating a Scene \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the scene \n stage.setTitle(\"Sample application\"); \n \n //Adding the scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of a scene \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n} " }, { "code": null, "e": 21320, "s": 21226, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 21362, "s": 21320, "text": "javac DrawingLine.java \njava DrawingLine\n" }, { "code": null, "e": 21463, "s": 21362, "text": "On executing, the above program generates a JavaFX window displaying a straight line as shown below." }, { "code": null, "e": 21551, "s": 21463, "text": "We can also embed text in JavaFX scene. This example shows how to embed text in JavaFX." }, { "code": null, "e": 21577, "s": 21551, "text": "Following are the steps −" }, { "code": null, "e": 21724, "s": 21577, "text": "Create a Java Class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows." }, { "code": null, "e": 21864, "s": 21724, "text": "public class DrawingLine extends Application { \n @Override \n public void start(Stage primaryStage) throws Exception { \n } \n}" }, { "code": null, "e": 22012, "s": 21864, "text": "You can embed text into a JavaFX scene by instantiating the class named Text which belongs to a package javafx.scene.shape, instantiate this class." }, { "code": null, "e": 22169, "s": 22012, "text": "You can instantiate this class by passing text to be embedded, in String format Or, you can create text object using the default constructor as shown below." }, { "code": null, "e": 22220, "s": 22169, "text": "//Creating a Text object \nText text = new Text();\n" }, { "code": null, "e": 22397, "s": 22220, "text": "You can set font to the text using the setFont() method of the Text class. This method accepts a font object as parameters. Set the font of the given text to 45 as shown below." }, { "code": null, "e": 22455, "s": 22397, "text": "//Setting font to the text \ntext.setFont(new Font(45)); \n" }, { "code": null, "e": 22606, "s": 22455, "text": "You can set the position of the text on the X-Y plane by setting the X,Y coordinates using the respective setter methods setX() and setY() as follows." }, { "code": null, "e": 22676, "s": 22606, "text": "//setting the position of the text \ntext.setX(50); \ntext.setY(150); \n" }, { "code": null, "e": 22829, "s": 22676, "text": "You can set the text to be added using the setText() method of the Text class. This method accepts a string parameter representing the text to be added." }, { "code": null, "e": 22872, "s": 22829, "text": "text.setText(\"Welcome to Tutorialspoint\");" }, { "code": null, "e": 23000, "s": 22872, "text": "In the start() method, create a group object by instantiating the class named Group, which belongs to the package javafx.scene." }, { "code": null, "e": 23158, "s": 23000, "text": "Pass the Text (node) object, created in the previous step, as a parameter to the constructor of the Group class, in order to add it to the group as follows −" }, { "code": null, "e": 23188, "s": 23158, "text": "Group root = new Group(text)\n" }, { "code": null, "e": 23360, "s": 23188, "text": "Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class, pass the Group object (root), created in the previous step." }, { "code": null, "e": 23529, "s": 23360, "text": "In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows." }, { "code": null, "e": 23572, "s": 23529, "text": "Scene scene = new Scene(group ,600, 300);\n" }, { "code": null, "e": 23762, "s": 23572, "text": "You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter." }, { "code": null, "e": 23858, "s": 23762, "text": "Using the primaryStage object, set the title of the scene as Sample Application as shown below." }, { "code": null, "e": 23904, "s": 23858, "text": "primaryStage.setTitle(\"Sample Application\");\n" }, { "code": null, "e": 24080, "s": 23904, "text": "You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as follows." }, { "code": null, "e": 24111, "s": 24080, "text": "primaryStage.setScene(scene);\n" }, { "code": null, "e": 24206, "s": 24111, "text": "Display the contents of the scene using the method named show() of the Stage class as follows." }, { "code": null, "e": 24228, "s": 24206, "text": "primaryStage.show();\n" }, { "code": null, "e": 24354, "s": 24228, "text": "Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows." }, { "code": null, "e": 24421, "s": 24354, "text": "public static void main(String args[]){ \n launch(args); \n} " }, { "code": null, "e": 24532, "s": 24421, "text": "Following is the program to display text using JavaFX. Save this code in a file with name DisplayingText.java." }, { "code": null, "e": 25922, "s": 24532, "text": "import javafx.application.Application; \nimport javafx.collections.ObservableList; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.stage.Stage; \nimport javafx.scene.text.Font; \nimport javafx.scene.text.Text; \n \npublic class DisplayingText extends Application { \n @Override \n public void start(Stage stage) { \n //Creating a Text object \n Text text = new Text(); \n \n //Setting font to the text \n text.setFont(new Font(45)); \n \n //setting the position of the text \n text.setX(50); \n text.setY(150); \n \n //Setting the text to be added. \n text.setText(\"Welcome to Tutorialspoint\"); \n \n //Creating a Group object \n Group root = new Group(); \n \n //Retrieving the observable list object \n ObservableList list = root.getChildren(); \n \n //Setting the text object as a node to the group object \n list.add(text); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Sample Application\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n} " }, { "code": null, "e": 26016, "s": 25922, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 26064, "s": 26016, "text": "javac DisplayingText.java \njava DisplayingText\n" }, { "code": null, "e": 26154, "s": 26064, "text": "On executing, the above program generates a JavaFX window displaying text as shown below." }, { "code": null, "e": 26189, "s": 26154, "text": "\n 33 Lectures \n 7.5 hours \n" }, { "code": null, "e": 26200, "s": 26189, "text": " Syed Raza" }, { "code": null, "e": 26236, "s": 26200, "text": "\n 64 Lectures \n 12.5 hours \n" }, { "code": null, "e": 26272, "s": 26236, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 26305, "s": 26272, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 26341, "s": 26305, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 26348, "s": 26341, "text": " Print" }, { "code": null, "e": 26359, "s": 26348, "text": " Add Notes" } ]
Is JavaScript a case sensitive language?
JavaScript is a case-sensitive language. This means that the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters. So the identifiers Time and TIME will convey different meanings in JavaScript. NOTE − Care should be taken while writing variable and function names in JavaScript. The following example shows JavaScript is a case-sensitive language: <!DOCTYPE html> <html> <body> <h3>My favorite subject</h3> <p id="demo"></p> <script> var subject, Subject; subject = "Java"; Subject = "Maths"; document.getElementById("demo").innerHTML = subject; </script> </body> </html>
[ { "code": null, "e": 1261, "s": 1062, "text": "JavaScript is a case-sensitive language. This means that the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters." }, { "code": null, "e": 1340, "s": 1261, "text": "So the identifiers Time and TIME will convey different meanings in JavaScript." }, { "code": null, "e": 1425, "s": 1340, "text": "NOTE − Care should be taken while writing variable and function names in JavaScript." }, { "code": null, "e": 1494, "s": 1425, "text": "The following example shows JavaScript is a case-sensitive language:" }, { "code": null, "e": 1788, "s": 1494, "text": "<!DOCTYPE html>\n<html>\n <body>\n <h3>My favorite subject</h3>\n <p id=\"demo\"></p>\n <script>\n var subject, Subject;\n subject = \"Java\";\n Subject = \"Maths\";\n document.getElementById(\"demo\").innerHTML = subject;\n </script>\n </body>\n</html>" } ]
A Practical Approach to Linear Regression in Machine Learning | by Ashwin Raj | Towards Data Science
In the previous blog post, I tried to give you some intuition about the basics of machine learning. In this article, we will be getting started with our first Machine Learning algorithm, that is Linear Regression. First, we will be going through the mathematical aspects of Linear Regression and then I will try to throw some light on important regression terms like hypothesis and cost function and finally we will be implementing what we have learned by building our very own regression model. Regression models are supervised learning models that are generally used when the value to be predicted is of discrete or quantitative nature. One of the most common example where regression models are used is predicting the price of a house by training the data of sale of houses of that region. The idea behind Linear Regression model is to obtain a line that best fits the data. By best fit, what is meant is that the total distance of all points from our regression line should be minimal. Often this distance of the points from our regression line is referred to as an Error though it is technically not one. We know that the straight line equation is of the form: where y is the Dependent Variable, x is the Independent Variable, m is the Slope of the line and c is the Coefficient (or the y-intercept). Herein, y is regarded as the dependent variable as its value depends on the values of the independent variable and the other parameters. This equation is the basis for any Linear Regression problem and is referred to as the Hypothesis function for Linear Regression. The goal of most machine learning algorithms is to construct a model i.e. a hypothesis to estimate the dependent variable based on our independent variable(s). This hypothesis, maps our inputs to the output. The hypothesis for linear regression is usually presented as: In the above mentioned expression, hθ(x) is our hypothesis, θ0 is the intercept and θ1 is the coefficient of the model. Cost functions are used to calculate how the model is performing. In layman’s words, cost function is the sum of all the errors. While building our ML model, our aim is to minimize the cost function. One common function that is often used in regression problems is the Mean Squared Error or MSE, which measure the difference between the known value and the predicted value. It turns out that taking the root of the above equation is far better option as the values would be less complicated and thus Root Mean Squared Error or RMSE is generally used. We can also use other parameters such as Mean Absolute Error for evaluating a regression model. RMSE tells us how close the data points are to the regression line. Now we will be implementing what we have learned till now by building our very own linear regression model to predict the price of a house. Here I will be using Google Colab for building this model. You can also use other IDEs like Jupyter notebooks for playing around with the model. The code used for this linear regression project can be found here. Our first step is to import the libraries that might be required to build our model. It is not necessary to import all the libraries at just one place. To get started we will be importing Pandas, Numpy, Matplotlib etc. #Import Required Librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns#Read the Datasetdf=pd.read_csv('kc_house_data.csv') Once these libraries have been imported our next step will be fetching the dataset and loading our data. While loading the data, it is important to note that the file name shall have its format (.csv/.xls) specified at the end. The data that I used for this model can be downloaded directly from here. CSV files are most commonly used for such purposes, though excel sheet can also be used. The only difference would be that instead of read_csv(), we will have to use read_excel() while using an excel sheet as dataset. After successfully loading the data, our next step is to visualize this data. Data visualization is an important part in the role of a data scientist. It is recommended to visualize the data so as to find any correlation between the different parameters. #Visualising the data using heatmapplt.figure()sns.heatmap(df.corr(),cmap='coolwarm')plt.show() Matplotlib and Seashore are excellent libraries that can be used to visualize our data on various different plots. While visualizing our data, we found that there is a strong correlation between the two parameters: sqft_living and price. Thereby we will be using these parameters for building our model. #Selecting the required parametersarea = df[‘sqft_living’]price = df['price']x = np.array(area).reshape(-1,1)y = np.array(price) More parameters can also be added to the model though it might affect its accuracy. The model that uses various features to predict the outcome of the response variables is called Multivariate Regression model. After selecting the desired parameters the next step is to import the method train_test_split from sklearn library. This is used to split our data into training and testing data. Commonly 70–80% of the data is taken as the training dataset while the remaining data constitutes the testing dataset. #Import LinearRegression and split the data into training and testing datasetfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(x,y,test_size=0.2,random_state = 0)y_train = y_train.reshape(-1,1)y_test = y_test.reshape(-1,1)#Fit the model over the training datasetfrom sklearn.linear_model import LinearRegressionmodel = LinearRegression()model.fit(X_train,y_train) After this LinearRegression is imported from sklearn.model_selection and the model is fit over the training dataset. The intercept and coefficient of our model can be calculated as shown below: #Calculate intercept and coefficientprint(model.intercept_)print(model.coef_)pred=model.predict(X_test)predictions = pred.reshape(-1,1)#Calculate root mean squared error to evaluate model performancefrom sklearn.metrics import mean_squared_errorprint('MSE : ', mean_squared_error(y_test,predictions)print('RMSE : ', np.sqrt(mean_squared_error(y_test,predictions))) The performance of the model can be evaluated by finding the root mean squared error of the model. Lesser the RMSE, better the model. Gradient descent is an iterative optimization algorithm to find the minimum of a function. To understand this algorithm imagine a person with no sense of direction who wants to get to the bottom of the valley. He goes down the slope and takes large steps when the slope is steep and small steps when the slope is less steep. He decides his next position based on his current position and stops when he gets to the bottom of the valley which was his goal. Similar is how gradient descent works. #Initializing the variablesm = 0c = 0L = 0.001epochs = 100n = float(len(x)) The gradient descent approach is applied step by step to our m and c. Initially let m = 0 and c = 0. Let L be our learning rate. This controls how much the value of m changes with each step. for i in range(epochs): Y_pred=m*x+c Dm = (-2/n)*sum(x*(y-Y_pred)) Dc = (-2/n)*sum(y-Y_pred) m = m-L*Dm c = c-L*Dcprint(m,c)#Predicting the valuesy_pred = df['sqft_living'].apply(lambda a:c+m*a)y_pred.head() Preferentially L is assigned a small value in order to improve the accuracy. Our next step is to calculate the partial derivative of the loss function with respect to m and c. Once this is done we update the values of c and m and repeat the process until our loss function is very small. With that, we have reached the end of this article. I hope this article would have helped you get a feel about the idea behind linear regression algorithms. If you have any question or if you believe I have made any mistake, contact me! You can get in touch with me via: Email or LinkedIn.
[ { "code": null, "e": 385, "s": 171, "text": "In the previous blog post, I tried to give you some intuition about the basics of machine learning. In this article, we will be getting started with our first Machine Learning algorithm, that is Linear Regression." }, { "code": null, "e": 667, "s": 385, "text": "First, we will be going through the mathematical aspects of Linear Regression and then I will try to throw some light on important regression terms like hypothesis and cost function and finally we will be implementing what we have learned by building our very own regression model." }, { "code": null, "e": 964, "s": 667, "text": "Regression models are supervised learning models that are generally used when the value to be predicted is of discrete or quantitative nature. One of the most common example where regression models are used is predicting the price of a house by training the data of sale of houses of that region." }, { "code": null, "e": 1337, "s": 964, "text": "The idea behind Linear Regression model is to obtain a line that best fits the data. By best fit, what is meant is that the total distance of all points from our regression line should be minimal. Often this distance of the points from our regression line is referred to as an Error though it is technically not one. We know that the straight line equation is of the form:" }, { "code": null, "e": 1614, "s": 1337, "text": "where y is the Dependent Variable, x is the Independent Variable, m is the Slope of the line and c is the Coefficient (or the y-intercept). Herein, y is regarded as the dependent variable as its value depends on the values of the independent variable and the other parameters." }, { "code": null, "e": 1904, "s": 1614, "text": "This equation is the basis for any Linear Regression problem and is referred to as the Hypothesis function for Linear Regression. The goal of most machine learning algorithms is to construct a model i.e. a hypothesis to estimate the dependent variable based on our independent variable(s)." }, { "code": null, "e": 2014, "s": 1904, "text": "This hypothesis, maps our inputs to the output. The hypothesis for linear regression is usually presented as:" }, { "code": null, "e": 2134, "s": 2014, "text": "In the above mentioned expression, hθ(x) is our hypothesis, θ0 is the intercept and θ1 is the coefficient of the model." }, { "code": null, "e": 2334, "s": 2134, "text": "Cost functions are used to calculate how the model is performing. In layman’s words, cost function is the sum of all the errors. While building our ML model, our aim is to minimize the cost function." }, { "code": null, "e": 2508, "s": 2334, "text": "One common function that is often used in regression problems is the Mean Squared Error or MSE, which measure the difference between the known value and the predicted value." }, { "code": null, "e": 2781, "s": 2508, "text": "It turns out that taking the root of the above equation is far better option as the values would be less complicated and thus Root Mean Squared Error or RMSE is generally used. We can also use other parameters such as Mean Absolute Error for evaluating a regression model." }, { "code": null, "e": 2989, "s": 2781, "text": "RMSE tells us how close the data points are to the regression line. Now we will be implementing what we have learned till now by building our very own linear regression model to predict the price of a house." }, { "code": null, "e": 3134, "s": 2989, "text": "Here I will be using Google Colab for building this model. You can also use other IDEs like Jupyter notebooks for playing around with the model." }, { "code": null, "e": 3202, "s": 3134, "text": "The code used for this linear regression project can be found here." }, { "code": null, "e": 3421, "s": 3202, "text": "Our first step is to import the libraries that might be required to build our model. It is not necessary to import all the libraries at just one place. To get started we will be importing Pandas, Numpy, Matplotlib etc." }, { "code": null, "e": 3589, "s": 3421, "text": "#Import Required Librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns#Read the Datasetdf=pd.read_csv('kc_house_data.csv')" }, { "code": null, "e": 3817, "s": 3589, "text": "Once these libraries have been imported our next step will be fetching the dataset and loading our data. While loading the data, it is important to note that the file name shall have its format (.csv/.xls) specified at the end." }, { "code": null, "e": 3891, "s": 3817, "text": "The data that I used for this model can be downloaded directly from here." }, { "code": null, "e": 4109, "s": 3891, "text": "CSV files are most commonly used for such purposes, though excel sheet can also be used. The only difference would be that instead of read_csv(), we will have to use read_excel() while using an excel sheet as dataset." }, { "code": null, "e": 4364, "s": 4109, "text": "After successfully loading the data, our next step is to visualize this data. Data visualization is an important part in the role of a data scientist. It is recommended to visualize the data so as to find any correlation between the different parameters." }, { "code": null, "e": 4460, "s": 4364, "text": "#Visualising the data using heatmapplt.figure()sns.heatmap(df.corr(),cmap='coolwarm')plt.show()" }, { "code": null, "e": 4575, "s": 4460, "text": "Matplotlib and Seashore are excellent libraries that can be used to visualize our data on various different plots." }, { "code": null, "e": 4764, "s": 4575, "text": "While visualizing our data, we found that there is a strong correlation between the two parameters: sqft_living and price. Thereby we will be using these parameters for building our model." }, { "code": null, "e": 4893, "s": 4764, "text": "#Selecting the required parametersarea = df[‘sqft_living’]price = df['price']x = np.array(area).reshape(-1,1)y = np.array(price)" }, { "code": null, "e": 5104, "s": 4893, "text": "More parameters can also be added to the model though it might affect its accuracy. The model that uses various features to predict the outcome of the response variables is called Multivariate Regression model." }, { "code": null, "e": 5402, "s": 5104, "text": "After selecting the desired parameters the next step is to import the method train_test_split from sklearn library. This is used to split our data into training and testing data. Commonly 70–80% of the data is taken as the training dataset while the remaining data constitutes the testing dataset." }, { "code": null, "e": 5820, "s": 5402, "text": "#Import LinearRegression and split the data into training and testing datasetfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(x,y,test_size=0.2,random_state = 0)y_train = y_train.reshape(-1,1)y_test = y_test.reshape(-1,1)#Fit the model over the training datasetfrom sklearn.linear_model import LinearRegressionmodel = LinearRegression()model.fit(X_train,y_train)" }, { "code": null, "e": 6014, "s": 5820, "text": "After this LinearRegression is imported from sklearn.model_selection and the model is fit over the training dataset. The intercept and coefficient of our model can be calculated as shown below:" }, { "code": null, "e": 6379, "s": 6014, "text": "#Calculate intercept and coefficientprint(model.intercept_)print(model.coef_)pred=model.predict(X_test)predictions = pred.reshape(-1,1)#Calculate root mean squared error to evaluate model performancefrom sklearn.metrics import mean_squared_errorprint('MSE : ', mean_squared_error(y_test,predictions)print('RMSE : ', np.sqrt(mean_squared_error(y_test,predictions)))" }, { "code": null, "e": 6513, "s": 6379, "text": "The performance of the model can be evaluated by finding the root mean squared error of the model. Lesser the RMSE, better the model." }, { "code": null, "e": 6723, "s": 6513, "text": "Gradient descent is an iterative optimization algorithm to find the minimum of a function. To understand this algorithm imagine a person with no sense of direction who wants to get to the bottom of the valley." }, { "code": null, "e": 7007, "s": 6723, "text": "He goes down the slope and takes large steps when the slope is steep and small steps when the slope is less steep. He decides his next position based on his current position and stops when he gets to the bottom of the valley which was his goal. Similar is how gradient descent works." }, { "code": null, "e": 7083, "s": 7007, "text": "#Initializing the variablesm = 0c = 0L = 0.001epochs = 100n = float(len(x))" }, { "code": null, "e": 7274, "s": 7083, "text": "The gradient descent approach is applied step by step to our m and c. Initially let m = 0 and c = 0. Let L be our learning rate. This controls how much the value of m changes with each step." }, { "code": null, "e": 7497, "s": 7274, "text": "for i in range(epochs): Y_pred=m*x+c Dm = (-2/n)*sum(x*(y-Y_pred)) Dc = (-2/n)*sum(y-Y_pred) m = m-L*Dm c = c-L*Dcprint(m,c)#Predicting the valuesy_pred = df['sqft_living'].apply(lambda a:c+m*a)y_pred.head()" }, { "code": null, "e": 7785, "s": 7497, "text": "Preferentially L is assigned a small value in order to improve the accuracy. Our next step is to calculate the partial derivative of the loss function with respect to m and c. Once this is done we update the values of c and m and repeat the process until our loss function is very small." } ]
MongoDB - Relationships
Relationships in MongoDB represent how various documents are logically related to each other. Relationships can be modeled via Embedded and Referenced approaches. Such relationships can be either 1:1, 1:N, N:1 or N:N. Let us consider the case of storing addresses for users. So, one user can have multiple addresses making this a 1:N relationship. Following is the sample document structure of user document − { "_id":ObjectId("52ffc33cd85242f436000001"), "name": "Tom Hanks", "contact": "987654321", "dob": "01-01-1991" } Following is the sample document structure of address document − { "_id":ObjectId("52ffc4a5d85242602e000000"), "building": "22 A, Indiana Apt", "pincode": 123456, "city": "Los Angeles", "state": "California" } In the embedded approach, we will embed the address document inside the user document. > db.users.insert({ { "_id":ObjectId("52ffc33cd85242f436000001"), "contact": "987654321", "dob": "01-01-1991", "name": "Tom Benzamin", "address": [ { "building": "22 A, Indiana Apt", "pincode": 123456, "city": "Los Angeles", "state": "California" }, { "building": "170 A, Acropolis Apt", "pincode": 456789, "city": "Chicago", "state": "Illinois" } ] } }) This approach maintains all the related data in a single document, which makes it easy to retrieve and maintain. The whole document can be retrieved in a single query such as − >db.users.findOne({"name":"Tom Benzamin"},{"address":1}) Note that in the above query, db and users are the database and collection respectively. The drawback is that if the embedded document keeps on growing too much in size, it can impact the read/write performance. This is the approach of designing normalized relationship. In this approach, both the user and address documents will be maintained separately but the user document will contain a field that will reference the address document's id field. { "_id":ObjectId("52ffc33cd85242f436000001"), "contact": "987654321", "dob": "01-01-1991", "name": "Tom Benzamin", "address_ids": [ ObjectId("52ffc4a5d85242602e000000"), ObjectId("52ffc4a5d85242602e000001") ] } As shown above, the user document contains the array field address_ids which contains ObjectIds of corresponding addresses. Using these ObjectIds, we can query the address documents and get address details from there. With this approach, we will need two queries: first to fetch the address_ids fields from user document and second to fetch these addresses from address collection. >var result = db.users.findOne({"name":"Tom Benzamin"},{"address_ids":1}) >var addresses = db.address.find({"_id":{"$in":result["address_ids"]}}) 44 Lectures 3 hours Arnab Chakraborty 54 Lectures 5.5 hours Eduonix Learning Solutions 44 Lectures 4.5 hours Kaushik Roy Chowdhury 40 Lectures 2.5 hours University Code 26 Lectures 8 hours Bassir Jafarzadeh 70 Lectures 2.5 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2771, "s": 2553, "text": "Relationships in MongoDB represent how various documents are logically related to each other. Relationships can be modeled via Embedded and Referenced approaches. Such relationships can be either 1:1, 1:N, N:1 or N:N." }, { "code": null, "e": 2901, "s": 2771, "text": "Let us consider the case of storing addresses for users. So, one user can have multiple addresses making this a 1:N relationship." }, { "code": null, "e": 2963, "s": 2901, "text": "Following is the sample document structure of user document −" }, { "code": null, "e": 3088, "s": 2963, "text": "{\n \"_id\":ObjectId(\"52ffc33cd85242f436000001\"),\n \"name\": \"Tom Hanks\",\n \"contact\": \"987654321\",\n \"dob\": \"01-01-1991\"\n}" }, { "code": null, "e": 3153, "s": 3088, "text": "Following is the sample document structure of address document −" }, { "code": null, "e": 3314, "s": 3153, "text": "{\n \"_id\":ObjectId(\"52ffc4a5d85242602e000000\"),\n \"building\": \"22 A, Indiana Apt\",\n \"pincode\": 123456,\n \"city\": \"Los Angeles\",\n \"state\": \"California\"\n} " }, { "code": null, "e": 3401, "s": 3314, "text": "In the embedded approach, we will embed the address document inside the user document." }, { "code": null, "e": 3814, "s": 3401, "text": "> db.users.insert({\n\t{\n\t\t\"_id\":ObjectId(\"52ffc33cd85242f436000001\"),\n\t\t\"contact\": \"987654321\",\n\t\t\"dob\": \"01-01-1991\",\n\t\t\"name\": \"Tom Benzamin\",\n\t\t\"address\": [\n\t\t\t{\n\t\t\t\t\"building\": \"22 A, Indiana Apt\",\n\t\t\t\t\"pincode\": 123456,\n\t\t\t\t\"city\": \"Los Angeles\",\n\t\t\t\t\"state\": \"California\"\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"building\": \"170 A, Acropolis Apt\",\n\t\t\t\t\"pincode\": 456789,\n\t\t\t\t\"city\": \"Chicago\",\n\t\t\t\t\"state\": \"Illinois\"\n\t\t\t}\n\t\t]\n\t}\n})" }, { "code": null, "e": 3991, "s": 3814, "text": "This approach maintains all the related data in a single document, which makes it easy to retrieve and maintain. The whole document can be retrieved in a single query such as −" }, { "code": null, "e": 4049, "s": 3991, "text": ">db.users.findOne({\"name\":\"Tom Benzamin\"},{\"address\":1})\n" }, { "code": null, "e": 4138, "s": 4049, "text": "Note that in the above query, db and users are the database and collection respectively." }, { "code": null, "e": 4261, "s": 4138, "text": "The drawback is that if the embedded document keeps on growing too much in size, it can impact the read/write performance." }, { "code": null, "e": 4500, "s": 4261, "text": "This is the approach of designing normalized relationship. In this approach, both the user and address documents will be maintained separately but the user document will contain a field that will reference the address document's id field." }, { "code": null, "e": 4741, "s": 4500, "text": "{\n \"_id\":ObjectId(\"52ffc33cd85242f436000001\"),\n \"contact\": \"987654321\",\n \"dob\": \"01-01-1991\",\n \"name\": \"Tom Benzamin\",\n \"address_ids\": [\n ObjectId(\"52ffc4a5d85242602e000000\"),\n ObjectId(\"52ffc4a5d85242602e000001\")\n ]\n}" }, { "code": null, "e": 5123, "s": 4741, "text": "As shown above, the user document contains the array field address_ids which contains ObjectIds of corresponding addresses. Using these ObjectIds, we can query the address documents and get address details from there. With this approach, we will need two queries: first to fetch the address_ids fields from user document and second to fetch these addresses from address collection." }, { "code": null, "e": 5270, "s": 5123, "text": ">var result = db.users.findOne({\"name\":\"Tom Benzamin\"},{\"address_ids\":1})\n>var addresses = db.address.find({\"_id\":{\"$in\":result[\"address_ids\"]}})\n" }, { "code": null, "e": 5303, "s": 5270, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 5322, "s": 5303, "text": " Arnab Chakraborty" }, { "code": null, "e": 5357, "s": 5322, "text": "\n 54 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5385, "s": 5357, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5420, "s": 5385, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5443, "s": 5420, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 5478, "s": 5443, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5495, "s": 5478, "text": " University Code" }, { "code": null, "e": 5528, "s": 5495, "text": "\n 26 Lectures \n 8 hours \n" }, { "code": null, "e": 5547, "s": 5528, "text": " Bassir Jafarzadeh" }, { "code": null, "e": 5582, "s": 5547, "text": "\n 70 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5602, "s": 5582, "text": " Skillbakerystudios" }, { "code": null, "e": 5609, "s": 5602, "text": " Print" }, { "code": null, "e": 5620, "s": 5609, "text": " Add Notes" } ]
Get date format DD/MM/YYYY with MySQL Select Query?
Use the STR_TO_DATE() function from MySQL to set a date format for displaying DD/MM/YYYY date. The syntax is as follows − SELECT STR_TO_DATE(yourColumnName,’%d/%m/%Y) as anyVariableName from yourTableName. To understand the above syntax, let us create a table − mysql> create table DateFormatDemo −> ( −> IssueDate varchar(100) −> ); Query OK, 0 rows affected (0.54 sec) Inserting some string dates into the table. The query to insert date is as follows − mysql> insert into DateFormatDemo values('26/11/2018'); Query OK, 1 row affected (0.14 sec) mysql> insert into DateFormatDemo values('27/11/2018'); Query OK, 1 row affected (0.18 sec) mysql> insert into DateFormatDemo values('2/12/2018'); Query OK, 1 row affected (0.13 sec) mysql> insert into DateFormatDemo values('3/12/2018'); Query OK, 1 row affected (0.14 sec) Now you can display all dates which I have inserted above. The query is as follows − mysql> select *from DateFormatDemo; The following is the output − +------------+ | IssueDate | +------------+ | 26/11/2018 | | 27/11/2018 | | 2/12/2018 | | 3/12/2018 | +------------+ 4 rows in set (0.00 sec) You can implement the syntax we discussed in the beginning to convert string to date format. The query is as follows − mysql> select STR_TO_DATE(IssueDate, '%d/%m/%Y') StringToDateFormatExample from DateFormatDemo; The following is the output − +---------------------------+ | StringToDateFormatExample | +---------------------------+ | 2018-11-26 | | 2018-11-27 | | 2018-12-02 | | 2018-12-03 | +---------------------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1184, "s": 1062, "text": "Use the STR_TO_DATE() function from MySQL to set a date format for displaying DD/MM/YYYY date. The syntax is as follows −" }, { "code": null, "e": 1268, "s": 1184, "text": "SELECT STR_TO_DATE(yourColumnName,’%d/%m/%Y) as anyVariableName from yourTableName." }, { "code": null, "e": 1324, "s": 1268, "text": "To understand the above syntax, let us create a table −" }, { "code": null, "e": 1445, "s": 1324, "text": "mysql> create table DateFormatDemo\n −> (\n −> IssueDate varchar(100)\n −> );\nQuery OK, 0 rows affected (0.54 sec)" }, { "code": null, "e": 1530, "s": 1445, "text": "Inserting some string dates into the table. The query to insert date is as follows −" }, { "code": null, "e": 1899, "s": 1530, "text": "mysql> insert into DateFormatDemo values('26/11/2018');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DateFormatDemo values('27/11/2018');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into DateFormatDemo values('2/12/2018');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into DateFormatDemo values('3/12/2018');\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 1984, "s": 1899, "text": "Now you can display all dates which I have inserted above. The query is as follows −" }, { "code": null, "e": 2020, "s": 1984, "text": "mysql> select *from DateFormatDemo;" }, { "code": null, "e": 2050, "s": 2020, "text": "The following is the output −" }, { "code": null, "e": 2195, "s": 2050, "text": "+------------+\n| IssueDate |\n+------------+\n| 26/11/2018 |\n| 27/11/2018 |\n| 2/12/2018 |\n| 3/12/2018 |\n+------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2314, "s": 2195, "text": "You can implement the syntax we discussed in the beginning to convert string to date format. The query is as follows −" }, { "code": null, "e": 2410, "s": 2314, "text": "mysql> select STR_TO_DATE(IssueDate, '%d/%m/%Y') StringToDateFormatExample from DateFormatDemo;" }, { "code": null, "e": 2440, "s": 2410, "text": "The following is the output −" }, { "code": null, "e": 2705, "s": 2440, "text": "+---------------------------+\n| StringToDateFormatExample |\n+---------------------------+\n| 2018-11-26 |\n| 2018-11-27 |\n| 2018-12-02 |\n| 2018-12-03 |\n+---------------------------+\n4 rows in set (0.00 sec)" } ]
How to get current location in android web view?
This example demonstrate about How to get current location in android web view. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <WebView android:id = "@+id/web_view" android:layout_width = "match_parent" android:layout_height = "match_parent" /> </LinearLayout> In the above code, we have taken web view to show mylocation.org. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.app.ProgressDialog; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.widget.EditText; public class MainActivity extends AppCompatActivity { @RequiresApi(api = Build.VERSION_CODES.P) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setMessage("Loading Data..."); progressDialog.setCancelable(false); WebView web_view = findViewById(R.id.web_view); web_view.requestFocus(); web_view.getSettings().setLightTouchEnabled(true); web_view.getSettings().setJavaScriptEnabled(true); web_view.getSettings().setGeolocationEnabled(true); web_view.loadUrl("https://mylocation.org/"); web_view.setWebChromeClient(new WebChromeClient() { public void onProgressChanged(WebView view, int progress) { if (progress < 100) { progressDialog.show(); } if (progress = = 100) { progressDialog.dismiss(); } } }); } } Step 4 − Add the following code to AndroidManifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.myapplication"> <uses-permission android:name = "android.permission.INTERNET"/> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1142, "s": 1062, "text": "This example demonstrate about How to get current location in android web view." }, { "code": null, "e": 1271, "s": 1142, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1336, "s": 1271, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1903, "s": 1336, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <WebView\n android:id = \"@+id/web_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 1969, "s": 1903, "text": "In the above code, we have taken web view to show mylocation.org." }, { "code": null, "e": 2026, "s": 1969, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3406, "s": 2026, "text": "package com.example.myapplication;\nimport android.app.ProgressDialog;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebView;\nimport android.widget.EditText;\npublic class MainActivity extends AppCompatActivity {\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final ProgressDialog progressDialog = new ProgressDialog(this);\n progressDialog.setMessage(\"Loading Data...\");\n progressDialog.setCancelable(false);\n WebView web_view = findViewById(R.id.web_view);\n web_view.requestFocus();\n web_view.getSettings().setLightTouchEnabled(true);\n web_view.getSettings().setJavaScriptEnabled(true);\n web_view.getSettings().setGeolocationEnabled(true);\n web_view.loadUrl(\"https://mylocation.org/\");\n web_view.setWebChromeClient(new WebChromeClient() {\n public void onProgressChanged(WebView view, int progress) {\n if (progress < 100) {\n progressDialog.show();\n }\n if (progress = = 100) {\n progressDialog.dismiss();\n }\n }\n });\n }\n}" }, { "code": null, "e": 3461, "s": 3406, "text": "Step 4 − Add the following code to AndroidManifest.xml" }, { "code": null, "e": 4238, "s": 3461, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.INTERNET\"/>\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4585, "s": 4238, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 4625, "s": 4585, "text": "Click here to download the project code" } ]
Node.js fs.dirent.name Property - GeeksforGeeks
19 Jan, 2022 The fs.Dirent.name property is an inbuilt application programming interface of class fs.Dirent within File System module which is used to provide the name of the particular dirent. Syntax: const dirent.name Parameter: This property does not accept any parameter.Return Value: This property returns the name of the particular dirent. Below programs illustrates the use of fs.dirent.name property in Node.js: Example 1: Filename: index.js Javascript // Node.js program to demonstrate the// dirent.name propertyconst fs = require('fs'); // Initiating async functionasync function stop(path) { // Creating and initiating dir's // underlying resource handle const dir = await fs.promises.opendir(path); // Synchronously reading the dir's // underlying resource handle // using readSync() method for (var i = 0; i <= 6; i++) { // Checking if the particular // dirent is SymbolicLink or // not by using name() method const value = (dir.readSync()).name; // Display the result console.log(value); }} // Catching errorstop('./').catch(console.error); Run index.js file using the following command: node index.js Output: abcd.cer cert.cer certfile.cer certificate1.cer example.txt features filename.txt Example 2: Filename: index.js Javascript // Node.js program to demonstrate the// dirent.name propertyconst fs = require('fs'); // Initiating async functionasync function stop(path) { let dir = null; try { // Creating and initiating directory's // underlying resource handle dir = await fs.promises.opendir( new URL('file:///F:/java/')); // Synchronously reading the File's // underlying resource handle // using readSync() method for (var i = 0; i <= 3; i++) { // Checking if the particular dirent // is File or not by using isFile() method const value = (dir.readSync()).name; // Display the result console.log(dir.readSync()); console.log(value); } } finally { if (dir) { // Display the result console.log("dir is closed successfully"); // Synchronously closeSyncing the // directory's underlying resource handle const promise = dir.closeSync(); } }} // Catching errorstop('./').catch(console.error); Run index.js file using the following command: node index.js Output: Dirent { name: 'books.txt', [Symbol(type)]: 1 } abcd.cer Dirent { name: 'certfile.cer', [Symbol(type)]: 1 } cert.cer Dirent { name: 'example.com_index.html', [Symbol(type)]: 1 } certificate1.cer Dirent { name: 'features', [Symbol(type)]: 2 } example.txt Reference: https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_dirent_name anikakapoor sweetyty Node.js-fs-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to build a basic CRUD app with Node.js and ReactJS ? How to connect Node.js with React.js ? Mongoose Populate() Method Express.js req.params Property How to Convert CSV to JSON file having Comma Separated values in Node.js ? Top 10 Front End Developer Skills That You Need in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24531, "s": 24503, "text": "\n19 Jan, 2022" }, { "code": null, "e": 24712, "s": 24531, "text": "The fs.Dirent.name property is an inbuilt application programming interface of class fs.Dirent within File System module which is used to provide the name of the particular dirent." }, { "code": null, "e": 24721, "s": 24712, "text": "Syntax: " }, { "code": null, "e": 24739, "s": 24721, "text": "const dirent.name" }, { "code": null, "e": 24865, "s": 24739, "text": "Parameter: This property does not accept any parameter.Return Value: This property returns the name of the particular dirent." }, { "code": null, "e": 24939, "s": 24865, "text": "Below programs illustrates the use of fs.dirent.name property in Node.js:" }, { "code": null, "e": 24971, "s": 24939, "text": "Example 1: Filename: index.js " }, { "code": null, "e": 24982, "s": 24971, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the// dirent.name propertyconst fs = require('fs'); // Initiating async functionasync function stop(path) { // Creating and initiating dir's // underlying resource handle const dir = await fs.promises.opendir(path); // Synchronously reading the dir's // underlying resource handle // using readSync() method for (var i = 0; i <= 6; i++) { // Checking if the particular // dirent is SymbolicLink or // not by using name() method const value = (dir.readSync()).name; // Display the result console.log(value); }} // Catching errorstop('./').catch(console.error);", "e": 25653, "s": 24982, "text": null }, { "code": null, "e": 25701, "s": 25653, "text": "Run index.js file using the following command: " }, { "code": null, "e": 25715, "s": 25701, "text": "node index.js" }, { "code": null, "e": 25725, "s": 25715, "text": "Output: " }, { "code": null, "e": 25807, "s": 25725, "text": "abcd.cer\ncert.cer\ncertfile.cer\ncertificate1.cer\nexample.txt\nfeatures\nfilename.txt" }, { "code": null, "e": 25838, "s": 25807, "text": "Example 2: Filename: index.js " }, { "code": null, "e": 25849, "s": 25838, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the// dirent.name propertyconst fs = require('fs'); // Initiating async functionasync function stop(path) { let dir = null; try { // Creating and initiating directory's // underlying resource handle dir = await fs.promises.opendir( new URL('file:///F:/java/')); // Synchronously reading the File's // underlying resource handle // using readSync() method for (var i = 0; i <= 3; i++) { // Checking if the particular dirent // is File or not by using isFile() method const value = (dir.readSync()).name; // Display the result console.log(dir.readSync()); console.log(value); } } finally { if (dir) { // Display the result console.log(\"dir is closed successfully\"); // Synchronously closeSyncing the // directory's underlying resource handle const promise = dir.closeSync(); } }} // Catching errorstop('./').catch(console.error);", "e": 26934, "s": 25849, "text": null }, { "code": null, "e": 26982, "s": 26934, "text": "Run index.js file using the following command: " }, { "code": null, "e": 26996, "s": 26982, "text": "node index.js" }, { "code": null, "e": 27005, "s": 26996, "text": "Output: " }, { "code": null, "e": 27259, "s": 27005, "text": "Dirent { name: 'books.txt', [Symbol(type)]: 1 }\nabcd.cer\nDirent { name: 'certfile.cer', [Symbol(type)]: 1 }\ncert.cer\nDirent { name: 'example.com_index.html', [Symbol(type)]: 1 }\ncertificate1.cer\nDirent { name: 'features', [Symbol(type)]: 2 }\nexample.txt" }, { "code": null, "e": 27340, "s": 27259, "text": "Reference: https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_dirent_name " }, { "code": null, "e": 27352, "s": 27340, "text": "anikakapoor" }, { "code": null, "e": 27361, "s": 27352, "text": "sweetyty" }, { "code": null, "e": 27379, "s": 27361, "text": "Node.js-fs-module" }, { "code": null, "e": 27387, "s": 27379, "text": "Node.js" }, { "code": null, "e": 27404, "s": 27387, "text": "Web Technologies" }, { "code": null, "e": 27502, "s": 27404, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27511, "s": 27502, "text": "Comments" }, { "code": null, "e": 27524, "s": 27511, "text": "Old Comments" }, { "code": null, "e": 27581, "s": 27524, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 27620, "s": 27581, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 27647, "s": 27620, "text": "Mongoose Populate() Method" }, { "code": null, "e": 27678, "s": 27647, "text": "Express.js req.params Property" }, { "code": null, "e": 27753, "s": 27678, "text": "How to Convert CSV to JSON file having Comma Separated values in Node.js ?" }, { "code": null, "e": 27809, "s": 27753, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27871, "s": 27809, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27914, "s": 27871, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27964, "s": 27914, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Box Blur Algorithm - With Python implementation - GeeksforGeeks
30 Dec, 2020 The pixels in an image are represented as integers. After blurring each pixel ‘x’ of the resulting image has a value equal to the average of the pixels surrounding ‘x’ including ‘x’. For example, consider a 3 * 3 image as Then, the resulting image after blur is blurred_image = So, the pixel of blurred image is calculated as (1 + 1 + 1 + 1 + 7 + 1 + 1 + 1 + 1) / 9 = 1.66666 = 1 Box blur is also known as box linear filter. Box blurs are frequently used to approximate Gaussian blur. A box blur is generally implemented as an image effect that affects the whole screen. The blurred colour of the current pixel is the average of the current pixel’s colour and its 8 neighbouring pixels. Note: For each 3 * 3 pixel matrix there is one blurred pixel calculated as above. FOr Example, Consider the below image.It’s blurred image is given below: Explanation:There are four 3 * 3 matrix possible in the above image. So there are 4 blurred pixel in the resulting image. The four matrices are: , , , and Implementation in Python: def square_matrix(square): """ This function will calculate the value x (i.e. blurred pixel value) for each 3 * 3 blur image. """ tot_sum = 0 # Calculate sum of all the pixels in 3 * 3 matrix for i in range(3): for j in range(3): tot_sum += square[i][j] return tot_sum // 9 # return the average of the sum of pixels def boxBlur(image): """ This function will calculate the blurred image for given n * n image. """ square = [] # This will store the 3 * 3 matrix # which will be used to find its blurred pixel square_row = [] # This will store one row of a 3 * 3 matrix and # will be appended in square blur_row = [] # Here we will store the resulting blurred # pixels possible in one row # and will append this in the blur_img blur_img = [] # This is the resulting blurred image # number of rows in the given image n_rows = len(image) # number of columns in the given image n_col = len(image[0]) # rp is row pointer and cp is column pointer rp, cp = 0, 0 # This while loop will be used to # calculate all the blurred pixel in the first row while rp <= n_rows - 3: while cp <= n_col-3: for i in range(rp, rp + 3): for j in range(cp, cp + 3): # append all the pixels in a row of 3 * 3 matrix square_row.append(image[i][j]) # append the row in the square i.e. 3 * 3 matrix square.append(square_row) square_row = [] # calculate the blurred pixel for given 3 * 3 matrix # i.e. square and append it in blur_row blur_row.append(square_matrix(square)) square = [] # increase the column pointer cp = cp + 1 # append the blur_row in blur_image blur_img.append(blur_row) blur_row = [] rp = rp + 1 # increase row pointer cp = 0 # start column pointer from 0 again # Return the resulting pixel matrix return blur_img # Driver codeimage = [[7, 4, 0, 1], [5, 6, 2, 2], [6, 10, 7, 8], [1, 4, 2, 0]] print(boxBlur(image)) Output: [[5, 4], [4, 4]] Test case 2: image = [[36, 0, 18, 9], [27, 54, 9, 0], [81, 63, 72, 45]] print(boxBlur(image)) Output: [[40, 30]] Further Read: Box Blur using PIL library | Python Image-Processing Python DSA-exercises Technical Scripter 2019 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 Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n30 Dec, 2020" }, { "code": null, "e": 24434, "s": 24212, "text": "The pixels in an image are represented as integers. After blurring each pixel ‘x’ of the resulting image has a value equal to the average of the pixels surrounding ‘x’ including ‘x’. For example, consider a 3 * 3 image as" }, { "code": null, "e": 24592, "s": 24434, "text": "Then, the resulting image after blur is blurred_image = So, the pixel of blurred image is calculated as (1 + 1 + 1 + 1 + 7 + 1 + 1 + 1 + 1) / 9 = 1.66666 = 1" }, { "code": null, "e": 24697, "s": 24592, "text": "Box blur is also known as box linear filter. Box blurs are frequently used to approximate Gaussian blur." }, { "code": null, "e": 24899, "s": 24697, "text": "A box blur is generally implemented as an image effect that affects the whole screen. The blurred colour of the current pixel is the average of the current pixel’s colour and its 8 neighbouring pixels." }, { "code": null, "e": 24981, "s": 24899, "text": "Note: For each 3 * 3 pixel matrix there is one blurred pixel calculated as above." }, { "code": null, "e": 25054, "s": 24981, "text": "FOr Example, Consider the below image.It’s blurred image is given below:" }, { "code": null, "e": 25199, "s": 25054, "text": "Explanation:There are four 3 * 3 matrix possible in the above image. So there are 4 blurred pixel in the resulting image. The four matrices are:" }, { "code": null, "e": 25213, "s": 25199, "text": ",\n\n,\n\n,\nand\n\n" }, { "code": null, "e": 25240, "s": 25213, "text": " Implementation in Python:" }, { "code": "def square_matrix(square): \"\"\" This function will calculate the value x (i.e. blurred pixel value) for each 3 * 3 blur image. \"\"\" tot_sum = 0 # Calculate sum of all the pixels in 3 * 3 matrix for i in range(3): for j in range(3): tot_sum += square[i][j] return tot_sum // 9 # return the average of the sum of pixels def boxBlur(image): \"\"\" This function will calculate the blurred image for given n * n image. \"\"\" square = [] # This will store the 3 * 3 matrix # which will be used to find its blurred pixel square_row = [] # This will store one row of a 3 * 3 matrix and # will be appended in square blur_row = [] # Here we will store the resulting blurred # pixels possible in one row # and will append this in the blur_img blur_img = [] # This is the resulting blurred image # number of rows in the given image n_rows = len(image) # number of columns in the given image n_col = len(image[0]) # rp is row pointer and cp is column pointer rp, cp = 0, 0 # This while loop will be used to # calculate all the blurred pixel in the first row while rp <= n_rows - 3: while cp <= n_col-3: for i in range(rp, rp + 3): for j in range(cp, cp + 3): # append all the pixels in a row of 3 * 3 matrix square_row.append(image[i][j]) # append the row in the square i.e. 3 * 3 matrix square.append(square_row) square_row = [] # calculate the blurred pixel for given 3 * 3 matrix # i.e. square and append it in blur_row blur_row.append(square_matrix(square)) square = [] # increase the column pointer cp = cp + 1 # append the blur_row in blur_image blur_img.append(blur_row) blur_row = [] rp = rp + 1 # increase row pointer cp = 0 # start column pointer from 0 again # Return the resulting pixel matrix return blur_img # Driver codeimage = [[7, 4, 0, 1], [5, 6, 2, 2], [6, 10, 7, 8], [1, 4, 2, 0]] print(boxBlur(image))", "e": 27703, "s": 25240, "text": null }, { "code": null, "e": 27711, "s": 27703, "text": "Output:" }, { "code": null, "e": 27730, "s": 27711, "text": "[[5, 4], \n[4, 4]]\n" }, { "code": null, "e": 27743, "s": 27730, "text": "Test case 2:" }, { "code": "image = [[36, 0, 18, 9], [27, 54, 9, 0], [81, 63, 72, 45]] print(boxBlur(image))", "e": 27843, "s": 27743, "text": null }, { "code": null, "e": 27851, "s": 27843, "text": "Output:" }, { "code": null, "e": 27862, "s": 27851, "text": "[[40, 30]]" }, { "code": null, "e": 27913, "s": 27862, "text": " Further Read: Box Blur using PIL library | Python" }, { "code": null, "e": 27930, "s": 27913, "text": "Image-Processing" }, { "code": null, "e": 27951, "s": 27930, "text": "Python DSA-exercises" }, { "code": null, "e": 27975, "s": 27951, "text": "Technical Scripter 2019" }, { "code": null, "e": 27982, "s": 27975, "text": "Python" }, { "code": null, "e": 28001, "s": 27982, "text": "Technical Scripter" }, { "code": null, "e": 28099, "s": 28001, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28108, "s": 28099, "text": "Comments" }, { "code": null, "e": 28121, "s": 28108, "text": "Old Comments" }, { "code": null, "e": 28153, "s": 28121, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28209, "s": 28153, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28230, "s": 28209, "text": "Python OOPs Concepts" }, { "code": null, "e": 28269, "s": 28230, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28311, "s": 28269, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28338, "s": 28311, "text": "Python Classes and Objects" }, { "code": null, "e": 28369, "s": 28338, "text": "Python | os.path.join() method" }, { "code": null, "e": 28411, "s": 28369, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28447, "s": 28411, "text": "Python | Pandas dataframe.groupby()" } ]
Changing ttk Button Height in Python
Ttk adds styles to the tkinter’s standard widget which can be configured through different properties and functions. We can change the height of the ttk button by using the grid(options) method. This method contains various attributes and properties with some different options. If we want to resize the ttk button, we can specify the value of internal padding such as ipadx and ipady. Let us understand it with an example, #Import tkinter library from tkinter import * from tkinter import ttk #Create an instance of tkinter frame or window win = Tk() #Set the geometry of tkinter frame win.geometry("750x250") #Create a button using the ttk themed widget button = ttk.Button(win, text = "Button") button.grid(ipadx=10, ipady=30 ) win.mainloop() In the above code, we have added internal padding to the button widget. Now, run the program to display the output,
[ { "code": null, "e": 1448, "s": 1062, "text": "Ttk adds styles to the tkinter’s standard widget which can be configured through different properties and functions. We can change the height of the ttk button by using the grid(options) method. This method contains various attributes and properties with some different options. If we want to resize the ttk button, we can specify the value of internal padding such as ipadx and ipady." }, { "code": null, "e": 1486, "s": 1448, "text": "Let us understand it with an example," }, { "code": null, "e": 1808, "s": 1486, "text": "#Import tkinter library\nfrom tkinter import *\nfrom tkinter import ttk\n#Create an instance of tkinter frame or window\nwin = Tk()\n#Set the geometry of tkinter frame\nwin.geometry(\"750x250\")\n#Create a button using the ttk themed widget\nbutton = ttk.Button(win, text = \"Button\")\nbutton.grid(ipadx=10, ipady=30 )\nwin.mainloop()" }, { "code": null, "e": 1924, "s": 1808, "text": "In the above code, we have added internal padding to the button widget. Now, run the program to display the output," } ]
Part 10: Discovering Multidimensional Time Series Motifs | by Sean Law | Towards Data Science
STUMPY is a powerful and scalable Python library for modern time series analysis and, at its core, efficiently computes something called a matrix profile. The goal of this multi-part series is to explain what the matrix profile is and how you can start leveraging STUMPY for all of your modern time series data mining tasks! Note: These tutorials were originally featured in the STUMPY documentation. Part 1: The Matrix ProfilePart 2: STUMPY BasicsPart 3: Time Series ChainsPart 4: Semantic SegmentationPart 5: Fast Approximate Matrix Profiles with STUMPYPart 6: Matrix Profiles for Streaming Time Series DataPart 7: Fast Pattern Searching with STUMPYPart 8: AB-Joins with STUMPYPart 9: Time Series Consensus MotifsPart 10: Discovering Multidimensional Time Series Motifs This tutorial utilizes the main takeaways from the Matrix Profile VI research paper and requires STUMPY v1.6.1 or newer. Also, the word “dimensionality” is overloaded for multi-dimensional time series since it is often used to refer to both the number of time series and to the number of data points in a subsequence. For clarity, we restrict our use of “dimensions” to refer only to the number of time series and not to the number of data points. Previously, we had introduced a concept called time series motifs, which are conserved patterns found within a 1-dimensional time series, T, that can be discovered by computing its matrix profile using STUMPY. This process of computing a matrix profile with one time series is commonly known as a “self-join” since the subsequences within time series T are only being compared with itself. Since the first 1-dimensional motif discovery algorithm was introduced in 2002, a lot of effort has been made to generalize motif-finding to the multi-dimensional case but producing multi-dimensional matrix profiles are computationally expensive and so extra care must be taken to minimize the added time complexity. Also, while it may be tempting to find motifs in all available dimensions (i.e., a motif must exist in all dimensions and occur simultaneously), it has been shown that this rarely produces meaningful motifs except in the most contrived situations. Instead, given a set of time series dimensions, we should filter them down to a subset of “useful” dimensions before assigning a subsequence as a motif. For example, take a look at this motion capture of a boxer throwing some punches: If we strictly focus on the boxer’s right arm in both cases, the two punches are almost identical. The position of the right shoulder, right elbow, and right hand (a three dimensional time series) are virtually the indistinguishable. So, identifying this punching motif is relatively straightforward when we limit ourselves to only a subset of all of the available body movement dimensions. However, if we incorporate the full set of motion capture markers from all of the limbs (i.e., increasing the number of dimensions from three), the differences captured by the left arm and the subtle noise in the footwork actually drowns out the the similarity of the right arm motions, making the previous punching motif impossible to find. This example demonstrates how classic multidimensional motif discovery algorithms are likely to fail since they try to use all of the available dimensions. So, not only do we need an efficient algorithm for computing the multi-dimensional matrix profile but we also need to establish an informed approach to guide us in selecting the relevant subset of dimensions that are to be used in identifying multi-dimensional motifs. In this tutorial, we will explain precisely what a multi-dimensional matrix profile is and then we’ll learn how to compute it using the mstump function (i.e., “multi-dimensional STUMP”) by exploring a simple toy dataset. To conclude, we’ll see if we can identify a meaningful sub-dimensional motif (i.e., that only uses a subset of dimensions) in this multi-dimensional time series data. Let’s import the packages that we’ll need to load, analyze, and plot the data. %matplotlib inlineimport pandas as pdimport numpy as npimport stumpyimport matplotlib.pyplot as pltplt.rcParams["figure.figsize"] = [20, 6] # width, heightplt.rcParams['xtick.direction'] = 'out' In this example data, we have a 3-dimensional time series labeled T1, T2, and T3. Can you spot where the motif is? Does that motif exist in one, two, or all three dimensions? df = pd.read_csv("https://zenodo.org/record/4328047/files/toy.csv?download=1")df.head() T1 T2 T30 0.565117 0.637180 0.7418221 0.493513 0.629415 0.7397312 0.469350 0.539220 0.7187573 0.444100 0.577670 0.7301694 0.373008 0.570180 0.752406fig, axs = plt.subplots(df.shape[1], sharex=True, gridspec_kw={'hspace': 0})plt.suptitle('Can You Spot The Multi-dimensional Motif?', fontsize='30')for i in range(df.shape[1]): axs[i].set_ylabel(f'T{i + 1}', fontsize='20') axs[i].set_xlabel('Time', fontsize ='20') axs[i].plot(df[f'T{i + 1}'])plt.show() Before diving into a multi-dimensional matrix profile analysis, let’s take a naive approach and simply run the classic 1-dimensional motif discovery algorithm, stumpy.stump, on each of the dimensions independently (using a window size of m = 30) and extract 1-dimensional motif pairs: m = 30mps = {} # Store the 1-dimensional matrix profilesmotifs_idx = {} # Store the index locations for each pair of 1-dimensional motifs (i.e., the index location of two smallest matrix profile values within each dimension)for dim_name in df.columns: mps[dim_name] = stumpy.stump(df[dim_name], m) motif_distance = np.round(mps[dim_name][:, 0].min(), 1) motifs_idx[dim_name] = np.argsort(mps[dim_name][:, 0])[:2] print(f"The motif pair matrix profile value in {dim_name} is {motif_distance}")The motif pair matrix profile value in T1 is 1.1The motif pair matrix profile value in T2 is 1.0The motif pair matrix profile value in T3 is 1.1 And when we plot the raw times series again (below) along with their independently discovered motifs (thick red lines), we can correctly match the visually obvious motif pairs in T1 and T2 starting near locations 150 and 350 (dotted vertical lines). Notice that these two motifs aren’t perfectly aligned in time (i.e., they aren’t occurring simultaneously) but they are reasonably close to each and their motif pair values are 1.1 and 1.0, respectively. This is a great start! fig, axs = plt.subplots(len(mps), sharex=True, gridspec_kw={'hspace': 0})for i, dim_name in enumerate(list(mps.keys())): axs[i].set_ylabel(dim_name, fontsize='20') axs[i].plot(df[dim_name]) axs[i].set_xlabel('Time', fontsize ='20') for idx in motifs_idx[dim_name]: axs[i].plot(df[dim_name].iloc[idx:idx+m], c='red', linewidth=4) axs[i].axvline(x=idx, linestyle="dashed", c='black')plt.show() However, when we examine T3, its motif pair are overlapping each other starting near position 50 (dotted vertical lines) and they are relatively far away from the motifs discovered in T1 and T2. Oh, no! In fact, T3 is actually a “random walk” time series that was purposely included in this set as a decoy and, unlike T1 and T2, T3 does not contain any conserved behavior whatsoever despite the fact that the distance between its motif pair is 1.1, a red herring. This illustrates a few important points: if there are additional irrelevant dimensions (i.e., T3), you will do about as well as random chance at discovering multi-dimensional motifs if you don’t ignore/dismiss those distracting dimensionsif you suspect that there are motifs in only a subset of the time series, how do you know which dimensions are involved, or how do you even know how many dimensions are relevant?doing motif search on all dimensions is almost always guaranteed to produce meaningless results, even if a subset of dimensions has clear and unambiguous motifs (like our example above) if there are additional irrelevant dimensions (i.e., T3), you will do about as well as random chance at discovering multi-dimensional motifs if you don’t ignore/dismiss those distracting dimensions if you suspect that there are motifs in only a subset of the time series, how do you know which dimensions are involved, or how do you even know how many dimensions are relevant? doing motif search on all dimensions is almost always guaranteed to produce meaningless results, even if a subset of dimensions has clear and unambiguous motifs (like our example above) A quick survey of all current multi-dimensional motif discovery algorithms in the literature (see Section II in Matrix Profile VI) reveals that they are slow, approximate, and brittle to irrelevant dimensions. In contrast, what we need is an algorithm that is fast, exact, and robust to hundreds of irrelevant dimensions and to spurious data. And this is where stumpy.mstump can help! There is no substitution for the multi-dimensional matrix profile definitions provided in the Matrix Profile VI paper (see Section III and Section IV) and so we refer the reader to this quintessential resource for a detailed walkthrough. However, to develop some basic intuition, we’ll share an oversimplified description for computing a multi-dimensional matrix profile but know that the stumpy.mstump function provides a highly efficient, accurate, and scalable variant to the naive explanation provided here. First and foremost, we must start by dispelling a common misconception regarding multi-dimensional matrix profiles: Multi-dimensional matrix profiles are not 1-dimensional matrix profiles stacked one on top of each other! So, what is a multi-dimensional matrix profile? To answer this question, let’s step away from our toy data example for a minute and suppose that we have a “multi-dimensional time series”, T=[T1,T2,T3,T4], which has d=4 dimensions and length n=7 (i.e., there are seven data points or “positions” within each dimension). Then, T simply has shape d×n (or 4×7). If we choose a window size, m=3, then we can define the ith “multi-dimensional subsequence” as a continuous subset of the values from T of length m starting from position i that has an overall shape of d×m (or 4×3). You can think of each multi-dimensional subsequence as a rectangular slice of T and T can only have exactly l=n−m+1 multi-dimensional subsequences. In our example, T has exactly l=5 multi-dimensional subsequences (i.e., we can incrementally slide a 4×3-shaped rectangle across the length of T only 5 times before we reach the end of T) and, for the ith multi-dimensional subsequence, we can iterate over each of its dimensions independently and compute an aggregated “multi-dimensional distance profile” (i.e., four1-dimensional distance profiles stacked one on top of each other). Essentially, the ith multi-dimensional distance profile has shape d×l (or 4×5) and gives you the pairwise distances between the ith multi-dimensional subsequence and all other possible multi-dimensional subsequences within T. Recall that our ultimate goal is to output something called the “multi-dimensional matrix profile” (and its corresponding “multi-dimensional matrix profile indices”), which has an overall shape of d×l (i.e., one set of d values for each of the l multi-dimensional subsequences). As it turns out, the values in the ith column of the multi-dimensional matrix profile is directly derived from the ith multi-dimensional distance profile. Continuing with our example, let’s illustrate this process using the fictitious array below to represent a typical multi-dimensional distance profile for the ith multi-dimensional subsequence: ith_distance_profile = array([[0.4, 0.2, 0.6, 0.5, 0.2, 0.1, 0.9], [0.7, 0.0, 0.2, 0.6, 0.1, 0.2, 0.9], [0.6, 0.7, 0.1, 0.5, 0.8, 0.3, 0.4], [0.7, 0.4, 0.3, 0.1, 0.2, 0.1, 0.7]]) With this, we can now identify the set of d values that form the ith column vector of the multi-dimensional matrix profile with shape d×1 (or 4×1). The value for the first dimension is found by extracting the smallest value in each column of the ith_distance_profile and then returning the minimum value in the reduced set. Then, the value for the second dimension is found by extracting the two smallest values in each column of the ith_distance_profile, averaging these two values, and then returning the minimum averaged value in the reduced set. Finally, the value for the kth out of d dimensions is found by extracting the k smallest values in each column of the ith_distance_profile, averaging these k values, and then returning the minimum averaged value in the reduced set. A naive algorithm might look something like this: ith_matrix_profile = np.full(d, np.inf)ith_indices = np.full(d, -1, dtype=np.int64)for k in range(1, d + 1): smallest_k = np.partition(ith_distance_profile, k, axis=0)[:k] # retrieves the smallest k values in each column averaged_smallest_k = smallest_k.mean(axis=0) min_val = averaged_smallest_k.min() if min_val < ith_matrix_profile[k - 1]: ith_matrix_profile[k - 1] = min_val ith_indices[k - 1] = averaged_smallest_k.argmin() Therefore, by simply advancing the ith multi-dimensional subsequence along the entire length of T and then computing its corresponding ith multi-dimensional matrix profile (and indices), we can easily populate the full multi-dimensional matrix profile and multi-dimensional matrix profile indices. And, hopefully, you’d agree with our initial statement that: Multi-dimensional matrix profiles are not 1-dimensional matrix profiles stacked one on top of each other! But then what exactly does each dimension of the multi-dimensional matrix profile tell us? Essentially, the kth dimension (or row) of the multi-dimensional matrix profile stores the distance between each subsequence and its nearest neighbor (the distance is computed using a k-dimensional distance function as we saw above). We should point out that, for the kth dimension of the multi-dimensional matrix profile, only a subset of time series dimensions (i.e., k out of d dimensions) are selected and this subset of chosen dimensions can change as you vary either the ith multi-dimensional subsequence and/or k. Now that we have a better understanding of what a multi-dimensional matrix profile is, let’s go ahead and compute it by simply calling the stumpy.mstump function on our original toy dataset: mps, indices = stumpy.mstump(df, m) Consequently, the “k-dimensional motif” can be found by locating the two lowest values in the correspond k-dimensional matrix profile, mps, (these two lowest values must be a tie). motifs_idx = np.argsort(mps, axis=1)[:, :2] Finally, we can plot the k-dimensional matrix profile (orange lines) for all possible values of k (i.e., P1, P2, and P3) alongside the original time series data (blue lines): fig, axs = plt.subplots(mps.shape[0] * 2, sharex=True, gridspec_kw={'hspace': 0})for k, dim_name in enumerate(df.columns): axs[k].set_ylabel(dim_name, fontsize='20') axs[k].plot(df[dim_name]) axs[k].set_xlabel('Time', fontsize ='20') axs[k + mps.shape[0]].set_ylabel(dim_name.replace('T', 'P'), fontsize='20') axs[k + mps.shape[0]].plot(mps[k], c='orange') axs[k + mps.shape[0]].set_xlabel('Time', fontsize ='20') axs[k].axvline(x=motifs_idx[1, 0], linestyle="dashed", c='black') axs[k].axvline(x=motifs_idx[1, 1], linestyle="dashed", c='black') axs[k + mps.shape[0]].axvline(x=motifs_idx[1, 0], linestyle="dashed", c='black') axs[k + mps.shape[0]].axvline(x=motifs_idx[1, 1], linestyle="dashed", c='black') if dim_name != 'T3': axs[k].plot(range(motifs_idx[k, 0], motifs_idx[k, 0] + m), df[dim_name].iloc[motifs_idx[k, 0] : motifs_idx[k, 0] + m], c='red', linewidth=4) axs[k].plot(range(motifs_idx[k, 1], motifs_idx[k, 1] + m), df[dim_name].iloc[motifs_idx[k, 1] : motifs_idx[k, 1] + m], c='red', linewidth=4) axs[k + mps.shape[0]].plot(motifs_idx[k, 0], mps[k, motifs_idx[k, 0]] + 1, marker="v", markersize=10, color='red') axs[k + mps.shape[0]].plot(motifs_idx[k, 1], mps[k, motifs_idx[k, 1]] + 1, marker="v", markersize=10, color='red') else: axs[k + mps.shape[0]].plot(motifs_idx[k, 0], mps[k, motifs_idx[k, 0]] + 1, marker="v", markersize=10, color='black') axs[k + mps.shape[0]].plot(motifs_idx[k, 1], mps[k, motifs_idx[k, 1]] + 1, marker="v", markersize=10, color='black')plt.show() Notice that the (implanted) semantically meaningful motif (thick red lines) can be spotted visually by inspecting the locations of the lowest points (red arrowheads) in either the P1 or P2 matrix profiles but the P3 case has identified the motif (black arrowheads) in an effectively random location, which further reinforces the point that we had made earlier: if there are additional irrelevant dimensions (i.e., T3), you will do about as well as random chance at discovering multi-dimensional motifs if you don’t ignore/dismiss those distracting dimensions Additionally, it may seem counterintuitive, but as demonstrated above, the lower dimensional motif(s) may or may not necessarily be a subset of the higher dimensional motif, since the lower dimensional motif pair could be closer than any subset of dimensions in the higher dimensional motif pair. In general, this is a subtle but important point to keep in mind. So then how do we choose the “right” k? One straightforward approach is to turn this into a classic elbow/knee finding problem by plotting the minimum matrix profile value in each dimension against k and then you look for the “turning point” (i.e., the point of maximum curvature): plt.plot(mps[range(mps.shape[0]), motifs_idx[:, 0]], c='red', linewidth='4')plt.xlabel('k (zero-based)', fontsize='20')plt.ylabel('Matrix Profile Value', fontsize='20')plt.xticks(range(mps.shape[0]))plt.plot(1, 1.3, marker="v", markersize=10, color='red')plt.show() Notice that the thick red line curves up sharply right after k=1 (red arrowhead) like a “hockey stick” and so, naturally, we should choose P2 and its motif as the best motif out of all possible k-dimensional motifs. To really drive home this point, let’s add a few more random walk decoys to our toy data set and compare the smallest k-dimensional matrix profile values again: for i in range(4, 11): df[f'T{i}'] = np.random.uniform(0.1, -0.1, size=df.shape[0]).cumsum()fig, axs = plt.subplots(df.shape[1], sharex=True, gridspec_kw={'hspace': 0})plt.suptitle('Can You Still Spot The Multi-dimensional Motif?', fontsize='30')for i in range(df.shape[1]): axs[i].set_ylabel(f'T{i + 1}', fontsize='20') axs[i].set_xlabel('Time', fontsize ='20') axs[i].plot(df[f'T{i + 1}'])plt.show() mps, indices = stumpy.mstump(df, m)motifs_idx = np.argsort(mps, axis=1)[:, :2]plt.plot(mps[range(mps.shape[0]), motifs_idx[:, 0]], c='red', linewidth='4')plt.xlabel('k (zero-based)', fontsize='20')plt.ylabel('Matrix Profile Value', fontsize='20')plt.xticks(range(mps.shape[0]))plt.plot(1, 1.3, marker="v", markersize=10, color='red')plt.show() Again, the “point of maximum curvature” occurs right after k=1 (red arrowhead) and so we should continue to choose P2 and its motif as the best motif out of all possible k-dimensional motifs. While this might seem like a rather manual task, we recommend automating this turning point selection process using the kneed Python package. The astute reader may have also recognized that the k-dimensional matrix profile really only reveals the location of a motif in time but it fails to disclose which k out of the d time series dimensions contains the desired motif pair. To recover this information, we must compute something called the “k-dimensional matrix profile subspace”. Luckily, the STUMPY convenience function, stumpy.subspace, can help us with this! To use stumpy.subspace, we simply pass in: the multi-dimensional time series, df, used to compute the multi-dimensional matrix profilethe window size, m, used to compute the multi-dimensional matrix profilethe indices for the kth-dimensional motif pair, motifs_idx[k][0] and indices[k][motifs_idx[k][0]]the desired (zero-based) dimension, k the multi-dimensional time series, df, used to compute the multi-dimensional matrix profile the window size, m, used to compute the multi-dimensional matrix profile the indices for the kth-dimensional motif pair, motifs_idx[k][0] and indices[k][motifs_idx[k][0]] the desired (zero-based) dimension, k k = 1S = stumpy.subspace(df, m, motifs_idx[k][0], indices[k][motifs_idx[k][0]], k)print(f"For k = {k}, the {k + 1}-dimensional subspace includes subsequences from {df.columns[S].values}")For k = 1, the 2-dimensional subspace includes subsequences from ['T2' 'T1'] So, after computing the multi-dimensional matrix profile using mstump and selecting the second dimension (i.e., k=1), according to the k-dimensional subspace, the motif should be extracted from T2 and T1 out of all of the possible time series dimensions. Dependent upon the total number of dimensions and the length of your time series dat, it may be computationally expensive to produce the multi-dimensional matrix profile. Thus, you can overcome this by trying mstumped, a distributed and parallel implementation of mstump that depends on Dask distributed: import stumpyfrom dask.distributed import Clientdask_client = Client()mps, indices = stumpy.mstumped(dask_client, df, m) # Note that a dask client is needed There may be situations where you want to find the best motif on k dimensions but you want to explicitly “include” or “exclude” a given subset of dimensions. In the trivial exclusion case, one just needs to omit the undesired time series dimensions before calling mstump: mps, indices = stumpy.mstump(df[df.columns.difference(['T3'])], m) # This excludes the `T3` dimension However, in the case of inclusion, the user may have specific time series dimensions that they’d always want to be included or prioritized in the multi-dimensional matrix profile output and so you can provide a list of (zero-based) dimensions as an parameter: mps, indices = stumpy.mstump(df, m, include=[0, 1]) So, in this example where we’ve instructed mstump to include=[0, 1] (i.e., T1 and T2), when k≥1, the kth dimensional matrix profile subspace will always include T1 and T2. Similarly, k<1 will include either T1 or T2. Finally, instead of searching for motifs, it is also possible to have mstump search for discords by simply passing in the discords=True parameter: mps, indices = stumpy.mstump(df, m, discords=True) Instead of returning the smallest average distance, this returns the largest average distance across k dimensions. This ability to return discords is unique to STUMPY and was not published in the original paper. Also note that it is possible to include specific dimensions and search for discords at the same time: mps, indices = stumpy.mstump(df, m, include=[0, 1], discords=True) In this case, the dimensions listed in include are honored first and then all subsequent dimensions are sorted by their largest average distance across kk dimensions. And that’s it! You’ve just learned the basics of how to analyze multi-dimensional time series data using stumpy.mstump (or stumpy.mstumped). Happy coding! Matrix Profile VI STUMPY Documentation STUMPY Matrix Profile Github Code Repository
[ { "code": null, "e": 497, "s": 172, "text": "STUMPY is a powerful and scalable Python library for modern time series analysis and, at its core, efficiently computes something called a matrix profile. The goal of this multi-part series is to explain what the matrix profile is and how you can start leveraging STUMPY for all of your modern time series data mining tasks!" }, { "code": null, "e": 573, "s": 497, "text": "Note: These tutorials were originally featured in the STUMPY documentation." }, { "code": null, "e": 944, "s": 573, "text": "Part 1: The Matrix ProfilePart 2: STUMPY BasicsPart 3: Time Series ChainsPart 4: Semantic SegmentationPart 5: Fast Approximate Matrix Profiles with STUMPYPart 6: Matrix Profiles for Streaming Time Series DataPart 7: Fast Pattern Searching with STUMPYPart 8: AB-Joins with STUMPYPart 9: Time Series Consensus MotifsPart 10: Discovering Multidimensional Time Series Motifs" }, { "code": null, "e": 1392, "s": 944, "text": "This tutorial utilizes the main takeaways from the Matrix Profile VI research paper and requires STUMPY v1.6.1 or newer. Also, the word “dimensionality” is overloaded for multi-dimensional time series since it is often used to refer to both the number of time series and to the number of data points in a subsequence. For clarity, we restrict our use of “dimensions” to refer only to the number of time series and not to the number of data points." }, { "code": null, "e": 2582, "s": 1392, "text": "Previously, we had introduced a concept called time series motifs, which are conserved patterns found within a 1-dimensional time series, T, that can be discovered by computing its matrix profile using STUMPY. This process of computing a matrix profile with one time series is commonly known as a “self-join” since the subsequences within time series T are only being compared with itself. Since the first 1-dimensional motif discovery algorithm was introduced in 2002, a lot of effort has been made to generalize motif-finding to the multi-dimensional case but producing multi-dimensional matrix profiles are computationally expensive and so extra care must be taken to minimize the added time complexity. Also, while it may be tempting to find motifs in all available dimensions (i.e., a motif must exist in all dimensions and occur simultaneously), it has been shown that this rarely produces meaningful motifs except in the most contrived situations. Instead, given a set of time series dimensions, we should filter them down to a subset of “useful” dimensions before assigning a subsequence as a motif. For example, take a look at this motion capture of a boxer throwing some punches:" }, { "code": null, "e": 3740, "s": 2582, "text": "If we strictly focus on the boxer’s right arm in both cases, the two punches are almost identical. The position of the right shoulder, right elbow, and right hand (a three dimensional time series) are virtually the indistinguishable. So, identifying this punching motif is relatively straightforward when we limit ourselves to only a subset of all of the available body movement dimensions. However, if we incorporate the full set of motion capture markers from all of the limbs (i.e., increasing the number of dimensions from three), the differences captured by the left arm and the subtle noise in the footwork actually drowns out the the similarity of the right arm motions, making the previous punching motif impossible to find. This example demonstrates how classic multidimensional motif discovery algorithms are likely to fail since they try to use all of the available dimensions. So, not only do we need an efficient algorithm for computing the multi-dimensional matrix profile but we also need to establish an informed approach to guide us in selecting the relevant subset of dimensions that are to be used in identifying multi-dimensional motifs." }, { "code": null, "e": 4128, "s": 3740, "text": "In this tutorial, we will explain precisely what a multi-dimensional matrix profile is and then we’ll learn how to compute it using the mstump function (i.e., “multi-dimensional STUMP”) by exploring a simple toy dataset. To conclude, we’ll see if we can identify a meaningful sub-dimensional motif (i.e., that only uses a subset of dimensions) in this multi-dimensional time series data." }, { "code": null, "e": 4207, "s": 4128, "text": "Let’s import the packages that we’ll need to load, analyze, and plot the data." }, { "code": null, "e": 4403, "s": 4207, "text": "%matplotlib inlineimport pandas as pdimport numpy as npimport stumpyimport matplotlib.pyplot as pltplt.rcParams[\"figure.figsize\"] = [20, 6] # width, heightplt.rcParams['xtick.direction'] = 'out'" }, { "code": null, "e": 4578, "s": 4403, "text": "In this example data, we have a 3-dimensional time series labeled T1, T2, and T3. Can you spot where the motif is? Does that motif exist in one, two, or all three dimensions?" }, { "code": null, "e": 5164, "s": 4578, "text": "df = pd.read_csv(\"https://zenodo.org/record/4328047/files/toy.csv?download=1\")df.head() T1 T2 T30 0.565117 0.637180 0.7418221 0.493513 0.629415 0.7397312 0.469350 0.539220 0.7187573 0.444100 0.577670 0.7301694 0.373008 0.570180 0.752406fig, axs = plt.subplots(df.shape[1], sharex=True, gridspec_kw={'hspace': 0})plt.suptitle('Can You Spot The Multi-dimensional Motif?', fontsize='30')for i in range(df.shape[1]): axs[i].set_ylabel(f'T{i + 1}', fontsize='20') axs[i].set_xlabel('Time', fontsize ='20') axs[i].plot(df[f'T{i + 1}'])plt.show()" }, { "code": null, "e": 5449, "s": 5164, "text": "Before diving into a multi-dimensional matrix profile analysis, let’s take a naive approach and simply run the classic 1-dimensional motif discovery algorithm, stumpy.stump, on each of the dimensions independently (using a window size of m = 30) and extract 1-dimensional motif pairs:" }, { "code": null, "e": 6100, "s": 5449, "text": "m = 30mps = {} # Store the 1-dimensional matrix profilesmotifs_idx = {} # Store the index locations for each pair of 1-dimensional motifs (i.e., the index location of two smallest matrix profile values within each dimension)for dim_name in df.columns: mps[dim_name] = stumpy.stump(df[dim_name], m) motif_distance = np.round(mps[dim_name][:, 0].min(), 1) motifs_idx[dim_name] = np.argsort(mps[dim_name][:, 0])[:2] print(f\"The motif pair matrix profile value in {dim_name} is {motif_distance}\")The motif pair matrix profile value in T1 is 1.1The motif pair matrix profile value in T2 is 1.0The motif pair matrix profile value in T3 is 1.1" }, { "code": null, "e": 6577, "s": 6100, "text": "And when we plot the raw times series again (below) along with their independently discovered motifs (thick red lines), we can correctly match the visually obvious motif pairs in T1 and T2 starting near locations 150 and 350 (dotted vertical lines). Notice that these two motifs aren’t perfectly aligned in time (i.e., they aren’t occurring simultaneously) but they are reasonably close to each and their motif pair values are 1.1 and 1.0, respectively. This is a great start!" }, { "code": null, "e": 6995, "s": 6577, "text": "fig, axs = plt.subplots(len(mps), sharex=True, gridspec_kw={'hspace': 0})for i, dim_name in enumerate(list(mps.keys())): axs[i].set_ylabel(dim_name, fontsize='20') axs[i].plot(df[dim_name]) axs[i].set_xlabel('Time', fontsize ='20') for idx in motifs_idx[dim_name]: axs[i].plot(df[dim_name].iloc[idx:idx+m], c='red', linewidth=4) axs[i].axvline(x=idx, linestyle=\"dashed\", c='black')plt.show()" }, { "code": null, "e": 7198, "s": 6995, "text": "However, when we examine T3, its motif pair are overlapping each other starting near position 50 (dotted vertical lines) and they are relatively far away from the motifs discovered in T1 and T2. Oh, no!" }, { "code": null, "e": 7500, "s": 7198, "text": "In fact, T3 is actually a “random walk” time series that was purposely included in this set as a decoy and, unlike T1 and T2, T3 does not contain any conserved behavior whatsoever despite the fact that the distance between its motif pair is 1.1, a red herring. This illustrates a few important points:" }, { "code": null, "e": 8061, "s": 7500, "text": "if there are additional irrelevant dimensions (i.e., T3), you will do about as well as random chance at discovering multi-dimensional motifs if you don’t ignore/dismiss those distracting dimensionsif you suspect that there are motifs in only a subset of the time series, how do you know which dimensions are involved, or how do you even know how many dimensions are relevant?doing motif search on all dimensions is almost always guaranteed to produce meaningless results, even if a subset of dimensions has clear and unambiguous motifs (like our example above)" }, { "code": null, "e": 8259, "s": 8061, "text": "if there are additional irrelevant dimensions (i.e., T3), you will do about as well as random chance at discovering multi-dimensional motifs if you don’t ignore/dismiss those distracting dimensions" }, { "code": null, "e": 8438, "s": 8259, "text": "if you suspect that there are motifs in only a subset of the time series, how do you know which dimensions are involved, or how do you even know how many dimensions are relevant?" }, { "code": null, "e": 8624, "s": 8438, "text": "doing motif search on all dimensions is almost always guaranteed to produce meaningless results, even if a subset of dimensions has clear and unambiguous motifs (like our example above)" }, { "code": null, "e": 9009, "s": 8624, "text": "A quick survey of all current multi-dimensional motif discovery algorithms in the literature (see Section II in Matrix Profile VI) reveals that they are slow, approximate, and brittle to irrelevant dimensions. In contrast, what we need is an algorithm that is fast, exact, and robust to hundreds of irrelevant dimensions and to spurious data. And this is where stumpy.mstump can help!" }, { "code": null, "e": 9521, "s": 9009, "text": "There is no substitution for the multi-dimensional matrix profile definitions provided in the Matrix Profile VI paper (see Section III and Section IV) and so we refer the reader to this quintessential resource for a detailed walkthrough. However, to develop some basic intuition, we’ll share an oversimplified description for computing a multi-dimensional matrix profile but know that the stumpy.mstump function provides a highly efficient, accurate, and scalable variant to the naive explanation provided here." }, { "code": null, "e": 9637, "s": 9521, "text": "First and foremost, we must start by dispelling a common misconception regarding multi-dimensional matrix profiles:" }, { "code": null, "e": 9743, "s": 9637, "text": "Multi-dimensional matrix profiles are not 1-dimensional matrix profiles stacked one on top of each other!" }, { "code": null, "e": 11125, "s": 9743, "text": "So, what is a multi-dimensional matrix profile? To answer this question, let’s step away from our toy data example for a minute and suppose that we have a “multi-dimensional time series”, T=[T1,T2,T3,T4], which has d=4 dimensions and length n=7 (i.e., there are seven data points or “positions” within each dimension). Then, T simply has shape d×n (or 4×7). If we choose a window size, m=3, then we can define the ith “multi-dimensional subsequence” as a continuous subset of the values from T of length m starting from position i that has an overall shape of d×m (or 4×3). You can think of each multi-dimensional subsequence as a rectangular slice of T and T can only have exactly l=n−m+1 multi-dimensional subsequences. In our example, T has exactly l=5 multi-dimensional subsequences (i.e., we can incrementally slide a 4×3-shaped rectangle across the length of T only 5 times before we reach the end of T) and, for the ith multi-dimensional subsequence, we can iterate over each of its dimensions independently and compute an aggregated “multi-dimensional distance profile” (i.e., four1-dimensional distance profiles stacked one on top of each other). Essentially, the ith multi-dimensional distance profile has shape d×l (or 4×5) and gives you the pairwise distances between the ith multi-dimensional subsequence and all other possible multi-dimensional subsequences within T." }, { "code": null, "e": 11752, "s": 11125, "text": "Recall that our ultimate goal is to output something called the “multi-dimensional matrix profile” (and its corresponding “multi-dimensional matrix profile indices”), which has an overall shape of d×l (i.e., one set of d values for each of the l multi-dimensional subsequences). As it turns out, the values in the ith column of the multi-dimensional matrix profile is directly derived from the ith multi-dimensional distance profile. Continuing with our example, let’s illustrate this process using the fictitious array below to represent a typical multi-dimensional distance profile for the ith multi-dimensional subsequence:" }, { "code": null, "e": 12018, "s": 11752, "text": "ith_distance_profile = array([[0.4, 0.2, 0.6, 0.5, 0.2, 0.1, 0.9], [0.7, 0.0, 0.2, 0.6, 0.1, 0.2, 0.9], [0.6, 0.7, 0.1, 0.5, 0.8, 0.3, 0.4], [0.7, 0.4, 0.3, 0.1, 0.2, 0.1, 0.7]])" }, { "code": null, "e": 12850, "s": 12018, "text": "With this, we can now identify the set of d values that form the ith column vector of the multi-dimensional matrix profile with shape d×1 (or 4×1). The value for the first dimension is found by extracting the smallest value in each column of the ith_distance_profile and then returning the minimum value in the reduced set. Then, the value for the second dimension is found by extracting the two smallest values in each column of the ith_distance_profile, averaging these two values, and then returning the minimum averaged value in the reduced set. Finally, the value for the kth out of d dimensions is found by extracting the k smallest values in each column of the ith_distance_profile, averaging these k values, and then returning the minimum averaged value in the reduced set. A naive algorithm might look something like this:" }, { "code": null, "e": 13306, "s": 12850, "text": "ith_matrix_profile = np.full(d, np.inf)ith_indices = np.full(d, -1, dtype=np.int64)for k in range(1, d + 1): smallest_k = np.partition(ith_distance_profile, k, axis=0)[:k] # retrieves the smallest k values in each column averaged_smallest_k = smallest_k.mean(axis=0) min_val = averaged_smallest_k.min() if min_val < ith_matrix_profile[k - 1]: ith_matrix_profile[k - 1] = min_val ith_indices[k - 1] = averaged_smallest_k.argmin()" }, { "code": null, "e": 13665, "s": 13306, "text": "Therefore, by simply advancing the ith multi-dimensional subsequence along the entire length of T and then computing its corresponding ith multi-dimensional matrix profile (and indices), we can easily populate the full multi-dimensional matrix profile and multi-dimensional matrix profile indices. And, hopefully, you’d agree with our initial statement that:" }, { "code": null, "e": 13771, "s": 13665, "text": "Multi-dimensional matrix profiles are not 1-dimensional matrix profiles stacked one on top of each other!" }, { "code": null, "e": 14383, "s": 13771, "text": "But then what exactly does each dimension of the multi-dimensional matrix profile tell us? Essentially, the kth dimension (or row) of the multi-dimensional matrix profile stores the distance between each subsequence and its nearest neighbor (the distance is computed using a k-dimensional distance function as we saw above). We should point out that, for the kth dimension of the multi-dimensional matrix profile, only a subset of time series dimensions (i.e., k out of d dimensions) are selected and this subset of chosen dimensions can change as you vary either the ith multi-dimensional subsequence and/or k." }, { "code": null, "e": 14574, "s": 14383, "text": "Now that we have a better understanding of what a multi-dimensional matrix profile is, let’s go ahead and compute it by simply calling the stumpy.mstump function on our original toy dataset:" }, { "code": null, "e": 14610, "s": 14574, "text": "mps, indices = stumpy.mstump(df, m)" }, { "code": null, "e": 14791, "s": 14610, "text": "Consequently, the “k-dimensional motif” can be found by locating the two lowest values in the correspond k-dimensional matrix profile, mps, (these two lowest values must be a tie)." }, { "code": null, "e": 14835, "s": 14791, "text": "motifs_idx = np.argsort(mps, axis=1)[:, :2]" }, { "code": null, "e": 15010, "s": 14835, "text": "Finally, we can plot the k-dimensional matrix profile (orange lines) for all possible values of k (i.e., P1, P2, and P3) alongside the original time series data (blue lines):" }, { "code": null, "e": 16579, "s": 15010, "text": "fig, axs = plt.subplots(mps.shape[0] * 2, sharex=True, gridspec_kw={'hspace': 0})for k, dim_name in enumerate(df.columns): axs[k].set_ylabel(dim_name, fontsize='20') axs[k].plot(df[dim_name]) axs[k].set_xlabel('Time', fontsize ='20') axs[k + mps.shape[0]].set_ylabel(dim_name.replace('T', 'P'), fontsize='20') axs[k + mps.shape[0]].plot(mps[k], c='orange') axs[k + mps.shape[0]].set_xlabel('Time', fontsize ='20') axs[k].axvline(x=motifs_idx[1, 0], linestyle=\"dashed\", c='black') axs[k].axvline(x=motifs_idx[1, 1], linestyle=\"dashed\", c='black') axs[k + mps.shape[0]].axvline(x=motifs_idx[1, 0], linestyle=\"dashed\", c='black') axs[k + mps.shape[0]].axvline(x=motifs_idx[1, 1], linestyle=\"dashed\", c='black') if dim_name != 'T3': axs[k].plot(range(motifs_idx[k, 0], motifs_idx[k, 0] + m), df[dim_name].iloc[motifs_idx[k, 0] : motifs_idx[k, 0] + m], c='red', linewidth=4) axs[k].plot(range(motifs_idx[k, 1], motifs_idx[k, 1] + m), df[dim_name].iloc[motifs_idx[k, 1] : motifs_idx[k, 1] + m], c='red', linewidth=4) axs[k + mps.shape[0]].plot(motifs_idx[k, 0], mps[k, motifs_idx[k, 0]] + 1, marker=\"v\", markersize=10, color='red') axs[k + mps.shape[0]].plot(motifs_idx[k, 1], mps[k, motifs_idx[k, 1]] + 1, marker=\"v\", markersize=10, color='red') else: axs[k + mps.shape[0]].plot(motifs_idx[k, 0], mps[k, motifs_idx[k, 0]] + 1, marker=\"v\", markersize=10, color='black') axs[k + mps.shape[0]].plot(motifs_idx[k, 1], mps[k, motifs_idx[k, 1]] + 1, marker=\"v\", markersize=10, color='black')plt.show()" }, { "code": null, "e": 16940, "s": 16579, "text": "Notice that the (implanted) semantically meaningful motif (thick red lines) can be spotted visually by inspecting the locations of the lowest points (red arrowheads) in either the P1 or P2 matrix profiles but the P3 case has identified the motif (black arrowheads) in an effectively random location, which further reinforces the point that we had made earlier:" }, { "code": null, "e": 17138, "s": 16940, "text": "if there are additional irrelevant dimensions (i.e., T3), you will do about as well as random chance at discovering multi-dimensional motifs if you don’t ignore/dismiss those distracting dimensions" }, { "code": null, "e": 17501, "s": 17138, "text": "Additionally, it may seem counterintuitive, but as demonstrated above, the lower dimensional motif(s) may or may not necessarily be a subset of the higher dimensional motif, since the lower dimensional motif pair could be closer than any subset of dimensions in the higher dimensional motif pair. In general, this is a subtle but important point to keep in mind." }, { "code": null, "e": 17783, "s": 17501, "text": "So then how do we choose the “right” k? One straightforward approach is to turn this into a classic elbow/knee finding problem by plotting the minimum matrix profile value in each dimension against k and then you look for the “turning point” (i.e., the point of maximum curvature):" }, { "code": null, "e": 18049, "s": 17783, "text": "plt.plot(mps[range(mps.shape[0]), motifs_idx[:, 0]], c='red', linewidth='4')plt.xlabel('k (zero-based)', fontsize='20')plt.ylabel('Matrix Profile Value', fontsize='20')plt.xticks(range(mps.shape[0]))plt.plot(1, 1.3, marker=\"v\", markersize=10, color='red')plt.show()" }, { "code": null, "e": 18265, "s": 18049, "text": "Notice that the thick red line curves up sharply right after k=1 (red arrowhead) like a “hockey stick” and so, naturally, we should choose P2 and its motif as the best motif out of all possible k-dimensional motifs." }, { "code": null, "e": 18426, "s": 18265, "text": "To really drive home this point, let’s add a few more random walk decoys to our toy data set and compare the smallest k-dimensional matrix profile values again:" }, { "code": null, "e": 18840, "s": 18426, "text": "for i in range(4, 11): df[f'T{i}'] = np.random.uniform(0.1, -0.1, size=df.shape[0]).cumsum()fig, axs = plt.subplots(df.shape[1], sharex=True, gridspec_kw={'hspace': 0})plt.suptitle('Can You Still Spot The Multi-dimensional Motif?', fontsize='30')for i in range(df.shape[1]): axs[i].set_ylabel(f'T{i + 1}', fontsize='20') axs[i].set_xlabel('Time', fontsize ='20') axs[i].plot(df[f'T{i + 1}'])plt.show()" }, { "code": null, "e": 19184, "s": 18840, "text": "mps, indices = stumpy.mstump(df, m)motifs_idx = np.argsort(mps, axis=1)[:, :2]plt.plot(mps[range(mps.shape[0]), motifs_idx[:, 0]], c='red', linewidth='4')plt.xlabel('k (zero-based)', fontsize='20')plt.ylabel('Matrix Profile Value', fontsize='20')plt.xticks(range(mps.shape[0]))plt.plot(1, 1.3, marker=\"v\", markersize=10, color='red')plt.show()" }, { "code": null, "e": 19518, "s": 19184, "text": "Again, the “point of maximum curvature” occurs right after k=1 (red arrowhead) and so we should continue to choose P2 and its motif as the best motif out of all possible k-dimensional motifs. While this might seem like a rather manual task, we recommend automating this turning point selection process using the kneed Python package." }, { "code": null, "e": 19942, "s": 19518, "text": "The astute reader may have also recognized that the k-dimensional matrix profile really only reveals the location of a motif in time but it fails to disclose which k out of the d time series dimensions contains the desired motif pair. To recover this information, we must compute something called the “k-dimensional matrix profile subspace”. Luckily, the STUMPY convenience function, stumpy.subspace, can help us with this!" }, { "code": null, "e": 19985, "s": 19942, "text": "To use stumpy.subspace, we simply pass in:" }, { "code": null, "e": 20283, "s": 19985, "text": "the multi-dimensional time series, df, used to compute the multi-dimensional matrix profilethe window size, m, used to compute the multi-dimensional matrix profilethe indices for the kth-dimensional motif pair, motifs_idx[k][0] and indices[k][motifs_idx[k][0]]the desired (zero-based) dimension, k" }, { "code": null, "e": 20375, "s": 20283, "text": "the multi-dimensional time series, df, used to compute the multi-dimensional matrix profile" }, { "code": null, "e": 20448, "s": 20375, "text": "the window size, m, used to compute the multi-dimensional matrix profile" }, { "code": null, "e": 20546, "s": 20448, "text": "the indices for the kth-dimensional motif pair, motifs_idx[k][0] and indices[k][motifs_idx[k][0]]" }, { "code": null, "e": 20584, "s": 20546, "text": "the desired (zero-based) dimension, k" }, { "code": null, "e": 20848, "s": 20584, "text": "k = 1S = stumpy.subspace(df, m, motifs_idx[k][0], indices[k][motifs_idx[k][0]], k)print(f\"For k = {k}, the {k + 1}-dimensional subspace includes subsequences from {df.columns[S].values}\")For k = 1, the 2-dimensional subspace includes subsequences from ['T2' 'T1']" }, { "code": null, "e": 21103, "s": 20848, "text": "So, after computing the multi-dimensional matrix profile using mstump and selecting the second dimension (i.e., k=1), according to the k-dimensional subspace, the motif should be extracted from T2 and T1 out of all of the possible time series dimensions." }, { "code": null, "e": 21408, "s": 21103, "text": "Dependent upon the total number of dimensions and the length of your time series dat, it may be computationally expensive to produce the multi-dimensional matrix profile. Thus, you can overcome this by trying mstumped, a distributed and parallel implementation of mstump that depends on Dask distributed:" }, { "code": null, "e": 21566, "s": 21408, "text": "import stumpyfrom dask.distributed import Clientdask_client = Client()mps, indices = stumpy.mstumped(dask_client, df, m) # Note that a dask client is needed" }, { "code": null, "e": 21838, "s": 21566, "text": "There may be situations where you want to find the best motif on k dimensions but you want to explicitly “include” or “exclude” a given subset of dimensions. In the trivial exclusion case, one just needs to omit the undesired time series dimensions before calling mstump:" }, { "code": null, "e": 21941, "s": 21838, "text": "mps, indices = stumpy.mstump(df[df.columns.difference(['T3'])], m) # This excludes the `T3` dimension" }, { "code": null, "e": 22201, "s": 21941, "text": "However, in the case of inclusion, the user may have specific time series dimensions that they’d always want to be included or prioritized in the multi-dimensional matrix profile output and so you can provide a list of (zero-based) dimensions as an parameter:" }, { "code": null, "e": 22253, "s": 22201, "text": "mps, indices = stumpy.mstump(df, m, include=[0, 1])" }, { "code": null, "e": 22470, "s": 22253, "text": "So, in this example where we’ve instructed mstump to include=[0, 1] (i.e., T1 and T2), when k≥1, the kth dimensional matrix profile subspace will always include T1 and T2. Similarly, k<1 will include either T1 or T2." }, { "code": null, "e": 22617, "s": 22470, "text": "Finally, instead of searching for motifs, it is also possible to have mstump search for discords by simply passing in the discords=True parameter:" }, { "code": null, "e": 22668, "s": 22617, "text": "mps, indices = stumpy.mstump(df, m, discords=True)" }, { "code": null, "e": 22983, "s": 22668, "text": "Instead of returning the smallest average distance, this returns the largest average distance across k dimensions. This ability to return discords is unique to STUMPY and was not published in the original paper. Also note that it is possible to include specific dimensions and search for discords at the same time:" }, { "code": null, "e": 23050, "s": 22983, "text": "mps, indices = stumpy.mstump(df, m, include=[0, 1], discords=True)" }, { "code": null, "e": 23217, "s": 23050, "text": "In this case, the dimensions listed in include are honored first and then all subsequent dimensions are sorted by their largest average distance across kk dimensions." }, { "code": null, "e": 23372, "s": 23217, "text": "And that’s it! You’ve just learned the basics of how to analyze multi-dimensional time series data using stumpy.mstump (or stumpy.mstumped). Happy coding!" }, { "code": null, "e": 23390, "s": 23372, "text": "Matrix Profile VI" }, { "code": null, "e": 23411, "s": 23390, "text": "STUMPY Documentation" } ]
Using Lambda Function with Amazon DynamoDB
DynamoDB can trigger AWS Lambda when the data in added to the tables, updated or deleted. In this chapter, we will work on a simple example that will add items to the DynamoDB table and AWS Lambda which will read the data and send mail with the data added. To use Amazon DB and AWS Lambda, we need to follow the steps as shown below − Create a table in DynamoDB with primary key Create a table in DynamoDB with primary key Create a role which will have permission to work with DynamoDBand AWS Lambda. Create a role which will have permission to work with DynamoDBand AWS Lambda. Create function in AWS Lambda Create function in AWS Lambda AWS Lambda Trigger to send mail AWS Lambda Trigger to send mail Add data in DynamoDB Add data in DynamoDB Let us discuss each of this step in detail. We are going to work out on following example which shows the basic interaction between DynamoDB and AWS Lambda. This example will help you to understand the following operations − Creating a table called customer in Dynamodb table and how to enter data in that table. Creating a table called customer in Dynamodb table and how to enter data in that table. Triggering AWS Lambda function once the data is entered and sending mail using Amazon SES service. Triggering AWS Lambda function once the data is entered and sending mail using Amazon SES service. The basic block diagram that explains the flow of the example is as shown below − Log in to AWS console. Go to AWS Services and select DynamoDB as shown below. Select DynamoDB. DynamoDB shows the options as shown below − Now, click Create table to create the table as shown. We have named the table as customer with primary key for that table as cust_id. Click on Create button to add the table to dynamodb. The table created is as shown below − We can add items to the table created as follows − Click Items and click Create item button as shown − To create role, Go to AWS services and click IAM. Let us create a policy to be used only for the DynamoDB table created earlier − Now, choose a Service. Observe that the service we have selected is DynamoDB. For Actions we have taken all Dynamodb actions ie access to list, read and write. For resources, we will select the table resource type actions. When you click it, you can see a screen as follows − Now, select table and Add ARN to it as shown. We will get ARN details from customer table created as shown below − Enter arn details here − Click Add button to save the changes. Once done Click on Review policy. Enter the name of the policy, description etc as shown below − Click on create policy to save it. Add the policy to the role to be created. Select Role from left side and enter the details. Observe that the policies added are newpolicyfordynamdb, awslambdafullaccess, cloudwatchfullaccess and amazonsesfullaccess. Add the role and will use it while creating AWS Lambda function. Thus, we have created Lambda function called newlambdafordynamodb as shown. Now, let us add DynamodDB trigger to the AWS Lambda created. The runtime we shall use is Node.js. You can find the following details in Dynamodb trigger that are to be configured for AWS Lambda − Now, simply click Add to add the trigger to AWS Lambda. AWS Lambda will get triggered when data is inserted intoAWS Lambda. The event parameter will have the dynamodb data inserted. This will read the data from the event and send email. To send email, you need to follow the steps given below − Go to AWS service and select SES (simple email service). Validate the email to which we need to send an email as shown − Click the button Verify a New Email Address to add the email address. Enter an email address to verify it. The email address will receive and activation mail from Amazon which needs to be clicked. Once the activation is done, the email id is verified and can be used with AWS services. The AWS Lambda code which reads data from the event and sends email is given below − var aws = require('aws-sdk'); var ses = new aws.SES({ region: 'us-east-1' }); exports.handler = function(event, context, callback) { console.log(event); let tabledetails = JSON.parse(JSON.stringify(event.Records[0].dynamodb)); console.log(tabledetails.NewImage.address.S); let customerid = tabledetails.NewImage.cust_id.S; let name = tabledetails.NewImage.name.S; let address = tabledetails.NewImage.address.S; var eParams = { Destination: { ToAddresses: ["[email protected]"] }, Message: { Body: { Text: { Data: "The data added is as follows:\n CustomerId:"+customerid+"\n Name:"+name+"\nAddress:"+address } }, Subject: { Data: "Data Inserted in Dynamodb table customer" } }, Source: "[email protected]" }; console.log('===SENDING EMAIL==='); var email = ses.sendEmail(eParams, function(err, data) { if (err) console.log(err); else { console.log("===EMAIL SENT==="); console.log("EMAIL CODE END"); console.log('EMAIL: ', email); context.succeed(event); callback(null, "email is send"); } }); } Now, save the Lambda function and data in DynamoDB table. Use the following sequence to add data in DynamoDB. Go to the table customer created in Dynamodb. Click Create item. Click Save button and check the email id provided in AWS Lambda to see if the mail has been sent by AWS Lambda. 35 Lectures 7.5 hours Mr. Pradeep Kshetrapal 30 Lectures 3.5 hours Priyanka Choudhary 44 Lectures 7.5 hours Eduonix Learning Solutions 51 Lectures 6 hours Manuj Aggarwal 41 Lectures 5 hours AR Shankar 14 Lectures 1 hours Zach Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2663, "s": 2406, "text": "DynamoDB can trigger AWS Lambda when the data in added to the tables, updated or deleted. In this chapter, we will work on a simple example that will add items to the DynamoDB table and AWS Lambda which will read the data and send mail with the data added." }, { "code": null, "e": 2741, "s": 2663, "text": "To use Amazon DB and AWS Lambda, we need to follow the steps as shown below −" }, { "code": null, "e": 2785, "s": 2741, "text": "Create a table in DynamoDB with primary key" }, { "code": null, "e": 2829, "s": 2785, "text": "Create a table in DynamoDB with primary key" }, { "code": null, "e": 2907, "s": 2829, "text": "Create a role which will have permission to work with DynamoDBand AWS Lambda." }, { "code": null, "e": 2985, "s": 2907, "text": "Create a role which will have permission to work with DynamoDBand AWS Lambda." }, { "code": null, "e": 3015, "s": 2985, "text": "Create function in AWS Lambda" }, { "code": null, "e": 3045, "s": 3015, "text": "Create function in AWS Lambda" }, { "code": null, "e": 3077, "s": 3045, "text": "AWS Lambda Trigger to send mail" }, { "code": null, "e": 3109, "s": 3077, "text": "AWS Lambda Trigger to send mail" }, { "code": null, "e": 3130, "s": 3109, "text": "Add data in DynamoDB" }, { "code": null, "e": 3151, "s": 3130, "text": "Add data in DynamoDB" }, { "code": null, "e": 3195, "s": 3151, "text": "Let us discuss each of this step in detail." }, { "code": null, "e": 3376, "s": 3195, "text": "We are going to work out on following example which shows the basic interaction between DynamoDB and AWS Lambda. This example will help you to understand the following operations −" }, { "code": null, "e": 3464, "s": 3376, "text": "Creating a table called customer in Dynamodb table and how to enter data in that table." }, { "code": null, "e": 3552, "s": 3464, "text": "Creating a table called customer in Dynamodb table and how to enter data in that table." }, { "code": null, "e": 3651, "s": 3552, "text": "Triggering AWS Lambda function once the data is entered and sending mail using Amazon SES service." }, { "code": null, "e": 3750, "s": 3651, "text": "Triggering AWS Lambda function once the data is entered and sending mail using Amazon SES service." }, { "code": null, "e": 3832, "s": 3750, "text": "The basic block diagram that explains the flow of the example is as shown below −" }, { "code": null, "e": 3927, "s": 3832, "text": "Log in to AWS console. Go to AWS Services and select DynamoDB as shown below. Select DynamoDB." }, { "code": null, "e": 3971, "s": 3927, "text": "DynamoDB shows the options as shown below −" }, { "code": null, "e": 4158, "s": 3971, "text": "Now, click Create table to create the table as shown. We have named the table as customer with primary key for that table as cust_id. Click on Create button to add the table to dynamodb." }, { "code": null, "e": 4196, "s": 4158, "text": "The table created is as shown below −" }, { "code": null, "e": 4247, "s": 4196, "text": "We can add items to the table created as follows −" }, { "code": null, "e": 4299, "s": 4247, "text": "Click Items and click Create item button as shown −" }, { "code": null, "e": 4349, "s": 4299, "text": "To create role, Go to AWS services and click IAM." }, { "code": null, "e": 4429, "s": 4349, "text": "Let us create a policy to be used only for the DynamoDB table created earlier −" }, { "code": null, "e": 4705, "s": 4429, "text": "Now, choose a Service. Observe that the service we have selected is DynamoDB. For Actions we have taken all Dynamodb actions ie access to list, read and write. For resources, we will select the table resource type actions. When you click it, you can see a screen as follows −" }, { "code": null, "e": 4820, "s": 4705, "text": "Now, select table and Add ARN to it as shown. We will get ARN details from customer table created as shown below −" }, { "code": null, "e": 4845, "s": 4820, "text": "Enter arn details here −" }, { "code": null, "e": 4980, "s": 4845, "text": "Click Add button to save the changes. Once done Click on Review policy. Enter the name of the policy, description etc as shown below −" }, { "code": null, "e": 5107, "s": 4980, "text": "Click on create policy to save it. Add the policy to the role to be created. Select Role from left side and enter the details." }, { "code": null, "e": 5296, "s": 5107, "text": "Observe that the policies added are newpolicyfordynamdb, awslambdafullaccess, cloudwatchfullaccess and amazonsesfullaccess. Add the role and will use it while creating AWS Lambda function." }, { "code": null, "e": 5372, "s": 5296, "text": "Thus, we have created Lambda function called newlambdafordynamodb as shown." }, { "code": null, "e": 5470, "s": 5372, "text": "Now, let us add DynamodDB trigger to the AWS Lambda created. The runtime we shall use is Node.js." }, { "code": null, "e": 5568, "s": 5470, "text": "You can find the following details in Dynamodb trigger that are to be configured for AWS Lambda −" }, { "code": null, "e": 5624, "s": 5568, "text": "Now, simply click Add to add the trigger to AWS Lambda." }, { "code": null, "e": 5805, "s": 5624, "text": "AWS Lambda will get triggered when data is inserted intoAWS Lambda. The event parameter will have the dynamodb data inserted. This will read the data from the event and send email." }, { "code": null, "e": 5863, "s": 5805, "text": "To send email, you need to follow the steps given below −" }, { "code": null, "e": 5984, "s": 5863, "text": "Go to AWS service and select SES (simple email service). Validate the email to which we need to send an email as shown −" }, { "code": null, "e": 6054, "s": 5984, "text": "Click the button Verify a New Email Address to add the email address." }, { "code": null, "e": 6270, "s": 6054, "text": "Enter an email address to verify it. The email address will receive and activation mail from Amazon which needs to be clicked. Once the activation is done, the email id is verified and can be used with AWS services." }, { "code": null, "e": 6355, "s": 6270, "text": "The AWS Lambda code which reads data from the event and sends email is given below −" }, { "code": null, "e": 7573, "s": 6355, "text": "var aws = require('aws-sdk');\nvar ses = new aws.SES({\n region: 'us-east-1'\n});\nexports.handler = function(event, context, callback) {\n console.log(event);\n let tabledetails = JSON.parse(JSON.stringify(event.Records[0].dynamodb));\n console.log(tabledetails.NewImage.address.S);\n let customerid = tabledetails.NewImage.cust_id.S;\n let name = tabledetails.NewImage.name.S;\n let address = tabledetails.NewImage.address.S;\n\t\n var eParams = {\n Destination: {\n ToAddresses: [\"[email protected]\"]\n },\n Message: {\n Body: {\n Text: {\n Data: \"The data added is as follows:\\n CustomerId:\"+customerid+\"\\n Name:\"+name+\"\\nAddress:\"+address\n }\n },\n Subject: {\n Data: \"Data Inserted in Dynamodb table customer\"\n }\n },\n Source: \"[email protected]\"\n };\n console.log('===SENDING EMAIL===');\n var email = ses.sendEmail(eParams, function(err, data) {\n if (err) console.log(err);\n else {\n console.log(\"===EMAIL SENT===\");\n console.log(\"EMAIL CODE END\");\n console.log('EMAIL: ', email);\n context.succeed(event);\n callback(null, \"email is send\");\n }\n });\n}" }, { "code": null, "e": 7631, "s": 7573, "text": "Now, save the Lambda function and data in DynamoDB table." }, { "code": null, "e": 7683, "s": 7631, "text": "Use the following sequence to add data in DynamoDB." }, { "code": null, "e": 7729, "s": 7683, "text": "Go to the table customer created in Dynamodb." }, { "code": null, "e": 7748, "s": 7729, "text": "Click Create item." }, { "code": null, "e": 7860, "s": 7748, "text": "Click Save button and check the email id provided in AWS Lambda to see if the mail has been sent by AWS Lambda." }, { "code": null, "e": 7895, "s": 7860, "text": "\n 35 Lectures \n 7.5 hours \n" }, { "code": null, "e": 7919, "s": 7895, "text": " Mr. Pradeep Kshetrapal" }, { "code": null, "e": 7954, "s": 7919, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7974, "s": 7954, "text": " Priyanka Choudhary" }, { "code": null, "e": 8009, "s": 7974, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8037, "s": 8009, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8070, "s": 8037, "text": "\n 51 Lectures \n 6 hours \n" }, { "code": null, "e": 8086, "s": 8070, "text": " Manuj Aggarwal" }, { "code": null, "e": 8119, "s": 8086, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 8131, "s": 8119, "text": " AR Shankar" }, { "code": null, "e": 8164, "s": 8131, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8177, "s": 8164, "text": " Zach Miller" }, { "code": null, "e": 8184, "s": 8177, "text": " Print" }, { "code": null, "e": 8195, "s": 8184, "text": " Add Notes" } ]
Add two fractions | Practice | GeeksforGeeks
You are given four numbers num1, den1, num2, and den2. You need to find (num1/den1)+(num2/den2) and output the result in the form of (numx/denx). Input Format: The first line of input contains an integer T denoting the number of test cases . Then T test cases follow . Each test case contains four integers num1, den1, num2, den2 respectively . Output Format: For each test case, in a new line, output will be the fraction in the form a/b where the fraction denotes the sum of the two given fractions in reduced form. Your Task: Since this is a function problem, you don't need to worry about the testcases. Your task is to complete the function addFraction which adds the two fractions and prints the resulting fraction. The function takes four arguments num1, den1, num2, den2 where num1, num2 denotes the numerators of two fractions and den1, den2 denotes their denominators. Constraints: 1 <= T <= 100 1 <= den1,den2,num1,num2 <= 1000 Example: Input 1 1 500 2 500 Output 3/500 Explanation: In above test case 1/500+2/500=3/500 Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. 0 daxeshparmar02053 days ago Without using GCD int res1 = (num1 * den2) + (num2 * den1); int res2 = den1 * den2; int divider = 2; int minOf2 = Math.min(res1,res2); while (divider <= minOf2) { if (res1 % divider == 0 && res2 % divider == 0){ res1 = res1 / divider; res2 = res2 / divider; } else { divider++; } } System.out.println(res1 + "/" + res2); 0 pranjalverma83492 weeks ago // { Driver Code Starts#include<bits/stdc++.h>using namespace std; void addFraction(int num1, int den1, int num2, int den2); int main(){ int T; cin>>T; while(T--) { int a,b,c,d,resultNum,resultDen; cin>>a>>b>>c>>d; addFraction(a,b,c,d); }}// } Driver Code Ends long long gcd(long A,long B) { if(B==0) { return A; } return(gcd(B,A%B)); }void addFraction(int num1, int den1, int num2,int den2){ int l,g; l=(den1*den2)/gcd(den1,den2); num1=num1*(l/den1)+num2*(l/den2); g=gcd(l,num1); cout<<num1/g<<"/"<<l/g<<endl; } +1 ayushshukla34663 months ago void addFraction(int num1, int den1, int num2,int den2){//Your code here long long den = (den1*den2)/__gcd(den1,den2); long long n1 = den / den1; long long n2 = den / den2; long long num = (n1*num1)+(n2*num2); long long n = __gcd(num,den); num = num / n; den = den / n; cout << num << "/" << den << endl; } 0 ramyan18143 months ago int gcd(int a,int b){ if(b==0) return a; return gcd(b,a%b);} void addFraction(int num1, int den1, int num2,int den2){ int lcm=(den1*den2)/gcd(den1,den2); int num=(lcm/den1)*num1+(lcm/den2)*num2; int g=gcd(v,lcm); v=v/g; lcm=lcm/g; cout<<v<<"/"<<lcm<<"\n"; } 0 GURRAM VAMSI7 months ago GURRAM VAMSI def gcd(a,b): if b==0: return a return gcd(b,a%b)def addFraction(n1, d1, n2, d2): #Code here num=(n1*d2+n2*d1) dem=d1*d2 cf=gcd(num,dem) print(num//cf,end='/') print(dem//cf) +1 Ritesh Keshri9 months ago Ritesh Keshri //EASIEST APPROACHint gcd(int a,int b){ if(a==0) return b; return gcd(b%a,a);} int lcm(int a,int b){ int n=gcd(a,b); return (n*(a/n)*(b/n));}void addFraction(int num1, int den1, int num2,int den2){ int n=lcm(den1,den2); int sum=(n/den1)*num1 + (n/den2)*num2; int m=gcd(n,sum); n=n/m; sum=sum/m; cout<<sum<<" "<<n;="" }=""> 0 sankirtana gv9 months ago sankirtana gv void addFraction(int num1, int den1, int num2,int den2){ int lcm = (den1*den2)/__gcd(den1,den2); int v = (lcm/den1)*num1 + (lcm/den2)*num2; int g = __gcd(v,lcm); v = v/g; lcm = lcm/g; cout<<v<<" "<<lcm<<"\n";="" }=""> 0 Rajesh Kumar9 months ago Rajesh Kumar long long int gcd(long long int den1,long long int den2){ if(den1==0) return den2; return gcd(den2%den1,den1);} long long int lcmoftwo(long long int den1,long long int den2){ long long int hcf=gcd(den1,den2); return (den1*den2)/hcf;}//You are required to complete this function/void addFraction(int num1, int den1, int num2,int den2){ long long int sum=0; if(num1==0) cout<<num2<<" "<<den2<<endl;="" if(num2="=0)" cout<<num1<<"="" "<<den1<<endl;="" if(den1="=den2)" {;="" cout<<num1+num2<<"="" "<<den1<<endl;="" }="" else="" {="" long="" long="" int="" lcm="lcmoftwo(den1,den2);" long="" long="" int="" rem1="lcm/den1;" long="" long="" int="" rem2="lcm/den2;" sum="(num1*rem1+num2*rem2);" cout<<sum<<"="" "<<lcm<<endl;="" }="" }how="" can="" i="" do="" fraction="" in="" simple=""> 0 Sawi Sharma1 year ago Sawi Sharma Python3 solusann: def addFraction(num1, den1, num2, den2): #Code here import math nums=num1*den2+num2*den1 dens=den1*den2 gcd=math.gcd(nums,dens) print(str(int(nums/gcd))+"/"+str(int(dens/gcd))) 0 Mahesh Mehetre1 year ago Mahesh Mehetre Execution Time:0.01https://uploads.disquscdn.c... We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 385, "s": 238, "text": "You are given four numbers num1, den1, num2, and den2. You need to find (num1/den1)+(num2/den2) and output the result in the form of (numx/denx). " }, { "code": null, "e": 584, "s": 385, "text": "Input Format:\nThe first line of input contains an integer T denoting the number of test cases . Then T test cases follow . Each test case contains four integers num1, den1, num2, den2 respectively ." }, { "code": null, "e": 758, "s": 584, "text": "Output Format:\nFor each test case, in a new line, output will be the fraction in the form a/b where the fraction denotes the sum of the two given fractions in reduced form." }, { "code": null, "e": 1120, "s": 758, "text": "Your Task:\nSince this is a function problem, you don't need to worry about the testcases. Your task is to complete the function addFraction which adds the two fractions and prints the resulting fraction. The function takes four arguments num1, den1, num2, den2 where num1, num2 denotes the numerators of two fractions and den1, den2 denotes their denominators." }, { "code": null, "e": 1180, "s": 1120, "text": "Constraints:\n1 <= T <= 100\n1 <= den1,den2,num1,num2 <= 1000" }, { "code": null, "e": 1222, "s": 1180, "text": "Example:\nInput\n1\n1 500 2 500\nOutput\n3/500" }, { "code": null, "e": 1272, "s": 1222, "text": "Explanation:\nIn above test case 1/500+2/500=3/500" }, { "code": null, "e": 1583, "s": 1274, "text": "Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code." }, { "code": null, "e": 1585, "s": 1583, "text": "0" }, { "code": null, "e": 1612, "s": 1585, "text": "daxeshparmar02053 days ago" }, { "code": null, "e": 1631, "s": 1612, "text": "Without using GCD " }, { "code": null, "e": 2043, "s": 1631, "text": " int res1 = (num1 * den2) + (num2 * den1); int res2 = den1 * den2; int divider = 2; int minOf2 = Math.min(res1,res2); while (divider <= minOf2) { if (res1 % divider == 0 && res2 % divider == 0){ res1 = res1 / divider; res2 = res2 / divider; } else { divider++; } } System.out.println(res1 + \"/\" + res2);" }, { "code": null, "e": 2047, "s": 2045, "text": "0" }, { "code": null, "e": 2075, "s": 2047, "text": "pranjalverma83492 weeks ago" }, { "code": null, "e": 2142, "s": 2075, "text": "// { Driver Code Starts#include<bits/stdc++.h>using namespace std;" }, { "code": null, "e": 2215, "s": 2142, "text": "void addFraction(int num1, int den1, int num2, int den2);" }, { "code": null, "e": 2353, "s": 2215, "text": "int main(){ int T; cin>>T; while(T--) { int a,b,c,d,resultNum,resultDen; cin>>a>>b>>c>>d; addFraction(a,b,c,d);" }, { "code": null, "e": 2380, "s": 2353, "text": " }}// } Driver Code Ends" }, { "code": null, "e": 2781, "s": 2380, "text": "long long gcd(long A,long B) { if(B==0) { return A; } return(gcd(B,A%B)); }void addFraction(int num1, int den1, int num2,int den2){ int l,g; l=(den1*den2)/gcd(den1,den2); num1=num1*(l/den1)+num2*(l/den2); g=gcd(l,num1); cout<<num1/g<<\"/\"<<l/g<<endl; }" }, { "code": null, "e": 2784, "s": 2781, "text": "+1" }, { "code": null, "e": 2812, "s": 2784, "text": "ayushshukla34663 months ago" }, { "code": null, "e": 3149, "s": 2812, "text": "void addFraction(int num1, int den1, int num2,int den2){//Your code here long long den = (den1*den2)/__gcd(den1,den2); long long n1 = den / den1; long long n2 = den / den2; long long num = (n1*num1)+(n2*num2); long long n = __gcd(num,den); num = num / n; den = den / n; cout << num << \"/\" << den << endl; }" }, { "code": null, "e": 3151, "s": 3149, "text": "0" }, { "code": null, "e": 3174, "s": 3151, "text": "ramyan18143 months ago" }, { "code": null, "e": 3245, "s": 3174, "text": "int gcd(int a,int b){ if(b==0) return a; return gcd(b,a%b);}" }, { "code": null, "e": 3504, "s": 3245, "text": "void addFraction(int num1, int den1, int num2,int den2){ int lcm=(den1*den2)/gcd(den1,den2); int num=(lcm/den1)*num1+(lcm/den2)*num2; int g=gcd(v,lcm); v=v/g; lcm=lcm/g; cout<<v<<\"/\"<<lcm<<\"\\n\"; }" }, { "code": null, "e": 3506, "s": 3504, "text": "0" }, { "code": null, "e": 3531, "s": 3506, "text": "GURRAM VAMSI7 months ago" }, { "code": null, "e": 3544, "s": 3531, "text": "GURRAM VAMSI" }, { "code": null, "e": 3750, "s": 3544, "text": "def gcd(a,b): if b==0: return a return gcd(b,a%b)def addFraction(n1, d1, n2, d2): #Code here num=(n1*d2+n2*d1) dem=d1*d2 cf=gcd(num,dem) print(num//cf,end='/') print(dem//cf)" }, { "code": null, "e": 3753, "s": 3750, "text": "+1" }, { "code": null, "e": 3779, "s": 3753, "text": "Ritesh Keshri9 months ago" }, { "code": null, "e": 3793, "s": 3779, "text": "Ritesh Keshri" }, { "code": null, "e": 3858, "s": 3793, "text": "//EASIEST APPROACHint gcd(int a,int b){ if(a==0) return b;" }, { "code": null, "e": 3882, "s": 3858, "text": " return gcd(b%a,a);}" }, { "code": null, "e": 3923, "s": 3882, "text": "int lcm(int a,int b){ int n=gcd(a,b);" }, { "code": null, "e": 4073, "s": 3923, "text": " return (n*(a/n)*(b/n));}void addFraction(int num1, int den1, int num2,int den2){ int n=lcm(den1,den2); int sum=(n/den1)*num1 + (n/den2)*num2;" }, { "code": null, "e": 4145, "s": 4073, "text": " int m=gcd(n,sum); n=n/m; sum=sum/m; cout<<sum<<\" \"<<n;=\"\" }=\"\">" }, { "code": null, "e": 4147, "s": 4145, "text": "0" }, { "code": null, "e": 4173, "s": 4147, "text": "sankirtana gv9 months ago" }, { "code": null, "e": 4187, "s": 4173, "text": "sankirtana gv" }, { "code": null, "e": 4423, "s": 4187, "text": "void addFraction(int num1, int den1, int num2,int den2){ int lcm = (den1*den2)/__gcd(den1,den2); int v = (lcm/den1)*num1 + (lcm/den2)*num2; int g = __gcd(v,lcm); v = v/g; lcm = lcm/g; cout<<v<<\" \"<<lcm<<\"\\n\";=\"\" }=\"\">" }, { "code": null, "e": 4425, "s": 4423, "text": "0" }, { "code": null, "e": 4450, "s": 4425, "text": "Rajesh Kumar9 months ago" }, { "code": null, "e": 4463, "s": 4450, "text": "Rajesh Kumar" }, { "code": null, "e": 4588, "s": 4463, "text": "long long int gcd(long long int den1,long long int den2){ if(den1==0) return den2; return gcd(den2%den1,den1);}" }, { "code": null, "e": 5277, "s": 4588, "text": "long long int lcmoftwo(long long int den1,long long int den2){ long long int hcf=gcd(den1,den2); return (den1*den2)/hcf;}//You are required to complete this function/void addFraction(int num1, int den1, int num2,int den2){ long long int sum=0; if(num1==0) cout<<num2<<\" \"<<den2<<endl;=\"\" if(num2=\"=0)\" cout<<num1<<\"=\"\" \"<<den1<<endl;=\"\" if(den1=\"=den2)\" {;=\"\" cout<<num1+num2<<\"=\"\" \"<<den1<<endl;=\"\" }=\"\" else=\"\" {=\"\" long=\"\" long=\"\" int=\"\" lcm=\"lcmoftwo(den1,den2);\" long=\"\" long=\"\" int=\"\" rem1=\"lcm/den1;\" long=\"\" long=\"\" int=\"\" rem2=\"lcm/den2;\" sum=\"(num1*rem1+num2*rem2);\" cout<<sum<<\"=\"\" \"<<lcm<<endl;=\"\" }=\"\" }how=\"\" can=\"\" i=\"\" do=\"\" fraction=\"\" in=\"\" simple=\"\">" }, { "code": null, "e": 5279, "s": 5277, "text": "0" }, { "code": null, "e": 5301, "s": 5279, "text": "Sawi Sharma1 year ago" }, { "code": null, "e": 5313, "s": 5301, "text": "Sawi Sharma" }, { "code": null, "e": 5331, "s": 5313, "text": "Python3 solusann:" }, { "code": null, "e": 5526, "s": 5331, "text": "def addFraction(num1, den1, num2, den2): #Code here import math nums=num1*den2+num2*den1 dens=den1*den2 gcd=math.gcd(nums,dens) print(str(int(nums/gcd))+\"/\"+str(int(dens/gcd)))" }, { "code": null, "e": 5528, "s": 5526, "text": "0" }, { "code": null, "e": 5553, "s": 5528, "text": "Mahesh Mehetre1 year ago" }, { "code": null, "e": 5568, "s": 5553, "text": "Mahesh Mehetre" }, { "code": null, "e": 5618, "s": 5568, "text": "Execution Time:0.01https://uploads.disquscdn.c..." }, { "code": null, "e": 5764, "s": 5618, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5800, "s": 5764, "text": " Login to access your submissions. " }, { "code": null, "e": 5810, "s": 5800, "text": "\nProblem\n" }, { "code": null, "e": 5820, "s": 5810, "text": "\nContest\n" }, { "code": null, "e": 5883, "s": 5820, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6031, "s": 5883, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6239, "s": 6031, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6345, "s": 6239, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
numpy.random.geometric() in Python - GeeksforGeeks
15 Jul, 2020 With the help of numpy.random.geometric() method, we can get the random samples of geometric distribution and return the random samples of numpy array by using this method. geometric distribution Syntax : numpy.random.geometric(p, size=None) Return : Return the random samples of numpy array. Example #1 : In this example we can see that by using numpy.random.geometric() method, we are able to get the random samples of geometric distribution and return the random samples as numpy array by using this method. Python3 # import numpy and geometricimport numpy as npimport matplotlib.pyplot as plt # Using geometric() methodgfg = np.random.geometric(0.65, 1000) count, bins, ignored = plt.hist(gfg, 40, density = True)plt.show() Output : Example #2 : Python3 # import numpy and geometricimport numpy as npimport matplotlib.pyplot as plt # Using geometric() methodgfg = np.random.geometric(0.85, 1000) count, bins, ignored = plt.hist(gfg, 10, density = True)plt.show() Output : Python numpy-Random Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n15 Jul, 2020" }, { "code": null, "e": 24074, "s": 23901, "text": "With the help of numpy.random.geometric() method, we can get the random samples of geometric distribution and return the random samples of numpy array by using this method." }, { "code": null, "e": 24097, "s": 24074, "text": "geometric distribution" }, { "code": null, "e": 24143, "s": 24097, "text": "Syntax : numpy.random.geometric(p, size=None)" }, { "code": null, "e": 24194, "s": 24143, "text": "Return : Return the random samples of numpy array." }, { "code": null, "e": 24207, "s": 24194, "text": "Example #1 :" }, { "code": null, "e": 24412, "s": 24207, "text": "In this example we can see that by using numpy.random.geometric() method, we are able to get the random samples of geometric distribution and return the random samples as numpy array by using this method." }, { "code": null, "e": 24420, "s": 24412, "text": "Python3" }, { "code": "# import numpy and geometricimport numpy as npimport matplotlib.pyplot as plt # Using geometric() methodgfg = np.random.geometric(0.65, 1000) count, bins, ignored = plt.hist(gfg, 40, density = True)plt.show()", "e": 24631, "s": 24420, "text": null }, { "code": null, "e": 24640, "s": 24631, "text": "Output :" }, { "code": null, "e": 24653, "s": 24640, "text": "Example #2 :" }, { "code": null, "e": 24661, "s": 24653, "text": "Python3" }, { "code": "# import numpy and geometricimport numpy as npimport matplotlib.pyplot as plt # Using geometric() methodgfg = np.random.geometric(0.85, 1000) count, bins, ignored = plt.hist(gfg, 10, density = True)plt.show()", "e": 24872, "s": 24661, "text": null }, { "code": null, "e": 24881, "s": 24872, "text": "Output :" }, { "code": null, "e": 24901, "s": 24881, "text": "Python numpy-Random" }, { "code": null, "e": 24914, "s": 24901, "text": "Python-numpy" }, { "code": null, "e": 24921, "s": 24914, "text": "Python" }, { "code": null, "e": 25019, "s": 24921, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25028, "s": 25019, "text": "Comments" }, { "code": null, "e": 25041, "s": 25028, "text": "Old Comments" }, { "code": null, "e": 25073, "s": 25041, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25129, "s": 25073, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25171, "s": 25129, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25213, "s": 25171, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25249, "s": 25213, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 25271, "s": 25249, "text": "Defaultdict in Python" }, { "code": null, "e": 25310, "s": 25271, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25337, "s": 25310, "text": "Python Classes and Objects" }, { "code": null, "e": 25368, "s": 25337, "text": "Python | os.path.join() method" } ]
Hadoop Tutorial
02 Mar, 2021 Big Data is a collection of data that is growing exponentially, and it is huge in volume with a lot of complexity as it comes from various resources. This data may be structured data, unstructured or semi-structured. So to handle or manage it efficiently, Hadoop comes into the picture. Hadoop is a framework written in Java programming language that works over the collection of commodity hardware. Before Hadoop, we are using a single system for storing and processing data. Also, we are dependent on RDBMS which only stores the structured data. To solve the problem of such huge complex data, Hadoop provides the best solution. So let’s get started. Basics Installation and Environment Setup Components of Hadoop Cluster, Rack & Schedulers HDFS MapReduce MapReduce Programs Hadoop Streaming Hadoop File and Commands Misc What is Big Data? What is Unstructured Data? What is Semi-Structured Data? 5V’s of Big Data Hadoop – Solution to Big Data Evolution of Hadoop Different Versions of Hadoop RDBMS vs Hadoop Hadoop Architecture Hadoop 2.x vs Hadoop 3.x Hadoop – Ecosystem How to Install Hadoop in Linux? Installing and Setting Up Hadoop in Windows 10 Installing Single Node Cluster Hadoop on Windows Configuring Eclipse with Apache Hadoop Hadoop Distributed File System(HDFS) MapReduce YARN Hadoop Cluster Hadoop – Cluster, Properties and its Types Hadoop – Rack and Rack Awareness Hadoop – Schedulers and Types of Schedulers Hadoop – Different Modes of Operation Various Filesystems in Hadoop Why a Block in HDFS is so Large? Daemons and Their Features File Blocks and Replication Factor Data Read Operation Map Reduce in Hadoop MapReduce Architecture Mapper In MapReduce Reducer in Map-Reduce MapReduce Job Execution Hadoop MapReduce – Data Flow Job Initializations in MapReduce How does Job run on MapReduce? How MapReduce Completes a Task? Weather Data Analysis For Analyzing Hot And Cold Days Finding The Average Age of Male and Female Died in Titanic Disaster How to Execute Character Count Program in MapReduce Hadoop? What is Hadoop Streaming? Hadoop Streaming Using Python – Word Count Problem Hadoop – File Permission and ACL(Access Control List) Hadoop – copyFromLocal Command Hadoop – getmerge Command Hadoop Version 3.0 – What’s New? Top 7 Reasons to Learn Hadoop Top 10 Hadoop Analytics Tools For Big Data Top 5 Recommended Books To Learn Hadoop Features of Hadoop Which Makes It Popular Hadoop vs Spark vs Flink Hadoop Hadoop Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Mar, 2021" }, { "code": null, "e": 315, "s": 28, "text": "Big Data is a collection of data that is growing exponentially, and it is huge in volume with a lot of complexity as it comes from various resources. This data may be structured data, unstructured or semi-structured. So to handle or manage it efficiently, Hadoop comes into the picture." }, { "code": null, "e": 681, "s": 315, "text": "Hadoop is a framework written in Java programming language that works over the collection of commodity hardware. Before Hadoop, we are using a single system for storing and processing data. Also, we are dependent on RDBMS which only stores the structured data. To solve the problem of such huge complex data, Hadoop provides the best solution. So let’s get started." }, { "code": null, "e": 688, "s": 681, "text": "Basics" }, { "code": null, "e": 723, "s": 688, "text": "Installation and Environment Setup" }, { "code": null, "e": 744, "s": 723, "text": "Components of Hadoop" }, { "code": null, "e": 771, "s": 744, "text": "Cluster, Rack & Schedulers" }, { "code": null, "e": 776, "s": 771, "text": "HDFS" }, { "code": null, "e": 786, "s": 776, "text": "MapReduce" }, { "code": null, "e": 805, "s": 786, "text": "MapReduce Programs" }, { "code": null, "e": 822, "s": 805, "text": "Hadoop Streaming" }, { "code": null, "e": 847, "s": 822, "text": "Hadoop File and Commands" }, { "code": null, "e": 852, "s": 847, "text": "Misc" }, { "code": null, "e": 873, "s": 855, "text": "What is Big Data?" }, { "code": null, "e": 900, "s": 873, "text": "What is Unstructured Data?" }, { "code": null, "e": 930, "s": 900, "text": "What is Semi-Structured Data?" }, { "code": null, "e": 947, "s": 930, "text": "5V’s of Big Data" }, { "code": null, "e": 977, "s": 947, "text": "Hadoop – Solution to Big Data" }, { "code": null, "e": 997, "s": 977, "text": "Evolution of Hadoop" }, { "code": null, "e": 1026, "s": 997, "text": "Different Versions of Hadoop" }, { "code": null, "e": 1042, "s": 1026, "text": "RDBMS vs Hadoop" }, { "code": null, "e": 1062, "s": 1042, "text": "Hadoop Architecture" }, { "code": null, "e": 1087, "s": 1062, "text": "Hadoop 2.x vs Hadoop 3.x" }, { "code": null, "e": 1106, "s": 1087, "text": "Hadoop – Ecosystem" }, { "code": null, "e": 1138, "s": 1106, "text": "How to Install Hadoop in Linux?" }, { "code": null, "e": 1185, "s": 1138, "text": "Installing and Setting Up Hadoop in Windows 10" }, { "code": null, "e": 1234, "s": 1185, "text": "Installing Single Node Cluster Hadoop on Windows" }, { "code": null, "e": 1273, "s": 1234, "text": "Configuring Eclipse with Apache Hadoop" }, { "code": null, "e": 1310, "s": 1273, "text": "Hadoop Distributed File System(HDFS)" }, { "code": null, "e": 1320, "s": 1310, "text": "MapReduce" }, { "code": null, "e": 1325, "s": 1320, "text": "YARN" }, { "code": null, "e": 1340, "s": 1325, "text": "Hadoop Cluster" }, { "code": null, "e": 1383, "s": 1340, "text": "Hadoop – Cluster, Properties and its Types" }, { "code": null, "e": 1416, "s": 1383, "text": "Hadoop – Rack and Rack Awareness" }, { "code": null, "e": 1460, "s": 1416, "text": "Hadoop – Schedulers and Types of Schedulers" }, { "code": null, "e": 1498, "s": 1460, "text": "Hadoop – Different Modes of Operation" }, { "code": null, "e": 1528, "s": 1498, "text": "Various Filesystems in Hadoop" }, { "code": null, "e": 1561, "s": 1528, "text": "Why a Block in HDFS is so Large?" }, { "code": null, "e": 1588, "s": 1561, "text": "Daemons and Their Features" }, { "code": null, "e": 1623, "s": 1588, "text": "File Blocks and Replication Factor" }, { "code": null, "e": 1643, "s": 1623, "text": "Data Read Operation" }, { "code": null, "e": 1664, "s": 1643, "text": "Map Reduce in Hadoop" }, { "code": null, "e": 1687, "s": 1664, "text": "MapReduce Architecture" }, { "code": null, "e": 1707, "s": 1687, "text": "Mapper In MapReduce" }, { "code": null, "e": 1729, "s": 1707, "text": "Reducer in Map-Reduce" }, { "code": null, "e": 1753, "s": 1729, "text": "MapReduce Job Execution" }, { "code": null, "e": 1782, "s": 1753, "text": "Hadoop MapReduce – Data Flow" }, { "code": null, "e": 1815, "s": 1782, "text": "Job Initializations in MapReduce" }, { "code": null, "e": 1846, "s": 1815, "text": "How does Job run on MapReduce?" }, { "code": null, "e": 1878, "s": 1846, "text": "How MapReduce Completes a Task?" }, { "code": null, "e": 1932, "s": 1878, "text": "Weather Data Analysis For Analyzing Hot And Cold Days" }, { "code": null, "e": 2000, "s": 1932, "text": "Finding The Average Age of Male and Female Died in Titanic Disaster" }, { "code": null, "e": 2060, "s": 2000, "text": "How to Execute Character Count Program in MapReduce Hadoop?" }, { "code": null, "e": 2086, "s": 2060, "text": "What is Hadoop Streaming?" }, { "code": null, "e": 2137, "s": 2086, "text": "Hadoop Streaming Using Python – Word Count Problem" }, { "code": null, "e": 2191, "s": 2137, "text": "Hadoop – File Permission and ACL(Access Control List)" }, { "code": null, "e": 2222, "s": 2191, "text": "Hadoop – copyFromLocal Command" }, { "code": null, "e": 2248, "s": 2222, "text": "Hadoop – getmerge Command" }, { "code": null, "e": 2281, "s": 2248, "text": "Hadoop Version 3.0 – What’s New?" }, { "code": null, "e": 2311, "s": 2281, "text": "Top 7 Reasons to Learn Hadoop" }, { "code": null, "e": 2354, "s": 2311, "text": "Top 10 Hadoop Analytics Tools For Big Data" }, { "code": null, "e": 2394, "s": 2354, "text": "Top 5 Recommended Books To Learn Hadoop" }, { "code": null, "e": 2436, "s": 2394, "text": "Features of Hadoop Which Makes It Popular" }, { "code": null, "e": 2461, "s": 2436, "text": "Hadoop vs Spark vs Flink" }, { "code": null, "e": 2468, "s": 2461, "text": "Hadoop" }, { "code": null, "e": 2475, "s": 2468, "text": "Hadoop" } ]
Python – Insert after every Nth element in a list
10 Dec, 2020 Sometimes we need to perform a single insertion in python, this can be easily done with the help of the insert function. But sometimes, we require to insert in a repeated manner after every n numbers, for that there can be numerous shorthands that can be quite handy. Lets discuss certain ways in which this can be done. Method #1 : Using join() + enumerate()We can use the join function to join each of nth substring with the digit K and enumerate can do the task of performing the selective iteration of list. # Python3 code to demonstrate # inserting K after every Nth number# using join() + enumerate() # initializing listtest_list = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] # printing original listprint ("The original list is : " + str(test_list)) # initializing k k = 'x' # initializing NN = 3 # using join() + enumerate()# inserting K after every Nth number res = list(''.join(i + k * (N % 3 == 2) for N, i in enumerate(test_list))) # printing result print ("The lists after insertion : " + str(res)) The original list is : [‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’]The lists after insertion : [‘g’, ‘e’, ‘e’, ‘x’, ‘k’, ‘s’, ‘f’, ‘x’, ‘o’, ‘r’, ‘g’, ‘x’, ‘e’, ‘e’, ‘k’, ‘x’, ‘s’] Method #2 : Using itertools.chain()This method also has the ability to perform a similar task using an iterator and hence an improvement in the performance. This function performs a similar task but uses chain method to join the n substrings. # Python3 code to demonstrate # inserting K after every Nth number# using itertool.chain()from itertools import chain # initializing listtest_list = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] # printing original listprint ("The original list is : " + str(test_list)) # initializing k k = 'x' # initializing NN = 3 # using itertool.chain()# inserting K after every Nth number res = list(chain(*[test_list[i : i+N] + [k] if len(test_list[i : i+N]) == N else test_list[i : i+N] for i in range(0, len(test_list), N)])) # printing result print ("The lists after insertion : " + str(res)) The original list is : [‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’]The lists after insertion : [‘g’, ‘e’, ‘e’, ‘x’, ‘k’, ‘s’, ‘f’, ‘x’, ‘o’, ‘r’, ‘g’, ‘x’, ‘e’, ‘e’, ‘k’, ‘x’, ‘s’] Marketing Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Dec, 2020" }, { "code": null, "e": 349, "s": 28, "text": "Sometimes we need to perform a single insertion in python, this can be easily done with the help of the insert function. But sometimes, we require to insert in a repeated manner after every n numbers, for that there can be numerous shorthands that can be quite handy. Lets discuss certain ways in which this can be done." }, { "code": null, "e": 540, "s": 349, "text": "Method #1 : Using join() + enumerate()We can use the join function to join each of nth substring with the digit K and enumerate can do the task of performing the selective iteration of list." }, { "code": "# Python3 code to demonstrate # inserting K after every Nth number# using join() + enumerate() # initializing listtest_list = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] # printing original listprint (\"The original list is : \" + str(test_list)) # initializing k k = 'x' # initializing NN = 3 # using join() + enumerate()# inserting K after every Nth number res = list(''.join(i + k * (N % 3 == 2) for N, i in enumerate(test_list))) # printing result print (\"The lists after insertion : \" + str(res))", "e": 1107, "s": 540, "text": null }, { "code": null, "e": 1309, "s": 1107, "text": "The original list is : [‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’]The lists after insertion : [‘g’, ‘e’, ‘e’, ‘x’, ‘k’, ‘s’, ‘f’, ‘x’, ‘o’, ‘r’, ‘g’, ‘x’, ‘e’, ‘e’, ‘k’, ‘x’, ‘s’]" }, { "code": null, "e": 1553, "s": 1309, "text": " Method #2 : Using itertools.chain()This method also has the ability to perform a similar task using an iterator and hence an improvement in the performance. This function performs a similar task but uses chain method to join the n substrings." }, { "code": "# Python3 code to demonstrate # inserting K after every Nth number# using itertool.chain()from itertools import chain # initializing listtest_list = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] # printing original listprint (\"The original list is : \" + str(test_list)) # initializing k k = 'x' # initializing NN = 3 # using itertool.chain()# inserting K after every Nth number res = list(chain(*[test_list[i : i+N] + [k] if len(test_list[i : i+N]) == N else test_list[i : i+N] for i in range(0, len(test_list), N)])) # printing result print (\"The lists after insertion : \" + str(res))", "e": 2228, "s": 1553, "text": null }, { "code": null, "e": 2430, "s": 2228, "text": "The original list is : [‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’]The lists after insertion : [‘g’, ‘e’, ‘e’, ‘x’, ‘k’, ‘s’, ‘f’, ‘x’, ‘o’, ‘r’, ‘g’, ‘x’, ‘e’, ‘e’, ‘k’, ‘x’, ‘s’]" }, { "code": null, "e": 2440, "s": 2430, "text": "Marketing" }, { "code": null, "e": 2461, "s": 2440, "text": "Python list-programs" }, { "code": null, "e": 2473, "s": 2461, "text": "python-list" }, { "code": null, "e": 2480, "s": 2473, "text": "Python" }, { "code": null, "e": 2496, "s": 2480, "text": "Python Programs" }, { "code": null, "e": 2508, "s": 2496, "text": "python-list" } ]
iomanip setfill() function in C++ with Examples
11 Oct, 2019 The setfill() method of iomaip library in C++ is used to set the ios library fill character based on the character specified as the parameter to this method. Syntax: setfill(char c) Parameters: This method accepts c as a parameter which is the character argument corresponding to which the fill is to be set. Return Value: This method does not returns anything. It only acts as stream manipulators. Example 1: // C++ code to demonstrate// the working of setfill() function #include <iomanip>#include <ios>#include <iostream> using namespace std; int main(){ // Initializing the integer int num = 50; cout << "Before setting the fill char: \n" << setw(10); cout << num << endl; // Using setfill() cout << "Setting the fill char" << " setfill to *: \n" << setfill('*') << setw(10); cout << num << endl; return 0;} Before setting the fill char: 50 Setting the fill char setfill to *: ********50 Example 2: // C++ code to demonstrate// the working of setfill() function #include <iomanip>#include <ios>#include <iostream> using namespace std; int main(){ // Initializing the integer int num = 50; cout << "Before setting the fill char: \n" << setw(10); cout << num << endl; cout << "Setting the fill" << " char setfill to $: \n" << setfill('$') << setw(10); cout << num << endl; return 0;} Before setting the fill char: 50 Setting the fill char setfill to $: $$$$$$$$50 Reference: http://www.cplusplus.com/reference/iomanip/setfill/ CPP-Functions cpp-input-output cpp-manipulators C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Priority Queue in C++ Standard Template Library (STL) Sorting a vector in C++ Inheritance in C++ The C++ Standard Template Library (STL) C++ Classes and Objects Substring in C++
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2019" }, { "code": null, "e": 186, "s": 28, "text": "The setfill() method of iomaip library in C++ is used to set the ios library fill character based on the character specified as the parameter to this method." }, { "code": null, "e": 194, "s": 186, "text": "Syntax:" }, { "code": null, "e": 211, "s": 194, "text": "setfill(char c)\n" }, { "code": null, "e": 338, "s": 211, "text": "Parameters: This method accepts c as a parameter which is the character argument corresponding to which the fill is to be set." }, { "code": null, "e": 428, "s": 338, "text": "Return Value: This method does not returns anything. It only acts as stream manipulators." }, { "code": null, "e": 439, "s": 428, "text": "Example 1:" }, { "code": "// C++ code to demonstrate// the working of setfill() function #include <iomanip>#include <ios>#include <iostream> using namespace std; int main(){ // Initializing the integer int num = 50; cout << \"Before setting the fill char: \\n\" << setw(10); cout << num << endl; // Using setfill() cout << \"Setting the fill char\" << \" setfill to *: \\n\" << setfill('*') << setw(10); cout << num << endl; return 0;}", "e": 908, "s": 439, "text": null }, { "code": null, "e": 999, "s": 908, "text": "Before setting the fill char: \n 50\nSetting the fill char setfill to *: \n********50\n" }, { "code": null, "e": 1010, "s": 999, "text": "Example 2:" }, { "code": "// C++ code to demonstrate// the working of setfill() function #include <iomanip>#include <ios>#include <iostream> using namespace std; int main(){ // Initializing the integer int num = 50; cout << \"Before setting the fill char: \\n\" << setw(10); cout << num << endl; cout << \"Setting the fill\" << \" char setfill to $: \\n\" << setfill('$') << setw(10); cout << num << endl; return 0;}", "e": 1457, "s": 1010, "text": null }, { "code": null, "e": 1548, "s": 1457, "text": "Before setting the fill char: \n 50\nSetting the fill char setfill to $: \n$$$$$$$$50\n" }, { "code": null, "e": 1611, "s": 1548, "text": "Reference: http://www.cplusplus.com/reference/iomanip/setfill/" }, { "code": null, "e": 1625, "s": 1611, "text": "CPP-Functions" }, { "code": null, "e": 1642, "s": 1625, "text": "cpp-input-output" }, { "code": null, "e": 1659, "s": 1642, "text": "cpp-manipulators" }, { "code": null, "e": 1663, "s": 1659, "text": "C++" }, { "code": null, "e": 1667, "s": 1663, "text": "CPP" }, { "code": null, "e": 1765, "s": 1667, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1792, "s": 1765, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 1835, "s": 1792, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 1869, "s": 1835, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 1894, "s": 1869, "text": "unordered_map in C++ STL" }, { "code": null, "e": 1948, "s": 1894, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 1972, "s": 1948, "text": "Sorting a vector in C++" }, { "code": null, "e": 1991, "s": 1972, "text": "Inheritance in C++" }, { "code": null, "e": 2031, "s": 1991, "text": "The C++ Standard Template Library (STL)" }, { "code": null, "e": 2055, "s": 2031, "text": "C++ Classes and Objects" } ]
React-Bootstrap InputGroup Component - GeeksforGeeks
30 Apr, 2021 React-Bootstrap is a front-end framework that was designed keeping react in mind. InputGroup Component provides a way to put one add-on or button on either side or both sides of an input. We can use the following approach in ReactJS to use the react-bootstrap InputGroup Component. InputGroup Props: As: It can be used as a custom element type for this component. HasValidation: It is used in form validation to handle the input’s rounded corners. Size: It is used to control the size of buttons and form elements. BsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. folder name, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. folder name, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap npm install bootstrap Step 3: After creating the ReactJS application, Install the required module using the following command: npm install react-bootstrap npm install bootstrap Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from "react";import "bootstrap/dist/css/bootstrap.css";import InputGroup from "react-bootstrap/InputGroup";import Button from "react-bootstrap/Button";import Form from "react-bootstrap/Form"; export default function App() { return ( <div style={{ display: "block", width: 700, padding: 30 }}> <h4>React-Bootstrap InputGroup Component</h4> <InputGroup className="mb-3"> <InputGroup.Prepend> <InputGroup.Text>User Details Form => </InputGroup.Text> </InputGroup.Prepend> <Form style={{ padding: 10 }}> <Form.Group> <Form.Label>Enter your full name:</Form.Label> <Form.Control type="text" placeholder="Enter your full name" /> </Form.Group> <Form.Group> <Form.Label>Enter your email address:</Form.Label> <Form.Control type="email" placeholder="Enter your your email address" /> </Form.Group> <Form.Group> <Form.Label>Enter your age:</Form.Label> <Form.Control type="number" placeholder="Enter your age" /> </Form.Group> <Button variant="primary" type="submit"> Click here to submit form </Button> </Form> </InputGroup> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://react-bootstrap.github.io/components/input-group/ React-Bootstrap ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook Axios in React: A Guide for Beginners How to set background images in ReactJS ? How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24924, "s": 24896, "text": "\n30 Apr, 2021" }, { "code": null, "e": 25206, "s": 24924, "text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. InputGroup Component provides a way to put one add-on or button on either side or both sides of an input. We can use the following approach in ReactJS to use the react-bootstrap InputGroup Component." }, { "code": null, "e": 25224, "s": 25206, "text": "InputGroup Props:" }, { "code": null, "e": 25288, "s": 25224, "text": "As: It can be used as a custom element type for this component." }, { "code": null, "e": 25372, "s": 25288, "text": "HasValidation: It is used in form validation to handle the input’s rounded corners." }, { "code": null, "e": 25439, "s": 25372, "text": "Size: It is used to control the size of buttons and form elements." }, { "code": null, "e": 25523, "s": 25439, "text": "BsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 25573, "s": 25523, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25668, "s": 25573, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 25732, "s": 25668, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 25764, "s": 25732, "text": "npx create-react-app foldername" }, { "code": null, "e": 25878, "s": 25764, "text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command:cd foldername" }, { "code": null, "e": 25979, "s": 25878, "text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command:" }, { "code": null, "e": 25993, "s": 25979, "text": "cd foldername" }, { "code": null, "e": 26148, "s": 25993, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap \nnpm install bootstrap" }, { "code": null, "e": 26253, "s": 26148, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 26304, "s": 26253, "text": "npm install react-bootstrap \nnpm install bootstrap" }, { "code": null, "e": 26356, "s": 26304, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26374, "s": 26356, "text": "Project Structure" }, { "code": null, "e": 26504, "s": 26374, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 26511, "s": 26504, "text": "App.js" }, { "code": "import React from \"react\";import \"bootstrap/dist/css/bootstrap.css\";import InputGroup from \"react-bootstrap/InputGroup\";import Button from \"react-bootstrap/Button\";import Form from \"react-bootstrap/Form\"; export default function App() { return ( <div style={{ display: \"block\", width: 700, padding: 30 }}> <h4>React-Bootstrap InputGroup Component</h4> <InputGroup className=\"mb-3\"> <InputGroup.Prepend> <InputGroup.Text>User Details Form => </InputGroup.Text> </InputGroup.Prepend> <Form style={{ padding: 10 }}> <Form.Group> <Form.Label>Enter your full name:</Form.Label> <Form.Control type=\"text\" placeholder=\"Enter your full name\" /> </Form.Group> <Form.Group> <Form.Label>Enter your email address:</Form.Label> <Form.Control type=\"email\" placeholder=\"Enter your your email address\" /> </Form.Group> <Form.Group> <Form.Label>Enter your age:</Form.Label> <Form.Control type=\"number\" placeholder=\"Enter your age\" /> </Form.Group> <Button variant=\"primary\" type=\"submit\"> Click here to submit form </Button> </Form> </InputGroup> </div> );}", "e": 27860, "s": 26511, "text": null }, { "code": null, "e": 27973, "s": 27860, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 27983, "s": 27973, "text": "npm start" }, { "code": null, "e": 28082, "s": 27983, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 28151, "s": 28082, "text": "Reference: https://react-bootstrap.github.io/components/input-group/" }, { "code": null, "e": 28167, "s": 28151, "text": "React-Bootstrap" }, { "code": null, "e": 28175, "s": 28167, "text": "ReactJS" }, { "code": null, "e": 28192, "s": 28175, "text": "Web Technologies" }, { "code": null, "e": 28290, "s": 28192, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28317, "s": 28290, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 28355, "s": 28317, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 28397, "s": 28355, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 28432, "s": 28397, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 28490, "s": 28432, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 28530, "s": 28490, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28563, "s": 28530, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28608, "s": 28563, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28658, "s": 28608, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
C++ Pointer to an Array
It is most likely that you would not understand this chapter until you go through the chapter related C++ Pointers. So assuming you have bit understanding on pointers in C++, let us start: An array name is a constant pointer to the first element of the array. Therefore, in the declaration − double balance[50]; balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p the address of the first element of balance − double *p; double balance[10]; p = balance; It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4]. Once you store the address of first element in p, you can access array elements using *p, *(p+1), *(p+2) and so on. Below is the example to show all the concepts discussed above − #include <iostream> using namespace std; int main () { // an array with 5 elements. double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; double *p; p = balance; // output each array element's value cout << "Array values using pointer " << endl; for ( int i = 0; i < 5; i++ ) { cout << "*(p + " << i << ") : "; cout << *(p + i) << endl; } cout << "Array values using balance as address " << endl; for ( int i = 0; i < 5; i++ ) { cout << "*(balance + " << i << ") : "; cout << *(balance + i) << endl; } return 0; } When the above code is compiled and executed, it produces the following result − Array values using pointer *(p + 0) : 1000 *(p + 1) : 2 *(p + 2) : 3.4 *(p + 3) : 17 *(p + 4) : 50 Array values using balance as address *(balance + 0) : 1000 *(balance + 1) : 2 *(balance + 2) : 3.4 *(balance + 3) : 17 *(balance + 4) : 50 In the above example, p is a pointer to double which means it can store address of a variable of double type. Once we have address in p, then *p will give us value available at the address stored in p, as we have shown in the above example. 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2434, "s": 2318, "text": "It is most likely that you would not understand this chapter until you go through the chapter related C++ Pointers." }, { "code": null, "e": 2610, "s": 2434, "text": "So assuming you have bit understanding on pointers in C++, let us start: An array name is a constant pointer to the first element of the array. Therefore, in the declaration −" }, { "code": null, "e": 2631, "s": 2610, "text": "double balance[50];\n" }, { "code": null, "e": 2825, "s": 2631, "text": "balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p the address of the first element of balance −" }, { "code": null, "e": 2871, "s": 2825, "text": "double *p;\ndouble balance[10];\n\np = balance;\n" }, { "code": null, "e": 3023, "s": 2871, "text": "It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4]." }, { "code": null, "e": 3203, "s": 3023, "text": "Once you store the address of first element in p, you can access array elements using *p, *(p+1), *(p+2) and so on. Below is the example to show all the concepts discussed above −" }, { "code": null, "e": 3791, "s": 3203, "text": "#include <iostream>\nusing namespace std;\n \nint main () {\n // an array with 5 elements.\n double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};\n double *p;\n\n p = balance;\n \n // output each array element's value \n cout << \"Array values using pointer \" << endl;\n \n for ( int i = 0; i < 5; i++ ) {\n cout << \"*(p + \" << i << \") : \";\n cout << *(p + i) << endl;\n }\n cout << \"Array values using balance as address \" << endl;\n \n for ( int i = 0; i < 5; i++ ) {\n cout << \"*(balance + \" << i << \") : \";\n cout << *(balance + i) << endl;\n }\n \n return 0;\n}" }, { "code": null, "e": 3872, "s": 3791, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4112, "s": 3872, "text": "Array values using pointer\n*(p + 0) : 1000\n*(p + 1) : 2\n*(p + 2) : 3.4\n*(p + 3) : 17\n*(p + 4) : 50\nArray values using balance as address\n*(balance + 0) : 1000\n*(balance + 1) : 2\n*(balance + 2) : 3.4\n*(balance + 3) : 17\n*(balance + 4) : 50\n" }, { "code": null, "e": 4353, "s": 4112, "text": "In the above example, p is a pointer to double which means it can store address of a variable of double type. Once we have address in p, then *p will give us value available at the address stored in p, as we have shown in the above example." }, { "code": null, "e": 4390, "s": 4353, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 4409, "s": 4390, "text": " Arnab Chakraborty" }, { "code": null, "e": 4441, "s": 4409, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 4464, "s": 4441, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 4500, "s": 4464, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 4517, "s": 4500, "text": " Frahaan Hussain" }, { "code": null, "e": 4552, "s": 4517, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4569, "s": 4552, "text": " Frahaan Hussain" }, { "code": null, "e": 4604, "s": 4569, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4621, "s": 4604, "text": " Frahaan Hussain" }, { "code": null, "e": 4656, "s": 4621, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4673, "s": 4656, "text": " Frahaan Hussain" }, { "code": null, "e": 4680, "s": 4673, "text": " Print" }, { "code": null, "e": 4691, "s": 4680, "text": " Add Notes" } ]
Binary Search using pthread - GeeksforGeeks
26 Dec, 2017 Binary search is a popular method of searching in a sorted array or list. It simply divides the list into two halves and discard the half which has zero probability of having the key. On dividing we check the mid point for the key and uses the lower half if key is less than mid point and upper half if key is greater than mid point. Binary search has time complexity of O(log(n)). Binary search can also be implemented using multi-threading where we utilizes the cores of processor by providing each thread a portion of list to search for the key. Number of threads depends upon the number of cores your processor has and its better to create one thread for each core. Examples: Input : list = 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220 key = 7 Output : 7 found in list Input : list = 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220 key = 111 Output : 111 not found in list Note – It is advised to execute the program in Linux based system.Compile in linux using following code: g++ -pthread program_name.cpp // CPP Program to perform binary search using pthreads#include <iostream>using namespace std; // size of array#define MAX 16 // maximum number of threads#define MAX_THREAD 4 // array to be searchedint a[] = { 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220 }; // key that needs to be searchedint key = 110;bool found = false;int part = 0; void* binary_search(void* arg){ // Each thread checks 1/4 of the array for the key int thread_part = part++; int mid; int low = thread_part * (MAX / 4); int high = (thread_part + 1) * (MAX / 4); // search for the key until low < high // or key is found in any portion of array while (low < high && !found) { // normal iterative binary search algorithm mid = (high - low) / 2 + low; if (a[mid] == key) { found = true; break; } else if (a[mid] > key) high = mid - 1; else low = mid + 1; }} // Driver Codeint main(){ pthread_t threads[MAX_THREAD]; for (int i = 0; i < MAX_THREAD; i++) pthread_create(&threads[i], NULL, binary_search, (void*)NULL); for (int i = 0; i < MAX_THREAD; i++) pthread_join(threads[i], NULL); // key found in array if (found) cout << key << " found in array" << endl; // key not found in array else cout << key << " not found in array" << endl; return 0;} Output: 110 found in array Binary Search Divide and Conquer Searching Searching Divide and Conquer Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Binary Search In JavaScript Find a Fixed Point (Value equal to index) in a given array Convex Hull using Divide and Conquer Algorithm Binary Search (bisect) in Python Multiply two polynomials Linear Search Search an element in a sorted and rotated array Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1 Program to find largest element in an array
[ { "code": null, "e": 26271, "s": 26243, "text": "\n26 Dec, 2017" }, { "code": null, "e": 26653, "s": 26271, "text": "Binary search is a popular method of searching in a sorted array or list. It simply divides the list into two halves and discard the half which has zero probability of having the key. On dividing we check the mid point for the key and uses the lower half if key is less than mid point and upper half if key is greater than mid point. Binary search has time complexity of O(log(n))." }, { "code": null, "e": 26820, "s": 26653, "text": "Binary search can also be implemented using multi-threading where we utilizes the cores of processor by providing each thread a portion of list to search for the key." }, { "code": null, "e": 26941, "s": 26820, "text": "Number of threads depends upon the number of cores your processor has and its better to create one thread for each core." }, { "code": null, "e": 26951, "s": 26941, "text": "Examples:" }, { "code": null, "e": 27201, "s": 26951, "text": "Input : list = 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220\n key = 7\nOutput : 7 found in list\n\nInput : list = 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220\n key = 111\nOutput : 111 not found in list\n" }, { "code": null, "e": 27306, "s": 27201, "text": "Note – It is advised to execute the program in Linux based system.Compile in linux using following code:" }, { "code": null, "e": 27337, "s": 27306, "text": "g++ -pthread program_name.cpp\n" }, { "code": "// CPP Program to perform binary search using pthreads#include <iostream>using namespace std; // size of array#define MAX 16 // maximum number of threads#define MAX_THREAD 4 // array to be searchedint a[] = { 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220 }; // key that needs to be searchedint key = 110;bool found = false;int part = 0; void* binary_search(void* arg){ // Each thread checks 1/4 of the array for the key int thread_part = part++; int mid; int low = thread_part * (MAX / 4); int high = (thread_part + 1) * (MAX / 4); // search for the key until low < high // or key is found in any portion of array while (low < high && !found) { // normal iterative binary search algorithm mid = (high - low) / 2 + low; if (a[mid] == key) { found = true; break; } else if (a[mid] > key) high = mid - 1; else low = mid + 1; }} // Driver Codeint main(){ pthread_t threads[MAX_THREAD]; for (int i = 0; i < MAX_THREAD; i++) pthread_create(&threads[i], NULL, binary_search, (void*)NULL); for (int i = 0; i < MAX_THREAD; i++) pthread_join(threads[i], NULL); // key found in array if (found) cout << key << \" found in array\" << endl; // key not found in array else cout << key << \" not found in array\" << endl; return 0;}", "e": 28764, "s": 27337, "text": null }, { "code": null, "e": 28772, "s": 28764, "text": "Output:" }, { "code": null, "e": 28792, "s": 28772, "text": "110 found in array\n" }, { "code": null, "e": 28806, "s": 28792, "text": "Binary Search" }, { "code": null, "e": 28825, "s": 28806, "text": "Divide and Conquer" }, { "code": null, "e": 28835, "s": 28825, "text": "Searching" }, { "code": null, "e": 28845, "s": 28835, "text": "Searching" }, { "code": null, "e": 28864, "s": 28845, "text": "Divide and Conquer" }, { "code": null, "e": 28878, "s": 28864, "text": "Binary Search" }, { "code": null, "e": 28976, "s": 28878, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29004, "s": 28976, "text": "Binary Search In JavaScript" }, { "code": null, "e": 29063, "s": 29004, "text": "Find a Fixed Point (Value equal to index) in a given array" }, { "code": null, "e": 29110, "s": 29063, "text": "Convex Hull using Divide and Conquer Algorithm" }, { "code": null, "e": 29143, "s": 29110, "text": "Binary Search (bisect) in Python" }, { "code": null, "e": 29168, "s": 29143, "text": "Multiply two polynomials" }, { "code": null, "e": 29182, "s": 29168, "text": "Linear Search" }, { "code": null, "e": 29230, "s": 29182, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 29254, "s": 29230, "text": "Find the Missing Number" }, { "code": null, "e": 29310, "s": 29254, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" } ]
How to count duplicates in Pandas Dataframe? - GeeksforGeeks
28 Jul, 2020 Let us see how to count duplicates in a Pandas DataFrame. Our task is to count the number of duplicate entries in a single column and multiple columns. Under a single column : We will be using the pivot_table() function to count the duplicates in a single column. The column in which the duplicates are to be found will be passed as the value of the index parameter. The value of aggfunc will be ‘size’. # importing the moduleimport pandas as pd # creating the DataFramedf = pd.DataFrame({'Name' : ['Mukul', 'Rohan', 'Mayank', 'Sundar', 'Aakash'], 'Course' : ['BCA', 'BBA', 'BCA', 'MBA', 'BBA'], 'Location' : ['Saharanpur', 'Meerut', 'Agra', 'Saharanpur', 'Meerut']}) # counting the duplicatesdups = df.pivot_table(index = ['Course'], aggfunc ='size') # displaying the duplicate Seriesprint(dups) Output : Across multiple columns : We will be using the pivot_table() function to count the duplicates across multiple columns. The columns in which the duplicates are to be found will be passed as the value of the index parameter as a list. The value of aggfunc will be ‘size’. # importing the moduleimport pandas as pd # creating the DataFramedf = pd.DataFrame({'Name' : ['Mukul', 'Rohan', 'Mayank', 'Sundar', 'Aakash'], 'Course' : ['BCA', 'BBA', 'BCA', 'MBA', 'BBA'], 'Location' : ['Saharanpur', 'Meerut', 'Agra', 'Saharanpur', 'Meerut']}) # counting the duplicatesdups = df.pivot_table(index = ['Course', 'Location'], aggfunc ='size') # displaying the duplicate Seriesprint(dups) Output Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Different ways to create Pandas Dataframe Enumerate() in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists *args and **kwargs in Python Check if element exists in list in Python How To Convert Python Dictionary To JSON? Convert integer to string in Python
[ { "code": null, "e": 25034, "s": 25006, "text": "\n28 Jul, 2020" }, { "code": null, "e": 25186, "s": 25034, "text": "Let us see how to count duplicates in a Pandas DataFrame. Our task is to count the number of duplicate entries in a single column and multiple columns." }, { "code": null, "e": 25438, "s": 25186, "text": "Under a single column : We will be using the pivot_table() function to count the duplicates in a single column. The column in which the duplicates are to be found will be passed as the value of the index parameter. The value of aggfunc will be ‘size’." }, { "code": "# importing the moduleimport pandas as pd # creating the DataFramedf = pd.DataFrame({'Name' : ['Mukul', 'Rohan', 'Mayank', 'Sundar', 'Aakash'], 'Course' : ['BCA', 'BBA', 'BCA', 'MBA', 'BBA'], 'Location' : ['Saharanpur', 'Meerut', 'Agra', 'Saharanpur', 'Meerut']}) # counting the duplicatesdups = df.pivot_table(index = ['Course'], aggfunc ='size') # displaying the duplicate Seriesprint(dups)", "e": 25933, "s": 25438, "text": null }, { "code": null, "e": 25942, "s": 25933, "text": "Output :" }, { "code": null, "e": 26212, "s": 25942, "text": "Across multiple columns : We will be using the pivot_table() function to count the duplicates across multiple columns. The columns in which the duplicates are to be found will be passed as the value of the index parameter as a list. The value of aggfunc will be ‘size’." }, { "code": "# importing the moduleimport pandas as pd # creating the DataFramedf = pd.DataFrame({'Name' : ['Mukul', 'Rohan', 'Mayank', 'Sundar', 'Aakash'], 'Course' : ['BCA', 'BBA', 'BCA', 'MBA', 'BBA'], 'Location' : ['Saharanpur', 'Meerut', 'Agra', 'Saharanpur', 'Meerut']}) # counting the duplicatesdups = df.pivot_table(index = ['Course', 'Location'], aggfunc ='size') # displaying the duplicate Seriesprint(dups)", "e": 26719, "s": 26212, "text": null }, { "code": null, "e": 26726, "s": 26719, "text": "Output" }, { "code": null, "e": 26750, "s": 26726, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26764, "s": 26750, "text": "Python-pandas" }, { "code": null, "e": 26771, "s": 26764, "text": "Python" }, { "code": null, "e": 26869, "s": 26771, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26887, "s": 26869, "text": "Python Dictionary" }, { "code": null, "e": 26919, "s": 26887, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26961, "s": 26919, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26983, "s": 26961, "text": "Enumerate() in Python" }, { "code": null, "e": 27027, "s": 26983, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27064, "s": 27027, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27093, "s": 27064, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27135, "s": 27093, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27177, "s": 27135, "text": "How To Convert Python Dictionary To JSON?" } ]
array::empty() in C++ STL - GeeksforGeeks
26 Mar, 2018 Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. empty() function is used to check if the array container is empty or not. Syntax : arrayname.empty() Parameters : No parameters are passed. Returns : True, if array is empty False, Otherwise Examples: Input : myarray{1, 2, 3, 4, 5}; myarray.empty(); Output : False Input : myarray{}; myarray.empty(); Output : True Errors and Exceptions 1. It has a no exception throw guarantee.2. Shows error when a parameter is passed. // Non Empty array example// CPP program to illustrate// Implementation of empty() function#include <array>#include <iostream>using namespace std; int main(){ array<int, 5> myarray{ 1, 2, 3, 4 }; if (myarray.empty()) { cout << "True"; } else { cout << "False"; } return 0;} Output : False // Empty array example// CPP program to illustrate// Implementation of empty() function#include <array>#include <iostream>using namespace std; int main(){ array<int, 0> myarray; if (myarray.empty()) { cout << "True"; } else { cout << "False"; } return 0;} Output : True cpp-array STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Iterators in C++ STL Friend class and function in C++ Polymorphism in C++ Sorting a vector in C++ Convert string to char array in C++ List in C++ Standard Template Library (STL) Inline Functions in C++ std::string class in C++ Destructors in C++
[ { "code": null, "e": 24018, "s": 23990, "text": "\n26 Mar, 2018" }, { "code": null, "e": 24205, "s": 24018, "text": "Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays." }, { "code": null, "e": 24279, "s": 24205, "text": "empty() function is used to check if the array container is empty or not." }, { "code": null, "e": 24288, "s": 24279, "text": "Syntax :" }, { "code": null, "e": 24397, "s": 24288, "text": "arrayname.empty()\nParameters :\nNo parameters are passed.\nReturns :\nTrue, if array is empty\nFalse, Otherwise\n" }, { "code": null, "e": 24407, "s": 24397, "text": "Examples:" }, { "code": null, "e": 24543, "s": 24407, "text": "Input : myarray{1, 2, 3, 4, 5};\n myarray.empty();\nOutput : False\n\nInput : myarray{};\n myarray.empty();\nOutput : True\n" }, { "code": null, "e": 24565, "s": 24543, "text": "Errors and Exceptions" }, { "code": null, "e": 24649, "s": 24565, "text": "1. It has a no exception throw guarantee.2. Shows error when a parameter is passed." }, { "code": "// Non Empty array example// CPP program to illustrate// Implementation of empty() function#include <array>#include <iostream>using namespace std; int main(){ array<int, 5> myarray{ 1, 2, 3, 4 }; if (myarray.empty()) { cout << \"True\"; } else { cout << \"False\"; } return 0;}", "e": 24956, "s": 24649, "text": null }, { "code": null, "e": 24965, "s": 24956, "text": "Output :" }, { "code": null, "e": 24972, "s": 24965, "text": "False\n" }, { "code": "// Empty array example// CPP program to illustrate// Implementation of empty() function#include <array>#include <iostream>using namespace std; int main(){ array<int, 0> myarray; if (myarray.empty()) { cout << \"True\"; } else { cout << \"False\"; } return 0;}", "e": 25261, "s": 24972, "text": null }, { "code": null, "e": 25270, "s": 25261, "text": "Output :" }, { "code": null, "e": 25276, "s": 25270, "text": "True\n" }, { "code": null, "e": 25286, "s": 25276, "text": "cpp-array" }, { "code": null, "e": 25290, "s": 25286, "text": "STL" }, { "code": null, "e": 25294, "s": 25290, "text": "C++" }, { "code": null, "e": 25298, "s": 25294, "text": "STL" }, { "code": null, "e": 25302, "s": 25298, "text": "CPP" }, { "code": null, "e": 25400, "s": 25302, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25409, "s": 25400, "text": "Comments" }, { "code": null, "e": 25422, "s": 25409, "text": "Old Comments" }, { "code": null, "e": 25450, "s": 25422, "text": "Operator Overloading in C++" }, { "code": null, "e": 25471, "s": 25450, "text": "Iterators in C++ STL" }, { "code": null, "e": 25504, "s": 25471, "text": "Friend class and function in C++" }, { "code": null, "e": 25524, "s": 25504, "text": "Polymorphism in C++" }, { "code": null, "e": 25548, "s": 25524, "text": "Sorting a vector in C++" }, { "code": null, "e": 25584, "s": 25548, "text": "Convert string to char array in C++" }, { "code": null, "e": 25628, "s": 25584, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 25652, "s": 25628, "text": "Inline Functions in C++" }, { "code": null, "e": 25677, "s": 25652, "text": "std::string class in C++" } ]
C++ Library - <complex>
It implements the complex class to contain complex numbers in cartesian form and several functions and overloads to operate with them. Following is the declaration for std::complex. template< class T > class complex; T − Type of both the real and imaginary components of the complex number. Print Add Notes Bookmark this page
[ { "code": null, "e": 2738, "s": 2603, "text": "It implements the complex class to contain complex numbers in cartesian form and several functions and overloads to operate with them." }, { "code": null, "e": 2785, "s": 2738, "text": "Following is the declaration for std::complex." }, { "code": null, "e": 2820, "s": 2785, "text": "template< class T >\nclass complex;" }, { "code": null, "e": 2894, "s": 2820, "text": "T − Type of both the real and imaginary components of the complex number." }, { "code": null, "e": 2901, "s": 2894, "text": " Print" }, { "code": null, "e": 2912, "s": 2901, "text": " Add Notes" } ]
Difference between Confusion and Diffusion - GeeksforGeeks
03 Jun, 2019 Confusion and diffusion area unit the properties for creating a secure cipher. Each Confusion and diffusion area unit wont to stop the secret writing key from its deduction or ultimately for preventing the first message. Confusion is employed for making uninformed cipher text whereas diffusion is employed for increasing the redundancy of the plain text over the foremost a part of the cipher text to create it obscure. The stream cipher solely depends on confusion, or else, diffusion is employed by each stream and block cipher. Confusion = Substitution a --> b Caesar Cipher Diffusion = Transposition or Permutation abcd --> dacb DES Let’s see the difference b/w Confusion and Diffusion: cryptography Computer Networks Difference Between cryptography Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Advanced Encryption Standard (AES) Intrusion Detection System (IDS) GSM in Wireless Communication Multiple Access Protocols in Computer Network Stop and Wait ARQ Difference between BFS and DFS Class method vs Static method in Python Stack vs Heap Memory Allocation Difference between Process and Thread Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24534, "s": 24506, "text": "\n03 Jun, 2019" }, { "code": null, "e": 24755, "s": 24534, "text": "Confusion and diffusion area unit the properties for creating a secure cipher. Each Confusion and diffusion area unit wont to stop the secret writing key from its deduction or ultimately for preventing the first message." }, { "code": null, "e": 25066, "s": 24755, "text": "Confusion is employed for making uninformed cipher text whereas diffusion is employed for increasing the redundancy of the plain text over the foremost a part of the cipher text to create it obscure. The stream cipher solely depends on confusion, or else, diffusion is employed by each stream and block cipher." }, { "code": null, "e": 25186, "s": 25066, "text": "Confusion = Substitution\na --> b\nCaesar Cipher \n\n\nDiffusion = Transposition or Permutation\nabcd --> dacb\n DES " }, { "code": null, "e": 25240, "s": 25186, "text": "Let’s see the difference b/w Confusion and Diffusion:" }, { "code": null, "e": 25253, "s": 25240, "text": "cryptography" }, { "code": null, "e": 25271, "s": 25253, "text": "Computer Networks" }, { "code": null, "e": 25290, "s": 25271, "text": "Difference Between" }, { "code": null, "e": 25303, "s": 25290, "text": "cryptography" }, { "code": null, "e": 25321, "s": 25303, "text": "Computer Networks" }, { "code": null, "e": 25419, "s": 25321, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25428, "s": 25419, "text": "Comments" }, { "code": null, "e": 25441, "s": 25428, "text": "Old Comments" }, { "code": null, "e": 25476, "s": 25441, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 25509, "s": 25476, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 25539, "s": 25509, "text": "GSM in Wireless Communication" }, { "code": null, "e": 25585, "s": 25539, "text": "Multiple Access Protocols in Computer Network" }, { "code": null, "e": 25603, "s": 25585, "text": "Stop and Wait ARQ" }, { "code": null, "e": 25634, "s": 25603, "text": "Difference between BFS and DFS" }, { "code": null, "e": 25674, "s": 25634, "text": "Class method vs Static method in Python" }, { "code": null, "e": 25706, "s": 25674, "text": "Stack vs Heap Memory Allocation" }, { "code": null, "e": 25744, "s": 25706, "text": "Difference between Process and Thread" } ]
ASP Server.URLEncode Method - GeeksforGeeks
02 Mar, 2021 The ASP Server.URLEncode method is used to apply URL encoding rules to convert to a specified string. Below are given the URLEncode converts characters as follows: Spaces ( ) are converted to plus signs (+). Non-alphanumeric characters are escaped to their hexadecimal representation. Syntax: Server.URLEncode(string) Parameter Values: It contains a string value that specifies the string to be encoded. Example: ASP <%response.write(Server.URLEncode("https://www.geeksforgeeks.org"))%> Output: https%3A%2F%2Fwww%2Egeeksforgeeks%2Eorg ASP-Basics ASP-Methods Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React HTML Cheat Sheet - A Basic Guide to HTML REST API (Introduction) Difference Between PUT and PATCH Request How to execute PHP code using command line ? How to redirect to another page in ReactJS ?
[ { "code": null, "e": 26279, "s": 26251, "text": "\n02 Mar, 2021" }, { "code": null, "e": 26444, "s": 26279, "text": "The ASP Server.URLEncode method is used to apply URL encoding rules to convert to a specified string. Below are given the URLEncode converts characters as follows: " }, { "code": null, "e": 26488, "s": 26444, "text": "Spaces ( ) are converted to plus signs (+)." }, { "code": null, "e": 26565, "s": 26488, "text": "Non-alphanumeric characters are escaped to their hexadecimal representation." }, { "code": null, "e": 26574, "s": 26565, "text": "Syntax: " }, { "code": null, "e": 26599, "s": 26574, "text": "Server.URLEncode(string)" }, { "code": null, "e": 26686, "s": 26599, "text": "Parameter Values: It contains a string value that specifies the string to be encoded. " }, { "code": null, "e": 26696, "s": 26686, "text": "Example: " }, { "code": null, "e": 26700, "s": 26696, "text": "ASP" }, { "code": "<%response.write(Server.URLEncode(\"https://www.geeksforgeeks.org\"))%>", "e": 26770, "s": 26700, "text": null }, { "code": null, "e": 26780, "s": 26770, "text": "Output: " }, { "code": null, "e": 26820, "s": 26780, "text": "https%3A%2F%2Fwww%2Egeeksforgeeks%2Eorg" }, { "code": null, "e": 26831, "s": 26820, "text": "ASP-Basics" }, { "code": null, "e": 26843, "s": 26831, "text": "ASP-Methods" }, { "code": null, "e": 26860, "s": 26843, "text": "Web Technologies" }, { "code": null, "e": 26958, "s": 26860, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26998, "s": 26958, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27043, "s": 26998, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27086, "s": 27043, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27147, "s": 27086, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27219, "s": 27147, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27260, "s": 27219, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 27284, "s": 27260, "text": "REST API (Introduction)" }, { "code": null, "e": 27325, "s": 27284, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27370, "s": 27325, "text": "How to execute PHP code using command line ?" } ]
How to iterate through a dictionary in Python?
There are two ways of iterating through a Python dictionary object. One is to fetch associated value for each key in keys() list. >>> D1 = {1:'a', 2:'b', 3:'c'} >>> for k in D1.keys(): print (k, D1[k]) 1 a 2 b 3 c There is also items() method of dictionary object which returns list of tuples, each tuple having key and value. Each tuple is then unpacked to two variables to print one dictionary item at a time. >>> D1={1:'a', 2:'b', 3:'c'} >>> for k, v in D1.items(): print (k, v) 1 a 2 b 3 c
[ { "code": null, "e": 1192, "s": 1062, "text": "There are two ways of iterating through a Python dictionary object. One is to fetch associated value for each key in keys() list." }, { "code": null, "e": 1280, "s": 1192, "text": ">>> D1 = {1:'a', 2:'b', 3:'c'} \n>>> for k in D1.keys():\n print (k, D1[k])\n1 a\n2 b\n3 c" }, { "code": null, "e": 1478, "s": 1280, "text": "There is also items() method of dictionary object which returns list of tuples, each tuple having key and value. Each tuple is then unpacked to two variables to print one dictionary item at a time." }, { "code": null, "e": 1564, "s": 1478, "text": ">>> D1={1:'a', 2:'b', 3:'c'} \n>>> for k, v in D1.items():\n print (k, v)\n1 a\n2 b\n3 c" } ]
Java Program for Iterative Merge Sort - GeeksforGeeks
12 Jan, 2018 Following is a typical recursive implementation of Merge Sort that uses last element as pivot. // Recursive Java Program for merge sort import java.util.Arrays;public class GFG{ public static void mergeSort(int[] array) { if(array == null) { return; } if(array.length > 1) { int mid = array.length / 2; // Split left part int[] left = new int[mid]; for(int i = 0; i < mid; i++) { left[i] = array[i]; } // Split right part int[] right = new int[array.length - mid]; for(int i = mid; i < array.length; i++) { right[i - mid] = array[i]; } mergeSort(left); mergeSort(right); int i = 0; int j = 0; int k = 0; // Merge left and right arrays while(i < left.length && j < right.length) { if(left[i] < right[j]) { array[k] = left[i]; i++; } else { array[k] = right[j]; j++; } k++; } // Collect remaining elements while(i < left.length) { array[k] = left[i]; i++; k++; } while(j < right.length) { array[k] = right[j]; j++; k++; } } } // Driver program to test above functions. public static void main(String[] args) { int arr[] = {12, 11, 13, 5, 6, 7}; int i=0; System.out.println("Given array is"); for(i=0; i<arr.length; i++) System.out.print(arr[i]+" "); mergeSort(arr); System.out.println("\n"); System.out.println("Sorted array is"); for(i=0; i<arr.length; i++) System.out.print(arr[i]+" "); }} // Code Contributed by Mohit Gupta_OMG Please refer complete article on Iterative Merge Sort for more details! Merge Sort Java Programs Sorting Sorting Merge Sort Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate Over the Characters of a String in Java How to Get Elements By Index from HashSet in Java? Java Program to Write into a File Java Program to Read a File to String How to Write Data into Excel Sheet using Java?
[ { "code": null, "e": 26295, "s": 26267, "text": "\n12 Jan, 2018" }, { "code": null, "e": 26390, "s": 26295, "text": "Following is a typical recursive implementation of Merge Sort that uses last element as pivot." }, { "code": "// Recursive Java Program for merge sort import java.util.Arrays;public class GFG{ public static void mergeSort(int[] array) { if(array == null) { return; } if(array.length > 1) { int mid = array.length / 2; // Split left part int[] left = new int[mid]; for(int i = 0; i < mid; i++) { left[i] = array[i]; } // Split right part int[] right = new int[array.length - mid]; for(int i = mid; i < array.length; i++) { right[i - mid] = array[i]; } mergeSort(left); mergeSort(right); int i = 0; int j = 0; int k = 0; // Merge left and right arrays while(i < left.length && j < right.length) { if(left[i] < right[j]) { array[k] = left[i]; i++; } else { array[k] = right[j]; j++; } k++; } // Collect remaining elements while(i < left.length) { array[k] = left[i]; i++; k++; } while(j < right.length) { array[k] = right[j]; j++; k++; } } } // Driver program to test above functions. public static void main(String[] args) { int arr[] = {12, 11, 13, 5, 6, 7}; int i=0; System.out.println(\"Given array is\"); for(i=0; i<arr.length; i++) System.out.print(arr[i]+\" \"); mergeSort(arr); System.out.println(\"\\n\"); System.out.println(\"Sorted array is\"); for(i=0; i<arr.length; i++) System.out.print(arr[i]+\" \"); }} // Code Contributed by Mohit Gupta_OMG", "e": 28395, "s": 26390, "text": null }, { "code": null, "e": 28467, "s": 28395, "text": "Please refer complete article on Iterative Merge Sort for more details!" }, { "code": null, "e": 28478, "s": 28467, "text": "Merge Sort" }, { "code": null, "e": 28492, "s": 28478, "text": "Java Programs" }, { "code": null, "e": 28500, "s": 28492, "text": "Sorting" }, { "code": null, "e": 28508, "s": 28500, "text": "Sorting" }, { "code": null, "e": 28519, "s": 28508, "text": "Merge Sort" }, { "code": null, "e": 28617, "s": 28519, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28665, "s": 28617, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 28716, "s": 28665, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 28750, "s": 28716, "text": "Java Program to Write into a File" }, { "code": null, "e": 28788, "s": 28750, "text": "Java Program to Read a File to String" } ]
Count natural numbers whose all permutation are greater than that number in C++
We are given a natural number let’s say, num and the task is to calculate the count of all those natural numbers whose all permutations are greater than that number. We are working with the following conditions − The data should be natural numbers only The data should be natural numbers only All the possible permutations or arrangement of a natural number should be equal or greater than the given number. For example, the number is 20Consider all the numbers till 20 starting from 1 i.e. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20Now check those numbers whose arrangement or permutation is equaled or greater than the given number i.e. 20. Numbers are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11=11, 12<21, 13<31, 14<41, 15<51, 16<61, 17<71, 18<81, 19<91. So the count will be 18. All the possible permutations or arrangement of a natural number should be equal or greater than the given number. For example, the number is 20 Consider all the numbers till 20 starting from 1 i.e. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 Consider all the numbers till 20 starting from 1 i.e. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 Now check those numbers whose arrangement or permutation is equaled or greater than the given number i.e. 20. Numbers are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11=11, 12<21, 13<31, 14<41, 15<51, 16<61, 17<71, 18<81, 19<91. So the count will be 18. Now check those numbers whose arrangement or permutation is equaled or greater than the given number i.e. 20. Numbers are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11=11, 12<21, 13<31, 14<41, 15<51, 16<61, 17<71, 18<81, 19<91. So the count will be 18. Input − num = 10 Output − count is 9 Explanation − numbers 1, 2, 3, 4, 5, 6, 7, 8, 9 are the numbers that are equals to the number when arranged in any manner. Input − num = 13 Output − count is 12 Explanation − numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12<21, 13<31 are the numbers that are equals to greater than the number when arranged in any manner. Input the value of number num Input the value of number num Set the max_size to 9 as there will always be at least 9 numbers that will have permutation equals to or greater than the number itself. Set the max_size to 9 as there will always be at least 9 numbers that will have permutation equals to or greater than the number itself. Start the loop from 0 till max_size Start the loop from 0 till max_size Inside the loop, create a list type variable and check if i is less than or equals to num IF yes then insert i to the list and increment the count by 1 Inside the loop, create a list type variable and check if i is less than or equals to num IF yes then insert i to the list and increment the count by 1 Traverse the list from the end till the beginning and start another loop from the first element till 9. Traverse the list from the end till the beginning and start another loop from the first element till 9. Check if temp <= num then push temp at the front in the list and increase the count by 1 Check if temp <= num then push temp at the front in the list and increase the count by 1 Return the count Return the count Print the result. Print the result. Live Demo #include<bits/stdc++.h> using namespace std; //function to Count natural numbers whose //all permutation are greater than that number void count(int num){ int count = 0; int max_size = 9; for (int i = 1; i <= max_size; i++){ list<int> lists; if (i <= num){ //insert element at the end of the list lists.push_back(i); count = count + 1; } //iterator starts from the last of the list for(auto iter = lists.end(); iter != lists.begin(); ++iter){ int first_ele = lists.front(); lists.pop_front(); for (int next = first_ele%10; next <= 9; next++){ int temp = first_ele*10 + next; if (temp <= num){ lists.push_front(temp); count++; } } } } cout<<"count of num "<<num <<" is "<<count<<endl; } int main(){ count(1); count(9); count(7); count(0); count(12); return 0; } If we run the above code we will get the following output − count of num 1 is 1 count of num 9 is 9 count of num 7 is 7 count of num 0 is 0 count of num 12 is 11
[ { "code": null, "e": 1228, "s": 1062, "text": "We are given a natural number let’s say, num and the task is to calculate the count of all those natural numbers whose all permutations are greater than that number." }, { "code": null, "e": 1275, "s": 1228, "text": "We are working with the following conditions −" }, { "code": null, "e": 1315, "s": 1275, "text": "The data should be natural numbers only" }, { "code": null, "e": 1355, "s": 1315, "text": "The data should be natural numbers only" }, { "code": null, "e": 1859, "s": 1355, "text": "All the possible permutations or arrangement of a natural number should be equal or greater than the given number. For example, the number is 20Consider all the numbers till 20 starting from 1 i.e. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20Now check those numbers whose arrangement or permutation is equaled or greater than the given number i.e. 20. Numbers are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11=11, 12<21, 13<31, 14<41, 15<51, 16<61, 17<71, 18<81, 19<91. So the count will be 18." }, { "code": null, "e": 2004, "s": 1859, "text": "All the possible permutations or arrangement of a natural number should be equal or greater than the given number. For example, the number is 20" }, { "code": null, "e": 2128, "s": 2004, "text": "Consider all the numbers till 20 starting from 1 i.e. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20" }, { "code": null, "e": 2252, "s": 2128, "text": "Consider all the numbers till 20 starting from 1 i.e. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20" }, { "code": null, "e": 2489, "s": 2252, "text": "Now check those numbers whose arrangement or permutation is equaled or greater than the given number i.e. 20. Numbers are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11=11, 12<21, 13<31, 14<41, 15<51, 16<61, 17<71, 18<81, 19<91. So the count will be 18." }, { "code": null, "e": 2726, "s": 2489, "text": "Now check those numbers whose arrangement or permutation is equaled or greater than the given number i.e. 20. Numbers are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11=11, 12<21, 13<31, 14<41, 15<51, 16<61, 17<71, 18<81, 19<91. So the count will be 18." }, { "code": null, "e": 2743, "s": 2726, "text": "Input − num = 10" }, { "code": null, "e": 2763, "s": 2743, "text": "Output − count is 9" }, { "code": null, "e": 2886, "s": 2763, "text": "Explanation − numbers 1, 2, 3, 4, 5, 6, 7, 8, 9 are the numbers that are equals to the number when arranged in any manner." }, { "code": null, "e": 2903, "s": 2886, "text": "Input − num = 13" }, { "code": null, "e": 2924, "s": 2903, "text": "Output − count is 12" }, { "code": null, "e": 3078, "s": 2924, "text": "Explanation − numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12<21, 13<31 are the numbers that are equals to greater than the number when arranged in any manner." }, { "code": null, "e": 3108, "s": 3078, "text": "Input the value of number num" }, { "code": null, "e": 3138, "s": 3108, "text": "Input the value of number num" }, { "code": null, "e": 3275, "s": 3138, "text": "Set the max_size to 9 as there will always be at least 9 numbers that will have permutation equals to or greater than the number itself." }, { "code": null, "e": 3412, "s": 3275, "text": "Set the max_size to 9 as there will always be at least 9 numbers that will have permutation equals to or greater than the number itself." }, { "code": null, "e": 3448, "s": 3412, "text": "Start the loop from 0 till max_size" }, { "code": null, "e": 3484, "s": 3448, "text": "Start the loop from 0 till max_size" }, { "code": null, "e": 3636, "s": 3484, "text": "Inside the loop, create a list type variable and check if i is less than or equals to num IF yes then insert i to the list and increment the count by 1" }, { "code": null, "e": 3788, "s": 3636, "text": "Inside the loop, create a list type variable and check if i is less than or equals to num IF yes then insert i to the list and increment the count by 1" }, { "code": null, "e": 3892, "s": 3788, "text": "Traverse the list from the end till the beginning and start another loop from the first element till 9." }, { "code": null, "e": 3996, "s": 3892, "text": "Traverse the list from the end till the beginning and start another loop from the first element till 9." }, { "code": null, "e": 4085, "s": 3996, "text": "Check if temp <= num then push temp at the front in the list and increase the count by 1" }, { "code": null, "e": 4174, "s": 4085, "text": "Check if temp <= num then push temp at the front in the list and increase the count by 1" }, { "code": null, "e": 4191, "s": 4174, "text": "Return the count" }, { "code": null, "e": 4208, "s": 4191, "text": "Return the count" }, { "code": null, "e": 4226, "s": 4208, "text": "Print the result." }, { "code": null, "e": 4244, "s": 4226, "text": "Print the result." }, { "code": null, "e": 4255, "s": 4244, "text": " Live Demo" }, { "code": null, "e": 5214, "s": 4255, "text": "#include<bits/stdc++.h>\nusing namespace std;\n//function to Count natural numbers whose\n//all permutation are greater than that number\nvoid count(int num){\n int count = 0;\n int max_size = 9;\n for (int i = 1; i <= max_size; i++){\n list<int> lists;\n if (i <= num){\n //insert element at the end of the list\n lists.push_back(i);\n count = count + 1;\n }\n //iterator starts from the last of the list\n for(auto iter = lists.end(); iter != lists.begin(); ++iter){\n int first_ele = lists.front();\n lists.pop_front();\n for (int next = first_ele%10; next <= 9; next++){\n int temp = first_ele*10 + next;\n if (temp <= num){\n lists.push_front(temp);\n count++;\n }\n }\n }\n }\n cout<<\"count of num \"<<num <<\" is \"<<count<<endl;\n}\nint main(){\n count(1);\n count(9);\n count(7);\n count(0);\n count(12);\n return 0;\n}" }, { "code": null, "e": 5274, "s": 5214, "text": "If we run the above code we will get the following output −" }, { "code": null, "e": 5376, "s": 5274, "text": "count of num 1 is 1\ncount of num 9 is 9\ncount of num 7 is 7\ncount of num 0 is 0\ncount of num 12 is 11" } ]
Pandas Query for SQL-like Querying | by Matt Przybyla | Towards Data Science
DatasetPandasQueryTutorial CodeSummaryReferences Dataset Pandas Query Tutorial Code Summary References The dataset used in this analysis and tutorial for pandas query is a dummy dataset created to mimic a dataframe with both text and numeric features. Feel free to use your own .csv file with either or both text and numeric columns to follow the tutorial. Pandas [2] is one of the most common libraries used by data scientists and machine learning engineers. It is mainly used in the exploratory data analysis step of building a model, as well as the ad-hoc analysis of model results. It also contains several functions, including the query function. The query function in pandas is a useful function that acts similarly to the ‘where’ clause in SQL. The benefit of it, however, is that you do not need to keep switching from pandas, Jupyter Notebook, and the SQL platform you are currently using. Some other benefits are listed below: compiles several conditions simple function that works off your pandas dataframe references descriptive statistics instead of having to subquery I have compiled several examples of how the pandas query function can be used. The screenshot below includes a summary of useful examples with a query. Below, you can see how there are both text and numeric conditions that can be satisfied. Find rows where a certain column contains a certain text value, or create a descriptive statistic using the ‘@’ symbol. For example, ‘@mean_of_column’ is referencing a value you have established from using the ‘.mean()’ function. In line 65, rows returned had a ‘Blue’ value and a ‘Confirmed_Recovery’ value that is greater than the mean of ‘Confirmed_Recovery’ itself, while also including the ‘Label_3’ value. The tutorial code referenced in the grey box is all of the code used to demonstrate the query function. First, I imported pandas and read my dataframe. Then, I add new rows that I knew would satisfy certain conditions for displaying how the query function could be used. The ‘append’ function was useful here as well because it quickly added new rows to the dataframe without having to explicitly call out each column, once in a series format. I returned the ‘df.tail()’ to see if the rows returned were what I was expecting. I then returned rows where values from one column equalled that of another. You can also use this same logic but reverse it to see which values for the columns you specify to not equal one another. Next, you can compare if the value of one column is bigger than one value of another column, or vice versa. The most useful feature, I believe, of query is the ‘@’ method. Just like SQL where a subquery can be used to reference for selecting rows where certain conditions are satisfied, so can this method. The ‘@’ method saves the value that you want to compare against. For the example below, I looked at the mean of one column to compare. Lastly, you can execute several conditions in one line of code using the query function by inputting ‘&’ similar to that of ‘and’ in SQL. # All the python code below for use:# import libraryimport pandas as pd# read in your dataframedf = pd.read_csv('/Users/example.csv')# write out new rowsrows = [pd.Series([100, 100, 20,'Blue','Label_1'], index=df.columns),pd.Series([100, 80, 60,'Blue','Label_1'], index=df.columns),pd.Series([80, 60, 100,'Blue','Label_1'], index=df.columns)]# append the multiple rowsnew_df = df.append(rows , ignore_index=True)# check the newest 3 rows you madenew_df.tail(3)# return rows where values from one column equal that of another# they do not for this comparisonnew_df.query('Confirmed_Test == Confirmed_New')# return rows where values from one column equal that of another# they do for this comparisonnew_df.query('Confirmed_Test == Confirmed_Recovery')# return rows where values from one column do not equal that of another# they do for this comparisonnew_df.query('Confirmed_New != Confirmed_Recovery').head()# return rows where values from one column are bigger than that of anothernew_df.query('Confirmed_New > Confirmed_Recovery').head()# see which rows where the 'Confirmed_New' values# are greater than the mean of the total column# use the '@' to reference 'cn_mean'cn_mean = new_df['Confirmed_New'].mean()new_df.query('Confirmed_New > @cn_mean').head()# multiple conditions examplecn_min = new_df['Confirmed_New'].min()cn_max = new_df['Confirmed_New'].max()new_df.query('Confirmed_New > @cn_min & Confirmed_New < @cn_max').head()# text conditions# use double quotes for matching on the string value# all the rows returned have 'Blue' for the 'Text_Feature' columnnew_df.query('Text_Feature == "Blue"').head()# return rows which have a 'Blue' value, and a 'Confirmed_Recovery' that is greater# than the mean of 'Confirmed_Recovery' itself, while also satisfying the 'Label_3' value# only 3 return here (did not print out head())cr_mean = new_df['Confirmed_Recovery'].mean()new_df.query('Text_Feature == "Blue" & Confirmed_Recovery > @cr_mean & Text_Predictor == "Label_3"') To see the code in python-format rather than written out, here is the embedded gist [4]: The query function from pandas is an easy and quick way to manipulate your dataframe. You can use SQL-like clauses that return certain rows from satisfying the conditions that you determine. It is beneficial if you are already in your Jupyter Notebook .ipynb file or .py file rather than having to re-upload or execute SQL commands on a SQL platform. Pandas query is also intuitive and does not take long to learn. I hope you found the examples in this article to be useful. Thank you for reading! [1] Mélody P, Unsplash (2017) [2] pandas, pandas (2020) [3] M.Przybyla, screenshot (2020) [4] M.Przybyla, gist (2020)
[ { "code": null, "e": 220, "s": 171, "text": "DatasetPandasQueryTutorial CodeSummaryReferences" }, { "code": null, "e": 228, "s": 220, "text": "Dataset" }, { "code": null, "e": 235, "s": 228, "text": "Pandas" }, { "code": null, "e": 241, "s": 235, "text": "Query" }, { "code": null, "e": 255, "s": 241, "text": "Tutorial Code" }, { "code": null, "e": 263, "s": 255, "text": "Summary" }, { "code": null, "e": 274, "s": 263, "text": "References" }, { "code": null, "e": 528, "s": 274, "text": "The dataset used in this analysis and tutorial for pandas query is a dummy dataset created to mimic a dataframe with both text and numeric features. Feel free to use your own .csv file with either or both text and numeric columns to follow the tutorial." }, { "code": null, "e": 823, "s": 528, "text": "Pandas [2] is one of the most common libraries used by data scientists and machine learning engineers. It is mainly used in the exploratory data analysis step of building a model, as well as the ad-hoc analysis of model results. It also contains several functions, including the query function." }, { "code": null, "e": 1108, "s": 823, "text": "The query function in pandas is a useful function that acts similarly to the ‘where’ clause in SQL. The benefit of it, however, is that you do not need to keep switching from pandas, Jupyter Notebook, and the SQL platform you are currently using. Some other benefits are listed below:" }, { "code": null, "e": 1136, "s": 1108, "text": "compiles several conditions" }, { "code": null, "e": 1189, "s": 1136, "text": "simple function that works off your pandas dataframe" }, { "code": null, "e": 1253, "s": 1189, "text": "references descriptive statistics instead of having to subquery" }, { "code": null, "e": 1906, "s": 1253, "text": "I have compiled several examples of how the pandas query function can be used. The screenshot below includes a summary of useful examples with a query. Below, you can see how there are both text and numeric conditions that can be satisfied. Find rows where a certain column contains a certain text value, or create a descriptive statistic using the ‘@’ symbol. For example, ‘@mean_of_column’ is referencing a value you have established from using the ‘.mean()’ function. In line 65, rows returned had a ‘Blue’ value and a ‘Confirmed_Recovery’ value that is greater than the mean of ‘Confirmed_Recovery’ itself, while also including the ‘Label_3’ value." }, { "code": null, "e": 2432, "s": 1906, "text": "The tutorial code referenced in the grey box is all of the code used to demonstrate the query function. First, I imported pandas and read my dataframe. Then, I add new rows that I knew would satisfy certain conditions for displaying how the query function could be used. The ‘append’ function was useful here as well because it quickly added new rows to the dataframe without having to explicitly call out each column, once in a series format. I returned the ‘df.tail()’ to see if the rows returned were what I was expecting." }, { "code": null, "e": 2738, "s": 2432, "text": "I then returned rows where values from one column equalled that of another. You can also use this same logic but reverse it to see which values for the columns you specify to not equal one another. Next, you can compare if the value of one column is bigger than one value of another column, or vice versa." }, { "code": null, "e": 3072, "s": 2738, "text": "The most useful feature, I believe, of query is the ‘@’ method. Just like SQL where a subquery can be used to reference for selecting rows where certain conditions are satisfied, so can this method. The ‘@’ method saves the value that you want to compare against. For the example below, I looked at the mean of one column to compare." }, { "code": null, "e": 3210, "s": 3072, "text": "Lastly, you can execute several conditions in one line of code using the query function by inputting ‘&’ similar to that of ‘and’ in SQL." }, { "code": null, "e": 5188, "s": 3210, "text": "# All the python code below for use:# import libraryimport pandas as pd# read in your dataframedf = pd.read_csv('/Users/example.csv')# write out new rowsrows = [pd.Series([100, 100, 20,'Blue','Label_1'], index=df.columns),pd.Series([100, 80, 60,'Blue','Label_1'], index=df.columns),pd.Series([80, 60, 100,'Blue','Label_1'], index=df.columns)]# append the multiple rowsnew_df = df.append(rows , ignore_index=True)# check the newest 3 rows you madenew_df.tail(3)# return rows where values from one column equal that of another# they do not for this comparisonnew_df.query('Confirmed_Test == Confirmed_New')# return rows where values from one column equal that of another# they do for this comparisonnew_df.query('Confirmed_Test == Confirmed_Recovery')# return rows where values from one column do not equal that of another# they do for this comparisonnew_df.query('Confirmed_New != Confirmed_Recovery').head()# return rows where values from one column are bigger than that of anothernew_df.query('Confirmed_New > Confirmed_Recovery').head()# see which rows where the 'Confirmed_New' values# are greater than the mean of the total column# use the '@' to reference 'cn_mean'cn_mean = new_df['Confirmed_New'].mean()new_df.query('Confirmed_New > @cn_mean').head()# multiple conditions examplecn_min = new_df['Confirmed_New'].min()cn_max = new_df['Confirmed_New'].max()new_df.query('Confirmed_New > @cn_min & Confirmed_New < @cn_max').head()# text conditions# use double quotes for matching on the string value# all the rows returned have 'Blue' for the 'Text_Feature' columnnew_df.query('Text_Feature == \"Blue\"').head()# return rows which have a 'Blue' value, and a 'Confirmed_Recovery' that is greater# than the mean of 'Confirmed_Recovery' itself, while also satisfying the 'Label_3' value# only 3 return here (did not print out head())cr_mean = new_df['Confirmed_Recovery'].mean()new_df.query('Text_Feature == \"Blue\" & Confirmed_Recovery > @cr_mean & Text_Predictor == \"Label_3\"')" }, { "code": null, "e": 5277, "s": 5188, "text": "To see the code in python-format rather than written out, here is the embedded gist [4]:" }, { "code": null, "e": 5775, "s": 5277, "text": "The query function from pandas is an easy and quick way to manipulate your dataframe. You can use SQL-like clauses that return certain rows from satisfying the conditions that you determine. It is beneficial if you are already in your Jupyter Notebook .ipynb file or .py file rather than having to re-upload or execute SQL commands on a SQL platform. Pandas query is also intuitive and does not take long to learn. I hope you found the examples in this article to be useful. Thank you for reading!" }, { "code": null, "e": 5806, "s": 5775, "text": "[1] Mélody P, Unsplash (2017)" }, { "code": null, "e": 5832, "s": 5806, "text": "[2] pandas, pandas (2020)" }, { "code": null, "e": 5866, "s": 5832, "text": "[3] M.Przybyla, screenshot (2020)" } ]
HowTo profile TensorFlow:. Nowadays TensorFlow one of the most... | by Illarion Khlestov | Towards Data Science
Nowadays TensorFlow one of the most used library for machine learning. Sometimes it may be quite useful to profile tensorflow graph and know what operations take more time and what less. This can be done with tensorflow timeline module. Unfortunately, I cannot find any clear tutorial how to use it. So in this blog post, I will try to resolve this issue with such topics covered: How to perform profiling of tensorflow code. How to merge timelines from multiply session runs. What issues may occur during profiling and how to resolve them. First let’s define simple example, followed by StackOverflow answer: You should note additional options and run_metadata provided to the session run. This script should work as on CPU, as on GPU. After execution, we will have a timeline_01.json file with our profiled data stored in Chrome trace format. If your script failed — try the first solution from Issues during profiling section. To view stored data, we should use Chrome browser(unfortunately only it supports own tracing format, as far as I know). Go to the page chrome://tracing. In the upper left corner, you will find Load button. Press it and load our JSON file. On the top you will see time axis in ms. To get more precise info about some operation just click on it. Also on the right side, there are simple tools exist: selection, pan, zoom and timing. Now let’s define more complicated example with some placeholders and optimizer: Now our operations stored under the variable scopes. With such approach, operations names will be started with the scope name and clearly distinguished on the timeline. Also, code store traces for three runs. If we execute the script on CPU we receive three relatively similar timelines such this: But if we check results from GPU profiling first results will be different from next ones: You may note that first run takes on GPU much more time than later ones. This happens because on first run tensorflow performs some GPU initialization routines, and later they will be optimized. If you want the more accurate timeline, you should store the tracings after one hundred runs or so. Also now all incoming/outcoming flows are started with variable scope name, and we know exactly where one or another operation exist in the source code. What if we want to store multiply session runs in one file for some reason? Unfortunately, this can be done only manually. Inside Chrome trace format there are stored definitions for every event and it’s running time. At the first iteration we will store all data, but on next runs, we will only update running time, not definitions itself. Here is only the class definition for merging events, and the full example you may find here: And we receive such cool merged timeline: It seems that initialization still takes a lot, so let’s zoom to the right side: Now we can see some repeated pattern. There no any particular separators between runs, but we may visually distinguish them. There are some troubles may exist during profiling. First of all, it may not work at all. If you’ve met some error like this: I tensorflow/stream_executor/dso_loader.cc:126] Couldn't open CUDA library libcupti.so.8.0. LD_LIBRARY_PATH: and you sure that without profiling all works as expected it can be resolved according to the GitHub issue with the installation of the additional library libcupti-dev. This command should fix described error: sudo apt-get install libcupti-dev Second is delays during runs. On the last image we saw that there is a gap between runs. For large networks, this can take really large amount of time. This bug cannot be fully resolved, but the delays may be decreased with a custom C++ protobuf library. It’s clearly described in the tensorflow docs how to perform an installation. I hope with such profiling you will understand more deeply what’s going in tensorflow under the hood and what parts of your graph may be optimized. All code examples with already generated timelines on CPU and GPU are stored in this repo. Thanks for reading!
[ { "code": null, "e": 553, "s": 172, "text": "Nowadays TensorFlow one of the most used library for machine learning. Sometimes it may be quite useful to profile tensorflow graph and know what operations take more time and what less. This can be done with tensorflow timeline module. Unfortunately, I cannot find any clear tutorial how to use it. So in this blog post, I will try to resolve this issue with such topics covered:" }, { "code": null, "e": 598, "s": 553, "text": "How to perform profiling of tensorflow code." }, { "code": null, "e": 649, "s": 598, "text": "How to merge timelines from multiply session runs." }, { "code": null, "e": 713, "s": 649, "text": "What issues may occur during profiling and how to resolve them." }, { "code": null, "e": 782, "s": 713, "text": "First let’s define simple example, followed by StackOverflow answer:" }, { "code": null, "e": 1102, "s": 782, "text": "You should note additional options and run_metadata provided to the session run. This script should work as on CPU, as on GPU. After execution, we will have a timeline_01.json file with our profiled data stored in Chrome trace format. If your script failed — try the first solution from Issues during profiling section." }, { "code": null, "e": 1341, "s": 1102, "text": "To view stored data, we should use Chrome browser(unfortunately only it supports own tracing format, as far as I know). Go to the page chrome://tracing. In the upper left corner, you will find Load button. Press it and load our JSON file." }, { "code": null, "e": 1533, "s": 1341, "text": "On the top you will see time axis in ms. To get more precise info about some operation just click on it. Also on the right side, there are simple tools exist: selection, pan, zoom and timing." }, { "code": null, "e": 1613, "s": 1533, "text": "Now let’s define more complicated example with some placeholders and optimizer:" }, { "code": null, "e": 1782, "s": 1613, "text": "Now our operations stored under the variable scopes. With such approach, operations names will be started with the scope name and clearly distinguished on the timeline." }, { "code": null, "e": 1911, "s": 1782, "text": "Also, code store traces for three runs. If we execute the script on CPU we receive three relatively similar timelines such this:" }, { "code": null, "e": 2002, "s": 1911, "text": "But if we check results from GPU profiling first results will be different from next ones:" }, { "code": null, "e": 2297, "s": 2002, "text": "You may note that first run takes on GPU much more time than later ones. This happens because on first run tensorflow performs some GPU initialization routines, and later they will be optimized. If you want the more accurate timeline, you should store the tracings after one hundred runs or so." }, { "code": null, "e": 2450, "s": 2297, "text": "Also now all incoming/outcoming flows are started with variable scope name, and we know exactly where one or another operation exist in the source code." }, { "code": null, "e": 2885, "s": 2450, "text": "What if we want to store multiply session runs in one file for some reason? Unfortunately, this can be done only manually. Inside Chrome trace format there are stored definitions for every event and it’s running time. At the first iteration we will store all data, but on next runs, we will only update running time, not definitions itself. Here is only the class definition for merging events, and the full example you may find here:" }, { "code": null, "e": 2927, "s": 2885, "text": "And we receive such cool merged timeline:" }, { "code": null, "e": 3008, "s": 2927, "text": "It seems that initialization still takes a lot, so let’s zoom to the right side:" }, { "code": null, "e": 3133, "s": 3008, "text": "Now we can see some repeated pattern. There no any particular separators between runs, but we may visually distinguish them." }, { "code": null, "e": 3259, "s": 3133, "text": "There are some troubles may exist during profiling. First of all, it may not work at all. If you’ve met some error like this:" }, { "code": null, "e": 3368, "s": 3259, "text": "I tensorflow/stream_executor/dso_loader.cc:126] Couldn't open CUDA library libcupti.so.8.0. LD_LIBRARY_PATH:" }, { "code": null, "e": 3578, "s": 3368, "text": "and you sure that without profiling all works as expected it can be resolved according to the GitHub issue with the installation of the additional library libcupti-dev. This command should fix described error:" }, { "code": null, "e": 3612, "s": 3578, "text": "sudo apt-get install libcupti-dev" }, { "code": null, "e": 3945, "s": 3612, "text": "Second is delays during runs. On the last image we saw that there is a gap between runs. For large networks, this can take really large amount of time. This bug cannot be fully resolved, but the delays may be decreased with a custom C++ protobuf library. It’s clearly described in the tensorflow docs how to perform an installation." }, { "code": null, "e": 4184, "s": 3945, "text": "I hope with such profiling you will understand more deeply what’s going in tensorflow under the hood and what parts of your graph may be optimized. All code examples with already generated timelines on CPU and GPU are stored in this repo." } ]
Python | Convert string to DateTime and vice-versa - GeeksforGeeks
30 Jun, 2020 Write a Python program to convert a given string to datetime and vice-versa. Program to convert string to DateTime using strptime() function. Examples: Input : Dec 4 2018 10:07AM Output : 2018-12-04 10:07:00 Input : Jun 12 2013 5:30PM Output : 2013-06-12 17:30:00 strptime() is available in datetime and time modules and is used for Date-Time Conversion. This function changes the given string of datetime into the desired format. Syntax: datetime.strptime(date_string, format) The arguments date_string and format should be of string type. import datetime # Function to convert string to datetimedef convert(date_time): format = '%b %d %Y %I:%M%p' # The format datetime_str = datetime.datetime.strptime(date_time, format) return datetime_str # Driver codedate_time = 'Dec 4 2018 10:07AM'print(convert(date_time)) Output: 2018-12-04 10:07:00 Program to convert DateTime to stringExamples: Input : 2018-12-04 10:07:00 Output : Dec 4 2018 10:07:00AM Input : 2013-06-12 17:30:00Jun 12 2013 5:30PM Output : Jun 12 2013 5:30:00PM Python strftime() function is present in datetime and time modules to create a string representation based on the specified format string. Syntax: datetime_object.strftime(format_str) Another similar function is available in time module which converts a tuple or struct_time object to a string as specified by the format argument. import time # Function to convert string to datetimedef convert(datetime_str): datetime_str = time.mktime(datetime_str) format = "%b %d %Y %r" # The format dateTime = time.strftime(format, time.gmtime(datetime_str)) return dateTime # Driver codedate_time = (2018, 12, 4, 10, 7, 00, 1, 48, 0)print(convert(date_time)) Output: Dec 04 2018 10:07:00 AM Akanksha_Rai Python string-programs python-string Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe sum() function in Python Create a Pandas DataFrame from Lists Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python program to check whether a number is Prime or not Python | Convert a list to dictionary
[ { "code": null, "e": 24441, "s": 24413, "text": "\n30 Jun, 2020" }, { "code": null, "e": 24518, "s": 24441, "text": "Write a Python program to convert a given string to datetime and vice-versa." }, { "code": null, "e": 24583, "s": 24518, "text": "Program to convert string to DateTime using strptime() function." }, { "code": null, "e": 24593, "s": 24583, "text": "Examples:" }, { "code": null, "e": 24709, "s": 24593, "text": "Input : Dec 4 2018 10:07AM \nOutput : 2018-12-04 10:07:00\n\nInput : Jun 12 2013 5:30PM \nOutput : 2013-06-12 17:30:00\n" }, { "code": null, "e": 24876, "s": 24709, "text": "strptime() is available in datetime and time modules and is used for Date-Time Conversion. This function changes the given string of datetime into the desired format." }, { "code": null, "e": 24884, "s": 24876, "text": "Syntax:" }, { "code": null, "e": 24923, "s": 24884, "text": "datetime.strptime(date_string, format)" }, { "code": null, "e": 24986, "s": 24923, "text": "The arguments date_string and format should be of string type." }, { "code": "import datetime # Function to convert string to datetimedef convert(date_time): format = '%b %d %Y %I:%M%p' # The format datetime_str = datetime.datetime.strptime(date_time, format) return datetime_str # Driver codedate_time = 'Dec 4 2018 10:07AM'print(convert(date_time))", "e": 25275, "s": 24986, "text": null }, { "code": null, "e": 25283, "s": 25275, "text": "Output:" }, { "code": null, "e": 25303, "s": 25283, "text": "2018-12-04 10:07:00" }, { "code": null, "e": 25351, "s": 25303, "text": " Program to convert DateTime to stringExamples:" }, { "code": null, "e": 25494, "s": 25351, "text": "Input : 2018-12-04 10:07:00 \nOutput : Dec 4 2018 10:07:00AM \n\nInput : 2013-06-12 17:30:00Jun 12 2013 5:30PM \nOutput : Jun 12 2013 5:30:00PM \n" }, { "code": null, "e": 25633, "s": 25494, "text": "Python strftime() function is present in datetime and time modules to create a string representation based on the specified format string." }, { "code": null, "e": 25641, "s": 25633, "text": "Syntax:" }, { "code": null, "e": 25678, "s": 25641, "text": "datetime_object.strftime(format_str)" }, { "code": null, "e": 25825, "s": 25678, "text": "Another similar function is available in time module which converts a tuple or struct_time object to a string as specified by the format argument." }, { "code": "import time # Function to convert string to datetimedef convert(datetime_str): datetime_str = time.mktime(datetime_str) format = \"%b %d %Y %r\" # The format dateTime = time.strftime(format, time.gmtime(datetime_str)) return dateTime # Driver codedate_time = (2018, 12, 4, 10, 7, 00, 1, 48, 0)print(convert(date_time))", "e": 26162, "s": 25825, "text": null }, { "code": null, "e": 26170, "s": 26162, "text": "Output:" }, { "code": null, "e": 26194, "s": 26170, "text": "Dec 04 2018 10:07:00 AM" }, { "code": null, "e": 26207, "s": 26194, "text": "Akanksha_Rai" }, { "code": null, "e": 26230, "s": 26207, "text": "Python string-programs" }, { "code": null, "e": 26244, "s": 26230, "text": "python-string" }, { "code": null, "e": 26251, "s": 26244, "text": "Python" }, { "code": null, "e": 26267, "s": 26251, "text": "Python Programs" }, { "code": null, "e": 26365, "s": 26267, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26374, "s": 26365, "text": "Comments" }, { "code": null, "e": 26387, "s": 26374, "text": "Old Comments" }, { "code": null, "e": 26409, "s": 26387, "text": "Enumerate() in Python" }, { "code": null, "e": 26441, "s": 26409, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26483, "s": 26441, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26508, "s": 26483, "text": "sum() function in Python" }, { "code": null, "e": 26545, "s": 26508, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26567, "s": 26545, "text": "Defaultdict in Python" }, { "code": null, "e": 26606, "s": 26567, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26652, "s": 26606, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26709, "s": 26652, "text": "Python program to check whether a number is Prime or not" } ]
Check that the String does not contain certain characters in Java
Let’s say the following is our string with special characters. String str = "test*$demo"; Check for the special characters. Pattern pattern = Pattern.compile("[^A-Za-z0-9]"); Matcher match = pattern.matcher(str); boolean val = match.find(); Now, if the bool value “val” is true, that would mean the special characters are in the string. if (val == true) System.out.println("Special characters are in the string."); Live Demo import java.util.regex.Matcher; import java.util.regex.Pattern; public class Demo { public static void main(String []args) { String str = "test*$demo"; System.out.println("String: "+str); Pattern pattern = Pattern.compile("[^A-Za-z0-9]"); Matcher match = pattern.matcher(str); boolean val = match.find(); if (val == true) System.out.println("Special characters are in the string."); else System.out.println("Special characters are not in the string."); } } String: test*$demo Special characters are in the string. The following is another example with a different input. Live Demo import java.util.regex.Matcher; import java.util.regex.Pattern; public class Demo { public static void main(String []args) { String str = "testdemo"; System.out.println("String: "+str); Pattern pattern = Pattern.compile("[^A-Za-z0-9]"); Matcher match = pattern.matcher(str); boolean val = match.find(); if (val == true) System.out.println("Special characters are in the string."); else System.out.println("Special characters are not in the string."); } } String: testdemo Special characters are not in the string...
[ { "code": null, "e": 1125, "s": 1062, "text": "Let’s say the following is our string with special characters." }, { "code": null, "e": 1152, "s": 1125, "text": "String str = \"test*$demo\";" }, { "code": null, "e": 1186, "s": 1152, "text": "Check for the special characters." }, { "code": null, "e": 1303, "s": 1186, "text": "Pattern pattern = Pattern.compile(\"[^A-Za-z0-9]\");\nMatcher match = pattern.matcher(str);\nboolean val = match.find();" }, { "code": null, "e": 1399, "s": 1303, "text": "Now, if the bool value “val” is true, that would mean the special characters are in the string." }, { "code": null, "e": 1477, "s": 1399, "text": "if (val == true)\nSystem.out.println(\"Special characters are in the string.\");" }, { "code": null, "e": 1488, "s": 1477, "text": " Live Demo" }, { "code": null, "e": 2011, "s": 1488, "text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class Demo {\n public static void main(String []args) {\n String str = \"test*$demo\";\n System.out.println(\"String: \"+str);\n Pattern pattern = Pattern.compile(\"[^A-Za-z0-9]\");\n Matcher match = pattern.matcher(str);\n boolean val = match.find();\n if (val == true)\n System.out.println(\"Special characters are in the string.\");\n else\n System.out.println(\"Special characters are not in the string.\");\n }\n}" }, { "code": null, "e": 2068, "s": 2011, "text": "String: test*$demo\nSpecial characters are in the string." }, { "code": null, "e": 2125, "s": 2068, "text": "The following is another example with a different input." }, { "code": null, "e": 2136, "s": 2125, "text": " Live Demo" }, { "code": null, "e": 2654, "s": 2136, "text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class Demo {\n public static void main(String []args) {\n String str = \"testdemo\";\n System.out.println(\"String: \"+str);\n Pattern pattern = Pattern.compile(\"[^A-Za-z0-9]\");\n Matcher match = pattern.matcher(str);\n boolean val = match.find();\n if (val == true)\n System.out.println(\"Special characters are in the string.\");\n else\n System.out.println(\"Special characters are not in the string.\");\n }\n}" }, { "code": null, "e": 2715, "s": 2654, "text": "String: testdemo\nSpecial characters are not in the string..." } ]
How to display mean inside boxplot created by using boxplot function in R?
A boxplot shows the median as a measure of center along with other values but we might want to compare the means as well. Therefore, showing mean with a point is likely to be preferred if we want to compare many boxplots. This can be done by using points(mean(“Vector_name”)), if we are plotting the columns of an R data frame then we will reference them instead of vector name. Consider the below data and the boxplot − Live Demo x<-runif(100,2,5) boxplot(x) Adding mean point to the boxplot − points(mean(x),col="red")
[ { "code": null, "e": 1441, "s": 1062, "text": "A boxplot shows the median as a measure of center along with other values but we might want to compare the means as well. Therefore, showing mean with a point is likely to be preferred if we want to compare many boxplots. This can be done by using points(mean(“Vector_name”)), if we are plotting the columns of an R data frame then we will reference them instead of vector name." }, { "code": null, "e": 1483, "s": 1441, "text": "Consider the below data and the boxplot −" }, { "code": null, "e": 1494, "s": 1483, "text": " Live Demo" }, { "code": null, "e": 1523, "s": 1494, "text": "x<-runif(100,2,5)\nboxplot(x)" }, { "code": null, "e": 1558, "s": 1523, "text": "Adding mean point to the boxplot −" }, { "code": null, "e": 1584, "s": 1558, "text": "points(mean(x),col=\"red\")" } ]
map emplace() in C++ STL
In this article we will be discussing the working, syntax and examples of map::emplace() function in C++ STL. Maps are the associative container, which facilitates to store the elements formed by a combination of key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in the map container are accessed by its unique keys. The map::emplace( ) is a function which comes under <map> header file. This function constructs and inserts an element into the associated map container. emplace() inserts the new element if the key of the element which is to be emplaced is unique. The insertion only happens if there is no element with the same key of the value which is to be inserted. This function works the same as insert() which copies and moves the existing object into the container. If the element is successfully inserted the size of the container is increased by 1 map_name.emplace(Args&& args); This function accepts the following parameter − args − The arguments or values which we want to be emplaced or inserted. If the insertion is successful then the function returns the iterator pointing to the new element which is inserted. Else it returns the iterator to equivalent value which is already present in the container. map<char, int> newmap; emplace( ‘a’, 1); a Live Demo #include <bits/stdc++.h> using namespace std; int main() { map<int, int> TP_Map; TP_Map.emplace(4, 50); TP_Map.emplace(2, 30); TP_Map.emplace(1, 10); TP_Map.emplace(1, 20); TP_Map.emplace(1, 30); cout<<"TP Map is : \n"; cout << "MAP_KEY\tMAP_ELEMENT\n"; for (auto i = TP_Map.begin(); i!= TP_Map.end(); i++) cout << i->first << "\t" << i->second << endl; return 0; } TP Map is: MAP_KEY MAP_ELEMENT 1 10 2 30 4 50
[ { "code": null, "e": 1172, "s": 1062, "text": "In this article we will be discussing the working, syntax and examples of map::emplace() function in C++ STL." }, { "code": null, "e": 1482, "s": 1172, "text": "Maps are the associative container, which facilitates to store the elements formed by a combination of key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in the map container are accessed by its unique keys." }, { "code": null, "e": 1636, "s": 1482, "text": "The map::emplace( ) is a function which comes under <map> header file. This function constructs and inserts an element into the associated map container." }, { "code": null, "e": 1941, "s": 1636, "text": "emplace() inserts the new element if the key of the element which is to be emplaced is unique. The insertion only happens if there is no element with the same key of the value which is to be inserted. This function works the same as insert() which copies and moves the existing object into the container." }, { "code": null, "e": 2025, "s": 1941, "text": "If the element is successfully inserted the size of the container is increased by 1" }, { "code": null, "e": 2056, "s": 2025, "text": "map_name.emplace(Args&& args);" }, { "code": null, "e": 2104, "s": 2056, "text": "This function accepts the following parameter −" }, { "code": null, "e": 2177, "s": 2104, "text": "args − The arguments or values which we want to be emplaced or inserted." }, { "code": null, "e": 2386, "s": 2177, "text": "If the insertion is successful then the function returns the iterator pointing to the new element which is inserted. Else it returns the iterator to equivalent value which is already present in the container." }, { "code": null, "e": 2427, "s": 2386, "text": "map<char, int> newmap;\nemplace( ‘a’, 1);" }, { "code": null, "e": 2429, "s": 2427, "text": "a" }, { "code": null, "e": 2440, "s": 2429, "text": " Live Demo" }, { "code": null, "e": 2842, "s": 2440, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n map<int, int> TP_Map;\n TP_Map.emplace(4, 50);\n TP_Map.emplace(2, 30);\n TP_Map.emplace(1, 10);\n TP_Map.emplace(1, 20);\n TP_Map.emplace(1, 30);\n cout<<\"TP Map is : \\n\";\n cout << \"MAP_KEY\\tMAP_ELEMENT\\n\";\n for (auto i = TP_Map.begin(); i!= TP_Map.end(); i++)\n cout << i->first << \"\\t\" << i->second << endl;\n return 0;\n}" }, { "code": null, "e": 2927, "s": 2842, "text": "TP Map is:\nMAP_KEY MAP_ELEMENT\n1 10\n2 30\n4 50" } ]
Making Python Packages Part 2: How to Publish & Test Your Package on PyPI with Poetry | by Skylar Kerzner | Towards Data Science
In the last edition of this guide, we published a python package to PyPI using a traditional setup.py. It required a strange Manifest.in file, didn’t come with any testing, and we didn’t even discuss dependency management with a requirements.txt. Why? Because that is not the way in 2021, my friends. Dependency management is about the Python libraries used by your package. If you import numpy and use its classes/functions, your package will depend on the version of numpy. If a new version of numpy uses different syntax or gets rid of a function, then your package won’t work on that version of numpy. We need to keep track of what version you were using. Or what if you use numpy and pandas, and they both depend on different versions of some other library. Who will keep track of these things?! Poetry will. Poetry is a Python library that we can use to create a package, publish it to PyPI more easily, AND it will deal with dependency management for us. Yay! To get started, we just install poetry pip install poetry As always, try pip3 (the version for python3)if you don’t have pip. Poetry new Our first command is to create the directory. No more mkdir’s at the beginning of our project when we have poetry. Really, don’t make a directory for your project before you do this, because poetry is going to create a directory with your project name and put everything in there including a subdirectory also named for your project, where the source code will live. So if you make a directory for your project and do this in there, you’re gonna end up with a russian doll situation: my_package/my_package/my_package/yikes. Instead, just go to the directory where all your packages will live (so when you run ls, you see your other projects), and run: poetry new Now you can see your poetry directory with all its parts, inclduing the all-important pyproject.toml. And now we can start building a package with Poetry! Virtual environments But first, a quick detour on how poetry works as a virtual environment. A virtual environment is an isolated digital environment where libraries, codes and interpreters are completely separated from the others on your computer. If you go in a digital environment and try to import numpy, it won’t exist, because it isn’t installed in that digital environment. Conversely, if you install a library in a digital environment, it wont be installed on the rest of your computer. Essentially, the libraries available in an environment are all stored in some directory in that environment. A virtual environment uses its own directory of available libraries, so it has no relationship with your computer’s directory of available libraries. When we ran poetry new, we created a virtual environment! When we run code from the command line while in a poetry directory, we are not in the virtual environment. However if we start a command with poetry run the-rest-of-the-command then we can run that command in the poetry environment. Or, if we run poetry shell then we will enter our poetry folder’s virtual environment, where we can use the libraries that we will install through poetry. Exit a virtual shell with ctrl+d. Poetry add Indeed let’s look at installing libraries with poetry, which will manage our dependencies nicely. Let’s go into that pyproject.toml we created. It’s going to contain two major things: The documentation for our project (well, including referencing the README and LICENSE). We’ll get back to documentation after we finish this libraries business.The range of library versions our package needs The documentation for our project (well, including referencing the README and LICENSE). We’ll get back to documentation after we finish this libraries business. The range of library versions our package needs When we make our package, we’ll need to tell poetry what versions of libraries we are using. That’s easy with the command: poetry add library-name where library-name is the name of whatever library we are using, like numpy. That command will add the library version to our pyproject.toml. It’s really a range of versions following semantic versioning. You can see the syntax here: https://classic.yarnpkg.com/en/docs/dependency-versions/. It will also install the library in our Poetry virtual environment. poetry.lock If you poetry add a library, which will also install that library, you’ll not only see your pyproject.toml automatically updated — you’ll also gain a new file: poetry.lock. That pyproject.toml notes the range of library versions that are acceptable for your package, and only lists the libraries that you’ve directly added with poetry add. On the other hand, the poetry.lock notes the exact library versions that are installed in your package. And it includes every library that your dependencies need. So if you poetry add seaborn, then while your pyproject.toml will just gain seaborn, your poetry.lock will gain: atomicwrites, attrs, colorama, cycler, fonttools, kiwisolver, matplotlib, more-itertools, numpy, packaing, pandas, pillow, pluggy, py, pyparsing, pytest, pytz, scipy, setuptools-scm, six, tomli, wcwidth, and seaborn because that’s every library that seaborn depends on, plus every library that each of those depend on, recursively until every library that seaborn needs has the libraries it needs. Side note on others using your source code Now, if someone clones your package from github, they will have your pyproject.toml, but didn’t install your libraries yet. They’ll need to run poetry install If they also have your poetry.lock, they will install the exact versions stated in your poetry.lock. If they don’t have your poetry.lock, then poetry will do what it did for you — figure out the write versions to install, and write it in a poetry.lock. In summary, the poetry.lock lists all exact library versions installed when a package runs, so that users of your package can all use the same versions of everything. Project Description with pyproject.toml Alrighty so I’ll skip toward the PyPI publishing ASAP, we just need to be a bit decent with our package documentation here. That section on the top of your pyproject.toml will contain everything that setup.py contains in the traditional packaging method without Poetry. The top of your pyproject.toml should look like: pyproject.toml [tool.poetry]name = “” #your package nameversion = “0.0.1”description = “” #a short description of your package that will be used in PyPI searchauthors = [“your-name <your-email>”]license = “MIT”readme = “README.md”homepage = “” #can be the reporepository = “”keywords = [“test”, “dependencies”, “documentation”]classifiers = [“Development Status :: 5 — Production/Stable”,“Intended Audience :: Education”,“Operating System :: MacOS”,“License :: OSI Approved :: MIT License”,“Programming Language :: Python :: 3”,]include = [“LICENSE”,] Go ahead and copy that into your toml and update the fields: fill in your name and email, project name and version, short description, repo/homepage, and fill out those classifiers using the options here: https://pypi.org/pypi?%3Aaction=list_classifiers As you can see, we are referencing a README.md, so change your README.rst to an md (markdown) file if you like. You’ll put the long project description including the change log in that README.md, so it can look something like: README.md My long description blah blah blah blah.Change Log================0.0.1 (Dec 1, 2021) — — — — — — — — — — — — — — — -- First Release0.0.2 (Dec 2, 2021) — — — — — — — — — — — — — — — -- Did some more stuff Publishing to PyPI Okay here we go. I’ll skip to the juicy part, and then I’ll go back and offer some tips. You can publish to PyPI in one line. Afffter you setup your credentials one time with: poetry config http-basic.pypi username password Those are your credentials from pypi.org, which you can get from making an account on their webpage. After you set up those credentials, then here’s that one line publish: poetry publish --build my_package And you’re on PyPI just like that! There is a separate poetry build command but you can just do the build at the same time as the publish with that build flag ( — build). Testing on Test PyPI But maybe before we go throwing our half-baked package on PyPI, we can test it on a test version of PyPI. This test PyPI will allow us to mimic updating to PyPI, then pip installing our own package to see if it works as expected. The first step to do this is to make a new account on test.pypi.org (yes, you need a separate account from your pypi account, but it can have the same username). You can then add the repository to poetry: poetry config repositories.testpypi https://test.pypi.org/legacy/ publish to that repository: poetry publish –-build -r testpypi and pip install your package from that repository: pip install --index-url https://test.pypi.org/simple/ my_package Sidebar: Troubleshooting that pip install If you’re having trouble, this longer command line function solves some of the common issues: python3 -m pip install -i https://test.pypi.org/simple/ — extra-index-url https://pypi.org/simple my_package==0.0.1 The python -m before pip is to make sure you’re using the right pip version. You can also try looking into your pip version and python version with which pipwhich pythonpip --versionpython --version or updating pip with python -m pip install --upgrade pip As always you might need to switch python with python3 or pip with pip3. The extra index url points to the normal PyPI repo (rather than the test), which your dependencies need to be downloaded from. Finally, I’ve also added the version, which you should replace with your package version number, so that it gets the right one. Installing and importing in a new virtual environment When you’re trying that pip install, I would go into a new virtual environment, just so that your package module name isn’t confused with the name of the directory we were in, which was also named your package name. I like to just go to my top level project directory, create a new directory with poetry new, enter its virtual environment with poetry shell and pip install it from the test PyPI. Then I run the python interpreter in the virtual environment with poetry run python Now, import your package and functions in Python! You can first try: import my_package Next, try importing your functions. If they’re in the __init__.py you can import them directly, as in from my_package import my_function Or if they’re in a file at the same level as the __init__.py, you’ll specify the file name without the .py to get its module name. e.g. utils.py is just called utils. from my_package.my_module import my_function If there’s a folder at that level, with .py files in it, turn the folder into a package by adding an __init__.py to that folder too. The init files can be empty. So if my_package is the whole library,inside the my_package folder is my_subpackage folder, which contains .py files and an init file,inside my_subpackage folder is my_module.pyinside my_module.py lives my_function, my_package is the whole library, inside the my_package folder is my_subpackage folder, which contains .py files and an init file, inside my_subpackage folder is my_module.py inside my_module.py lives my_function, it would be: from my_package.my_subpackage.my_module import my_function You can also check what functions are in an imported module with: dir(my_package.my_module) Bonus: Updating all dependencies with poetry update Why is there always a bonus section about updating things? Anyway, in order to update all the libraries (dependencies) and write them to your poetry.lock, you run: poetry update Don’t confuse that with updating poetry, which can be done via pip install --upgrade poetry or poetry self update Thanks for reading! Please follow me to learn more about Python and Data Science! Check out Part 1 of this guide to learn how to publish to PyPI the old fashioned way with a setup.py, some others tips, plus some good humor. I was on a roll that day:
[ { "code": null, "e": 274, "s": 171, "text": "In the last edition of this guide, we published a python package to PyPI using a traditional setup.py." }, { "code": null, "e": 472, "s": 274, "text": "It required a strange Manifest.in file, didn’t come with any testing, and we didn’t even discuss dependency management with a requirements.txt. Why? Because that is not the way in 2021, my friends." }, { "code": null, "e": 647, "s": 472, "text": "Dependency management is about the Python libraries used by your package. If you import numpy and use its classes/functions, your package will depend on the version of numpy." }, { "code": null, "e": 831, "s": 647, "text": "If a new version of numpy uses different syntax or gets rid of a function, then your package won’t work on that version of numpy. We need to keep track of what version you were using." }, { "code": null, "e": 972, "s": 831, "text": "Or what if you use numpy and pandas, and they both depend on different versions of some other library. Who will keep track of these things?!" }, { "code": null, "e": 985, "s": 972, "text": "Poetry will." }, { "code": null, "e": 1138, "s": 985, "text": "Poetry is a Python library that we can use to create a package, publish it to PyPI more easily, AND it will deal with dependency management for us. Yay!" }, { "code": null, "e": 1177, "s": 1138, "text": "To get started, we just install poetry" }, { "code": null, "e": 1196, "s": 1177, "text": "pip install poetry" }, { "code": null, "e": 1264, "s": 1196, "text": "As always, try pip3 (the version for python3)if you don’t have pip." }, { "code": null, "e": 1275, "s": 1264, "text": "Poetry new" }, { "code": null, "e": 1390, "s": 1275, "text": "Our first command is to create the directory. No more mkdir’s at the beginning of our project when we have poetry." }, { "code": null, "e": 1642, "s": 1390, "text": "Really, don’t make a directory for your project before you do this, because poetry is going to create a directory with your project name and put everything in there including a subdirectory also named for your project, where the source code will live." }, { "code": null, "e": 1799, "s": 1642, "text": "So if you make a directory for your project and do this in there, you’re gonna end up with a russian doll situation: my_package/my_package/my_package/yikes." }, { "code": null, "e": 1927, "s": 1799, "text": "Instead, just go to the directory where all your packages will live (so when you run ls, you see your other projects), and run:" }, { "code": null, "e": 1938, "s": 1927, "text": "poetry new" }, { "code": null, "e": 2040, "s": 1938, "text": "Now you can see your poetry directory with all its parts, inclduing the all-important pyproject.toml." }, { "code": null, "e": 2093, "s": 2040, "text": "And now we can start building a package with Poetry!" }, { "code": null, "e": 2114, "s": 2093, "text": "Virtual environments" }, { "code": null, "e": 2186, "s": 2114, "text": "But first, a quick detour on how poetry works as a virtual environment." }, { "code": null, "e": 2342, "s": 2186, "text": "A virtual environment is an isolated digital environment where libraries, codes and interpreters are completely separated from the others on your computer." }, { "code": null, "e": 2474, "s": 2342, "text": "If you go in a digital environment and try to import numpy, it won’t exist, because it isn’t installed in that digital environment." }, { "code": null, "e": 2588, "s": 2474, "text": "Conversely, if you install a library in a digital environment, it wont be installed on the rest of your computer." }, { "code": null, "e": 2847, "s": 2588, "text": "Essentially, the libraries available in an environment are all stored in some directory in that environment. A virtual environment uses its own directory of available libraries, so it has no relationship with your computer’s directory of available libraries." }, { "code": null, "e": 3047, "s": 2847, "text": "When we ran poetry new, we created a virtual environment! When we run code from the command line while in a poetry directory, we are not in the virtual environment. However if we start a command with" }, { "code": null, "e": 3082, "s": 3047, "text": "poetry run the-rest-of-the-command" }, { "code": null, "e": 3138, "s": 3082, "text": "then we can run that command in the poetry environment." }, { "code": null, "e": 3152, "s": 3138, "text": "Or, if we run" }, { "code": null, "e": 3165, "s": 3152, "text": "poetry shell" }, { "code": null, "e": 3293, "s": 3165, "text": "then we will enter our poetry folder’s virtual environment, where we can use the libraries that we will install through poetry." }, { "code": null, "e": 3327, "s": 3293, "text": "Exit a virtual shell with ctrl+d." }, { "code": null, "e": 3338, "s": 3327, "text": "Poetry add" }, { "code": null, "e": 3436, "s": 3338, "text": "Indeed let’s look at installing libraries with poetry, which will manage our dependencies nicely." }, { "code": null, "e": 3522, "s": 3436, "text": "Let’s go into that pyproject.toml we created. It’s going to contain two major things:" }, { "code": null, "e": 3730, "s": 3522, "text": "The documentation for our project (well, including referencing the README and LICENSE). We’ll get back to documentation after we finish this libraries business.The range of library versions our package needs" }, { "code": null, "e": 3891, "s": 3730, "text": "The documentation for our project (well, including referencing the README and LICENSE). We’ll get back to documentation after we finish this libraries business." }, { "code": null, "e": 3939, "s": 3891, "text": "The range of library versions our package needs" }, { "code": null, "e": 4062, "s": 3939, "text": "When we make our package, we’ll need to tell poetry what versions of libraries we are using. That’s easy with the command:" }, { "code": null, "e": 4086, "s": 4062, "text": "poetry add library-name" }, { "code": null, "e": 4163, "s": 4086, "text": "where library-name is the name of whatever library we are using, like numpy." }, { "code": null, "e": 4378, "s": 4163, "text": "That command will add the library version to our pyproject.toml. It’s really a range of versions following semantic versioning. You can see the syntax here: https://classic.yarnpkg.com/en/docs/dependency-versions/." }, { "code": null, "e": 4446, "s": 4378, "text": "It will also install the library in our Poetry virtual environment." }, { "code": null, "e": 4458, "s": 4446, "text": "poetry.lock" }, { "code": null, "e": 4631, "s": 4458, "text": "If you poetry add a library, which will also install that library, you’ll not only see your pyproject.toml automatically updated — you’ll also gain a new file: poetry.lock." }, { "code": null, "e": 4798, "s": 4631, "text": "That pyproject.toml notes the range of library versions that are acceptable for your package, and only lists the libraries that you’ve directly added with poetry add." }, { "code": null, "e": 4961, "s": 4798, "text": "On the other hand, the poetry.lock notes the exact library versions that are installed in your package. And it includes every library that your dependencies need." }, { "code": null, "e": 4991, "s": 4961, "text": "So if you poetry add seaborn," }, { "code": null, "e": 5046, "s": 4991, "text": "then while your pyproject.toml will just gain seaborn," }, { "code": null, "e": 5074, "s": 5046, "text": "your poetry.lock will gain:" }, { "code": null, "e": 5290, "s": 5074, "text": "atomicwrites, attrs, colorama, cycler, fonttools, kiwisolver, matplotlib, more-itertools, numpy, packaing, pandas, pillow, pluggy, py, pyparsing, pytest, pytz, scipy, setuptools-scm, six, tomli, wcwidth, and seaborn" }, { "code": null, "e": 5472, "s": 5290, "text": "because that’s every library that seaborn depends on, plus every library that each of those depend on, recursively until every library that seaborn needs has the libraries it needs." }, { "code": null, "e": 5515, "s": 5472, "text": "Side note on others using your source code" }, { "code": null, "e": 5659, "s": 5515, "text": "Now, if someone clones your package from github, they will have your pyproject.toml, but didn’t install your libraries yet. They’ll need to run" }, { "code": null, "e": 5674, "s": 5659, "text": "poetry install" }, { "code": null, "e": 5775, "s": 5674, "text": "If they also have your poetry.lock, they will install the exact versions stated in your poetry.lock." }, { "code": null, "e": 5927, "s": 5775, "text": "If they don’t have your poetry.lock, then poetry will do what it did for you — figure out the write versions to install, and write it in a poetry.lock." }, { "code": null, "e": 6094, "s": 5927, "text": "In summary, the poetry.lock lists all exact library versions installed when a package runs, so that users of your package can all use the same versions of everything." }, { "code": null, "e": 6134, "s": 6094, "text": "Project Description with pyproject.toml" }, { "code": null, "e": 6258, "s": 6134, "text": "Alrighty so I’ll skip toward the PyPI publishing ASAP, we just need to be a bit decent with our package documentation here." }, { "code": null, "e": 6404, "s": 6258, "text": "That section on the top of your pyproject.toml will contain everything that setup.py contains in the traditional packaging method without Poetry." }, { "code": null, "e": 6453, "s": 6404, "text": "The top of your pyproject.toml should look like:" }, { "code": null, "e": 6468, "s": 6453, "text": "pyproject.toml" }, { "code": null, "e": 7005, "s": 6468, "text": "[tool.poetry]name = “” #your package nameversion = “0.0.1”description = “” #a short description of your package that will be used in PyPI searchauthors = [“your-name <your-email>”]license = “MIT”readme = “README.md”homepage = “” #can be the reporepository = “”keywords = [“test”, “dependencies”, “documentation”]classifiers = [“Development Status :: 5 — Production/Stable”,“Intended Audience :: Education”,“Operating System :: MacOS”,“License :: OSI Approved :: MIT License”,“Programming Language :: Python :: 3”,]include = [“LICENSE”,]" }, { "code": null, "e": 7259, "s": 7005, "text": "Go ahead and copy that into your toml and update the fields: fill in your name and email, project name and version, short description, repo/homepage, and fill out those classifiers using the options here: https://pypi.org/pypi?%3Aaction=list_classifiers" }, { "code": null, "e": 7486, "s": 7259, "text": "As you can see, we are referencing a README.md, so change your README.rst to an md (markdown) file if you like. You’ll put the long project description including the change log in that README.md, so it can look something like:" }, { "code": null, "e": 7496, "s": 7486, "text": "README.md" }, { "code": null, "e": 7701, "s": 7496, "text": "My long description blah blah blah blah.Change Log================0.0.1 (Dec 1, 2021) — — — — — — — — — — — — — — — -- First Release0.0.2 (Dec 2, 2021) — — — — — — — — — — — — — — — -- Did some more stuff" }, { "code": null, "e": 7720, "s": 7701, "text": "Publishing to PyPI" }, { "code": null, "e": 7809, "s": 7720, "text": "Okay here we go. I’ll skip to the juicy part, and then I’ll go back and offer some tips." }, { "code": null, "e": 7896, "s": 7809, "text": "You can publish to PyPI in one line. Afffter you setup your credentials one time with:" }, { "code": null, "e": 7944, "s": 7896, "text": "poetry config http-basic.pypi username password" }, { "code": null, "e": 8045, "s": 7944, "text": "Those are your credentials from pypi.org, which you can get from making an account on their webpage." }, { "code": null, "e": 8116, "s": 8045, "text": "After you set up those credentials, then here’s that one line publish:" }, { "code": null, "e": 8150, "s": 8116, "text": "poetry publish --build my_package" }, { "code": null, "e": 8185, "s": 8150, "text": "And you’re on PyPI just like that!" }, { "code": null, "e": 8321, "s": 8185, "text": "There is a separate poetry build command but you can just do the build at the same time as the publish with that build flag ( — build)." }, { "code": null, "e": 8342, "s": 8321, "text": "Testing on Test PyPI" }, { "code": null, "e": 8448, "s": 8342, "text": "But maybe before we go throwing our half-baked package on PyPI, we can test it on a test version of PyPI." }, { "code": null, "e": 8572, "s": 8448, "text": "This test PyPI will allow us to mimic updating to PyPI, then pip installing our own package to see if it works as expected." }, { "code": null, "e": 8734, "s": 8572, "text": "The first step to do this is to make a new account on test.pypi.org (yes, you need a separate account from your pypi account, but it can have the same username)." }, { "code": null, "e": 8777, "s": 8734, "text": "You can then add the repository to poetry:" }, { "code": null, "e": 8843, "s": 8777, "text": "poetry config repositories.testpypi https://test.pypi.org/legacy/" }, { "code": null, "e": 8871, "s": 8843, "text": "publish to that repository:" }, { "code": null, "e": 8906, "s": 8871, "text": "poetry publish –-build -r testpypi" }, { "code": null, "e": 8957, "s": 8906, "text": "and pip install your package from that repository:" }, { "code": null, "e": 9022, "s": 8957, "text": "pip install --index-url https://test.pypi.org/simple/ my_package" }, { "code": null, "e": 9064, "s": 9022, "text": "Sidebar: Troubleshooting that pip install" }, { "code": null, "e": 9158, "s": 9064, "text": "If you’re having trouble, this longer command line function solves some of the common issues:" }, { "code": null, "e": 9274, "s": 9158, "text": "python3 -m pip install -i https://test.pypi.org/simple/ — extra-index-url https://pypi.org/simple my_package==0.0.1" }, { "code": null, "e": 9422, "s": 9274, "text": "The python -m before pip is to make sure you’re using the right pip version. You can also try looking into your pip version and python version with" }, { "code": null, "e": 9474, "s": 9422, "text": "which pipwhich pythonpip --versionpython --version " }, { "code": null, "e": 9495, "s": 9474, "text": "or updating pip with" }, { "code": null, "e": 9532, "s": 9495, "text": " python -m pip install --upgrade pip" }, { "code": null, "e": 9605, "s": 9532, "text": "As always you might need to switch python with python3 or pip with pip3." }, { "code": null, "e": 9732, "s": 9605, "text": "The extra index url points to the normal PyPI repo (rather than the test), which your dependencies need to be downloaded from." }, { "code": null, "e": 9860, "s": 9732, "text": "Finally, I’ve also added the version, which you should replace with your package version number, so that it gets the right one." }, { "code": null, "e": 9914, "s": 9860, "text": "Installing and importing in a new virtual environment" }, { "code": null, "e": 10130, "s": 9914, "text": "When you’re trying that pip install, I would go into a new virtual environment, just so that your package module name isn’t confused with the name of the directory we were in, which was also named your package name." }, { "code": null, "e": 10258, "s": 10130, "text": "I like to just go to my top level project directory, create a new directory with poetry new, enter its virtual environment with" }, { "code": null, "e": 10271, "s": 10258, "text": "poetry shell" }, { "code": null, "e": 10310, "s": 10271, "text": "and pip install it from the test PyPI." }, { "code": null, "e": 10376, "s": 10310, "text": "Then I run the python interpreter in the virtual environment with" }, { "code": null, "e": 10394, "s": 10376, "text": "poetry run python" }, { "code": null, "e": 10463, "s": 10394, "text": "Now, import your package and functions in Python! You can first try:" }, { "code": null, "e": 10481, "s": 10463, "text": "import my_package" }, { "code": null, "e": 10583, "s": 10481, "text": "Next, try importing your functions. If they’re in the __init__.py you can import them directly, as in" }, { "code": null, "e": 10618, "s": 10583, "text": "from my_package import my_function" }, { "code": null, "e": 10785, "s": 10618, "text": "Or if they’re in a file at the same level as the __init__.py, you’ll specify the file name without the .py to get its module name. e.g. utils.py is just called utils." }, { "code": null, "e": 10830, "s": 10785, "text": "from my_package.my_module import my_function" }, { "code": null, "e": 10992, "s": 10830, "text": "If there’s a folder at that level, with .py files in it, turn the folder into a package by adding an __init__.py to that folder too. The init files can be empty." }, { "code": null, "e": 10998, "s": 10992, "text": "So if" }, { "code": null, "e": 11208, "s": 10998, "text": "my_package is the whole library,inside the my_package folder is my_subpackage folder, which contains .py files and an init file,inside my_subpackage folder is my_module.pyinside my_module.py lives my_function," }, { "code": null, "e": 11241, "s": 11208, "text": "my_package is the whole library," }, { "code": null, "e": 11338, "s": 11241, "text": "inside the my_package folder is my_subpackage folder, which contains .py files and an init file," }, { "code": null, "e": 11382, "s": 11338, "text": "inside my_subpackage folder is my_module.py" }, { "code": null, "e": 11421, "s": 11382, "text": "inside my_module.py lives my_function," }, { "code": null, "e": 11434, "s": 11421, "text": "it would be:" }, { "code": null, "e": 11493, "s": 11434, "text": "from my_package.my_subpackage.my_module import my_function" }, { "code": null, "e": 11559, "s": 11493, "text": "You can also check what functions are in an imported module with:" }, { "code": null, "e": 11585, "s": 11559, "text": "dir(my_package.my_module)" }, { "code": null, "e": 11637, "s": 11585, "text": "Bonus: Updating all dependencies with poetry update" }, { "code": null, "e": 11696, "s": 11637, "text": "Why is there always a bonus section about updating things?" }, { "code": null, "e": 11801, "s": 11696, "text": "Anyway, in order to update all the libraries (dependencies) and write them to your poetry.lock, you run:" }, { "code": null, "e": 11815, "s": 11801, "text": "poetry update" }, { "code": null, "e": 11878, "s": 11815, "text": "Don’t confuse that with updating poetry, which can be done via" }, { "code": null, "e": 11907, "s": 11878, "text": "pip install --upgrade poetry" }, { "code": null, "e": 11910, "s": 11907, "text": "or" }, { "code": null, "e": 11929, "s": 11910, "text": "poetry self update" }, { "code": null, "e": 11949, "s": 11929, "text": "Thanks for reading!" }, { "code": null, "e": 12011, "s": 11949, "text": "Please follow me to learn more about Python and Data Science!" } ]
Python 3 - Tkinter Menubutton
A menubutton is the part of a drop-down menu that stays on the screen all the time. Every menubutton is associated with a Menu widget that can display the choices for that menubutton when the user clicks on it. Here is the simple syntax to create this widget − w = Menubutton ( master, option, ... ) master − This represents the parent window. master − This represents the parent window. options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas. options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas. activebackground The background color when the mouse is over the menubutton. activeforeground The foreground color when the mouse is over the menubutton. anchor This options controls where the text is positioned if the widget has more space than the text needs. The default is anchor = CENTER, which centers the text. bg The normal background color displayed behind the label and indicator. bitmap To display a bitmap on the menubutton, set this option to a bitmap name. bd The size of the border around the indicator. Default is 2 pixels. cursor The cursor that appears when the mouse is over this menubutton. direction Set direction = LEFT to display the menu to the left of the button; use direction = RIGHT to display the menu to the right of the button; or use direction = 'above' to place the menu above the button. disabledforeground The foreground color shown on this menubutton when it is disabled. fg The foreground color when the mouse is not over the menubutton. height The height of the menubutton in lines of text (not pixels!). The default is to fit the menubutton's size to its contents. highlightcolor Color shown in the focus highlight when the widget has the focus. image To display an image on this menubutton, justify This option controls where the text is located when the text doesn't fill the menubutton: use justify = LEFT to left-justify the text (this is the default); use justify = CENTER to center it, or justify = RIGHT to right-justify. menu To associate the menubutton with a set of choices, set this option to the Menu object containing those choices. That menu object must have been created by passing the associated menubutton to the constructor as its first argument. padx How much space to leave to the left and right of the text of the menubutton. Default is 1. pady How much space to leave above and below the text of the menubutton. Default is 1. relief Selects three-dimensional border shading effects. The default is RAISED. state Normally, menubuttons respond to the mouse. Set state = DISABLED to gray out the menubutton and make it unresponsive. text To display text on the menubutton, set this option to the string containing the desired text. Newlines ("\n") within the string will cause line breaks. textvariable You can associate a control variable of class StringVar with this menubutton. Setting that control variable will change the displayed text. underline Normally, no underline appears under the text on the menubutton. To underline one of the characters, set this option to the index of that character. width The width of the widget in characters. The default is 20. wraplength Normally, lines are not wrapped. You can set this option to a number of characters and all lines will be broken into pieces no longer than that number. Try the following example yourself − # !/usr/bin/python3 from tkinter import * import tkinter top = Tk() mb = Menubutton ( top, text = "condiments", relief = RAISED ) mb.grid() mb.menu = Menu ( mb, tearoff = 0 ) mb["menu"] = mb.menu mayoVar = IntVar() ketchVar = IntVar() mb.menu.add_checkbutton ( label = "mayo", variable = mayoVar ) mb.menu.add_checkbutton ( label = "ketchup", variable = ketchVar ) mb.pack() top.mainloop() When the above code is executed, it produces the following result − 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": 2551, "s": 2340, "text": "A menubutton is the part of a drop-down menu that stays on the screen all the time. Every menubutton is associated with a Menu widget that can display the choices for that menubutton when the user clicks on it." }, { "code": null, "e": 2601, "s": 2551, "text": "Here is the simple syntax to create this widget −" }, { "code": null, "e": 2641, "s": 2601, "text": "w = Menubutton ( master, option, ... )\n" }, { "code": null, "e": 2685, "s": 2641, "text": "master − This represents the parent window." }, { "code": null, "e": 2729, "s": 2685, "text": "master − This represents the parent window." }, { "code": null, "e": 2869, "s": 2729, "text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas." }, { "code": null, "e": 3009, "s": 2869, "text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas." }, { "code": null, "e": 3026, "s": 3009, "text": "activebackground" }, { "code": null, "e": 3086, "s": 3026, "text": "The background color when the mouse is over the menubutton." }, { "code": null, "e": 3103, "s": 3086, "text": "activeforeground" }, { "code": null, "e": 3163, "s": 3103, "text": "The foreground color when the mouse is over the menubutton." }, { "code": null, "e": 3170, "s": 3163, "text": "anchor" }, { "code": null, "e": 3327, "s": 3170, "text": "This options controls where the text is positioned if the widget has more space than the text needs. The default is anchor = CENTER, which centers the text." }, { "code": null, "e": 3330, "s": 3327, "text": "bg" }, { "code": null, "e": 3400, "s": 3330, "text": "The normal background color displayed behind the label and indicator." }, { "code": null, "e": 3407, "s": 3400, "text": "bitmap" }, { "code": null, "e": 3480, "s": 3407, "text": "To display a bitmap on the menubutton, set this option to a bitmap name." }, { "code": null, "e": 3483, "s": 3480, "text": "bd" }, { "code": null, "e": 3549, "s": 3483, "text": "The size of the border around the indicator. Default is 2 pixels." }, { "code": null, "e": 3556, "s": 3549, "text": "cursor" }, { "code": null, "e": 3620, "s": 3556, "text": "The cursor that appears when the mouse is over this menubutton." }, { "code": null, "e": 3630, "s": 3620, "text": "direction" }, { "code": null, "e": 3831, "s": 3630, "text": "Set direction = LEFT to display the menu to the left of the button; use direction = RIGHT to display the menu to the right of the button; or use direction = 'above' to place the menu above the button." }, { "code": null, "e": 3850, "s": 3831, "text": "disabledforeground" }, { "code": null, "e": 3917, "s": 3850, "text": "The foreground color shown on this menubutton when it is disabled." }, { "code": null, "e": 3920, "s": 3917, "text": "fg" }, { "code": null, "e": 3984, "s": 3920, "text": "The foreground color when the mouse is not over the menubutton." }, { "code": null, "e": 3991, "s": 3984, "text": "height" }, { "code": null, "e": 4113, "s": 3991, "text": "The height of the menubutton in lines of text (not pixels!). The default is to fit the menubutton's size to its contents." }, { "code": null, "e": 4128, "s": 4113, "text": "highlightcolor" }, { "code": null, "e": 4194, "s": 4128, "text": "Color shown in the focus highlight when the widget has the focus." }, { "code": null, "e": 4200, "s": 4194, "text": "image" }, { "code": null, "e": 4240, "s": 4200, "text": "To display an image on this menubutton," }, { "code": null, "e": 4248, "s": 4240, "text": "justify" }, { "code": null, "e": 4477, "s": 4248, "text": "This option controls where the text is located when the text doesn't fill the menubutton: use justify = LEFT to left-justify the text (this is the default); use justify = CENTER to center it, or justify = RIGHT to right-justify." }, { "code": null, "e": 4482, "s": 4477, "text": "menu" }, { "code": null, "e": 4713, "s": 4482, "text": "To associate the menubutton with a set of choices, set this option to the Menu object containing those choices. That menu object must have been created by passing the associated menubutton to the constructor as its first argument." }, { "code": null, "e": 4718, "s": 4713, "text": "padx" }, { "code": null, "e": 4809, "s": 4718, "text": "How much space to leave to the left and right of the text of the menubutton. Default is 1." }, { "code": null, "e": 4814, "s": 4809, "text": "pady" }, { "code": null, "e": 4896, "s": 4814, "text": "How much space to leave above and below the text of the menubutton. Default is 1." }, { "code": null, "e": 4903, "s": 4896, "text": "relief" }, { "code": null, "e": 4976, "s": 4903, "text": "Selects three-dimensional border shading effects. The default is RAISED." }, { "code": null, "e": 4982, "s": 4976, "text": "state" }, { "code": null, "e": 5100, "s": 4982, "text": "Normally, menubuttons respond to the mouse. Set state = DISABLED to gray out the menubutton and make it unresponsive." }, { "code": null, "e": 5105, "s": 5100, "text": "text" }, { "code": null, "e": 5257, "s": 5105, "text": "To display text on the menubutton, set this option to the string containing the desired text. Newlines (\"\\n\") within the string will cause line breaks." }, { "code": null, "e": 5270, "s": 5257, "text": "textvariable" }, { "code": null, "e": 5410, "s": 5270, "text": "You can associate a control variable of class StringVar with this menubutton. Setting that control variable will change the displayed text." }, { "code": null, "e": 5420, "s": 5410, "text": "underline" }, { "code": null, "e": 5569, "s": 5420, "text": "Normally, no underline appears under the text on the menubutton. To underline one of the characters, set this option to the index of that character." }, { "code": null, "e": 5575, "s": 5569, "text": "width" }, { "code": null, "e": 5633, "s": 5575, "text": "The width of the widget in characters. The default is 20." }, { "code": null, "e": 5644, "s": 5633, "text": "wraplength" }, { "code": null, "e": 5796, "s": 5644, "text": "Normally, lines are not wrapped. You can set this option to a number of characters and all lines will be broken into pieces no longer than that number." }, { "code": null, "e": 5833, "s": 5796, "text": "Try the following example yourself −" }, { "code": null, "e": 6291, "s": 5833, "text": "# !/usr/bin/python3\nfrom tkinter import *\n\nimport tkinter\n\ntop = Tk()\n\nmb = Menubutton ( top, text = \"condiments\", relief = RAISED )\nmb.grid()\nmb.menu = Menu ( mb, tearoff = 0 )\nmb[\"menu\"] = mb.menu\n \nmayoVar = IntVar()\nketchVar = IntVar()\n\nmb.menu.add_checkbutton ( label = \"mayo\",\n variable = mayoVar )\nmb.menu.add_checkbutton ( label = \"ketchup\",\n variable = ketchVar )\n\nmb.pack()\ntop.mainloop()" }, { "code": null, "e": 6360, "s": 6291, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 6397, "s": 6360, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6413, "s": 6397, "text": " Malhar Lathkar" }, { "code": null, "e": 6446, "s": 6413, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 6465, "s": 6446, "text": " Arnab Chakraborty" }, { "code": null, "e": 6500, "s": 6465, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 6522, "s": 6500, "text": " In28Minutes Official" }, { "code": null, "e": 6556, "s": 6522, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 6584, "s": 6556, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6619, "s": 6584, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6633, "s": 6619, "text": " Lets Kode It" }, { "code": null, "e": 6666, "s": 6633, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 6683, "s": 6666, "text": " Abhilash Nelson" }, { "code": null, "e": 6690, "s": 6683, "text": " Print" }, { "code": null, "e": 6701, "s": 6690, "text": " Add Notes" } ]
Program to design parking system in Python
Suppose you want to design a parking system. A parking lot has three different kinds of parking spaces − big, medium, and small. And there are fixed number of slots for each size. Make a class called OurParkingSystem with of two methods − constructor(big, medium, small) − This constructor is taking the number of slots available for different spaces and initializes object of the OurParkingSystem class. constructor(big, medium, small) − This constructor is taking the number of slots available for different spaces and initializes object of the OurParkingSystem class. addCar(carType) − This method checks whether there is a parking space of given carType for the car that wants to put inside the parking lot. addCar(carType) − This method checks whether there is a parking space of given carType for the car that wants to put inside the parking lot. The three slots big, medium, or small, are represented by 1, 2, and 3 respectively. The constraint is a car can only park in a parking space if carType is matched. If there is no space available, return false, otherwise park the car in that size space and return true. If there are 2 spaces for big car, no space for medium car and 1 space for small car, then constructor call will be like OurParkingSystem(2, 0, 1), and if we call addCar like − addCar(3) − add one small car and return true addCar(2) − No space to add medium car so return false addCar(3) − No space to add a new small car so return false addCar(1) − add one big car and return true addCar(1) − add another big car and return true addCar(1) − No space for another big car so return false To solve this, we will follow these steps − Define a function constructor() . This will take big, medium, small Define a function constructor() . This will take big, medium, small sp := a list like [0,big,medium,small] sp := a list like [0,big,medium,small] Define a function addCar() . This will take carType Define a function addCar() . This will take carType if sp[carType] > 0, thensp[carType] := sp[carType] - 1return True if sp[carType] > 0, then sp[carType] := sp[carType] - 1 sp[carType] := sp[carType] - 1 return True return True return False return False Let us see the following implementation to get better understanding − Live Demo class OurParkingSystem: def __init__(self, big, medium, small): self.sp = [0,big,medium,small] def addCar(self, carType): if(self.sp[carType] >0 ): self.sp[carType] -= 1 return True return False ps = OurParkingSystem(2, 0, 1) print(ps.addCar(3)) print(ps.addCar(2)) print(ps.addCar(3)) print(ps.addCar(1)) print(ps.addCar(1)) print(ps.addCar(1)) ps.addCar(3) ps.addCar(2) ps.addCar(3) ps.addCar(1) ps.addCar(1) ps.addCar(1) True False False True True False
[ { "code": null, "e": 1301, "s": 1062, "text": "Suppose you want to design a parking system. A parking lot has three different kinds of parking spaces − big, medium, and small. And there are fixed number of slots for each size. Make a class called OurParkingSystem with of two methods −" }, { "code": null, "e": 1467, "s": 1301, "text": "constructor(big, medium, small) − This constructor is taking the number of slots available for different spaces and initializes object of the OurParkingSystem class." }, { "code": null, "e": 1633, "s": 1467, "text": "constructor(big, medium, small) − This constructor is taking the number of slots available for different spaces and initializes object of the OurParkingSystem class." }, { "code": null, "e": 1774, "s": 1633, "text": "addCar(carType) − This method checks whether there is a parking space of given carType for the car that wants to put inside the parking lot." }, { "code": null, "e": 1915, "s": 1774, "text": "addCar(carType) − This method checks whether there is a parking space of given carType for the car that wants to put inside the parking lot." }, { "code": null, "e": 2184, "s": 1915, "text": "The three slots big, medium, or small, are represented by 1, 2, and 3 respectively. The constraint is a car can only park in a parking space if carType is matched. If there is no space available, return false, otherwise park the car in that size space and return true." }, { "code": null, "e": 2361, "s": 2184, "text": "If there are 2 spaces for big car, no space for medium car and 1 space for small car, then constructor call will be like OurParkingSystem(2, 0, 1), and if we call addCar like −" }, { "code": null, "e": 2407, "s": 2361, "text": "addCar(3) − add one small car and return true" }, { "code": null, "e": 2462, "s": 2407, "text": "addCar(2) − No space to add medium car so return false" }, { "code": null, "e": 2522, "s": 2462, "text": "addCar(3) − No space to add a new small car so return false" }, { "code": null, "e": 2566, "s": 2522, "text": "addCar(1) − add one big car and return true" }, { "code": null, "e": 2614, "s": 2566, "text": "addCar(1) − add another big car and return true" }, { "code": null, "e": 2671, "s": 2614, "text": "addCar(1) − No space for another big car so return false" }, { "code": null, "e": 2715, "s": 2671, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 2783, "s": 2715, "text": "Define a function constructor() . This will take big, medium, small" }, { "code": null, "e": 2851, "s": 2783, "text": "Define a function constructor() . This will take big, medium, small" }, { "code": null, "e": 2890, "s": 2851, "text": "sp := a list like [0,big,medium,small]" }, { "code": null, "e": 2929, "s": 2890, "text": "sp := a list like [0,big,medium,small]" }, { "code": null, "e": 2981, "s": 2929, "text": "Define a function addCar() . This will take carType" }, { "code": null, "e": 3033, "s": 2981, "text": "Define a function addCar() . This will take carType" }, { "code": null, "e": 3099, "s": 3033, "text": "if sp[carType] > 0, thensp[carType] := sp[carType] - 1return True" }, { "code": null, "e": 3124, "s": 3099, "text": "if sp[carType] > 0, then" }, { "code": null, "e": 3155, "s": 3124, "text": "sp[carType] := sp[carType] - 1" }, { "code": null, "e": 3186, "s": 3155, "text": "sp[carType] := sp[carType] - 1" }, { "code": null, "e": 3198, "s": 3186, "text": "return True" }, { "code": null, "e": 3210, "s": 3198, "text": "return True" }, { "code": null, "e": 3223, "s": 3210, "text": "return False" }, { "code": null, "e": 3236, "s": 3223, "text": "return False" }, { "code": null, "e": 3306, "s": 3236, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3317, "s": 3306, "text": " Live Demo" }, { "code": null, "e": 3707, "s": 3317, "text": "class OurParkingSystem:\n def __init__(self, big, medium, small):\n self.sp = [0,big,medium,small]\n\n def addCar(self, carType):\n if(self.sp[carType] >0 ):\n self.sp[carType] -= 1\n return True\n return False\n\nps = OurParkingSystem(2, 0, 1)\nprint(ps.addCar(3))\nprint(ps.addCar(2))\nprint(ps.addCar(3))\nprint(ps.addCar(1))\nprint(ps.addCar(1))\nprint(ps.addCar(1))" }, { "code": null, "e": 3785, "s": 3707, "text": "ps.addCar(3)\nps.addCar(2)\nps.addCar(3)\nps.addCar(1)\nps.addCar(1)\nps.addCar(1)" }, { "code": null, "e": 3818, "s": 3785, "text": "True\nFalse\nFalse\nTrue\nTrue\nFalse" } ]
iText - Scaling an Image
In this chapter, we will see how to scale an image in a PDF document using the iText library. You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter to its constructor. To add image to the PDF, create an object of the image that is required to be added and add it using the add() method of the Document class. You can scale an image using the setAutoScale() method. Following are the steps to scale an image that exists on the PDF document. The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created. Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below. // Creating a PdfWriter String dest = "C:/itextExamples/autoScale.pdf"; PdfWriter writer = new PdfWriter(dest); When an object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified. The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor. Instantiate the PdfDocument class by passing the above created PdfWriter object to its constructor, as shown below. // Creating a PdfDocument PdfDocument pdfDoc = new PdfDocument(writer); Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class. The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument. Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps, as shown below. // Creating a Document Document document = new Document(pdfDoc); To create an image object, first of all, create an ImageData object using the create() method of the ImageDataFactory class. As a parameter of this method, pass a string parameter representing the path of the image, as shown below. // Creating an ImageData object String imageFile = "C:/itextExamples/javafxLogo.jpg"; ImageData data = ImageDataFactory.create(imageFile); Now, instantiate the Image class of the com.itextpdf.layout.element package. While instantiating, pass the ImageData object as a parameter to its constructor, as shown below. // Creating an Image object Image img = new Image(data); You can scale an image using the setAutoScale() method. // Setting the position of the image to the center of the page image.setFixedPosition(100, 250); Now, add the image object created in the previous step using the add() method of the Document class, as shown below. // Adding image to the document document.add(img); Close the document using the close() method of the Document class, as shown below. // Closing the document document.close(); The following Java program demonstrates how to scale an image with respective to the document size on a PDF document using the iText library. It creates a PDF document with the name autoScale.pdf, adds an image to it, scales it with respect to the page dimensions, saves it in the path C:/itextExamples/. Save this code in a file with name SettingAutoScale.java. import com.itextpdf.io.image.ImageData; import com.itextpdf.io.image.ImageDataFactory; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Image; public class SettingAutoScale { public static void main(String args[]) throws Exception{ // Creating a PdfWriter String dest = "C:/itextExamples/positionOfImage.pdf"; PdfWriter writer = new PdfWriter(dest); // Creating a PdfDocument PdfDocument pdfDoc = new PdfDocument(writer); // Creating a Document Document document = new Document(pdfDoc); // Creating an ImageData object String imFile = "C:/itextExamples/logo.jpg"; ImageData data = ImageDataFactory.create(imFile); // Creating an Image object Image image = new Image(data); // Setting the position of the image to the center of the page image.setFixedPosition(100,250); // Adding image to the document document.add(image); // Closing the document document.close(); System.out.println("Image Scaled"); } } Compile and execute the saved Java file from the command prompt using the following commands. javac SettingAutoScale.java java SettingAutoScale Upon execution, the above program creates a PDF document displaying the following message. Image Scaled If you verify the specified path, you can find the created PDF document as shown below. Print Add Notes Bookmark this page
[ { "code": null, "e": 2462, "s": 2368, "text": "In this chapter, we will see how to scale an image in a PDF document using the iText library." }, { "code": null, "e": 2641, "s": 2462, "text": "You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter to its constructor." }, { "code": null, "e": 2838, "s": 2641, "text": "To add image to the PDF, create an object of the image that is required to be added and add it using the add() method of the Document class. You can scale an image using the setAutoScale() method." }, { "code": null, "e": 2913, "s": 2838, "text": "Following are the steps to scale an image that exists on the PDF document." }, { "code": null, "e": 3142, "s": 2913, "text": "The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created." }, { "code": null, "e": 3291, "s": 3142, "text": "Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below." }, { "code": null, "e": 3407, "s": 3291, "text": "// Creating a PdfWriter \nString dest = \"C:/itextExamples/autoScale.pdf\"; \nPdfWriter writer = new PdfWriter(dest); \n" }, { "code": null, "e": 3547, "s": 3407, "text": "When an object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified." }, { "code": null, "e": 3799, "s": 3547, "text": "The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor." }, { "code": null, "e": 3915, "s": 3799, "text": "Instantiate the PdfDocument class by passing the above created PdfWriter object to its constructor, as shown below." }, { "code": null, "e": 3991, "s": 3915, "text": "// Creating a PdfDocument \nPdfDocument pdfDoc = new PdfDocument(writer); \n" }, { "code": null, "e": 4162, "s": 3991, "text": "Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class." }, { "code": null, "e": 4356, "s": 4162, "text": "The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument." }, { "code": null, "e": 4481, "s": 4356, "text": "Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps, as shown below." }, { "code": null, "e": 4550, "s": 4481, "text": "// Creating a Document \nDocument document = new Document(pdfDoc);\n" }, { "code": null, "e": 4782, "s": 4550, "text": "To create an image object, first of all, create an ImageData object using the create() method of the ImageDataFactory class. As a parameter of this method, pass a string parameter representing the path of the image, as shown below." }, { "code": null, "e": 4925, "s": 4782, "text": "// Creating an ImageData object \nString imageFile = \"C:/itextExamples/javafxLogo.jpg\"; \nImageData data = ImageDataFactory.create(imageFile); \n" }, { "code": null, "e": 5100, "s": 4925, "text": "Now, instantiate the Image class of the com.itextpdf.layout.element package. While instantiating, pass the ImageData object as a parameter to its constructor, as shown below." }, { "code": null, "e": 5160, "s": 5100, "text": "// Creating an Image object \nImage img = new Image(data); \n" }, { "code": null, "e": 5216, "s": 5160, "text": "You can scale an image using the setAutoScale() method." }, { "code": null, "e": 5316, "s": 5216, "text": "// Setting the position of the image to the center of the page \nimage.setFixedPosition(100, 250); \n" }, { "code": null, "e": 5433, "s": 5316, "text": "Now, add the image object created in the previous step using the add() method of the Document class, as shown below." }, { "code": null, "e": 5487, "s": 5433, "text": "// Adding image to the document \ndocument.add(img); \n" }, { "code": null, "e": 5570, "s": 5487, "text": "Close the document using the close() method of the Document class, as shown below." }, { "code": null, "e": 5615, "s": 5570, "text": "// Closing the document \ndocument.close(); \n" }, { "code": null, "e": 5920, "s": 5615, "text": "The following Java program demonstrates how to scale an image with respective to the document size on a PDF document using the iText library. It creates a PDF document with the name autoScale.pdf, adds an image to it, scales it with respect to the page dimensions, saves it in the path C:/itextExamples/." }, { "code": null, "e": 5978, "s": 5920, "text": "Save this code in a file with name SettingAutoScale.java." }, { "code": null, "e": 7357, "s": 5978, "text": "import com.itextpdf.io.image.ImageData; \nimport com.itextpdf.io.image.ImageDataFactory; \n\nimport com.itextpdf.kernel.pdf.PdfDocument; \nimport com.itextpdf.kernel.pdf.PdfWriter; \n\nimport com.itextpdf.layout.Document; \nimport com.itextpdf.layout.element.Image; \n\npublic class SettingAutoScale { \n public static void main(String args[]) throws Exception{ \n // Creating a PdfWriter \n String dest = \"C:/itextExamples/positionOfImage.pdf\"; \n PdfWriter writer = new PdfWriter(dest); \n \n // Creating a PdfDocument \n PdfDocument pdfDoc = new PdfDocument(writer); \n \n // Creating a Document \n Document document = new Document(pdfDoc); \n \n // Creating an ImageData object \n String imFile = \"C:/itextExamples/logo.jpg\"; \n ImageData data = ImageDataFactory.create(imFile); \n \n // Creating an Image object \n Image image = new Image(data); \n \n // Setting the position of the image to the center of the page \n image.setFixedPosition(100,250); \n \n // Adding image to the document \n document.add(image); \n \n // Closing the document \n document.close();\n System.out.println(\"Image Scaled\"); \n } \n} " }, { "code": null, "e": 7451, "s": 7357, "text": "Compile and execute the saved Java file from the command prompt using the following commands." }, { "code": null, "e": 7504, "s": 7451, "text": "javac SettingAutoScale.java \njava SettingAutoScale \n" }, { "code": null, "e": 7595, "s": 7504, "text": "Upon execution, the above program creates a PDF document displaying the following message." }, { "code": null, "e": 7609, "s": 7595, "text": "Image Scaled\n" }, { "code": null, "e": 7697, "s": 7609, "text": "If you verify the specified path, you can find the created PDF document as shown below." }, { "code": null, "e": 7704, "s": 7697, "text": " Print" }, { "code": null, "e": 7715, "s": 7704, "text": " Add Notes" } ]
PostgreSQL - SELECT Database
This chapter explains various methods of accessing the database. Assume that we have already created a database in our previous chapter. You can select the database using either of the following methods − Database SQL Prompt OS Command Prompt Assume you have already launched your PostgreSQL client and you have landed at the following SQL prompt − postgres=# You can check the available database list using \l, i.e., backslash el command as follows − postgres-# \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -----------+----------+----------+---------+-------+----------------------- postgres | postgres | UTF8 | C | C | template0 | postgres | UTF8 | C | C | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | UTF8 | C | C | =c/postgres + | | | | | postgres=CTc/postgres testdb | postgres | UTF8 | C | C | (4 rows) postgres-# Now, type the following command to connect/select a desired database; here, we will connect to the testdb database. postgres=# \c testdb; psql (9.2.4) Type "help" for help. You are now connected to database "testdb" as user "postgres". testdb=# You can select your database from the command prompt itself at the time when you login to your database. Following is a simple example − psql -h localhost -p 5432 -U postgress testdb Password for user postgress: **** psql (9.2.4) Type "help" for help. You are now connected to database "testdb" as user "postgres". testdb=# You are now logged into PostgreSQL testdb and ready to execute your commands inside testdb. To exit from the database, you can use the command \q. 23 Lectures 1.5 hours John Elder 49 Lectures 3.5 hours Niyazi Erdogan 126 Lectures 10.5 hours Abhishek And Pukhraj 35 Lectures 5 hours Karthikeya T 5 Lectures 51 mins Vinay Kumar 5 Lectures 52 mins Vinay Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 3030, "s": 2825, "text": "This chapter explains various methods of accessing the database. Assume that we have already created a database in our previous chapter. You can select the database using either of the following methods −" }, { "code": null, "e": 3050, "s": 3030, "text": "Database SQL Prompt" }, { "code": null, "e": 3068, "s": 3050, "text": "OS Command Prompt" }, { "code": null, "e": 3174, "s": 3068, "text": "Assume you have already launched your PostgreSQL client and you have landed at the following SQL prompt −" }, { "code": null, "e": 3186, "s": 3174, "text": "postgres=#\n" }, { "code": null, "e": 3278, "s": 3186, "text": "You can check the available database list using \\l, i.e., backslash el command as follows −" }, { "code": null, "e": 3923, "s": 3278, "text": "postgres-# \\l\n List of databases\n Name | Owner | Encoding | Collate | Ctype | Access privileges \n-----------+----------+----------+---------+-------+-----------------------\n postgres | postgres | UTF8 | C | C | \n template0 | postgres | UTF8 | C | C | =c/postgres +\n | | | | | postgres=CTc/postgres\n template1 | postgres | UTF8 | C | C | =c/postgres +\n | | | | | postgres=CTc/postgres\n testdb | postgres | UTF8 | C | C | \n(4 rows)\n\npostgres-# " }, { "code": null, "e": 4040, "s": 3923, "text": "Now, type the following command to connect/select a desired database; here, we will connect to the testdb database." }, { "code": null, "e": 4170, "s": 4040, "text": "postgres=# \\c testdb;\npsql (9.2.4)\nType \"help\" for help.\nYou are now connected to database \"testdb\" as user \"postgres\".\ntestdb=# " }, { "code": null, "e": 4307, "s": 4170, "text": "You can select your database from the command prompt itself at the time when you login to your database. Following is a simple example −" }, { "code": null, "e": 4495, "s": 4307, "text": "psql -h localhost -p 5432 -U postgress testdb\nPassword for user postgress: ****\npsql (9.2.4)\nType \"help\" for help.\nYou are now connected to database \"testdb\" as user \"postgres\".\ntestdb=# " }, { "code": null, "e": 4642, "s": 4495, "text": "You are now logged into PostgreSQL testdb and ready to execute your commands inside testdb. To exit from the database, you can use the command \\q." }, { "code": null, "e": 4677, "s": 4642, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4689, "s": 4677, "text": " John Elder" }, { "code": null, "e": 4724, "s": 4689, "text": "\n 49 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4740, "s": 4724, "text": " Niyazi Erdogan" }, { "code": null, "e": 4777, "s": 4740, "text": "\n 126 Lectures \n 10.5 hours \n" }, { "code": null, "e": 4799, "s": 4777, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4832, "s": 4799, "text": "\n 35 Lectures \n 5 hours \n" }, { "code": null, "e": 4846, "s": 4832, "text": " Karthikeya T" }, { "code": null, "e": 4877, "s": 4846, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 4890, "s": 4877, "text": " Vinay Kumar" }, { "code": null, "e": 4921, "s": 4890, "text": "\n 5 Lectures \n 52 mins\n" }, { "code": null, "e": 4934, "s": 4921, "text": " Vinay Kumar" }, { "code": null, "e": 4941, "s": 4934, "text": " Print" }, { "code": null, "e": 4952, "s": 4941, "text": " Add Notes" } ]
NHibernate - Caching
In this chapter, we will be covering how the caching works in NHibernate applications. It has built-in support for caching. It looks as a simple feature, but in reality, it is one of the most complex features. We will begin with the First Level Cache. This cache mechanism is enabled by default in NHibernate and we don’t need to do anything for working with cache. To understand this, let’s have a look into a simple example, as you can see that we have two records in our database. Now in this example, we will retrieve the student whose ID is 1 and we will use the same session query twice as shown in the following code. using HibernatingRhinos.Profiler.Appender.NHibernate; using NHibernate.Cache; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Linq; using System; using System.Linq; using System.Reflection; namespace NHibernateDemoApp { class Program { static void Main(string[] args) { NHibernateProfiler.Initialize(); var cfg = new Configuration(); String Data Source = asia13797\\sqlexpress; String Initial Catalog = NHibernateDemoDB; String Integrated Security = True; String Connect Timeout = 15; String Encrypt = False; String TrustServerCertificate = False; String ApplicationIntent = ReadWrite; String MultiSubnetFailover = False; cfg.DataBaseIntegration(x = > { x.ConnectionString = "Data Source + Initial Catalog + Integrated Security + Connect Timeout + Encrypt + TrustServerCertificate + ApplicationIntent + MultiSubnetFailover"; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.LogSqlInConsole = true; x.BatchSize = 10; }); //cfg.Configure(); cfg.Cache(c => { c.UseMinimalPuts = true; c.UseQueryCache = true; }); cfg.SessionFactory().Caching .Through<HashtableCacheProvider>() .WithDefaultExpiration(1440); cfg.AddAssembly(Assembly.GetExecutingAssembly()); var sefact = cfg.BuildSessionFactory(); using (var session = sefact.OpenSession()){ using (var tx = session.BeginTransaction()) { var studentUsingTheFirstQuery = session.Get<Student>(1); var studentUsingTheSecondQuery = session.Get<Student>(1); } Console.ReadLine(); } } } } Now let’s run this application and see the result in the NHibernate Profiler. You will be surprised to see that NHibernate fires only one query. This is how NHibernate uses the first level cache. When the first query is executed, then NHibernate cached the Student with ID = 1 in its first level cache. So, when the second query is executed then NHibernate first looks up the first level cache Student entity with ID = 1, if it finds that entity, then NHibernate knows that, there is no need to fire another query to retrieve the same employee object again. Print Add Notes Bookmark this page
[ { "code": null, "e": 2585, "s": 2333, "text": "In this chapter, we will be covering how the caching works in NHibernate applications. It has built-in support for caching. It looks as a simple feature, but in reality, it is one of the most complex features. We will begin with the First Level Cache." }, { "code": null, "e": 2817, "s": 2585, "text": "This cache mechanism is enabled by default in NHibernate and we don’t need to do anything for working with cache. To understand this, let’s have a look into a simple example, as you can see that we have two records in our database." }, { "code": null, "e": 2958, "s": 2817, "text": "Now in this example, we will retrieve the student whose ID is 1 and we will use the same session query twice as shown in the following code." }, { "code": null, "e": 4924, "s": 2958, "text": "using HibernatingRhinos.Profiler.Appender.NHibernate; \nusing NHibernate.Cache; \nusing NHibernate.Cfg; \nusing NHibernate.Dialect;\nusing NHibernate.Driver; \nusing NHibernate.Linq; \n\nusing System; \nusing System.Linq; \nusing System.Reflection;\nnamespace NHibernateDemoApp { \n \n class Program { \n static void Main(string[] args) {\n\t\t\n NHibernateProfiler.Initialize(); \n var cfg = new Configuration(); \n\t\t\t\n String Data Source = asia13797\\\\sqlexpress;\n String Initial Catalog = NHibernateDemoDB;\n String Integrated Security = True;\n String Connect Timeout = 15;\n String Encrypt = False;\n String TrustServerCertificate = False;\n String ApplicationIntent = ReadWrite;\n String MultiSubnetFailover = False;\n \n cfg.DataBaseIntegration(x = > { x.ConnectionString = \"Data Source + \n Initial Catalog + Integrated Security + Connect Timeout + Encrypt +\n TrustServerCertificate + ApplicationIntent + MultiSubnetFailover\";\n\t\t\t\t\n x.Driver<SqlClientDriver>(); \n x.Dialect<MsSql2008Dialect>(); \n x.LogSqlInConsole = true; \n x.BatchSize = 10; \n }); \n \n //cfg.Configure(); \n \n cfg.Cache(c => { \n c.UseMinimalPuts = true; \n c.UseQueryCache = true; \n }); \n\t\t\t\n cfg.SessionFactory().Caching .Through<HashtableCacheProvider>()\n .WithDefaultExpiration(1440); \n cfg.AddAssembly(Assembly.GetExecutingAssembly()); \n var sefact = cfg.BuildSessionFactory(); \n \n using (var session = sefact.OpenSession()){ \n\t\t\t\n using (var tx = session.BeginTransaction()) { \n var studentUsingTheFirstQuery = session.Get<Student>(1);\n var studentUsingTheSecondQuery = session.Get<Student>(1); \n } \n \n Console.ReadLine(); \n } \n } \n } \n}" }, { "code": null, "e": 5002, "s": 4924, "text": "Now let’s run this application and see the result in the NHibernate Profiler." }, { "code": null, "e": 5227, "s": 5002, "text": "You will be surprised to see that NHibernate fires only one query. This is how NHibernate uses the first level cache. When the first query is executed, then NHibernate cached the Student with ID = 1 in its first level cache." }, { "code": null, "e": 5482, "s": 5227, "text": "So, when the second query is executed then NHibernate first looks up the first level cache Student entity with ID = 1, if it finds that entity, then NHibernate knows that, there is no need to fire another query to retrieve the same employee object again." }, { "code": null, "e": 5489, "s": 5482, "text": " Print" }, { "code": null, "e": 5500, "s": 5489, "text": " Add Notes" } ]
Leonardo Number - GeeksforGeeks
28 May, 2021 The Leonardo numbers are a sequence of numbers given by the recurrence: The first few Leonardo Numbers are 1, 1, 3, 5, 9, 15, 25, 41, 67, 109, 177, 287, 465, 753, 1219, 1973, 3193, 5167, 8361, ··· The Leonardo numbers are related to the Fibonacci numbers by below relation:Given a number n, find n-th Leonardo number. Examples: Input : n = 0 Output : 1 Input : n = 3 Output : 5 A simple solution is to recursively compute values. C++ Java Python3 C# PHP Javascript // A simple recursive program to find n-th// leonardo number.#include <iostream>using namespace std; int leonardo(int n){ if (n == 0 || n == 1) return 1; return leonardo(n - 1) + leonardo(n - 2) + 1;} int main(){ cout << leonardo(3); return 0;} // A simple recursive program to find n-th// leonardo number.import java.io.*; class GFG { static int leonardo(int n) { if (n == 0 || n == 1) return 1; return (leonardo(n - 1) + leonardo(n - 2) + 1); } public static void main(String args[]) { System.out.println(leonardo(3)); }} /*This code is contributed by Nikita Tiwari.*/ # A simple recursive program to find n-th# leonardo number. def leonardo(n) : if (n == 0 or n == 1) : return 1 return (leonardo(n - 1) + leonardo(n - 2) + 1); # Driver code print(leonardo(3)) # This code is contributed by Nikita Tiwari. // A simple recursive program to// find n-th leonardo number.using System; class GFG { static int leonardo(int n) { if (n == 0 || n == 1) return 1; return (leonardo(n - 1) + leonardo(n - 2) + 1); } public static void Main() { Console.WriteLine(leonardo(3)); }} // This code is contributed by vt_m. <?php// A simple recursive PHP// program to find n-th// leonardo number. // function returns the// nth leonardo numberfunction leonardo($n){ if ($n == 0 || $n == 1) return 1; return leonardo($n - 1) + leonardo($n - 2) + 1;} // Driver Codeecho leonardo(3); // This code is contributed by ajit?> <script> // Javascript program to find n-th// leonardo number. function leonardo(n) { let dp = []; dp[0] = dp[1] = 1; for (let i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2] + 1; return dp[n]; } // Driver code document.write(leonardo(3)); </script> Output : 5 Time Complexity : Exponential A better solution is to use dynamic programming. C++ Java Python3 C# PHP JavaScript // A simple recursive program to find n-th// leonardo number.#include <iostream>using namespace std; int leonardo(int n){ int dp[n + 1]; dp[0] = dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2] + 1; return dp[n];} int main(){ cout << leonardo(3); return 0;} // A simple recursive program to find n-th// leonardo number.import java.io.*; class GFG { static int leonardo(int n) { int dp[] = new int[n + 1]; dp[0] = dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2] + 1; return dp[n]; } // Driver code public static void main(String[] args) { System.out.println(leonardo(3)); }} /*This code is contributed by vt_m.*/ # A simple recursive program# to find n-th leonardo number. def leonardo(n): dp = []; dp.append(1); dp.append(1); for i in range(2, n + 1): dp.append(dp[i - 1] + dp[i - 2] + 1); return dp[n]; # Driver codeprint(leonardo(3)); # This code is contributed by mits // A simple recursive program to// find n-th leonardo number.using System; class GFG { static int leonardo(int n) { int[] dp = new int[n + 1]; dp[0] = dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2] + 1; return dp[n]; } public static void Main() { Console.WriteLine(leonardo(3)); }}// This code is contributed by vt_m. <?php// A simple recursive program to// find n-th leonardo number. function leonardo( $n){ $dp[0] = $dp[1] = 1; for ($i = 2; $i <= $n; $i++) $dp[$i] = $dp[$i - 1] + $dp[$i - 2] + 1; return $dp[$n];} echo leonardo(3); // This code is contributed by ajit.?> <script>// A simple recursive program to find n-th// leonardo number. function leonardo(n) { var dp = Array.from({length: n+1}, (_, i) => 0); dp[0] = dp[1] = 1; for (var i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2] + 1; return dp[n]; } // Driver code document.write(leonardo(3)); // This code contributed by Princi Singh</script> Output : 5 Time Complexity : O(n) The best solution is to use relation with Fibonacci Numbers. We can find the n-th Fibonacci number in O(Log n) time [See method 4 of this] C++ Java Python3 C# PHP Javascript // A O(Log n) program to find n-th Leonardo// number.#include <iostream>using namespace std; /* Helper function that multiplies 2 matrices F and M of size 2*2, and puts the multiplication result back to F[][] */void multiply(int F[2][2], int M[2][2]){ int x = F[0][0] * M[0][0] + F[0][1] * M[1][0]; int y = F[0][0] * M[0][1] + F[0][1] * M[1][1]; int z = F[1][0] * M[0][0] + F[1][1] * M[1][0]; int w = F[1][0] * M[0][1] + F[1][1] * M[1][1]; F[0][0] = x; F[0][1] = y; F[1][0] = z; F[1][1] = w;} void power(int F[2][2], int n){ int i; int M[2][2] = { { 1, 1 }, { 1, 0 } }; // n - 1 times multiply the matrix // to {{1, 0}, {0, 1}} for (i = 2; i <= n; i++) multiply(F, M);} int fib(int n){ int F[2][2] = { { 1, 1 }, { 1, 0 } }; if (n == 0) return 0; power(F, n - 1); return F[0][0];} int leonardo(int n){ if (n == 0 || n == 1) return 1; return 2 * fib(n + 1) - 1;} int main(){ cout << leonardo(3); return 0;} // A O(Log n) program to find n-th Leonardo// number. class GFG { /* Helper function that multiplies 2 matrices F and M of size 2*2, and puts the multiplication result back to F[][] */ static void multiply(int F[][], int M[][]) { int x = F[0][0] * M[0][0] + F[0][1] * M[1][0]; int y = F[0][0] * M[0][1] + F[0][1] * M[1][1]; int z = F[1][0] * M[0][0] + F[1][1] * M[1][0]; int w = F[1][0] * M[0][1] + F[1][1] * M[1][1]; F[0][0] = x; F[0][1] = y; F[1][0] = z; F[1][1] = w; } static void power(int F[][], int n) { int i; int M[][] = { { 1, 1 }, { 1, 0 } }; // n - 1 times multiply the matrix // to {{1, 0}, {0, 1}} for (i = 2; i <= n; i++) multiply(F, M); } static int fib(int n) { int F[][] = { { 1, 1 }, { 1, 0 } }; if (n == 0) return 0; power(F, n - 1); return F[0][0]; } static int leonardo(int n) { if (n == 0 || n == 1) return 1; return 2 * fib(n + 1) - 1; } public static void main(String args[]) { System.out.println(leonardo(3)); }} /*This code is contributed by Nikita Tiwari.*/ # A O(Log n) program to find n-th Leonardo# number. # Helper function that multiplies 2 matrices# F and M of size 2 * 2, and puts the# multiplication result back to F[][]def multiply(F, M ) : x = F[0][0] * M[0][0] + F[0][1] * M[1][0] y = F[0][0] * M[0][1] + F[0][1] * M[1][1] z = F[1][0] * M[0][0] + F[1][1] * M[1][0] w = F[1][0] * M[0][1] + F[1][1] * M[1][1] F[0][0] = x F[0][1] = y F[1][0] = z F[1][1] = w def power(F, n) : M = [[ 1, 1 ], [ 1, 0 ] ] # n - 1 times multiply the matrix # to {{1, 0}, {0, 1}} for i in range(2, n + 1) : multiply(F, M) def fib(n) : F = [ [ 1, 1 ], [ 1, 0 ] ] if (n == 0) : return 0 power(F, n - 1) return F[0][0] def leonardo(n) : if (n == 0 or n == 1) : return 1 return (2 * fib(n + 1) - 1) # main method print(leonardo(3)) # This code is contributed by Nikita Tiwari. // A O(Log n) program to find// n-th Leonardo number.using System; class GFG { /* Helper function that multiplies 2 matrices F and M of size 2*2, and puts the multiplication result back to F[][] */ static void multiply(int[, ] F, int[, ] M) { int x = F[0, 0] * M[0, 0] + F[0, 1] * M[1, 0]; int y = F[0, 0] * M[0, 1] + F[0, 1] * M[1, 1]; int z = F[1, 0] * M[0, 0] + F[1, 1] * M[1, 0]; int w = F[1, 0] * M[0, 1] + F[1, 1] * M[1, 1]; F[0, 0] = x; F[0, 1] = y; F[1, 0] = z; F[1, 1] = w; } static void power(int[, ] F, int n) { int i; int[, ] M = { { 1, 1 }, { 1, 0 } }; // n - 1 times multiply the matrix // to {{1, 0}, {0, 1}} for (i = 2; i <= n; i++) multiply(F, M); } static int fib(int n) { int[, ] F = { { 1, 1 }, { 1, 0 } }; if (n == 0) return 0; power(F, n - 1); return F[0, 0]; } static int leonardo(int n) { if (n == 0 || n == 1) return 1; return 2 * fib(n + 1) - 1; } // Driver Code public static void Main() { Console.WriteLine(leonardo(3)); }} // This code is contributed by vt_m. <?php// A O(Log n) program to find n-th// Leonardo number. /* Helper function that multiplies 2 matricesF and M of size 2*2, and puts themultiplication result back to $F][] */function multiply(&$F, $M){ $x = $F[0][0] * $M[0][0] + $F[0][1] * $M[1][0]; $y = $F[0][0] * $M[0][1] + $F[0][1] * $M[1][1]; $z = $F[1][0] * $M[0][0] + $F[1][1] * $M[1][0]; $w = $F[1][0] * $M[0][1] + $F[1][1] * $M[1][1]; $F[0][0] = $x; $F[0][1] = $y; $F[1][0] = $z; $F[1][1] = $w;} function power(&$F, $n){ $M = array(array(1, 1), array(1, 0)); // n - 1 times multiply the matrix // to {{1, 0}, {0, 1}} for ($i = 2; $i <= $n; $i++) multiply($F, $M);} function fib($n){ $F = array(array(1, 1), array(1, 0)); if ($n == 0) return 0; power($F, $n - 1); return $F[0][0];} function leonardo($n){ if ($n == 0 || $n == 1) return 1; return 2 * fib($n + 1) - 1;} // Driver Codeecho leonardo(3); //This code is contributed by mits?> <script>// A O(Log n) program to find n-th Leonardo// number. /* Helper function that multiplies 2 matricesF and M of size 2*2, and puts themultiplication result back to F */function multiply(F , M){ var x = F[0][0] * M[0][0] + F[0][1] * M[1][0]; var y = F[0][0] * M[0][1] + F[0][1] * M[1][1]; var z = F[1][0] * M[0][0] + F[1][1] * M[1][0]; var w = F[1][0] * M[0][1] + F[1][1] * M[1][1]; F[0][0] = x; F[0][1] = y; F[1][0] = z; F[1][1] = w;} function power(F , n){ var i; var M = [ [ 1, 1 ], [ 1, 0 ] ]; // n - 1 times multiply the matrix // to {{1, 0], [0, 1}} for (i = 2; i <= n; i++) multiply(F, M);} function fib(n){ var F = [ [ 1, 1 ], [ 1, 0 ] ]; if (n == 0) return 0; power(F, n - 1); return F[0][0];} function leonardo(n){ if (n == 0 || n == 1) return 1; return 2 * fib(n + 1) - 1;} document.write(leonardo(3)); // This code is contributed by Amit Katiyar</script> Output : 5 Time Complexity : O(Log n)This article is contributed by Subhajit Saha. 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. jit_t Mithun Kumar sanjoy_62 princi singh amit143katiyar Fibonacci series Mathematical Mathematical series Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Program for Decimal to Binary Conversion Find all factors of a natural number | Set 1 Program to find sum of elements in a given array The Knight's tour problem | Backtracking-1 Program for factorial of a number Operators in C / C++
[ { "code": null, "e": 24347, "s": 24319, "text": "\n28 May, 2021" }, { "code": null, "e": 24666, "s": 24347, "text": "The Leonardo numbers are a sequence of numbers given by the recurrence: The first few Leonardo Numbers are 1, 1, 3, 5, 9, 15, 25, 41, 67, 109, 177, 287, 465, 753, 1219, 1973, 3193, 5167, 8361, ··· The Leonardo numbers are related to the Fibonacci numbers by below relation:Given a number n, find n-th Leonardo number. " }, { "code": null, "e": 24678, "s": 24666, "text": "Examples: " }, { "code": null, "e": 24729, "s": 24678, "text": "Input : n = 0\nOutput : 1\n\nInput : n = 3\nOutput : 5" }, { "code": null, "e": 24783, "s": 24729, "text": "A simple solution is to recursively compute values. " }, { "code": null, "e": 24787, "s": 24783, "text": "C++" }, { "code": null, "e": 24792, "s": 24787, "text": "Java" }, { "code": null, "e": 24800, "s": 24792, "text": "Python3" }, { "code": null, "e": 24803, "s": 24800, "text": "C#" }, { "code": null, "e": 24807, "s": 24803, "text": "PHP" }, { "code": null, "e": 24818, "s": 24807, "text": "Javascript" }, { "code": "// A simple recursive program to find n-th// leonardo number.#include <iostream>using namespace std; int leonardo(int n){ if (n == 0 || n == 1) return 1; return leonardo(n - 1) + leonardo(n - 2) + 1;} int main(){ cout << leonardo(3); return 0;}", "e": 25082, "s": 24818, "text": null }, { "code": "// A simple recursive program to find n-th// leonardo number.import java.io.*; class GFG { static int leonardo(int n) { if (n == 0 || n == 1) return 1; return (leonardo(n - 1) + leonardo(n - 2) + 1); } public static void main(String args[]) { System.out.println(leonardo(3)); }} /*This code is contributed by Nikita Tiwari.*/", "e": 25459, "s": 25082, "text": null }, { "code": "# A simple recursive program to find n-th# leonardo number. def leonardo(n) : if (n == 0 or n == 1) : return 1 return (leonardo(n - 1) + leonardo(n - 2) + 1); # Driver code print(leonardo(3)) # This code is contributed by Nikita Tiwari.", "e": 25720, "s": 25459, "text": null }, { "code": "// A simple recursive program to// find n-th leonardo number.using System; class GFG { static int leonardo(int n) { if (n == 0 || n == 1) return 1; return (leonardo(n - 1) + leonardo(n - 2) + 1); } public static void Main() { Console.WriteLine(leonardo(3)); }} // This code is contributed by vt_m.", "e": 26071, "s": 25720, "text": null }, { "code": "<?php// A simple recursive PHP// program to find n-th// leonardo number. // function returns the// nth leonardo numberfunction leonardo($n){ if ($n == 0 || $n == 1) return 1; return leonardo($n - 1) + leonardo($n - 2) + 1;} // Driver Codeecho leonardo(3); // This code is contributed by ajit?>", "e": 26388, "s": 26071, "text": null }, { "code": "<script> // Javascript program to find n-th// leonardo number. function leonardo(n) { let dp = []; dp[0] = dp[1] = 1; for (let i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2] + 1; return dp[n]; } // Driver code document.write(leonardo(3)); </script>", "e": 26712, "s": 26388, "text": null }, { "code": null, "e": 26722, "s": 26712, "text": "Output : " }, { "code": null, "e": 26724, "s": 26722, "text": "5" }, { "code": null, "e": 26754, "s": 26724, "text": "Time Complexity : Exponential" }, { "code": null, "e": 26805, "s": 26754, "text": "A better solution is to use dynamic programming. " }, { "code": null, "e": 26809, "s": 26805, "text": "C++" }, { "code": null, "e": 26814, "s": 26809, "text": "Java" }, { "code": null, "e": 26822, "s": 26814, "text": "Python3" }, { "code": null, "e": 26825, "s": 26822, "text": "C#" }, { "code": null, "e": 26829, "s": 26825, "text": "PHP" }, { "code": null, "e": 26840, "s": 26829, "text": "JavaScript" }, { "code": "// A simple recursive program to find n-th// leonardo number.#include <iostream>using namespace std; int leonardo(int n){ int dp[n + 1]; dp[0] = dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2] + 1; return dp[n];} int main(){ cout << leonardo(3); return 0;}", "e": 27144, "s": 26840, "text": null }, { "code": "// A simple recursive program to find n-th// leonardo number.import java.io.*; class GFG { static int leonardo(int n) { int dp[] = new int[n + 1]; dp[0] = dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2] + 1; return dp[n]; } // Driver code public static void main(String[] args) { System.out.println(leonardo(3)); }} /*This code is contributed by vt_m.*/", "e": 27589, "s": 27144, "text": null }, { "code": "# A simple recursive program# to find n-th leonardo number. def leonardo(n): dp = []; dp.append(1); dp.append(1); for i in range(2, n + 1): dp.append(dp[i - 1] + dp[i - 2] + 1); return dp[n]; # Driver codeprint(leonardo(3)); # This code is contributed by mits", "e": 27888, "s": 27589, "text": null }, { "code": "// A simple recursive program to// find n-th leonardo number.using System; class GFG { static int leonardo(int n) { int[] dp = new int[n + 1]; dp[0] = dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2] + 1; return dp[n]; } public static void Main() { Console.WriteLine(leonardo(3)); }}// This code is contributed by vt_m.", "e": 28296, "s": 27888, "text": null }, { "code": "<?php// A simple recursive program to// find n-th leonardo number. function leonardo( $n){ $dp[0] = $dp[1] = 1; for ($i = 2; $i <= $n; $i++) $dp[$i] = $dp[$i - 1] + $dp[$i - 2] + 1; return $dp[$n];} echo leonardo(3); // This code is contributed by ajit.?>", "e": 28589, "s": 28296, "text": null }, { "code": "<script>// A simple recursive program to find n-th// leonardo number. function leonardo(n) { var dp = Array.from({length: n+1}, (_, i) => 0); dp[0] = dp[1] = 1; for (var i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2] + 1; return dp[n]; } // Driver code document.write(leonardo(3)); // This code contributed by Princi Singh</script>", "e": 28978, "s": 28589, "text": null }, { "code": null, "e": 28989, "s": 28978, "text": "Output : " }, { "code": null, "e": 28991, "s": 28989, "text": "5" }, { "code": null, "e": 29014, "s": 28991, "text": "Time Complexity : O(n)" }, { "code": null, "e": 29155, "s": 29014, "text": "The best solution is to use relation with Fibonacci Numbers. We can find the n-th Fibonacci number in O(Log n) time [See method 4 of this] " }, { "code": null, "e": 29159, "s": 29155, "text": "C++" }, { "code": null, "e": 29164, "s": 29159, "text": "Java" }, { "code": null, "e": 29172, "s": 29164, "text": "Python3" }, { "code": null, "e": 29175, "s": 29172, "text": "C#" }, { "code": null, "e": 29179, "s": 29175, "text": "PHP" }, { "code": null, "e": 29190, "s": 29179, "text": "Javascript" }, { "code": "// A O(Log n) program to find n-th Leonardo// number.#include <iostream>using namespace std; /* Helper function that multiplies 2 matrices F and M of size 2*2, and puts the multiplication result back to F[][] */void multiply(int F[2][2], int M[2][2]){ int x = F[0][0] * M[0][0] + F[0][1] * M[1][0]; int y = F[0][0] * M[0][1] + F[0][1] * M[1][1]; int z = F[1][0] * M[0][0] + F[1][1] * M[1][0]; int w = F[1][0] * M[0][1] + F[1][1] * M[1][1]; F[0][0] = x; F[0][1] = y; F[1][0] = z; F[1][1] = w;} void power(int F[2][2], int n){ int i; int M[2][2] = { { 1, 1 }, { 1, 0 } }; // n - 1 times multiply the matrix // to {{1, 0}, {0, 1}} for (i = 2; i <= n; i++) multiply(F, M);} int fib(int n){ int F[2][2] = { { 1, 1 }, { 1, 0 } }; if (n == 0) return 0; power(F, n - 1); return F[0][0];} int leonardo(int n){ if (n == 0 || n == 1) return 1; return 2 * fib(n + 1) - 1;} int main(){ cout << leonardo(3); return 0;}", "e": 30184, "s": 29190, "text": null }, { "code": "// A O(Log n) program to find n-th Leonardo// number. class GFG { /* Helper function that multiplies 2 matrices F and M of size 2*2, and puts the multiplication result back to F[][] */ static void multiply(int F[][], int M[][]) { int x = F[0][0] * M[0][0] + F[0][1] * M[1][0]; int y = F[0][0] * M[0][1] + F[0][1] * M[1][1]; int z = F[1][0] * M[0][0] + F[1][1] * M[1][0]; int w = F[1][0] * M[0][1] + F[1][1] * M[1][1]; F[0][0] = x; F[0][1] = y; F[1][0] = z; F[1][1] = w; } static void power(int F[][], int n) { int i; int M[][] = { { 1, 1 }, { 1, 0 } }; // n - 1 times multiply the matrix // to {{1, 0}, {0, 1}} for (i = 2; i <= n; i++) multiply(F, M); } static int fib(int n) { int F[][] = { { 1, 1 }, { 1, 0 } }; if (n == 0) return 0; power(F, n - 1); return F[0][0]; } static int leonardo(int n) { if (n == 0 || n == 1) return 1; return 2 * fib(n + 1) - 1; } public static void main(String args[]) { System.out.println(leonardo(3)); }} /*This code is contributed by Nikita Tiwari.*/", "e": 31402, "s": 30184, "text": null }, { "code": "# A O(Log n) program to find n-th Leonardo# number. # Helper function that multiplies 2 matrices# F and M of size 2 * 2, and puts the# multiplication result back to F[][]def multiply(F, M ) : x = F[0][0] * M[0][0] + F[0][1] * M[1][0] y = F[0][0] * M[0][1] + F[0][1] * M[1][1] z = F[1][0] * M[0][0] + F[1][1] * M[1][0] w = F[1][0] * M[0][1] + F[1][1] * M[1][1] F[0][0] = x F[0][1] = y F[1][0] = z F[1][1] = w def power(F, n) : M = [[ 1, 1 ], [ 1, 0 ] ] # n - 1 times multiply the matrix # to {{1, 0}, {0, 1}} for i in range(2, n + 1) : multiply(F, M) def fib(n) : F = [ [ 1, 1 ], [ 1, 0 ] ] if (n == 0) : return 0 power(F, n - 1) return F[0][0] def leonardo(n) : if (n == 0 or n == 1) : return 1 return (2 * fib(n + 1) - 1) # main method print(leonardo(3)) # This code is contributed by Nikita Tiwari.", "e": 32297, "s": 31402, "text": null }, { "code": "// A O(Log n) program to find// n-th Leonardo number.using System; class GFG { /* Helper function that multiplies 2 matrices F and M of size 2*2, and puts the multiplication result back to F[][] */ static void multiply(int[, ] F, int[, ] M) { int x = F[0, 0] * M[0, 0] + F[0, 1] * M[1, 0]; int y = F[0, 0] * M[0, 1] + F[0, 1] * M[1, 1]; int z = F[1, 0] * M[0, 0] + F[1, 1] * M[1, 0]; int w = F[1, 0] * M[0, 1] + F[1, 1] * M[1, 1]; F[0, 0] = x; F[0, 1] = y; F[1, 0] = z; F[1, 1] = w; } static void power(int[, ] F, int n) { int i; int[, ] M = { { 1, 1 }, { 1, 0 } }; // n - 1 times multiply the matrix // to {{1, 0}, {0, 1}} for (i = 2; i <= n; i++) multiply(F, M); } static int fib(int n) { int[, ] F = { { 1, 1 }, { 1, 0 } }; if (n == 0) return 0; power(F, n - 1); return F[0, 0]; } static int leonardo(int n) { if (n == 0 || n == 1) return 1; return 2 * fib(n + 1) - 1; } // Driver Code public static void Main() { Console.WriteLine(leonardo(3)); }} // This code is contributed by vt_m.", "e": 33528, "s": 32297, "text": null }, { "code": "<?php// A O(Log n) program to find n-th// Leonardo number. /* Helper function that multiplies 2 matricesF and M of size 2*2, and puts themultiplication result back to $F][] */function multiply(&$F, $M){ $x = $F[0][0] * $M[0][0] + $F[0][1] * $M[1][0]; $y = $F[0][0] * $M[0][1] + $F[0][1] * $M[1][1]; $z = $F[1][0] * $M[0][0] + $F[1][1] * $M[1][0]; $w = $F[1][0] * $M[0][1] + $F[1][1] * $M[1][1]; $F[0][0] = $x; $F[0][1] = $y; $F[1][0] = $z; $F[1][1] = $w;} function power(&$F, $n){ $M = array(array(1, 1), array(1, 0)); // n - 1 times multiply the matrix // to {{1, 0}, {0, 1}} for ($i = 2; $i <= $n; $i++) multiply($F, $M);} function fib($n){ $F = array(array(1, 1), array(1, 0)); if ($n == 0) return 0; power($F, $n - 1); return $F[0][0];} function leonardo($n){ if ($n == 0 || $n == 1) return 1; return 2 * fib($n + 1) - 1;} // Driver Codeecho leonardo(3); //This code is contributed by mits?>", "e": 34532, "s": 33528, "text": null }, { "code": "<script>// A O(Log n) program to find n-th Leonardo// number. /* Helper function that multiplies 2 matricesF and M of size 2*2, and puts themultiplication result back to F */function multiply(F , M){ var x = F[0][0] * M[0][0] + F[0][1] * M[1][0]; var y = F[0][0] * M[0][1] + F[0][1] * M[1][1]; var z = F[1][0] * M[0][0] + F[1][1] * M[1][0]; var w = F[1][0] * M[0][1] + F[1][1] * M[1][1]; F[0][0] = x; F[0][1] = y; F[1][0] = z; F[1][1] = w;} function power(F , n){ var i; var M = [ [ 1, 1 ], [ 1, 0 ] ]; // n - 1 times multiply the matrix // to {{1, 0], [0, 1}} for (i = 2; i <= n; i++) multiply(F, M);} function fib(n){ var F = [ [ 1, 1 ], [ 1, 0 ] ]; if (n == 0) return 0; power(F, n - 1); return F[0][0];} function leonardo(n){ if (n == 0 || n == 1) return 1; return 2 * fib(n + 1) - 1;} document.write(leonardo(3)); // This code is contributed by Amit Katiyar</script>", "e": 35486, "s": 34532, "text": null }, { "code": null, "e": 35496, "s": 35486, "text": "Output : " }, { "code": null, "e": 35498, "s": 35496, "text": "5" }, { "code": null, "e": 35950, "s": 35498, "text": "Time Complexity : O(Log n)This article is contributed by Subhajit Saha. 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": 35956, "s": 35950, "text": "jit_t" }, { "code": null, "e": 35969, "s": 35956, "text": "Mithun Kumar" }, { "code": null, "e": 35979, "s": 35969, "text": "sanjoy_62" }, { "code": null, "e": 35992, "s": 35979, "text": "princi singh" }, { "code": null, "e": 36007, "s": 35992, "text": "amit143katiyar" }, { "code": null, "e": 36017, "s": 36007, "text": "Fibonacci" }, { "code": null, "e": 36024, "s": 36017, "text": "series" }, { "code": null, "e": 36037, "s": 36024, "text": "Mathematical" }, { "code": null, "e": 36050, "s": 36037, "text": "Mathematical" }, { "code": null, "e": 36057, "s": 36050, "text": "series" }, { "code": null, "e": 36067, "s": 36057, "text": "Fibonacci" }, { "code": null, "e": 36165, "s": 36067, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36174, "s": 36165, "text": "Comments" }, { "code": null, "e": 36187, "s": 36174, "text": "Old Comments" }, { "code": null, "e": 36211, "s": 36187, "text": "Merge two sorted arrays" }, { "code": null, "e": 36254, "s": 36211, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 36268, "s": 36254, "text": "Prime Numbers" }, { "code": null, "e": 36310, "s": 36268, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 36351, "s": 36310, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 36396, "s": 36351, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 36445, "s": 36396, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 36488, "s": 36445, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 36522, "s": 36488, "text": "Program for factorial of a number" } ]
Anomaly Detection : Isolation Forest with Statistical Rules | by adithya krishnan | Towards Data Science
This is a follow up article about anomaly detection with isolation forest . In the previous article we saw about anomaly detection with time series forecasting and classification. With isolation forest we had to deal with the contamination parameter which sets the percentage of points in our data to be anomalous. While that could be a good start to see initial results but that puts you in a problem where at any point x% of point will be returned anomalous. Lets look at one possible way to avoid it. Now lets start with direct implementation of isolation forest on a dataset which has timestamp and cpu_utilization as value: Link to dataset (https://github.com/numenta/NAB/tree/master/data/realAWSCloudwatch) import pandas as pdimport numpy as npfull_df=pd.read_csv('ec2_cpu_utilization_5f5533.csv')full_df.head() We have around 4000 data points at a 5 minute level ranging from Feb 14 to Feb 28. print(full_df['timestamp'].min())print(full_df['timestamp'].max())print(len(full_df['timestamp'])) Visualize the points to have an overview on time series data: # Using graph_objectsfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotimport plotly.plotly as pyimport matplotlib.pyplot as pltfrom matplotlib import pyplotimport plotly.graph_objs as goinit_notebook_mode(connected=True)import plotly.graph_objs as gofig = go.Figure(data=[go.Scatter(x=full_df['timestamp'], y=full_df['value'])])iplot(fig) I l filter the data for a specific day just to have simple visualization. Feb 24 seems to be a good option as there is a dip and significant spike in the data. df=full_df.loc[(full_df[‘timestamp’]>’2014–02–24 00:00:00')&(full_df[‘timestamp’]<’2014–02–24 23:59:59')]df.head()plot_data=go.Scatter(x=df['timestamp'], y=df['value'])fig=go.Figure(data=[plot_data])iplot(fig) Now lets start fitting this to an isolation forest model with contamination parameter set as 4% based on my intuition from the visualization. from sklearn.ensemble import IsolationForest#to_model_column='value'clf=IsolationForest(n_estimators=10, max_samples='auto', contamination=float(.04), \ max_features=1.0, bootstrap=False, n_jobs=-1, random_state=42, verbose=0,behaviour='new')clf.fit(df[['value']])df['scores']=clf.decision_function(df[['value']])df['anomaly']=clf.predict(df[['value']])df.head()df.loc[df['anomaly'] == 1,'anomaly'] = 0df.loc[df['anomaly'] == -1,'anomaly'] = 1df.value_counts() def plot_anomaly(df,metric_name): df.timestamp = pd.to_datetime(df['timestamp'].astype(str), format="%Y-%m-%d %H:%M:%S") dates = df.timestamp #identify the anomaly points and create a array of its values for plot bool_array = (abs(df['anomaly']) > 0) actuals = df["value"][-len(bool_array):] anomaly_points = bool_array * actuals anomaly_points[anomaly_points == 0] = np.nan #A dictionary for conditional format table based on anomaly color_map = {0: "'rgba(228, 222, 249, 0.65)'", 1: "red"}#Table which includes Date,Actuals,Change occured from previous point table = go.Table( domain=dict(x=[0, 1], y=[0, 0.3]), columnwidth=[1, 2], # columnorder=[0, 1, 2,], header=dict(height=20, values=[['<b>Date</b>'], ['<b>Actual Values </b>'], ], font=dict(color=['rgb(45, 45, 45)'] * 5, size=14), fill=dict(color='#d562be')), cells=dict(values=[df.round(3)[k].tolist() for k in ['timestamp', 'value']], line=dict(color='#506784'), align=['center'] * 5, font=dict(color=['rgb(40, 40, 40)'] * 5, size=12), # format = [None] + [",.4f"] + [',.4f'], # suffix=[None] * 4, suffix=[None] + [''] + [''] + ['%'] + [''], height=27, fill=dict(color=[df['anomaly'].map(color_map)],#map based on anomaly level from dictionary ) )) #Plot the actuals points Actuals = go.Scatter(name='Actuals', x=dates, y=df['value'], xaxis='x1', yaxis='y1', mode='line', marker=dict(size=12, line=dict(width=1), color="blue")) #Highlight the anomaly points anomalies_map = go.Scatter(name="Anomaly", showlegend=True, x=dates, y=anomaly_points, mode='markers', xaxis='x1', yaxis='y1', marker=dict(color="red", size=11, line=dict( color="red", width=2))) axis = dict( showline=True, zeroline=False, showgrid=True, mirror=True, ticklen=4, gridcolor='#ffffff', tickfont=dict(size=10)) layout = dict( width=1000, height=865, autosize=False, title=metric_name, margin=dict(t=75), showlegend=True, xaxis1=dict(axis, **dict(domain=[0, 1], anchor='y1', showticklabels=True)), yaxis1=dict(axis, **dict(domain=[2 * 0.21 + 0.20, 1], anchor='x1', hoverformat='.2f'))) fig = go.Figure(data=[table, anomalies_map, Actuals], layout=layout) iplot(fig) pyplot.show()plot_anomaly(df,'anomalies') print("Percentage of anomalies in data: {:.2f}".format((len(df.loc[df['anomaly']==1])/len(df))*100)) Looks good with some minor false anomalies as we the plot shows we have captured significant spike and few other dips and spikes. Now lets see what is the role of contamination parameter here. Isolation forest separates each point out from other points randomly and constructs a tree based on its number of splits with each point representing a node in tree. Outliers appear closer to the root in the tree and inliers appear in higher depth. In case of isolation forest , a forest of trees are created based on n_estimators and max_sample parameters and the score is derived from it. One can use score_samples/decision_fuction to get the normalized anomaly_score of each point here more the negative it is anomalous based on sklearn computation . Till this step contamination factor has no influence on the scores. From here when we apply predict in order to return anomaly 1/0 contamination acts as a cutoff/percentile on scores and returns top x percentile negative scores as anomalies. (For eg: If contamination is set as 0.05/5% then points with top 5% negative scores are labeled anomalies) df['scores'].hist() Inliers with positive scores are clubbed at right with positive scores. Points with negative scores are anomalies. This is the distribution of scores for this specific input points. Once we finalize our model based on this and predict the future points then our cutoff on scores for contamination might vary to give 4% of points as anomalous but the distribution of scores might change. To overcome instead of an hard coded percentage of points always being labeled as anomalies irrespective of change in scores we can use some statistical algorithm like Z-Score or IQR on the scores to detect those changes in scores and classify anomalies better. def iqr_bounds(scores,k=1.5): q1 = scores.quantile(0.25) q3 = scores.quantile(0.75) iqr = q3 - q1 lower_bound=(q1 - k * iqr) upper_bound=(q3 + k * iqr) print("Lower bound:{} \nUpper bound:{}".format(lower_bound,upper_bound)) return lower_bound,upper_boundlower_bound,upper_bound=iqr_bounds(df['scores'],k=2) df['anomaly']=0df['anomaly']=(df['scores'] < lower_bound) |(df['scores'] > upper_bound)df['anomaly']=df['anomaly'].astype(int)plot_anomaly(df,'iqr based') Percentage of points labeled as anomalies is around 2% here with k being set as 2 in IQR. print("Percentage of anomalies in data: {:.2f}".format((len(df.loc[df['anomaly']==1])/len(df))*100)) Now lets validate this with another data considering the same contamination and also with same k in IQR on scores: df=full_df.loc[(full_df['timestamp']>'2014-02-17 00:00:00')&(full_df['timestamp']<'2014-02-17 23:59:59')]# Using graph_objectsplot_data=go.Scatter(x=df['timestamp'], y=df['value'])fig=go.Figure(data=[plot_data])iplot(fig) By looking at the plot during this day the data looks different with fewer anomalies. from sklearn.ensemble import IsolationForest#to_model_column='value'clf=IsolationForest(n_estimators=10, max_samples='auto', contamination=float(.04), \ max_features=1.0, bootstrap=False, n_jobs=-1, random_state=42, verbose=0,behaviour='new')clf.fit(df[['value']])df['scores']=clf.decision_function(df[['value']])df['anomaly']=clf.predict(df[['value']])df.loc[df['anomaly'] == 1,'anomaly'] = 0df.loc[df['anomaly'] == -1,'anomaly'] = 1plot_anomaly(df,'anomalies') print("Percentage of anomalies in data: {:.2f}".format((len(df.loc[df['anomaly']==1])/len(df))*100)) Yes and here we see more of false anomalies from the visualization. The percentage of anomalous points remains same here as we have used the same contamination for data of new time frame. df['scores'].hist() lower_bound,upper_bound=iqr_bounds(df['scores'],k=2)df['anomaly']=0df['anomaly']=(df['scores'] < lower_bound) |(df['scores'] > upper_bound)df['anomaly']=df['anomaly'].astype(int)plot_anomaly(df,'iqr second case') print("Percentage of anomalies in data: {:.2f}".format((len(df.loc[df['anomaly']==1])/len(df))*100)) In this case the percentage of outliers is down in this method as the data distribution which reflects in the scores have changed. In real time anomaly detection the combination of statistical rules on isolation forest works better as you train you model and deploy and predict on future stream of data whose distribution might change from time to time and the scores of new data would be different. Also this k parameter in IQR can be tuned based on feedback on anomalies detected. If there are false positives then k should be decreased and if there are false negatives k should be decreased to find more anomalies. Will follow it up with some details on isolation forest algorithm new addition of warm start and interpreting results from isolation forest. Add on : Below is a multivariate anomaly 3d visualization using plotly express which I found to be cool. Play with it in all 3 dimensions to have a look at anomalies.
[ { "code": null, "e": 487, "s": 172, "text": "This is a follow up article about anomaly detection with isolation forest . In the previous article we saw about anomaly detection with time series forecasting and classification. With isolation forest we had to deal with the contamination parameter which sets the percentage of points in our data to be anomalous." }, { "code": null, "e": 676, "s": 487, "text": "While that could be a good start to see initial results but that puts you in a problem where at any point x% of point will be returned anomalous. Lets look at one possible way to avoid it." }, { "code": null, "e": 801, "s": 676, "text": "Now lets start with direct implementation of isolation forest on a dataset which has timestamp and cpu_utilization as value:" }, { "code": null, "e": 885, "s": 801, "text": "Link to dataset (https://github.com/numenta/NAB/tree/master/data/realAWSCloudwatch)" }, { "code": null, "e": 990, "s": 885, "text": "import pandas as pdimport numpy as npfull_df=pd.read_csv('ec2_cpu_utilization_5f5533.csv')full_df.head()" }, { "code": null, "e": 1073, "s": 990, "text": "We have around 4000 data points at a 5 minute level ranging from Feb 14 to Feb 28." }, { "code": null, "e": 1172, "s": 1073, "text": "print(full_df['timestamp'].min())print(full_df['timestamp'].max())print(len(full_df['timestamp']))" }, { "code": null, "e": 1234, "s": 1172, "text": "Visualize the points to have an overview on time series data:" }, { "code": null, "e": 1601, "s": 1234, "text": "# Using graph_objectsfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotimport plotly.plotly as pyimport matplotlib.pyplot as pltfrom matplotlib import pyplotimport plotly.graph_objs as goinit_notebook_mode(connected=True)import plotly.graph_objs as gofig = go.Figure(data=[go.Scatter(x=full_df['timestamp'], y=full_df['value'])])iplot(fig)" }, { "code": null, "e": 1761, "s": 1601, "text": "I l filter the data for a specific day just to have simple visualization. Feb 24 seems to be a good option as there is a dip and significant spike in the data." }, { "code": null, "e": 1971, "s": 1761, "text": "df=full_df.loc[(full_df[‘timestamp’]>’2014–02–24 00:00:00')&(full_df[‘timestamp’]<’2014–02–24 23:59:59')]df.head()plot_data=go.Scatter(x=df['timestamp'], y=df['value'])fig=go.Figure(data=[plot_data])iplot(fig)" }, { "code": null, "e": 2113, "s": 1971, "text": "Now lets start fitting this to an isolation forest model with contamination parameter set as 4% based on my intuition from the visualization." }, { "code": null, "e": 2597, "s": 2113, "text": "from sklearn.ensemble import IsolationForest#to_model_column='value'clf=IsolationForest(n_estimators=10, max_samples='auto', contamination=float(.04), \\ max_features=1.0, bootstrap=False, n_jobs=-1, random_state=42, verbose=0,behaviour='new')clf.fit(df[['value']])df['scores']=clf.decision_function(df[['value']])df['anomaly']=clf.predict(df[['value']])df.head()df.loc[df['anomaly'] == 1,'anomaly'] = 0df.loc[df['anomaly'] == -1,'anomaly'] = 1df.value_counts()" }, { "code": null, "e": 5685, "s": 2597, "text": "def plot_anomaly(df,metric_name): df.timestamp = pd.to_datetime(df['timestamp'].astype(str), format=\"%Y-%m-%d %H:%M:%S\") dates = df.timestamp #identify the anomaly points and create a array of its values for plot bool_array = (abs(df['anomaly']) > 0) actuals = df[\"value\"][-len(bool_array):] anomaly_points = bool_array * actuals anomaly_points[anomaly_points == 0] = np.nan #A dictionary for conditional format table based on anomaly color_map = {0: \"'rgba(228, 222, 249, 0.65)'\", 1: \"red\"}#Table which includes Date,Actuals,Change occured from previous point table = go.Table( domain=dict(x=[0, 1], y=[0, 0.3]), columnwidth=[1, 2], # columnorder=[0, 1, 2,], header=dict(height=20, values=[['<b>Date</b>'], ['<b>Actual Values </b>'], ], font=dict(color=['rgb(45, 45, 45)'] * 5, size=14), fill=dict(color='#d562be')), cells=dict(values=[df.round(3)[k].tolist() for k in ['timestamp', 'value']], line=dict(color='#506784'), align=['center'] * 5, font=dict(color=['rgb(40, 40, 40)'] * 5, size=12), # format = [None] + [\",.4f\"] + [',.4f'], # suffix=[None] * 4, suffix=[None] + [''] + [''] + ['%'] + [''], height=27, fill=dict(color=[df['anomaly'].map(color_map)],#map based on anomaly level from dictionary ) )) #Plot the actuals points Actuals = go.Scatter(name='Actuals', x=dates, y=df['value'], xaxis='x1', yaxis='y1', mode='line', marker=dict(size=12, line=dict(width=1), color=\"blue\")) #Highlight the anomaly points anomalies_map = go.Scatter(name=\"Anomaly\", showlegend=True, x=dates, y=anomaly_points, mode='markers', xaxis='x1', yaxis='y1', marker=dict(color=\"red\", size=11, line=dict( color=\"red\", width=2))) axis = dict( showline=True, zeroline=False, showgrid=True, mirror=True, ticklen=4, gridcolor='#ffffff', tickfont=dict(size=10)) layout = dict( width=1000, height=865, autosize=False, title=metric_name, margin=dict(t=75), showlegend=True, xaxis1=dict(axis, **dict(domain=[0, 1], anchor='y1', showticklabels=True)), yaxis1=dict(axis, **dict(domain=[2 * 0.21 + 0.20, 1], anchor='x1', hoverformat='.2f'))) fig = go.Figure(data=[table, anomalies_map, Actuals], layout=layout) iplot(fig) pyplot.show()plot_anomaly(df,'anomalies')" }, { "code": null, "e": 5786, "s": 5685, "text": "print(\"Percentage of anomalies in data: {:.2f}\".format((len(df.loc[df['anomaly']==1])/len(df))*100))" }, { "code": null, "e": 5979, "s": 5786, "text": "Looks good with some minor false anomalies as we the plot shows we have captured significant spike and few other dips and spikes. Now lets see what is the role of contamination parameter here." }, { "code": null, "e": 6370, "s": 5979, "text": "Isolation forest separates each point out from other points randomly and constructs a tree based on its number of splits with each point representing a node in tree. Outliers appear closer to the root in the tree and inliers appear in higher depth. In case of isolation forest , a forest of trees are created based on n_estimators and max_sample parameters and the score is derived from it." }, { "code": null, "e": 6533, "s": 6370, "text": "One can use score_samples/decision_fuction to get the normalized anomaly_score of each point here more the negative it is anomalous based on sklearn computation ." }, { "code": null, "e": 6882, "s": 6533, "text": "Till this step contamination factor has no influence on the scores. From here when we apply predict in order to return anomaly 1/0 contamination acts as a cutoff/percentile on scores and returns top x percentile negative scores as anomalies. (For eg: If contamination is set as 0.05/5% then points with top 5% negative scores are labeled anomalies)" }, { "code": null, "e": 6902, "s": 6882, "text": "df['scores'].hist()" }, { "code": null, "e": 7551, "s": 6902, "text": "Inliers with positive scores are clubbed at right with positive scores. Points with negative scores are anomalies. This is the distribution of scores for this specific input points. Once we finalize our model based on this and predict the future points then our cutoff on scores for contamination might vary to give 4% of points as anomalous but the distribution of scores might change. To overcome instead of an hard coded percentage of points always being labeled as anomalies irrespective of change in scores we can use some statistical algorithm like Z-Score or IQR on the scores to detect those changes in scores and classify anomalies better." }, { "code": null, "e": 7880, "s": 7551, "text": "def iqr_bounds(scores,k=1.5): q1 = scores.quantile(0.25) q3 = scores.quantile(0.75) iqr = q3 - q1 lower_bound=(q1 - k * iqr) upper_bound=(q3 + k * iqr) print(\"Lower bound:{} \\nUpper bound:{}\".format(lower_bound,upper_bound)) return lower_bound,upper_boundlower_bound,upper_bound=iqr_bounds(df['scores'],k=2)" }, { "code": null, "e": 8035, "s": 7880, "text": "df['anomaly']=0df['anomaly']=(df['scores'] < lower_bound) |(df['scores'] > upper_bound)df['anomaly']=df['anomaly'].astype(int)plot_anomaly(df,'iqr based')" }, { "code": null, "e": 8125, "s": 8035, "text": "Percentage of points labeled as anomalies is around 2% here with k being set as 2 in IQR." }, { "code": null, "e": 8226, "s": 8125, "text": "print(\"Percentage of anomalies in data: {:.2f}\".format((len(df.loc[df['anomaly']==1])/len(df))*100))" }, { "code": null, "e": 8341, "s": 8226, "text": "Now lets validate this with another data considering the same contamination and also with same k in IQR on scores:" }, { "code": null, "e": 8563, "s": 8341, "text": "df=full_df.loc[(full_df['timestamp']>'2014-02-17 00:00:00')&(full_df['timestamp']<'2014-02-17 23:59:59')]# Using graph_objectsplot_data=go.Scatter(x=df['timestamp'], y=df['value'])fig=go.Figure(data=[plot_data])iplot(fig)" }, { "code": null, "e": 8649, "s": 8563, "text": "By looking at the plot during this day the data looks different with fewer anomalies." }, { "code": null, "e": 9135, "s": 8649, "text": "from sklearn.ensemble import IsolationForest#to_model_column='value'clf=IsolationForest(n_estimators=10, max_samples='auto', contamination=float(.04), \\ max_features=1.0, bootstrap=False, n_jobs=-1, random_state=42, verbose=0,behaviour='new')clf.fit(df[['value']])df['scores']=clf.decision_function(df[['value']])df['anomaly']=clf.predict(df[['value']])df.loc[df['anomaly'] == 1,'anomaly'] = 0df.loc[df['anomaly'] == -1,'anomaly'] = 1plot_anomaly(df,'anomalies')" }, { "code": null, "e": 9236, "s": 9135, "text": "print(\"Percentage of anomalies in data: {:.2f}\".format((len(df.loc[df['anomaly']==1])/len(df))*100))" }, { "code": null, "e": 9424, "s": 9236, "text": "Yes and here we see more of false anomalies from the visualization. The percentage of anomalous points remains same here as we have used the same contamination for data of new time frame." }, { "code": null, "e": 9444, "s": 9424, "text": "df['scores'].hist()" }, { "code": null, "e": 9657, "s": 9444, "text": "lower_bound,upper_bound=iqr_bounds(df['scores'],k=2)df['anomaly']=0df['anomaly']=(df['scores'] < lower_bound) |(df['scores'] > upper_bound)df['anomaly']=df['anomaly'].astype(int)plot_anomaly(df,'iqr second case')" }, { "code": null, "e": 9758, "s": 9657, "text": "print(\"Percentage of anomalies in data: {:.2f}\".format((len(df.loc[df['anomaly']==1])/len(df))*100))" }, { "code": null, "e": 9889, "s": 9758, "text": "In this case the percentage of outliers is down in this method as the data distribution which reflects in the scores have changed." }, { "code": null, "e": 10158, "s": 9889, "text": "In real time anomaly detection the combination of statistical rules on isolation forest works better as you train you model and deploy and predict on future stream of data whose distribution might change from time to time and the scores of new data would be different." }, { "code": null, "e": 10376, "s": 10158, "text": "Also this k parameter in IQR can be tuned based on feedback on anomalies detected. If there are false positives then k should be decreased and if there are false negatives k should be decreased to find more anomalies." }, { "code": null, "e": 10517, "s": 10376, "text": "Will follow it up with some details on isolation forest algorithm new addition of warm start and interpreting results from isolation forest." } ]
MongoDB query to sort by the sum of specified object inside inner array?
To sort by the sum of specified object inside inner array, use matchalongwithsort. Let us create a collection with documents − > db.demo189.insertOne( ... { ... "_id" : 100, ... "List" : [ ... { ... "Value" : 10 ... }, .. .{ ... "Value" : 20 ... }, ... { ... "Value" : 10 ... } ... ] ... } ...); { "acknowledged" : true, "insertedId" : 100 } > db.demo189.insertOne( ... { ... "_id" : 101, ... "List" : [ ... { ... "Value" : 10 ... }, ... { ... "Value" : 10 ... }, ... { ... "Value" : 10 ... } ... ] ... } ...); { "acknowledged" : true, "insertedId" : 101 } Display all documents from a collection with the help of find() method − > db.demo189.find(); This will produce the following output − { "_id" : 100, "List" : [ { "Value" : 10 }, { "Value" : 20 }, { "Value" : 10 } ] } { "_id" : 101, "List" : [ { "Value" : 10 }, { "Value" : 10 }, { "Value" : 10 } ] } Following is the query to sort by the sum of specified object inside inner array − > db.demo189.aggregate([ ... { "$unwind" : "$List" }, ... { "$group" : { ... "_id" : "$_id", ... "total" : { ... "$sum" : { ... "$cond" : { ... "if" : { "$eq" : [ "$List.Value", 10 ] }, ... "then" : 1, ... "else" : 0 ... } ... } ... }, ... "List" : { ... "$push" : { ... "Value" : "$List.Value" ... } ... } ... }}, ... { "$sort" : { "total" : -1 } }, ... { "$project" : { ... "List" : 1 ... }} ...]) This will produce the following output − { "_id" : 101, "List" : [ { "Value" : 10 }, { "Value" : 10 }, { "Value" : 10 } ] } { "_id" : 100, "List" : [ { "Value" : 10 }, { "Value" : 20 }, { "Value" : 10 } ] }
[ { "code": null, "e": 1189, "s": 1062, "text": "To sort by the sum of specified object inside inner array, use matchalongwithsort. Let us create a collection with documents −" }, { "code": null, "e": 1819, "s": 1189, "text": "> db.demo189.insertOne(\n... {\n... \"_id\" : 100,\n... \"List\" : [\n... {\n... \"Value\" : 10\n... },\n.. .{\n... \"Value\" : 20\n... },\n... {\n... \"Value\" : 10\n... }\n... ]\n... }\n...);\n{ \"acknowledged\" : true, \"insertedId\" : 100 }\n> db.demo189.insertOne(\n... {\n... \"_id\" : 101,\n... \"List\" : [\n... {\n... \"Value\" : 10\n... },\n... {\n... \"Value\" : 10\n... },\n... {\n... \"Value\" : 10\n... }\n... ]\n... }\n...);\n{ \"acknowledged\" : true, \"insertedId\" : 101 }" }, { "code": null, "e": 1892, "s": 1819, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1913, "s": 1892, "text": "> db.demo189.find();" }, { "code": null, "e": 1954, "s": 1913, "text": "This will produce the following output −" }, { "code": null, "e": 2120, "s": 1954, "text": "{ \"_id\" : 100, \"List\" : [ { \"Value\" : 10 }, { \"Value\" : 20 }, { \"Value\" : 10 } ] }\n{ \"_id\" : 101, \"List\" : [ { \"Value\" : 10 }, { \"Value\" : 10 }, { \"Value\" : 10 } ] }" }, { "code": null, "e": 2204, "s": 2120, "text": "Following is the query to sort by the sum of specified object inside inner array − " }, { "code": null, "e": 2756, "s": 2204, "text": "> db.demo189.aggregate([\n... { \"$unwind\" : \"$List\" },\n... { \"$group\" : {\n... \"_id\" : \"$_id\",\n... \"total\" : {\n... \"$sum\" : {\n... \"$cond\" : {\n... \"if\" : { \"$eq\" : [ \"$List.Value\", 10 ] },\n... \"then\" : 1,\n... \"else\" : 0\n... }\n... }\n... },\n... \"List\" : {\n... \"$push\" : {\n... \"Value\" : \"$List.Value\"\n... }\n... }\n... }},\n... { \"$sort\" : { \"total\" : -1 } },\n... { \"$project\" : {\n... \"List\" : 1\n... }}\n...])" }, { "code": null, "e": 2797, "s": 2756, "text": "This will produce the following output −" }, { "code": null, "e": 2963, "s": 2797, "text": "{ \"_id\" : 101, \"List\" : [ { \"Value\" : 10 }, { \"Value\" : 10 }, { \"Value\" : 10 } ] }\n{ \"_id\" : 100, \"List\" : [ { \"Value\" : 10 }, { \"Value\" : 20 }, { \"Value\" : 10 } ] }" } ]
Analysis and Visualization of Unstructured Text | Towards Data Science
Stuck behind the paywall? Read this article with my friend link here. What will you do when I ask you to explain textual data? What steps will you take to build the textual visualization story? Here, I am not going to explain how you create a visualization story. But this article will help you to get the required information to build the visualization story and explain the textual data. Insights from textual data will help us to discover the connection between the articles. It will detect trends and patterns. Analysis of textual data will set aside the noise and uncovers previously unknown information. This analysis process is also known as Exploratory Text Analysis (ETA). With the help of K-means, Tf-IDF, word frequency, etc. method, we will analyze these textual data. Also, ETA is useful in the data cleaning process. We also visualize the results in graphs, word clouds, and plots using Matplotlib, seaborn, and Plotly libraries. Before analyzing the Textual Data, complete these pre-processing tasks. There is a lot of unstructured text data available for analysis. You can get data from the below sources. 1. Twitter text dataset from Kaggle. 2. Reddit and twitter dataset using API. 3. Scrape articles from a website using Beautifulsoup and Requests python library. I am going to use Reuters’ article available in SGML format. For analysis purposes, I will fetch the date, title, and article body from data files using the Beautifulsoup library. Use the below code to fetch the data from all data files and store the output in a single CSV file. 1. You can also use the Regex and OS library to combine or loop all the data files. 2. Each article’s body starts with <Reuters>, so use find_all(‘reuters’). 3. You can also use the pickle module to save data, instead of CSV. In this section, we remove noise such as null values, punctuation, numbers, etc. from the textual data. First, we remove the rows which contain null values in the text column. Then we deal with other column’s null values. import pandas as pd import rearticles_data = pd.read_csv(‘articles_data.csv’) print(articles_data.apply(lambda x: sum(x.isnull()))) articles_nonNull = articles_data.dropna(subset=[‘text’]) articles_nonNull.reset_index(inplace=True)def clean_text(text):‘’’Make text lowercase, remove text in square brackets,remove \n,remove punctuation and remove words containing numbers.’’’ text = str(text).lower() text = re.sub(‘<.*?>+’, ‘’, text) text = re.sub(‘[%s]’ % re.escape(string.punctuation), ‘’, text) text = re.sub(‘\n’, ‘’, text) text = re.sub(‘\w*\d\w*’, ‘’, text) return textarticles_nonNull[‘text_clean’]=articles_nonNull[‘text’]\ .apply(lambda x:clean_text(x)) · When we remove null values present in the text column, then the null values in other columns also vanishes. · We have used re method to remove noise in textual data. Steps taken in the data cleaning process may increase or decrease as per the textual data. So, study your text data carefully and frame your clean_text() method accordingly. As the pre-processing task is complete, we are going to move on to analyzing textual data. We know that the length of all the articles is not the same. So, we will consider those articles whose length equal to or more than one paragraph. As per the study, the average length of a sentence is 15–20 words. And there should be four sentences in a paragraph. articles_nonNull[‘word_length’] = articles_nonNull[‘text’].apply(lambda x: len(str(x).split())) print(articles_nonNull.describe())articles_word_limit = articles_nonNull[articles_nonNull[‘word_length’] > 60]plt.figure(figsize=(12,6)) p1=sns.kdeplot(articles_word_limit[‘word_length’], shade=True, color=”r”).set_title(‘Kernel Distribution of Number Of words’) · I have removed those articles whose length is less than 60 words. · Word_length distribution is right-skewed. · Most of the articles have around 150 words. · Reuters articles that contain fact or stock information have fewer words. In this section, we count the words present in the articles and analyze the result. We analyze the word count based on the N-gram method. N-gram is the occurrence of words based on its N value. We will remove the stopwords from the textual data. Because stopwords are noise and not have much use in the analysis. Let’s plot unigram words in a bar graph and word cloud for Unigram words. Share, trade, and stock are some of the most frequent words and based on the stock market and financial sector articles. So, we can say that most Reuters articles belong to the finance and Stock category. Let’s plot the bar graph and word cloud for Bigram words. article_bigrams = defaultdict(int)for tweet in articles_word_limit[‘temp_list_stopw’]: for word in generate_ngrams(tweet, n_gram=2): article_bigrams[word] += 1df_article_bigrams=pd.DataFrame(sorted(article_bigrams.items(), key=lambda x: x[1])[::-1])N=50# bar graph of top 50 bigram wordsfig, axes = plt.subplots(figsize=(18, 50), dpi=100)plt.tight_layout()sns.barplot(y=df_article_bigrams[0].values[:N], x=df_article_bigrams[1].values[:N], color=’red’)axes.spines[‘right’].set_visible(False)axes.set_xlabel(‘’)axes.set_ylabel(‘’)axes.tick_params(axis=’x’, labelsize=13)axes.tick_params(axis=’y’, labelsize=13)axes.set_title(f’Top {N} most common Bigrams in Reuters Articles’, fontsize=15)plt.show()#Word cloudwc = WordCloud(width=2000, height=1000, collocations=False, background_color=”white”, color_func=col_func, max_words=200, random_state=np.random.randint(1,8))\ .generate_from_frequencies(article_bigrams)fig, ax = plt.subplots(figsize=(20,10))ax.imshow(wc, interpolation=’bilinear’)ax.axis(“off”)ax.set_title(‘Trigram Words of Reuters Articles’, pad=24, fontdict=fd)plt.show() Bigram gives more information and context on text than unigram. Like, share loss bigram shows that most people lost money in stock. Let’s plot bar graph and word cloud for Trigrma words. article_trigrams = defaultdict(int)for tweet in articles_word_limit[‘temp_list_stopw’]: for word in generate_ngrams(tweet, n_gram=3): article_trigrams[word] += 1df_article_trigrams = pd.DataFrame(sorted(article_trigrams.items(), key=lambda x: x[1])[::-1])N=50# bar graph of top 50 trigram wordsfig, axes = plt.subplots(figsize=(18, 50), dpi=100)plt.tight_layout()sns.barplot(y=df_article_trigrams[0].values[:N], x=df_article_trigrams[1].values[:N], color=’red’)axes.spines[‘right’].set_visible(False)axes.set_xlabel(‘’)axes.set_ylabel(‘’)axes.tick_params(axis=’x’, labelsize=13)axes.tick_params(axis=’y’, labelsize=13)axes.set_title(f’Top {N} most common Trigrams in Reuters articles’, fontsize=15)plt.show()# word cloudwc = WordCloud(width=2000, height=1000, collocations=False,background_color=”white”,color_func=col_func,max_words=200,random_state=np.random.randint(1,8)).generate_from_frequencies(article_trigrams)fig, ax = plt.subplots(figsize=(20,10))ax.imshow(wc, interpolation=’bilinear’)ax.axis(“off”)ax.set_title(‘Trigrams Words of Reuters Articles’, pad=24, fontdict=fd)plt.show() Most trigrams are similar to bigrams. Trigrams words help us understand the text more than bigram. But not able to provide more information. So we end this section here. NER is a process to extract specific information from textual data. With the help of NER, we extract location, person name, date, quantity, and organization entity from the text. Learn more about NER here. We use the Spacy python library for this job. · From this graph, you can say that most articles contain news from the US, Japan, Canada, London, and China. · High mention of the US represents the focus of Reuters business in the US. · The person variable implies who are the famous people in 1987. This information helps us to know about those people. · The organization variable contains the most mention organization around the world. We are going to find unique words in the articles using TF-IDF. Term Frequency (TF) is a count of words per article. Inverse Document Frequency (IDF) measures the importance of words while considering all the mention articles. TF-IDF scores are high for those words which have a high count in one article and rare or not present in others. Let’s calculate the TF-IDF score and find unique words. from sklearn.feature_extraction.text import TfidfVectorizertfidf_vectorizer = TfidfVectorizer(use_idf=True)tfidf_vectorizer_vectors=tfidf_vectorizer.fit_transform(articles_word_limit[‘text_clean’])tfidf = tfidf_vectorizer_vectors.todense()tfidf[tfidf == 0] = np.nan#Use nanmean of numpy which will ignore nan while calculating meanmeans = np.nanmean(tfidf, axis=0)# convert it into a dictionary for later lookupMeans_words = dict(zip(tfidf_vectorizer.get_feature_names(), means.tolist()[0]))unique_words=sorted(means_words.items(), key=lambda x: x[1], reverse=True)print(unique_words) K-Means is an unsupervised Machine learning algorithm. It helps us to collect the same type of articles in one group. We can decide the number of groups or clusters by initializing k value. Know more about K-Means and how we select k value here. For reference, I choose k=4 to form four groups. from sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.cluster import KMeansfrom sklearn.metrics import adjusted_rand_scorevectorizer = TfidfVectorizer(stop_words=’english’,use_idf=True)X = vectorizer.fit_transform(articles_word_limit[‘text_clean’])k = 4model = KMeans(n_clusters=k, init=’k-means++’, max_iter=100, n_init=1)model.fit(X)order_centroids = model.cluster_centers_.argsort()[:, ::-1]terms = vectorizer.get_feature_names()clusters = model.labels_.tolist()articles_word_limit.index = clustersfor i in range(k): print(“Cluster %d words:” % i, end=’’)for title in articles_word_limit.ix[i [[‘text_clean’,’index’]].values.tolist(): print(‘ %s,’ % title, end=’’) It helps us in sorting the articles in different groups such as sports, money, finance, and more. The accuracy of K-Means is generally low. So, this is useful in low-level analysis. NER and K-Means are my favorite method for analysis. Others might like N-gram and Unique words methods. In this article, I have covered the most famous and unheard method for text visualization and analysis. All these methods in this article are unique and help you in visualization and analysis. I hope this article will help you to discover unknowns in your textual data. Other Articles by Author First step in EDA : Descriptive Statistic AnalysisAutomate Sentiment Analysis Process for Reddit Post: TextBlob and VADERDiscover the Sentiment of Reddit Subgroup using RoBERTa Model First step in EDA : Descriptive Statistic Analysis Automate Sentiment Analysis Process for Reddit Post: TextBlob and VADER Discover the Sentiment of Reddit Subgroup using RoBERTa Model
[ { "code": null, "e": 241, "s": 171, "text": "Stuck behind the paywall? Read this article with my friend link here." }, { "code": null, "e": 435, "s": 241, "text": "What will you do when I ask you to explain textual data? What steps will you take to build the textual visualization story? Here, I am not going to explain how you create a visualization story." }, { "code": null, "e": 561, "s": 435, "text": "But this article will help you to get the required information to build the visualization story and explain the textual data." }, { "code": null, "e": 781, "s": 561, "text": "Insights from textual data will help us to discover the connection between the articles. It will detect trends and patterns. Analysis of textual data will set aside the noise and uncovers previously unknown information." }, { "code": null, "e": 1002, "s": 781, "text": "This analysis process is also known as Exploratory Text Analysis (ETA). With the help of K-means, Tf-IDF, word frequency, etc. method, we will analyze these textual data. Also, ETA is useful in the data cleaning process." }, { "code": null, "e": 1115, "s": 1002, "text": "We also visualize the results in graphs, word clouds, and plots using Matplotlib, seaborn, and Plotly libraries." }, { "code": null, "e": 1187, "s": 1115, "text": "Before analyzing the Textual Data, complete these pre-processing tasks." }, { "code": null, "e": 1293, "s": 1187, "text": "There is a lot of unstructured text data available for analysis. You can get data from the below sources." }, { "code": null, "e": 1330, "s": 1293, "text": "1. Twitter text dataset from Kaggle." }, { "code": null, "e": 1371, "s": 1330, "text": "2. Reddit and twitter dataset using API." }, { "code": null, "e": 1454, "s": 1371, "text": "3. Scrape articles from a website using Beautifulsoup and Requests python library." }, { "code": null, "e": 1634, "s": 1454, "text": "I am going to use Reuters’ article available in SGML format. For analysis purposes, I will fetch the date, title, and article body from data files using the Beautifulsoup library." }, { "code": null, "e": 1734, "s": 1634, "text": "Use the below code to fetch the data from all data files and store the output in a single CSV file." }, { "code": null, "e": 1818, "s": 1734, "text": "1. You can also use the Regex and OS library to combine or loop all the data files." }, { "code": null, "e": 1892, "s": 1818, "text": "2. Each article’s body starts with <Reuters>, so use find_all(‘reuters’)." }, { "code": null, "e": 1960, "s": 1892, "text": "3. You can also use the pickle module to save data, instead of CSV." }, { "code": null, "e": 2182, "s": 1960, "text": "In this section, we remove noise such as null values, punctuation, numbers, etc. from the textual data. First, we remove the rows which contain null values in the text column. Then we deal with other column’s null values." }, { "code": null, "e": 2897, "s": 2182, "text": "import pandas as pd import rearticles_data = pd.read_csv(‘articles_data.csv’) print(articles_data.apply(lambda x: sum(x.isnull()))) articles_nonNull = articles_data.dropna(subset=[‘text’]) articles_nonNull.reset_index(inplace=True)def clean_text(text):‘’’Make text lowercase, remove text in square brackets,remove \\n,remove punctuation and remove words containing numbers.’’’ text = str(text).lower() text = re.sub(‘<.*?>+’, ‘’, text) text = re.sub(‘[%s]’ % re.escape(string.punctuation), ‘’, text) text = re.sub(‘\\n’, ‘’, text) text = re.sub(‘\\w*\\d\\w*’, ‘’, text) return textarticles_nonNull[‘text_clean’]=articles_nonNull[‘text’]\\ .apply(lambda x:clean_text(x))" }, { "code": null, "e": 3007, "s": 2897, "text": "· When we remove null values present in the text column, then the null values in other columns also vanishes." }, { "code": null, "e": 3065, "s": 3007, "text": "· We have used re method to remove noise in textual data." }, { "code": null, "e": 3239, "s": 3065, "text": "Steps taken in the data cleaning process may increase or decrease as per the textual data. So, study your text data carefully and frame your clean_text() method accordingly." }, { "code": null, "e": 3330, "s": 3239, "text": "As the pre-processing task is complete, we are going to move on to analyzing textual data." }, { "code": null, "e": 3595, "s": 3330, "text": "We know that the length of all the articles is not the same. So, we will consider those articles whose length equal to or more than one paragraph. As per the study, the average length of a sentence is 15–20 words. And there should be four sentences in a paragraph." }, { "code": null, "e": 3954, "s": 3595, "text": "articles_nonNull[‘word_length’] = articles_nonNull[‘text’].apply(lambda x: len(str(x).split())) print(articles_nonNull.describe())articles_word_limit = articles_nonNull[articles_nonNull[‘word_length’] > 60]plt.figure(figsize=(12,6)) p1=sns.kdeplot(articles_word_limit[‘word_length’], shade=True, color=”r”).set_title(‘Kernel Distribution of Number Of words’)" }, { "code": null, "e": 4022, "s": 3954, "text": "· I have removed those articles whose length is less than 60 words." }, { "code": null, "e": 4066, "s": 4022, "text": "· Word_length distribution is right-skewed." }, { "code": null, "e": 4112, "s": 4066, "text": "· Most of the articles have around 150 words." }, { "code": null, "e": 4188, "s": 4112, "text": "· Reuters articles that contain fact or stock information have fewer words." }, { "code": null, "e": 4382, "s": 4188, "text": "In this section, we count the words present in the articles and analyze the result. We analyze the word count based on the N-gram method. N-gram is the occurrence of words based on its N value." }, { "code": null, "e": 4501, "s": 4382, "text": "We will remove the stopwords from the textual data. Because stopwords are noise and not have much use in the analysis." }, { "code": null, "e": 4575, "s": 4501, "text": "Let’s plot unigram words in a bar graph and word cloud for Unigram words." }, { "code": null, "e": 4696, "s": 4575, "text": "Share, trade, and stock are some of the most frequent words and based on the stock market and financial sector articles." }, { "code": null, "e": 4780, "s": 4696, "text": "So, we can say that most Reuters articles belong to the finance and Stock category." }, { "code": null, "e": 4838, "s": 4780, "text": "Let’s plot the bar graph and word cloud for Bigram words." }, { "code": null, "e": 6083, "s": 4838, "text": "article_bigrams = defaultdict(int)for tweet in articles_word_limit[‘temp_list_stopw’]: for word in generate_ngrams(tweet, n_gram=2): article_bigrams[word] += 1df_article_bigrams=pd.DataFrame(sorted(article_bigrams.items(), key=lambda x: x[1])[::-1])N=50# bar graph of top 50 bigram wordsfig, axes = plt.subplots(figsize=(18, 50), dpi=100)plt.tight_layout()sns.barplot(y=df_article_bigrams[0].values[:N], x=df_article_bigrams[1].values[:N], color=’red’)axes.spines[‘right’].set_visible(False)axes.set_xlabel(‘’)axes.set_ylabel(‘’)axes.tick_params(axis=’x’, labelsize=13)axes.tick_params(axis=’y’, labelsize=13)axes.set_title(f’Top {N} most common Bigrams in Reuters Articles’, fontsize=15)plt.show()#Word cloudwc = WordCloud(width=2000, height=1000, collocations=False, background_color=”white”, color_func=col_func, max_words=200, random_state=np.random.randint(1,8))\\ .generate_from_frequencies(article_bigrams)fig, ax = plt.subplots(figsize=(20,10))ax.imshow(wc, interpolation=’bilinear’)ax.axis(“off”)ax.set_title(‘Trigram Words of Reuters Articles’, pad=24, fontdict=fd)plt.show()" }, { "code": null, "e": 6215, "s": 6083, "text": "Bigram gives more information and context on text than unigram. Like, share loss bigram shows that most people lost money in stock." }, { "code": null, "e": 6270, "s": 6215, "text": "Let’s plot bar graph and word cloud for Trigrma words." }, { "code": null, "e": 7455, "s": 6270, "text": "article_trigrams = defaultdict(int)for tweet in articles_word_limit[‘temp_list_stopw’]: for word in generate_ngrams(tweet, n_gram=3): article_trigrams[word] += 1df_article_trigrams = pd.DataFrame(sorted(article_trigrams.items(), key=lambda x: x[1])[::-1])N=50# bar graph of top 50 trigram wordsfig, axes = plt.subplots(figsize=(18, 50), dpi=100)plt.tight_layout()sns.barplot(y=df_article_trigrams[0].values[:N], x=df_article_trigrams[1].values[:N], color=’red’)axes.spines[‘right’].set_visible(False)axes.set_xlabel(‘’)axes.set_ylabel(‘’)axes.tick_params(axis=’x’, labelsize=13)axes.tick_params(axis=’y’, labelsize=13)axes.set_title(f’Top {N} most common Trigrams in Reuters articles’, fontsize=15)plt.show()# word cloudwc = WordCloud(width=2000, height=1000, collocations=False,background_color=”white”,color_func=col_func,max_words=200,random_state=np.random.randint(1,8)).generate_from_frequencies(article_trigrams)fig, ax = plt.subplots(figsize=(20,10))ax.imshow(wc, interpolation=’bilinear’)ax.axis(“off”)ax.set_title(‘Trigrams Words of Reuters Articles’, pad=24, fontdict=fd)plt.show()" }, { "code": null, "e": 7625, "s": 7455, "text": "Most trigrams are similar to bigrams. Trigrams words help us understand the text more than bigram. But not able to provide more information. So we end this section here." }, { "code": null, "e": 7877, "s": 7625, "text": "NER is a process to extract specific information from textual data. With the help of NER, we extract location, person name, date, quantity, and organization entity from the text. Learn more about NER here. We use the Spacy python library for this job." }, { "code": null, "e": 7987, "s": 7877, "text": "· From this graph, you can say that most articles contain news from the US, Japan, Canada, London, and China." }, { "code": null, "e": 8064, "s": 7987, "text": "· High mention of the US represents the focus of Reuters business in the US." }, { "code": null, "e": 8183, "s": 8064, "text": "· The person variable implies who are the famous people in 1987. This information helps us to know about those people." }, { "code": null, "e": 8268, "s": 8183, "text": "· The organization variable contains the most mention organization around the world." }, { "code": null, "e": 8495, "s": 8268, "text": "We are going to find unique words in the articles using TF-IDF. Term Frequency (TF) is a count of words per article. Inverse Document Frequency (IDF) measures the importance of words while considering all the mention articles." }, { "code": null, "e": 8608, "s": 8495, "text": "TF-IDF scores are high for those words which have a high count in one article and rare or not present in others." }, { "code": null, "e": 8664, "s": 8608, "text": "Let’s calculate the TF-IDF score and find unique words." }, { "code": null, "e": 9309, "s": 8664, "text": "from sklearn.feature_extraction.text import TfidfVectorizertfidf_vectorizer = TfidfVectorizer(use_idf=True)tfidf_vectorizer_vectors=tfidf_vectorizer.fit_transform(articles_word_limit[‘text_clean’])tfidf = tfidf_vectorizer_vectors.todense()tfidf[tfidf == 0] = np.nan#Use nanmean of numpy which will ignore nan while calculating meanmeans = np.nanmean(tfidf, axis=0)# convert it into a dictionary for later lookupMeans_words = dict(zip(tfidf_vectorizer.get_feature_names(), means.tolist()[0]))unique_words=sorted(means_words.items(), key=lambda x: x[1], reverse=True)print(unique_words)" }, { "code": null, "e": 9604, "s": 9309, "text": "K-Means is an unsupervised Machine learning algorithm. It helps us to collect the same type of articles in one group. We can decide the number of groups or clusters by initializing k value. Know more about K-Means and how we select k value here. For reference, I choose k=4 to form four groups." }, { "code": null, "e": 10329, "s": 9604, "text": "from sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.cluster import KMeansfrom sklearn.metrics import adjusted_rand_scorevectorizer = TfidfVectorizer(stop_words=’english’,use_idf=True)X = vectorizer.fit_transform(articles_word_limit[‘text_clean’])k = 4model = KMeans(n_clusters=k, init=’k-means++’, max_iter=100, n_init=1)model.fit(X)order_centroids = model.cluster_centers_.argsort()[:, ::-1]terms = vectorizer.get_feature_names()clusters = model.labels_.tolist()articles_word_limit.index = clustersfor i in range(k): print(“Cluster %d words:” % i, end=’’)for title in articles_word_limit.ix[i [[‘text_clean’,’index’]].values.tolist(): print(‘ %s,’ % title, end=’’)" }, { "code": null, "e": 10511, "s": 10329, "text": "It helps us in sorting the articles in different groups such as sports, money, finance, and more. The accuracy of K-Means is generally low. So, this is useful in low-level analysis." }, { "code": null, "e": 10808, "s": 10511, "text": "NER and K-Means are my favorite method for analysis. Others might like N-gram and Unique words methods. In this article, I have covered the most famous and unheard method for text visualization and analysis. All these methods in this article are unique and help you in visualization and analysis." }, { "code": null, "e": 10885, "s": 10808, "text": "I hope this article will help you to discover unknowns in your textual data." }, { "code": null, "e": 10910, "s": 10885, "text": "Other Articles by Author" }, { "code": null, "e": 11093, "s": 10910, "text": "First step in EDA : Descriptive Statistic AnalysisAutomate Sentiment Analysis Process for Reddit Post: TextBlob and VADERDiscover the Sentiment of Reddit Subgroup using RoBERTa Model" }, { "code": null, "e": 11144, "s": 11093, "text": "First step in EDA : Descriptive Statistic Analysis" }, { "code": null, "e": 11216, "s": 11144, "text": "Automate Sentiment Analysis Process for Reddit Post: TextBlob and VADER" } ]
Factorial of a large number
In computers, variables are stored in memory locations. But the size of the memory location is fixed, so when we try to find the factorial of some greater value like 15! or 20! the factorial value exceeds the memory range and returns wrong results. For calculation of large numbers, we have to use an array to store results. In each element of the array, is storing different digits of the result. But here we cannot multiply some number with the array directly, we have to perform manual multiplication process for all digits of the result array. Input: A big number: 50 Output: Factorial of given number is: 30414093201713378043612608166064768844377641568960512000000000000 multiply(x, multiplicand) Input: The number x, and the large multiplicand as an array. Output: Result after multiplication. Begin carry := 0 for all digits i of multiplicand, do prod := i*x+carry i := prod mod 10 carry := prod / 10 done while carry ≠ 0, do insert (carry mod 10) at the end of multiplicand array carry := carry/10 done End factorial(n) Input: The number n. Output: Find factorial of n. Begin define result array. insert 1 in the result for i := 2 to n, do multiply(i, result) done reverse the result return result End #include<iostream> #include<vector> #include<algorithm> using namespace std; void multiply(int x, vector<int>&multiplicand) { //multiply multiplicand with x int carry = 0; // Initialize carry to 0 vector<int>::iterator i; for (i=multiplicand.begin(); i!=multiplicand.end(); i++) { //multiply x with all digit of multiplicand int prod = (*i) * x + carry; *i = prod % 10; //put only the last digit of product carry = prod/10; //add remaining part with carry } while (carry) { //when carry is present multiplicand.push_back(carry%10); carry = carry/10; } } void factorial(int n) { vector<int> result; result.push_back(1); //at first store 1 as result for (int i=2; i<=n; i++) multiply(i, result); //multiply numbers 1*2*3*......*n cout << "Factorial of given number is: "<<endl; reverse(result.begin(), result.end()); vector<int>::iterator it; //reverse the order of result for(it = result.begin(); it != result.end(); it++) cout << *it; } int main() { factorial(50); } Factorial of given number is: 30414093201713378043612608166064768844377641568960512000000000000
[ { "code": null, "e": 1311, "s": 1062, "text": "In computers, variables are stored in memory locations. But the size of the memory location is fixed, so when we try to find the factorial of some greater value like 15! or 20! the factorial value exceeds the memory range and returns wrong results." }, { "code": null, "e": 1610, "s": 1311, "text": "For calculation of large numbers, we have to use an array to store results. In each element of the array, is storing different digits of the result. But here we cannot multiply some number with the array directly, we have to perform manual multiplication process for all digits of the result array." }, { "code": null, "e": 1738, "s": 1610, "text": "Input:\nA big number: 50\nOutput:\nFactorial of given number is:\n30414093201713378043612608166064768844377641568960512000000000000" }, { "code": null, "e": 1764, "s": 1738, "text": "multiply(x, multiplicand)" }, { "code": null, "e": 1825, "s": 1764, "text": "Input: The number x, and the large multiplicand as an array." }, { "code": null, "e": 1862, "s": 1825, "text": "Output: Result after multiplication." }, { "code": null, "e": 2124, "s": 1862, "text": "Begin\n carry := 0\n for all digits i of multiplicand, do\n prod := i*x+carry\n i := prod mod 10\n carry := prod / 10\n done\n\n while carry ≠ 0, do\n insert (carry mod 10) at the end of multiplicand array\n carry := carry/10\n done\nEnd" }, { "code": null, "e": 2137, "s": 2124, "text": "factorial(n)" }, { "code": null, "e": 2158, "s": 2137, "text": "Input: The number n." }, { "code": null, "e": 2187, "s": 2158, "text": "Output: Find factorial of n." }, { "code": null, "e": 2345, "s": 2187, "text": "Begin\n define result array.\n insert 1 in the result\n\n for i := 2 to n, do\n multiply(i, result)\n done\n\n reverse the result\n return result\nEnd" }, { "code": null, "e": 3438, "s": 2345, "text": "#include<iostream>\n#include<vector>\n#include<algorithm>\nusing namespace std;\n\nvoid multiply(int x, vector<int>&multiplicand) { //multiply multiplicand with x\n int carry = 0; // Initialize carry to 0\n vector<int>::iterator i;\n\n for (i=multiplicand.begin(); i!=multiplicand.end(); i++) { //multiply x with all digit of multiplicand\n int prod = (*i) * x + carry;\n *i = prod % 10; //put only the last digit of product\n carry = prod/10; //add remaining part with carry \n }\n\n while (carry) { //when carry is present\n multiplicand.push_back(carry%10);\n carry = carry/10;\n }\n}\n\nvoid factorial(int n) {\n vector<int> result;\n result.push_back(1); //at first store 1 as result\n\n for (int i=2; i<=n; i++)\n multiply(i, result); //multiply numbers 1*2*3*......*n\n\n cout << \"Factorial of given number is: \"<<endl;\n\n reverse(result.begin(), result.end());\n\n vector<int>::iterator it; //reverse the order of result\n\n for(it = result.begin(); it != result.end(); it++)\n cout << *it;\n}\n\nint main() {\n factorial(50);\n}" }, { "code": null, "e": 3534, "s": 3438, "text": "Factorial of given number is:\n30414093201713378043612608166064768844377641568960512000000000000" } ]
Course 2 — Data structure — Part 2: Priority queues and Disjoint set | by Phat Le | Towards Data Science
If we ever want to know how background job works, fastest way to find k smallest elements in an array, how merging tables in database works behind the scenes, keep reading. Because in this article, we will discuss about priority queues and disjoint set. Both data structures are beautiful to solve these problems. In the end, we will solve these problems above. Happy reading! Priority Queue is a Queue where each element is assigned a priority and elements com out in order by priority. Typical use case of priority queue is scheduling jobs. Each job has a priority and we process jobs in order of decreasing priority. While the current job is processed and new jobs may arrive. Priority Queue has some main operations: Insert(p): Adds a new element with priority p. ExtractMax(): Extracts an elements with maximum priority. ChangePriority(it, p): Changes the priority of an element pointed by it to p. Priority Queue is used in many algorithms: Dijkstra’s algorithm: finding a shortest path in a graph. Prim’s algorithms: constructing a minimum spanning tree of a graph. Huffman’s algorithm: constructing an optimum prefix-free encoding of a string. Heap sort: sorting a given sequence. You can implement priority with unsorted/sorted Array or List but each one has an trade off: But by using binary heap, we can do Insert with O(logn) and ExtractMax with O(logn). Binary heap has 2 types: binary min-heap and binary max-heap. In this article, we will discuss about binary max-heap. On the other side, binary min-heap has the same way of implementation. Binary max-heap is a binary tree(each node has zero, one or two children) where the value of each node is at least the values of its children. As you see, every children node has value not larger than the parent node. The root node has biggest value. Max-Heap has some basic operations: GetMax: just return the root value. Cost O(1). Insert: We will attach a new node to any leaf. If it violate the heap property, we will bubble up(called SiftUp) new node until the heap property is satisfied. O(tree height) As you see, we attach new node 32 to node 7, and we bubble it to node 29. ExtractMax: Root node R is the max value of max-heap. To pop out the root node, we just swap root node R to any leaf node A and remove node R. It may violate the property of heap. We will do SiftDown operation. As a parent node A, we want to SiftDown to children B and C, we will choose the max value of children B and C, and swap it to node A. We SiftDown until the property of heap is satisfied. We swap root node 42 and random leaf node 12 first, and remove node 42. The max-heap is violated now, we need to sift down node 12 as root down to children. At the final step, we have node 29 is root node. ChangePriority: We need to change priority of a node. Depend on the value of new priority we will do SiftDown or SiftUp to qualify the heap property. Remove: To remove a node A. We do it by 2 steps: Step 1: Make that value of node A becomes biggest(infinity). We will do SiftUp operation to make node A become a root node. Step 2: We do ExtractMax operation that describes above. We know how heap works, we need to find out the way to build a heap. To build a heap and keep a binary heap-tree shallows, we have to fill the new node from left to right on last level. It’s called complete binary tree. Formally: A binary tree is complete if all its levels are filled except possibly the last one which is filled from left to right. So the height of a complete binary tree with n nodes is at most O(logn). A complete binary tree has elements filled from left to right, so we can store the tree as an Array where Because we store as an array, each operation we perform need to keep the tree completed. # we store elements in array Hdef parent(i): return i/2def left_child(i): return 2idef right_child(i): return 2i + 1def sift_up(i): while i > 1 and H[parent(i)] < H[i]: swap H[parent(i)] and H[i] i <- parent(i)def sift_down(i): maxIndex <- i left <- left_child(i) if left <= size and H[left] > H[maxIndex]: maxIndex <- left right <- right_child(i) if right <= size and H[right] > H[maxIndex]: maxIndex <- right if i != maxIndex: swap H[i] and H[maxIndex] SiftDown(maxIndex)def insert(p): if size = maxSize: return ERROR size <- size + 1 H[size] <- p SiftUp(size)def extract_max(): result <- H[1] H[1] <- H[size] size <- size - 1 SiftDown(1) return resultdef remove(i): H[i] = ∞ sift_up(i) extract_max()def change_priority(i, p): oldp <- H[i] H[i] <- p if p > oldp: sift_up(i) else: sift_down(i) Back to sorting problem, we observer that the root node of a max heap is the maximum value. What if we do ExtractMax() and put into another array, the result will be sorted decrease array. It’s fundamental of selection sort. It costs O(nlogn). def heap_sort_selection_sort(A[1...n]): create an empty priority queue for i from 1 to n: Insert(A[i]) # Insert operation to build max-heap. for i from n downto 1: A[i] <- ExtractMax() In the matter of fact, we can do better heap-sort algorithm that didn’t use any extra array, it’s in-place heap sort algorithm. Given an array A = [ 4, 1, 3, 2, 16, 9, 10, 14 , 8, 7] We represent this array A as a heap: Now we need to repair all nodes to satisfy the property of max-heap. We can start repairing the nodes in all subtrees of depth 1(depth 0 is all the leaves). The node from depth 1 is from n/2 down to 1 def build_heap(A[1...n]): size <- n for i from n/2 downto 1: SiftDown(i) We start from parent node 5, 4, 3, 2, 1([16, 2, 3, 1, 4]). Each step, we do SiftDown operation. Finally, we can have a max heap(f). To sort a max heap, we just swap the node A[1] and A[size], remove A[size] and SiftDown(1). def heap_sort(A[1...n]): repeat (n-1) times: swap A[1] and A[size] size <- size - 1 SiftDown(1) Given an array A[1...n], and 1 ≤ k ≤ n. Output the last k elements of a sorted version of A. With heap sort, we easily solve this problem: def partial_sorting(A[1...n], k): build_heap(A) for i from 1 to k: extract_max() The running time is: O(n+klogn). For the small number k = O(n/logn), the cost will be O(n). Really impressive. Disjoint sets has many applications, one of them is determining the connected components of an undirected graph. Disjoint set data structure maintains the collection of S1, S2, ..., Sk of disjoint dynamic set. Each set we represent as a rooted tree. We can store these set(rooted trees) by using an array which is the value A[i] is the parent of node i or node i if it is the root. Disjoint set has some main operations: MakeSet(i): Create a set contain only one i: {i}. def make_set(i): parent[i] <- i Find(i): Finding i in a set, return root index def find(i): while i != parent[i]: i <- parent[i] return i Union(S1, S2): Merge 2 rooted trees. It’s the most important operation of disjoint set. We have 2 rooted trees and we want to union these trees. Normally, we have 2 ways to do that: The good one is the one with shorter of height. How do we know to choose the root node for union set? To answer that question, we just need to use a rank as heigh to choose the final root. In other words, we just hang the shorter one under the root of a taller one. To avoid re-calculating the rank(height) each time to do union operation, we need to store height of each subtree in an array rank[1...n] where rank[i] is the height of the subtree whose root is i. We change our implements of disjoint set operations: def make_set(i): parent[i] <- i rank[i] <- 0def find(i): while i != parent[i]: i <- parent[i] return idef union(i, j): i_id <- find(i) j_id <- find(j) if i_id == j_id: return if rank[i_id] > rank[j_id]: parent[j_id] <- i_id else: parent[i_id] <- j_id if rank[i_id] == rank[j_id]: rank[j_id] <- rank[j_id] + 1 Let visualize the process of building a disjoint set, and do union(2, 4), union(5, 2), union(3, 1), union(2, 3), union(2,6). Each step, we need to choose lower rank tree and attach it to higher rank tree. We only increase rank of result when we have 2 trees with the same rank. While building the tree, we can immediately realize that our tree will become higher, higher. Let see how to find element 6, we do travel to all parent node to get root node 5. Notice that all node 6, 12, 3 has same root node 5, so it will be wonderful if we can transform all their parent node into direct parent node 5 likes this one: You can see, we can compress the height and we can find element faster. You will be surprise to see that the implement of this heuristic so simple: def find(i): if i != parent[i]: parent[i] <- find(parent[i]) return parent[i] In this problem you will convert an array of integers into a heap. This is the crucial step of the sorting algorithm called HeapSort. It has guaranteed worst-case running time of O(n log n) as opposed to QuickSort’s average running time of O(n log n). QuickSort is usually used in practice, because typically it is faster, but HeapSort is used for external sort when you need to sort huge files that don’t t into memory of your computer. Problem Description Task. The first step of the HeapSort algorithm is to create a heap from the array you want to sort. By the way, did you know that algorithms based on Heaps are widely used for external sort, when you need to sort huge files that don’t t into memory of a computer? Your task is to implement this first step and convert a given array of integers into a heap. You will do that by applying a certain number of swaps to the array. Swap is an operation which exchanges elements ai and aj of the array a for some i and j. You will need to convert the array into a heap using only O(n) swaps, as was described in the lectures. Note that you will need to use a min-heap instead of a max-heap in this problem. Input Format. The first line of the input contains single integer n. The next line contains n space-separated integers ai. Output Format. The first line of the output should contain single integer m — the total number of swaps. m must satisfy conditions 0 ≤ m ≤ 4n. The next m lines should contain the swap operations used to convert the array a into a heap. Each swap is described by a pair of integers i,j — the 0-based indices of the elements to be swapped. After applying all the swaps in the specified order the array must become a heap, that is, for each i where 0 ≤ i ≤ n − 1 the following conditions must be true: 1. If 2i+1 ≤ n−1,then ai < a(2i+1).2. If 2i+2 ≤ n−1,then ai < a(2i+2). Note that all the elements of the input array are distinct. Note that any sequence of swaps that has length at most 4n and after which your initial array becomes a correct heap will be graded as correct. Sample 1. Input: 55 4 3 2 1 Output: 31 40 11 3 Explanation: After swapping elements 4 in position 1 and 1 in position 4 the array becomes 5 1 3 2 4.After swapping elements 5 in position 0 and 1 in position 1 the array becomes 1 5 3 2 4.After swapping elements 5 in position 1 and 2 in position 3 the array becomes 1 2 3 5 4, which is already a heap, because a0 =1 < 2 = a1, a0 =1 < 3=a2, a1=2 < 5=a3, a1=2 < 4=a4. Change the BuildHeap algorithm from the lecture to account for min-heap instead of max-heap and for 0-based indexing. While building a heap, we will do SiftDown operation from n/2-th down to 1-th node to repair a heap to satisfy min-heap property. Each time we swap nodes, we need to track it . In this problem you will simulate a program that processes a list of jobs in parallel. Operating systems such as Linux, MacOS or Windows all have special programs in them called schedulers which do exactly this with the programs on your computer. Problem Description Task. You have a program which is parallelized and uses n independent threads to process the given list of m jobs. Threads take jobs in the order they are given in the input. If there is a free thread, it immediately takes the next job from the list. If a thread has started processing a job, it doesn’t interrupt or stop until it finishes processing the job. If several threads try to take jobs from the list simultaneously, the thread with smaller index takes the job. For each job you know exactly how long will it take any thread to process this job, and this time is the same for all the threads. You need to determine for each job which thread will process it and when will it start processing. Input Format. The first line of the input contains integers n and m. The second line contains m integers ti — the times in seconds it takes any thread to process i-th job. The times are given in the same order as they are in the list from which threads take jobs. Threads are indexed starting from 0. Output Format. Output exactly m lines. i-th line (0-based index is used) should contain two space- separated integers — the 0-based index of the thread which will process the i-th job and the time in seconds when it will start processing that job. Sample 1. Input: 2 5 1 2 3 4 5 Output: 0 01 00 11 20 4 Explanation: 1. The two threads try to simultaneously take jobs from the list, so thread with index 0 actually takes the first job and starts working on it at the moment 0.2. The thread with index 1 takes the second job and starts working on it also at the moment 0.3. After 1 second, thread 0 is done with the first job and takes the third job from the list, and starts processing it immediately at time 1.4. One second later, thread 1 is done with the second job and takes the fourth job from the list, and starts processing it immediately at time 2.5. Finally, after 2 more seconds, thread 0 is done with the third job and takes the fifth job from the list, and starts processing it immediately at time 4. Think about the sequence of events when one of the threads becomes free (at the start and later after completing some job). How to apply priority queue to simulate processing of these events in the required order? Remember to consider the case when several threads become free simultaneously. Beware of integer over ow in this problem: use type long long in C++ and type long in Java wherever the regular type int can over ow given the restrictions in the problem statement. The idea is we need a priority queue to keep workers. We compare 2 workers by its status and index. To choose the next worker, we just choose the root min-heap tree. To mark it working, we need to ChangePriority of root tree and repair tree. In this problem, your goal is to simulate a sequence of merge operations with tables in a database. Problem Description Task. There are n tables stored in some database. The tables are numbered from 1 to n. All tables share the same set of columns. Each table contains either several rows with real data or a symbolic link to another table. Initially, all tables contain data, and i-th table has ri rows. You need to perform m of the following operations: 1. Consider table number destination(i). Traverse the path of symbolic links to get to the data. That is, while destination(i) contains a symbolic link instead of real data do destination(i) ← symlink(destination(i)) 2. Consider the table number source(i) and traverse the path of symbolic links from it in the same manner as for destination(i). 3. Now, destinationi and source(i) are the numbers of two tables with real data. If destination(i) != source(i), copy all the rows from table source(i) to table destination(i), then clear the table source(i) and instead of real data put a symbolic link to destination(i) into it. 4. Print the maximum size among all n tables (recall that size is the number of rows in the table). If the table contains only a symbolic link, its size is considered to be 0. See examples and explanations for further clarifications. Input Format. The first line of the input contains two integers n and m — the number of tables in the database and the number of merge queries to perform, respectively. The second line of the input contains n integers ri — the number of rows in the i-th table. Then follow m lines describing merge queries. Each of them contains two integers destination(i) and source(i) — the numbers of the tables to merge. Output Format. For each query print a line containing a single integer — the maximum of the sizes of all tables (in terms of the number of rows) after the corresponding operation. Sample 1. Input: 5 5 1 1 1 1 13 52 41 45 45 3 Output: 22355 Explanation: In this sample, all the tables initially have exactly 1 row of data. Consider the merging operations: 1. All the data from the table 5 is copied to table number 3. Table 5 now contains only a symbolic link to table 3, while table 3 has 2 rows. 2 becomes the new maximum size. 2. 2 and 4 are merged in the same way as 3 and 5. 3. We are trying to merge 1 and 4, but 4 has a symbolic link pointing to 2, so we actually copy all the data from the table number 2 to the table number 1, clear the table number 2 and put a symbolic link to the table number 1 in it. Table 1 now has 3 rows of data, and 3 becomes the new maximum size. 4. Traversing the path of symbolic links from 4 we have 4→2→1, and the path from 5 is 5→3. So we are actually merging tables 3 and 1. We copy all the rows from the table number 1 into the table number 3, and now the table number 3 has 5 rows of data, which is the new maximum. 5. All tables now directly or indirectly point to table 3, so all other merges won’t change anything. Sample 2. Input: 6 410 0 5 0 3 3 6 66 55 64 3 Output: 10 10 10 11 Explanation: In this example tables have diferent sizes. Let us consider the operations: 1. Merging the table number 6 with itself doesn’t change anything, and the maximum size is 10 (table number 1). 2. After merging the table number 5 into the table number 6, the table number 5 is cleared and has size 0, while the table number 6 has size 6. Still, the maximum size is 10. 3. By merging the table number 4 into the table number 5, we actually merge the table number 4 into the table number 6 (table 5 now contains just a symbolic link to table 6), so the table number 4 is cleared and has size 0, while the table number 6 has size 6. Still, the maximum size is 10. 4. By merging the table number 3 into the table number 4, we actually merge the table number 3 into the table number 6 (table 4 now contains just a symbolic link to table 6), so the table number 3 is cleared and has size 0, while the table number 6 has size 11, which is the new maximum size. Think how to use disjoint set union with path compression and union by rank heuristics to solve this problem. In particular, you should separate in your thinking the data structure that performs union/find operations from the merges of tables. If you’re asked to merge first table into second, but the rank of the second table is smaller than the rank of the first table, you can ignore the requested order while merging in the Disjoint Set Union data structure and join the node corresponding to the second table to the node corresponding to the first table instead in you Disjoint Set Union. However, you will need to store the number of the actual second table to which you were requested to merge the first table in the parent node of the corresponding Disjoint Set, and you will need an additional eld in the nodes of Disjoint Set Union to store it. We use parent array to store disjoint set. We use lines array to store maximum of root i. We need to build disjoint set with raking and path compression heuristic. See the chapter 6.4 in [CLRS] — Priority Queue See this min-heap visualization. See section 5.1.4 in [DPVo8] — Disjoint set Also see this tutorial on Disjoint Sets data structures. Also see this visualization of Disjoint Sets with and without Path Compression and Union by Rank heuristics. [DPV08] Sanjoy Dasgupta, Christos Papadimitriou, and Umesh Vazirani. Algorithms (1st Edition). McGraw-Hill Higher Education. 2008. [CLRS] Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein. Introduction to Algorithms (3rd Edition). MIT Press and McGraw-Hill. 2009.
[ { "code": null, "e": 549, "s": 172, "text": "If we ever want to know how background job works, fastest way to find k smallest elements in an array, how merging tables in database works behind the scenes, keep reading. Because in this article, we will discuss about priority queues and disjoint set. Both data structures are beautiful to solve these problems. In the end, we will solve these problems above. Happy reading!" }, { "code": null, "e": 852, "s": 549, "text": "Priority Queue is a Queue where each element is assigned a priority and elements com out in order by priority. Typical use case of priority queue is scheduling jobs. Each job has a priority and we process jobs in order of decreasing priority. While the current job is processed and new jobs may arrive." }, { "code": null, "e": 893, "s": 852, "text": "Priority Queue has some main operations:" }, { "code": null, "e": 940, "s": 893, "text": "Insert(p): Adds a new element with priority p." }, { "code": null, "e": 998, "s": 940, "text": "ExtractMax(): Extracts an elements with maximum priority." }, { "code": null, "e": 1076, "s": 998, "text": "ChangePriority(it, p): Changes the priority of an element pointed by it to p." }, { "code": null, "e": 1119, "s": 1076, "text": "Priority Queue is used in many algorithms:" }, { "code": null, "e": 1177, "s": 1119, "text": "Dijkstra’s algorithm: finding a shortest path in a graph." }, { "code": null, "e": 1245, "s": 1177, "text": "Prim’s algorithms: constructing a minimum spanning tree of a graph." }, { "code": null, "e": 1324, "s": 1245, "text": "Huffman’s algorithm: constructing an optimum prefix-free encoding of a string." }, { "code": null, "e": 1361, "s": 1324, "text": "Heap sort: sorting a given sequence." }, { "code": null, "e": 1454, "s": 1361, "text": "You can implement priority with unsorted/sorted Array or List but each one has an trade off:" }, { "code": null, "e": 1539, "s": 1454, "text": "But by using binary heap, we can do Insert with O(logn) and ExtractMax with O(logn)." }, { "code": null, "e": 1728, "s": 1539, "text": "Binary heap has 2 types: binary min-heap and binary max-heap. In this article, we will discuss about binary max-heap. On the other side, binary min-heap has the same way of implementation." }, { "code": null, "e": 1871, "s": 1728, "text": "Binary max-heap is a binary tree(each node has zero, one or two children) where the value of each node is at least the values of its children." }, { "code": null, "e": 1979, "s": 1871, "text": "As you see, every children node has value not larger than the parent node. The root node has biggest value." }, { "code": null, "e": 2015, "s": 1979, "text": "Max-Heap has some basic operations:" }, { "code": null, "e": 2062, "s": 2015, "text": "GetMax: just return the root value. Cost O(1)." }, { "code": null, "e": 2237, "s": 2062, "text": "Insert: We will attach a new node to any leaf. If it violate the heap property, we will bubble up(called SiftUp) new node until the heap property is satisfied. O(tree height)" }, { "code": null, "e": 2311, "s": 2237, "text": "As you see, we attach new node 32 to node 7, and we bubble it to node 29." }, { "code": null, "e": 2709, "s": 2311, "text": "ExtractMax: Root node R is the max value of max-heap. To pop out the root node, we just swap root node R to any leaf node A and remove node R. It may violate the property of heap. We will do SiftDown operation. As a parent node A, we want to SiftDown to children B and C, we will choose the max value of children B and C, and swap it to node A. We SiftDown until the property of heap is satisfied." }, { "code": null, "e": 2915, "s": 2709, "text": "We swap root node 42 and random leaf node 12 first, and remove node 42. The max-heap is violated now, we need to sift down node 12 as root down to children. At the final step, we have node 29 is root node." }, { "code": null, "e": 3065, "s": 2915, "text": "ChangePriority: We need to change priority of a node. Depend on the value of new priority we will do SiftDown or SiftUp to qualify the heap property." }, { "code": null, "e": 3114, "s": 3065, "text": "Remove: To remove a node A. We do it by 2 steps:" }, { "code": null, "e": 3238, "s": 3114, "text": "Step 1: Make that value of node A becomes biggest(infinity). We will do SiftUp operation to make node A become a root node." }, { "code": null, "e": 3295, "s": 3238, "text": "Step 2: We do ExtractMax operation that describes above." }, { "code": null, "e": 3525, "s": 3295, "text": "We know how heap works, we need to find out the way to build a heap. To build a heap and keep a binary heap-tree shallows, we have to fill the new node from left to right on last level. It’s called complete binary tree. Formally:" }, { "code": null, "e": 3718, "s": 3525, "text": "A binary tree is complete if all its levels are filled except possibly the last one which is filled from left to right. So the height of a complete binary tree with n nodes is at most O(logn)." }, { "code": null, "e": 3824, "s": 3718, "text": "A complete binary tree has elements filled from left to right, so we can store the tree as an Array where" }, { "code": null, "e": 3913, "s": 3824, "text": "Because we store as an array, each operation we perform need to keep the tree completed." }, { "code": null, "e": 4761, "s": 3913, "text": "# we store elements in array Hdef parent(i): return i/2def left_child(i): return 2idef right_child(i): return 2i + 1def sift_up(i): while i > 1 and H[parent(i)] < H[i]: swap H[parent(i)] and H[i] i <- parent(i)def sift_down(i): maxIndex <- i left <- left_child(i) if left <= size and H[left] > H[maxIndex]: maxIndex <- left right <- right_child(i) if right <= size and H[right] > H[maxIndex]: maxIndex <- right if i != maxIndex: swap H[i] and H[maxIndex] SiftDown(maxIndex)def insert(p): if size = maxSize: return ERROR size <- size + 1 H[size] <- p SiftUp(size)def extract_max(): result <- H[1] H[1] <- H[size] size <- size - 1 SiftDown(1) return resultdef remove(i): H[i] = ∞ sift_up(i) extract_max()def change_priority(i, p): oldp <- H[i] H[i] <- p if p > oldp: sift_up(i) else: sift_down(i)" }, { "code": null, "e": 5005, "s": 4761, "text": "Back to sorting problem, we observer that the root node of a max heap is the maximum value. What if we do ExtractMax() and put into another array, the result will be sorted decrease array. It’s fundamental of selection sort. It costs O(nlogn)." }, { "code": null, "e": 5199, "s": 5005, "text": "def heap_sort_selection_sort(A[1...n]): create an empty priority queue for i from 1 to n: Insert(A[i]) # Insert operation to build max-heap. for i from n downto 1: A[i] <- ExtractMax()" }, { "code": null, "e": 5342, "s": 5199, "text": "In the matter of fact, we can do better heap-sort algorithm that didn’t use any extra array, it’s in-place heap sort algorithm. Given an array" }, { "code": null, "e": 5382, "s": 5342, "text": "A = [ 4, 1, 3, 2, 16, 9, 10, 14 , 8, 7]" }, { "code": null, "e": 5419, "s": 5382, "text": "We represent this array A as a heap:" }, { "code": null, "e": 5620, "s": 5419, "text": "Now we need to repair all nodes to satisfy the property of max-heap. We can start repairing the nodes in all subtrees of depth 1(depth 0 is all the leaves). The node from depth 1 is from n/2 down to 1" }, { "code": null, "e": 5698, "s": 5620, "text": "def build_heap(A[1...n]): size <- n for i from n/2 downto 1: SiftDown(i)" }, { "code": null, "e": 5830, "s": 5698, "text": "We start from parent node 5, 4, 3, 2, 1([16, 2, 3, 1, 4]). Each step, we do SiftDown operation. Finally, we can have a max heap(f)." }, { "code": null, "e": 5922, "s": 5830, "text": "To sort a max heap, we just swap the node A[1] and A[size], remove A[size] and SiftDown(1)." }, { "code": null, "e": 6028, "s": 5922, "text": "def heap_sort(A[1...n]): repeat (n-1) times: swap A[1] and A[size] size <- size - 1 SiftDown(1)" }, { "code": null, "e": 6121, "s": 6028, "text": "Given an array A[1...n], and 1 ≤ k ≤ n. Output the last k elements of a sorted version of A." }, { "code": null, "e": 6167, "s": 6121, "text": "With heap sort, we easily solve this problem:" }, { "code": null, "e": 6253, "s": 6167, "text": "def partial_sorting(A[1...n], k): build_heap(A) for i from 1 to k: extract_max()" }, { "code": null, "e": 6364, "s": 6253, "text": "The running time is: O(n+klogn). For the small number k = O(n/logn), the cost will be O(n). Really impressive." }, { "code": null, "e": 6477, "s": 6364, "text": "Disjoint sets has many applications, one of them is determining the connected components of an undirected graph." }, { "code": null, "e": 6614, "s": 6477, "text": "Disjoint set data structure maintains the collection of S1, S2, ..., Sk of disjoint dynamic set. Each set we represent as a rooted tree." }, { "code": null, "e": 6746, "s": 6614, "text": "We can store these set(rooted trees) by using an array which is the value A[i] is the parent of node i or node i if it is the root." }, { "code": null, "e": 6785, "s": 6746, "text": "Disjoint set has some main operations:" }, { "code": null, "e": 6835, "s": 6785, "text": "MakeSet(i): Create a set contain only one i: {i}." }, { "code": null, "e": 6868, "s": 6835, "text": "def make_set(i): parent[i] <- i" }, { "code": null, "e": 6915, "s": 6868, "text": "Find(i): Finding i in a set, return root index" }, { "code": null, "e": 6979, "s": 6915, "text": "def find(i): while i != parent[i]: i <- parent[i] return i" }, { "code": null, "e": 7067, "s": 6979, "text": "Union(S1, S2): Merge 2 rooted trees. It’s the most important operation of disjoint set." }, { "code": null, "e": 7161, "s": 7067, "text": "We have 2 rooted trees and we want to union these trees. Normally, we have 2 ways to do that:" }, { "code": null, "e": 7263, "s": 7161, "text": "The good one is the one with shorter of height. How do we know to choose the root node for union set?" }, { "code": null, "e": 7625, "s": 7263, "text": "To answer that question, we just need to use a rank as heigh to choose the final root. In other words, we just hang the shorter one under the root of a taller one. To avoid re-calculating the rank(height) each time to do union operation, we need to store height of each subtree in an array rank[1...n] where rank[i] is the height of the subtree whose root is i." }, { "code": null, "e": 7678, "s": 7625, "text": "We change our implements of disjoint set operations:" }, { "code": null, "e": 8016, "s": 7678, "text": "def make_set(i): parent[i] <- i rank[i] <- 0def find(i): while i != parent[i]: i <- parent[i] return idef union(i, j): i_id <- find(i) j_id <- find(j) if i_id == j_id: return if rank[i_id] > rank[j_id]: parent[j_id] <- i_id else: parent[i_id] <- j_id if rank[i_id] == rank[j_id]: rank[j_id] <- rank[j_id] + 1" }, { "code": null, "e": 8141, "s": 8016, "text": "Let visualize the process of building a disjoint set, and do union(2, 4), union(5, 2), union(3, 1), union(2, 3), union(2,6)." }, { "code": null, "e": 8294, "s": 8141, "text": "Each step, we need to choose lower rank tree and attach it to higher rank tree. We only increase rank of result when we have 2 trees with the same rank." }, { "code": null, "e": 8471, "s": 8294, "text": "While building the tree, we can immediately realize that our tree will become higher, higher. Let see how to find element 6, we do travel to all parent node to get root node 5." }, { "code": null, "e": 8631, "s": 8471, "text": "Notice that all node 6, 12, 3 has same root node 5, so it will be wonderful if we can transform all their parent node into direct parent node 5 likes this one:" }, { "code": null, "e": 8779, "s": 8631, "text": "You can see, we can compress the height and we can find element faster. You will be surprise to see that the implement of this heuristic so simple:" }, { "code": null, "e": 8862, "s": 8779, "text": "def find(i): if i != parent[i]: parent[i] <- find(parent[i]) return parent[i]" }, { "code": null, "e": 9300, "s": 8862, "text": "In this problem you will convert an array of integers into a heap. This is the crucial step of the sorting algorithm called HeapSort. It has guaranteed worst-case running time of O(n log n) as opposed to QuickSort’s average running time of O(n log n). QuickSort is usually used in practice, because typically it is faster, but HeapSort is used for external sort when you need to sort huge files that don’t t into memory of your computer." }, { "code": null, "e": 9320, "s": 9300, "text": "Problem Description" }, { "code": null, "e": 9584, "s": 9320, "text": "Task. The first step of the HeapSort algorithm is to create a heap from the array you want to sort. By the way, did you know that algorithms based on Heaps are widely used for external sort, when you need to sort huge files that don’t t into memory of a computer?" }, { "code": null, "e": 10020, "s": 9584, "text": "Your task is to implement this first step and convert a given array of integers into a heap. You will do that by applying a certain number of swaps to the array. Swap is an operation which exchanges elements ai and aj of the array a for some i and j. You will need to convert the array into a heap using only O(n) swaps, as was described in the lectures. Note that you will need to use a min-heap instead of a max-heap in this problem." }, { "code": null, "e": 10143, "s": 10020, "text": "Input Format. The first line of the input contains single integer n. The next line contains n space-separated integers ai." }, { "code": null, "e": 10642, "s": 10143, "text": "Output Format. The first line of the output should contain single integer m — the total number of swaps. m must satisfy conditions 0 ≤ m ≤ 4n. The next m lines should contain the swap operations used to convert the array a into a heap. Each swap is described by a pair of integers i,j — the 0-based indices of the elements to be swapped. After applying all the swaps in the specified order the array must become a heap, that is, for each i where 0 ≤ i ≤ n − 1 the following conditions must be true:" }, { "code": null, "e": 10713, "s": 10642, "text": "1. If 2i+1 ≤ n−1,then ai < a(2i+1).2. If 2i+2 ≤ n−1,then ai < a(2i+2)." }, { "code": null, "e": 10917, "s": 10713, "text": "Note that all the elements of the input array are distinct. Note that any sequence of swaps that has length at most 4n and after which your initial array becomes a correct heap will be graded as correct." }, { "code": null, "e": 10927, "s": 10917, "text": "Sample 1." }, { "code": null, "e": 10934, "s": 10927, "text": "Input:" }, { "code": null, "e": 10945, "s": 10934, "text": "55 4 3 2 1" }, { "code": null, "e": 10953, "s": 10945, "text": "Output:" }, { "code": null, "e": 10964, "s": 10953, "text": "31 40 11 3" }, { "code": null, "e": 10977, "s": 10964, "text": "Explanation:" }, { "code": null, "e": 11331, "s": 10977, "text": "After swapping elements 4 in position 1 and 1 in position 4 the array becomes 5 1 3 2 4.After swapping elements 5 in position 0 and 1 in position 1 the array becomes 1 5 3 2 4.After swapping elements 5 in position 1 and 2 in position 3 the array becomes 1 2 3 5 4, which is already a heap, because a0 =1 < 2 = a1, a0 =1 < 3=a2, a1=2 < 5=a3, a1=2 < 4=a4." }, { "code": null, "e": 11449, "s": 11331, "text": "Change the BuildHeap algorithm from the lecture to account for min-heap instead of max-heap and for 0-based indexing." }, { "code": null, "e": 11626, "s": 11449, "text": "While building a heap, we will do SiftDown operation from n/2-th down to 1-th node to repair a heap to satisfy min-heap property. Each time we swap nodes, we need to track it ." }, { "code": null, "e": 11873, "s": 11626, "text": "In this problem you will simulate a program that processes a list of jobs in parallel. Operating systems such as Linux, MacOS or Windows all have special programs in them called schedulers which do exactly this with the programs on your computer." }, { "code": null, "e": 11893, "s": 11873, "text": "Problem Description" }, { "code": null, "e": 12594, "s": 11893, "text": "Task. You have a program which is parallelized and uses n independent threads to process the given list of m jobs. Threads take jobs in the order they are given in the input. If there is a free thread, it immediately takes the next job from the list. If a thread has started processing a job, it doesn’t interrupt or stop until it finishes processing the job. If several threads try to take jobs from the list simultaneously, the thread with smaller index takes the job. For each job you know exactly how long will it take any thread to process this job, and this time is the same for all the threads. You need to determine for each job which thread will process it and when will it start processing." }, { "code": null, "e": 12663, "s": 12594, "text": "Input Format. The first line of the input contains integers n and m." }, { "code": null, "e": 12858, "s": 12663, "text": "The second line contains m integers ti — the times in seconds it takes any thread to process i-th job. The times are given in the same order as they are in the list from which threads take jobs." }, { "code": null, "e": 12895, "s": 12858, "text": "Threads are indexed starting from 0." }, { "code": null, "e": 13143, "s": 12895, "text": "Output Format. Output exactly m lines. i-th line (0-based index is used) should contain two space- separated integers — the 0-based index of the thread which will process the i-th job and the time in seconds when it will start processing that job." }, { "code": null, "e": 13153, "s": 13143, "text": "Sample 1." }, { "code": null, "e": 13160, "s": 13153, "text": "Input:" }, { "code": null, "e": 13174, "s": 13160, "text": "2 5 1 2 3 4 5" }, { "code": null, "e": 13182, "s": 13174, "text": "Output:" }, { "code": null, "e": 13198, "s": 13182, "text": "0 01 00 11 20 4" }, { "code": null, "e": 13211, "s": 13198, "text": "Explanation:" }, { "code": null, "e": 13907, "s": 13211, "text": "1. The two threads try to simultaneously take jobs from the list, so thread with index 0 actually takes the first job and starts working on it at the moment 0.2. The thread with index 1 takes the second job and starts working on it also at the moment 0.3. After 1 second, thread 0 is done with the first job and takes the third job from the list, and starts processing it immediately at time 1.4. One second later, thread 1 is done with the second job and takes the fourth job from the list, and starts processing it immediately at time 2.5. Finally, after 2 more seconds, thread 0 is done with the third job and takes the fifth job from the list, and starts processing it immediately at time 4." }, { "code": null, "e": 14200, "s": 13907, "text": "Think about the sequence of events when one of the threads becomes free (at the start and later after completing some job). How to apply priority queue to simulate processing of these events in the required order? Remember to consider the case when several threads become free simultaneously." }, { "code": null, "e": 14382, "s": 14200, "text": "Beware of integer over ow in this problem: use type long long in C++ and type long in Java wherever the regular type int can over ow given the restrictions in the problem statement." }, { "code": null, "e": 14624, "s": 14382, "text": "The idea is we need a priority queue to keep workers. We compare 2 workers by its status and index. To choose the next worker, we just choose the root min-heap tree. To mark it working, we need to ChangePriority of root tree and repair tree." }, { "code": null, "e": 14724, "s": 14624, "text": "In this problem, your goal is to simulate a sequence of merge operations with tables in a database." }, { "code": null, "e": 14744, "s": 14724, "text": "Problem Description" }, { "code": null, "e": 15080, "s": 14744, "text": "Task. There are n tables stored in some database. The tables are numbered from 1 to n. All tables share the same set of columns. Each table contains either several rows with real data or a symbolic link to another table. Initially, all tables contain data, and i-th table has ri rows. You need to perform m of the following operations:" }, { "code": null, "e": 15297, "s": 15080, "text": "1. Consider table number destination(i). Traverse the path of symbolic links to get to the data. That is, while destination(i) contains a symbolic link instead of real data do destination(i) ← symlink(destination(i))" }, { "code": null, "e": 15426, "s": 15297, "text": "2. Consider the table number source(i) and traverse the path of symbolic links from it in the same manner as for destination(i)." }, { "code": null, "e": 15706, "s": 15426, "text": "3. Now, destinationi and source(i) are the numbers of two tables with real data. If destination(i) != source(i), copy all the rows from table source(i) to table destination(i), then clear the table source(i) and instead of real data put a symbolic link to destination(i) into it." }, { "code": null, "e": 15882, "s": 15706, "text": "4. Print the maximum size among all n tables (recall that size is the number of rows in the table). If the table contains only a symbolic link, its size is considered to be 0." }, { "code": null, "e": 15940, "s": 15882, "text": "See examples and explanations for further clarifications." }, { "code": null, "e": 16109, "s": 15940, "text": "Input Format. The first line of the input contains two integers n and m — the number of tables in the database and the number of merge queries to perform, respectively." }, { "code": null, "e": 16201, "s": 16109, "text": "The second line of the input contains n integers ri — the number of rows in the i-th table." }, { "code": null, "e": 16349, "s": 16201, "text": "Then follow m lines describing merge queries. Each of them contains two integers destination(i) and source(i) — the numbers of the tables to merge." }, { "code": null, "e": 16529, "s": 16349, "text": "Output Format. For each query print a line containing a single integer — the maximum of the sizes of all tables (in terms of the number of rows) after the corresponding operation." }, { "code": null, "e": 16539, "s": 16529, "text": "Sample 1." }, { "code": null, "e": 16546, "s": 16539, "text": "Input:" }, { "code": null, "e": 16575, "s": 16546, "text": "5 5 1 1 1 1 13 52 41 45 45 3" }, { "code": null, "e": 16583, "s": 16575, "text": "Output:" }, { "code": null, "e": 16589, "s": 16583, "text": "22355" }, { "code": null, "e": 16602, "s": 16589, "text": "Explanation:" }, { "code": null, "e": 16704, "s": 16602, "text": "In this sample, all the tables initially have exactly 1 row of data. Consider the merging operations:" }, { "code": null, "e": 16878, "s": 16704, "text": "1. All the data from the table 5 is copied to table number 3. Table 5 now contains only a symbolic link to table 3, while table 3 has 2 rows. 2 becomes the new maximum size." }, { "code": null, "e": 16928, "s": 16878, "text": "2. 2 and 4 are merged in the same way as 3 and 5." }, { "code": null, "e": 17230, "s": 16928, "text": "3. We are trying to merge 1 and 4, but 4 has a symbolic link pointing to 2, so we actually copy all the data from the table number 2 to the table number 1, clear the table number 2 and put a symbolic link to the table number 1 in it. Table 1 now has 3 rows of data, and 3 becomes the new maximum size." }, { "code": null, "e": 17507, "s": 17230, "text": "4. Traversing the path of symbolic links from 4 we have 4→2→1, and the path from 5 is 5→3. So we are actually merging tables 3 and 1. We copy all the rows from the table number 1 into the table number 3, and now the table number 3 has 5 rows of data, which is the new maximum." }, { "code": null, "e": 17609, "s": 17507, "text": "5. All tables now directly or indirectly point to table 3, so all other merges won’t change anything." }, { "code": null, "e": 17619, "s": 17609, "text": "Sample 2." }, { "code": null, "e": 17626, "s": 17619, "text": "Input:" }, { "code": null, "e": 17655, "s": 17626, "text": "6 410 0 5 0 3 3 6 66 55 64 3" }, { "code": null, "e": 17663, "s": 17655, "text": "Output:" }, { "code": null, "e": 17675, "s": 17663, "text": "10 10 10 11" }, { "code": null, "e": 17688, "s": 17675, "text": "Explanation:" }, { "code": null, "e": 17764, "s": 17688, "text": "In this example tables have diferent sizes. Let us consider the operations:" }, { "code": null, "e": 17876, "s": 17764, "text": "1. Merging the table number 6 with itself doesn’t change anything, and the maximum size is 10 (table number 1)." }, { "code": null, "e": 18051, "s": 17876, "text": "2. After merging the table number 5 into the table number 6, the table number 5 is cleared and has size 0, while the table number 6 has size 6. Still, the maximum size is 10." }, { "code": null, "e": 18343, "s": 18051, "text": "3. By merging the table number 4 into the table number 5, we actually merge the table number 4 into the table number 6 (table 5 now contains just a symbolic link to table 6), so the table number 4 is cleared and has size 0, while the table number 6 has size 6. Still, the maximum size is 10." }, { "code": null, "e": 18636, "s": 18343, "text": "4. By merging the table number 3 into the table number 4, we actually merge the table number 3 into the table number 6 (table 4 now contains just a symbolic link to table 6), so the table number 3 is cleared and has size 0, while the table number 6 has size 11, which is the new maximum size." }, { "code": null, "e": 19491, "s": 18636, "text": "Think how to use disjoint set union with path compression and union by rank heuristics to solve this problem. In particular, you should separate in your thinking the data structure that performs union/find operations from the merges of tables. If you’re asked to merge first table into second, but the rank of the second table is smaller than the rank of the first table, you can ignore the requested order while merging in the Disjoint Set Union data structure and join the node corresponding to the second table to the node corresponding to the first table instead in you Disjoint Set Union. However, you will need to store the number of the actual second table to which you were requested to merge the first table in the parent node of the corresponding Disjoint Set, and you will need an additional eld in the nodes of Disjoint Set Union to store it." }, { "code": null, "e": 19534, "s": 19491, "text": "We use parent array to store disjoint set." }, { "code": null, "e": 19581, "s": 19534, "text": "We use lines array to store maximum of root i." }, { "code": null, "e": 19655, "s": 19581, "text": "We need to build disjoint set with raking and path compression heuristic." }, { "code": null, "e": 19702, "s": 19655, "text": "See the chapter 6.4 in [CLRS] — Priority Queue" }, { "code": null, "e": 19735, "s": 19702, "text": "See this min-heap visualization." }, { "code": null, "e": 19779, "s": 19735, "text": "See section 5.1.4 in [DPVo8] — Disjoint set" }, { "code": null, "e": 19836, "s": 19779, "text": "Also see this tutorial on Disjoint Sets data structures." }, { "code": null, "e": 19945, "s": 19836, "text": "Also see this visualization of Disjoint Sets with and without Path Compression and Union by Rank heuristics." }, { "code": null, "e": 20076, "s": 19945, "text": "[DPV08] Sanjoy Dasgupta, Christos Papadimitriou, and Umesh Vazirani. Algorithms (1st Edition). McGraw-Hill Higher Education. 2008." } ]
Data Structures and Algorithms | Set 14 - GeeksforGeeks
05 Jul, 2018 Following questions have been asked in GATE CS 2008 exam. 1. We have a binary heap on n elements and wish to insert n more elements (not necessarily one after another) into this heap. The total time required for this is(A) Θ(logn)(B) Θ(n)(C) Θ(nlogn)(D) Θ(n2) The worst case time complexity for insertion in a binary heap is O(Logn) (Refer Wiki). So inserting n elements in a heap of size n should take Θ(nlogn) time.But choice (B) seems to be more appropriate answer. One of the solution of O(n) complexity can be to take the ‘n’ elements of the heap and other ‘n’ elements together and construct heap in O(2n) = O(n). Thanks to pankaj for suggesting this solution. 2. The Breadth First Search algorithm has been implemented using the queue data structure. One possible order of visiting the nodes of the following graph is (A) MNOPQR(B) NQMPOR(C) QMNPRO(D) QMNPOR Answer (C) 3. Consider the following functions: f(n) = 2^n g(n) = n! h(n) = n^logn Which of the following statements about the asymptotic behaviour of f(n), g(n), and h(n) is true?(A) f(n) = O(g(n)); g(n) = O(h(n))(B) f(n) = Ω(g(n)); g(n) = O(h(n))(C) g(n) = O(f(n)); h(n) = O(f(n))(D) h(n) = O(f(n)); g(n) = Ω(f(n)) Answer (D) According to order of growth: h(n) < f(n) < g(n) (g(n) is asymptotically greater than f(n) and f(n) is asymptotically greater than h(n) ) We can easily see above order by taking logs of the given 3 functions lognlogn < n < log(n!) (logs of the given f(n), g(n) and h(n)). Note that log(n!) = Θ(nlogn) 4. The minimum number of comparisons required to determine if an integer appears more than n/2 times in a sorted array of n integers is(A) Θ(n)(B) Θ(logn)(C) Θ(log*n)(D) Θ(n) Answer (B) Please see the post Check for Majority Element in a sorted array for details. Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. GATE-CS-2008 GATE-CS-DS-&-Algo GATE CS MCQ Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Page Replacement Algorithms in Operating Systems Normal Forms in DBMS Differences between TCP and UDP Semaphores in Process Synchronization Difference between Process and Thread Practice questions on Height balanced/AVL Tree Computer Networks | Set 1 Operating Systems | Set 1 Computer Networks | Set 2 Database Management Systems | Set 1
[ { "code": null, "e": 24410, "s": 24382, "text": "\n05 Jul, 2018" }, { "code": null, "e": 24468, "s": 24410, "text": "Following questions have been asked in GATE CS 2008 exam." }, { "code": null, "e": 24670, "s": 24468, "text": "1. We have a binary heap on n elements and wish to insert n more elements (not necessarily one after another) into this heap. The total time required for this is(A) Θ(logn)(B) Θ(n)(C) Θ(nlogn)(D) Θ(n2)" }, { "code": null, "e": 25077, "s": 24670, "text": "The worst case time complexity for insertion in a binary heap is O(Logn) (Refer Wiki). So inserting n elements in a heap of size n should take Θ(nlogn) time.But choice (B) seems to be more appropriate answer. One of the solution of O(n) complexity can be to take the ‘n’ elements of the heap and other ‘n’ elements together and construct heap in O(2n) = O(n). Thanks to pankaj for suggesting this solution." }, { "code": null, "e": 25235, "s": 25077, "text": "2. The Breadth First Search algorithm has been implemented using the queue data structure. One possible order of visiting the nodes of the following graph is" }, { "code": null, "e": 25276, "s": 25235, "text": "(A) MNOPQR(B) NQMPOR(C) QMNPRO(D) QMNPOR" }, { "code": null, "e": 25287, "s": 25276, "text": "Answer (C)" }, { "code": null, "e": 25324, "s": 25287, "text": "3. Consider the following functions:" }, { "code": null, "e": 25372, "s": 25324, "text": " f(n) = 2^n\n g(n) = n!\n h(n) = n^logn " }, { "code": null, "e": 25606, "s": 25372, "text": "Which of the following statements about the asymptotic behaviour of f(n), g(n), and h(n) is true?(A) f(n) = O(g(n)); g(n) = O(h(n))(B) f(n) = Ω(g(n)); g(n) = O(h(n))(C) g(n) = O(f(n)); h(n) = O(f(n))(D) h(n) = O(f(n)); g(n) = Ω(f(n))" }, { "code": null, "e": 25617, "s": 25606, "text": "Answer (D)" }, { "code": null, "e": 25825, "s": 25617, "text": "According to order of growth: h(n) < f(n) < g(n) (g(n) is asymptotically greater than f(n) and f(n) is asymptotically greater than h(n) )\nWe can easily see above order by taking logs of the given 3 functions" }, { "code": null, "e": 25893, "s": 25825, "text": " lognlogn < n < log(n!) (logs of the given f(n), g(n) and h(n))." }, { "code": null, "e": 25922, "s": 25893, "text": "Note that log(n!) = Θ(nlogn)" }, { "code": null, "e": 26097, "s": 25922, "text": "4. The minimum number of comparisons required to determine if an integer appears more than n/2 times in a sorted array of n integers is(A) Θ(n)(B) Θ(logn)(C) Θ(log*n)(D) Θ(n)" }, { "code": null, "e": 26108, "s": 26097, "text": "Answer (B)" }, { "code": null, "e": 26186, "s": 26108, "text": "Please see the post Check for Majority Element in a sorted array for details." }, { "code": null, "e": 26335, "s": 26186, "text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above." }, { "code": null, "e": 26348, "s": 26335, "text": "GATE-CS-2008" }, { "code": null, "e": 26366, "s": 26348, "text": "GATE-CS-DS-&-Algo" }, { "code": null, "e": 26374, "s": 26366, "text": "GATE CS" }, { "code": null, "e": 26378, "s": 26374, "text": "MCQ" }, { "code": null, "e": 26476, "s": 26378, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26525, "s": 26476, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 26546, "s": 26525, "text": "Normal Forms in DBMS" }, { "code": null, "e": 26578, "s": 26546, "text": "Differences between TCP and UDP" }, { "code": null, "e": 26616, "s": 26578, "text": "Semaphores in Process Synchronization" }, { "code": null, "e": 26654, "s": 26616, "text": "Difference between Process and Thread" }, { "code": null, "e": 26701, "s": 26654, "text": "Practice questions on Height balanced/AVL Tree" }, { "code": null, "e": 26727, "s": 26701, "text": "Computer Networks | Set 1" }, { "code": null, "e": 26753, "s": 26727, "text": "Operating Systems | Set 1" }, { "code": null, "e": 26779, "s": 26753, "text": "Computer Networks | Set 2" } ]
Division without using '/' operator - GeeksforGeeks
27 Jul, 2021 Given two numbers, divide one from other without using ‘/’ operator. Examples : Input : num1 = 13, num2 = 2 Output : 6 Input : num1 = 14, num2 = -2 Output : -7 Input : num1 = -11, num2 = 3 Output : -3 Input : num1 = 10, num2 = 10 Output : 1 Input : num1 = -6, num2 = -2 Output : 3 Input : num1 = 0, num2 = 5 Output : 0 In order to perform division operation without using ‘/’ operator we followed the approach, in which we count the number of successful or complete number of subtraction of num2 from num1. Where num1 is the number to be divided and num2 is the number from which we have to divide num1. C++ Java Python3 C# PHP Javascript // CPP program to divide a number by other// without using / operator#include <bits/stdc++.h>using namespace std; // Function to find division without using// '/' operatorint division(int num1, int num2){ if (num1 == 0) return 0; if (num2 == 0) return INT_MAX; bool negResult = false; // Handling negative numbers if (num1 < 0) { num1 = -num1 ; if (num2 < 0) num2 = - num2 ; else negResult = true; } else if (num2 < 0) { num2 = - num2 ; negResult = true; } // if num1 is greater than equal to num2 // subtract num2 from num1 and increase // quotient by one. int quotient = 0; while (num1 >= num2) { num1 = num1 - num2 ; quotient++ ; } // checking if neg equals to 1 then making // quotient negative if (negResult) quotient = - quotient ; return quotient ;} // Driver programint main(){ int num1 = 13, num2 = 2 ; cout << division(num1, num2); ; return 0;} // Java program to divide a number by other// without using / operatorimport java.io.*; class GFG{ // Function to find division without using // '/' operator static int division(int num1, int num2) { if (num1 == 0) return 0; if (num2 == 0) return Integer.MAX_VALUE; boolean negResult = false; // Handling negative numbers if (num1 < 0) { num1 = -num1 ; if (num2 < 0) num2 = - num2 ; else negResult = true; } else if (num2 < 0) { num2 = - num2 ; negResult = true; } // if num1 is greater than equal to num2 // subtract num2 from num1 and increase // quotient by one. int quotient = 0; while (num1 >= num2) { num1 = num1 - num2 ; quotient++ ; } // checking if neg equals to 1 then making // quotient negative if (negResult) quotient = - quotient ; return quotient ; } // Driver program public static void main (String[] args) { int num1 = 13, num2 = 2 ; System.out.println( division(num1, num2)); }} // This code is contributed by vt_m. # Python3 program to divide a number# by other without using / operator # Function to find division without # using '/' operatordef division(num1, num2): if (num1 == 0): return 0 if (num2 == 0): return INT_MAX negResult = 0 # Handling negative numbers if (num1 < 0): num1 = - num1 if (num2 < 0): num2 = - num2 else: negResult = true elif (num2 < 0): num2 = - num2 negResult = true # if num1 is greater than equal to num2 # subtract num2 from num1 and increase # quotient by one. quotient = 0 while (num1 >= num2): num1 = num1 - num2 quotient += 1 # checking if neg equals to 1 then # making quotient negative if (negResult): quotient = - quotient return quotient # Driver programnum1 = 13; num2 = 2print(division(num1, num2)) # This code is contributed by Ajit. // C# program to divide a number by other// without using / operatorusing System; class GFG{ // Function to find division without // using '/' operator static int division(int num1, int num2) { if (num1 == 0) return 0; if (num2 == 0) return int.MaxValue; bool negResult = false; // Handling negative numbers if (num1 < 0) { num1 = -num1 ; if (num2 < 0) num2 = - num2 ; else negResult = true; } else if (num2 < 0) { num2 = - num2 ; negResult = true; } // if num1 is greater than equal to num2 // subtract num2 from num1 and increase // quotient by one. int quotient = 0; while (num1 >= num2) { num1 = num1 - num2 ; quotient++ ; } // checking if neg equals to 1 then making // quotient negative if (negResult) quotient = - quotient ; return quotient ; } // Driver Code public static void Main () { int num1 = 13, num2 = 2 ; Console.Write( division(num1, num2)); }} // This code is contributed by nitin mittal. <?php// CPP program to divide a number by other// without using / operator // Function to find division without using// '/' operator function division($num1, $num2){ if ($num1 == 0) return 0; if ($num2 == 0) return INT_MAX; $negResult = false; // Handling negative numbers if ($num1 < 0) { $num1 = -$num1 ; if ($num2 < 0) $num2 = - $num2 ; else $negResult = true; } else if ($num2 < 0) { $num2 = - $num2 ; $negResult = true; } // if num1 is greater than equal to num2 // subtract num2 from num1 and increase // quotient by one. $quotient = 0; while ($num1 >= $num2) { $num1 = $num1 - $num2 ; $quotient++ ; } // checking if neg equals to 1 then making // quotient negative if ($negResult) $quotient = - $quotient ; return $quotient ;} // Driver program$num1 = 13; $num2 = 2 ;echo division($num1, $num2) ; // This code is contributed by ajit?> <script>// Javascript program to divide a number by other// without using / operator // Function to find division without using // '/' operator function division( num1, num2) { if (num1 == 0) return 0; if (num2 == 0) return Number.MAX_VALUE;; let negResult = false; // Handling negative numbers if (num1 < 0) { num1 = -num1; if (num2 < 0) num2 = -num2; else negResult = true; } else if (num2 < 0) { num2 = -num2; negResult = true; } // if num1 is greater than equal to num2 // subtract num2 from num1 and increase // quotient by one. let quotient = 0; while (num1 >= num2) { num1 = num1 - num2; quotient++; } // checking if neg equals to 1 then making // quotient negative if (negResult) quotient = -quotient; return quotient; } // Driver program let num1 = 13, num2 = 2; document.write(division(num1, num2)); // This code is contributed by gauravrajput1</script> Output : 6 nitin mittal jit_t GauravRajput1 sweetyty Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Prime Numbers Program to find sum of elements in a given array Program for Decimal to Binary Conversion Operators in C / C++ Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 24800, "s": 24772, "text": "\n27 Jul, 2021" }, { "code": null, "e": 24882, "s": 24800, "text": "Given two numbers, divide one from other without using ‘/’ operator. Examples : " }, { "code": null, "e": 25126, "s": 24882, "text": "Input : num1 = 13, num2 = 2\nOutput : 6\n\nInput : num1 = 14, num2 = -2\nOutput : -7\n\nInput : num1 = -11, num2 = 3\nOutput : -3\n\nInput : num1 = 10, num2 = 10\nOutput : 1\n\nInput : num1 = -6, num2 = -2\nOutput : 3\n\nInput : num1 = 0, num2 = 5\nOutput : 0" }, { "code": null, "e": 25414, "s": 25128, "text": "In order to perform division operation without using ‘/’ operator we followed the approach, in which we count the number of successful or complete number of subtraction of num2 from num1. Where num1 is the number to be divided and num2 is the number from which we have to divide num1. " }, { "code": null, "e": 25418, "s": 25414, "text": "C++" }, { "code": null, "e": 25423, "s": 25418, "text": "Java" }, { "code": null, "e": 25431, "s": 25423, "text": "Python3" }, { "code": null, "e": 25434, "s": 25431, "text": "C#" }, { "code": null, "e": 25438, "s": 25434, "text": "PHP" }, { "code": null, "e": 25449, "s": 25438, "text": "Javascript" }, { "code": "// CPP program to divide a number by other// without using / operator#include <bits/stdc++.h>using namespace std; // Function to find division without using// '/' operatorint division(int num1, int num2){ if (num1 == 0) return 0; if (num2 == 0) return INT_MAX; bool negResult = false; // Handling negative numbers if (num1 < 0) { num1 = -num1 ; if (num2 < 0) num2 = - num2 ; else negResult = true; } else if (num2 < 0) { num2 = - num2 ; negResult = true; } // if num1 is greater than equal to num2 // subtract num2 from num1 and increase // quotient by one. int quotient = 0; while (num1 >= num2) { num1 = num1 - num2 ; quotient++ ; } // checking if neg equals to 1 then making // quotient negative if (negResult) quotient = - quotient ; return quotient ;} // Driver programint main(){ int num1 = 13, num2 = 2 ; cout << division(num1, num2); ; return 0;}", "e": 26438, "s": 25449, "text": null }, { "code": "// Java program to divide a number by other// without using / operatorimport java.io.*; class GFG{ // Function to find division without using // '/' operator static int division(int num1, int num2) { if (num1 == 0) return 0; if (num2 == 0) return Integer.MAX_VALUE; boolean negResult = false; // Handling negative numbers if (num1 < 0) { num1 = -num1 ; if (num2 < 0) num2 = - num2 ; else negResult = true; } else if (num2 < 0) { num2 = - num2 ; negResult = true; } // if num1 is greater than equal to num2 // subtract num2 from num1 and increase // quotient by one. int quotient = 0; while (num1 >= num2) { num1 = num1 - num2 ; quotient++ ; } // checking if neg equals to 1 then making // quotient negative if (negResult) quotient = - quotient ; return quotient ; } // Driver program public static void main (String[] args) { int num1 = 13, num2 = 2 ; System.out.println( division(num1, num2)); }} // This code is contributed by vt_m.", "e": 27759, "s": 26438, "text": null }, { "code": "# Python3 program to divide a number# by other without using / operator # Function to find division without # using '/' operatordef division(num1, num2): if (num1 == 0): return 0 if (num2 == 0): return INT_MAX negResult = 0 # Handling negative numbers if (num1 < 0): num1 = - num1 if (num2 < 0): num2 = - num2 else: negResult = true elif (num2 < 0): num2 = - num2 negResult = true # if num1 is greater than equal to num2 # subtract num2 from num1 and increase # quotient by one. quotient = 0 while (num1 >= num2): num1 = num1 - num2 quotient += 1 # checking if neg equals to 1 then # making quotient negative if (negResult): quotient = - quotient return quotient # Driver programnum1 = 13; num2 = 2print(division(num1, num2)) # This code is contributed by Ajit.", "e": 28700, "s": 27759, "text": null }, { "code": "// C# program to divide a number by other// without using / operatorusing System; class GFG{ // Function to find division without // using '/' operator static int division(int num1, int num2) { if (num1 == 0) return 0; if (num2 == 0) return int.MaxValue; bool negResult = false; // Handling negative numbers if (num1 < 0) { num1 = -num1 ; if (num2 < 0) num2 = - num2 ; else negResult = true; } else if (num2 < 0) { num2 = - num2 ; negResult = true; } // if num1 is greater than equal to num2 // subtract num2 from num1 and increase // quotient by one. int quotient = 0; while (num1 >= num2) { num1 = num1 - num2 ; quotient++ ; } // checking if neg equals to 1 then making // quotient negative if (negResult) quotient = - quotient ; return quotient ; } // Driver Code public static void Main () { int num1 = 13, num2 = 2 ; Console.Write( division(num1, num2)); }} // This code is contributed by nitin mittal.", "e": 29994, "s": 28700, "text": null }, { "code": "<?php// CPP program to divide a number by other// without using / operator // Function to find division without using// '/' operator function division($num1, $num2){ if ($num1 == 0) return 0; if ($num2 == 0) return INT_MAX; $negResult = false; // Handling negative numbers if ($num1 < 0) { $num1 = -$num1 ; if ($num2 < 0) $num2 = - $num2 ; else $negResult = true; } else if ($num2 < 0) { $num2 = - $num2 ; $negResult = true; } // if num1 is greater than equal to num2 // subtract num2 from num1 and increase // quotient by one. $quotient = 0; while ($num1 >= $num2) { $num1 = $num1 - $num2 ; $quotient++ ; } // checking if neg equals to 1 then making // quotient negative if ($negResult) $quotient = - $quotient ; return $quotient ;} // Driver program$num1 = 13; $num2 = 2 ;echo division($num1, $num2) ; // This code is contributed by ajit?>", "e": 31037, "s": 29994, "text": null }, { "code": "<script>// Javascript program to divide a number by other// without using / operator // Function to find division without using // '/' operator function division( num1, num2) { if (num1 == 0) return 0; if (num2 == 0) return Number.MAX_VALUE;; let negResult = false; // Handling negative numbers if (num1 < 0) { num1 = -num1; if (num2 < 0) num2 = -num2; else negResult = true; } else if (num2 < 0) { num2 = -num2; negResult = true; } // if num1 is greater than equal to num2 // subtract num2 from num1 and increase // quotient by one. let quotient = 0; while (num1 >= num2) { num1 = num1 - num2; quotient++; } // checking if neg equals to 1 then making // quotient negative if (negResult) quotient = -quotient; return quotient; } // Driver program let num1 = 13, num2 = 2; document.write(division(num1, num2)); // This code is contributed by gauravrajput1</script>", "e": 32221, "s": 31037, "text": null }, { "code": null, "e": 32232, "s": 32221, "text": "Output : " }, { "code": null, "e": 32234, "s": 32232, "text": "6" }, { "code": null, "e": 32249, "s": 32236, "text": "nitin mittal" }, { "code": null, "e": 32255, "s": 32249, "text": "jit_t" }, { "code": null, "e": 32269, "s": 32255, "text": "GauravRajput1" }, { "code": null, "e": 32278, "s": 32269, "text": "sweetyty" }, { "code": null, "e": 32291, "s": 32278, "text": "Mathematical" }, { "code": null, "e": 32310, "s": 32291, "text": "School Programming" }, { "code": null, "e": 32323, "s": 32310, "text": "Mathematical" }, { "code": null, "e": 32421, "s": 32323, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32445, "s": 32421, "text": "Merge two sorted arrays" }, { "code": null, "e": 32459, "s": 32445, "text": "Prime Numbers" }, { "code": null, "e": 32508, "s": 32459, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32549, "s": 32508, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 32570, "s": 32549, "text": "Operators in C / C++" }, { "code": null, "e": 32588, "s": 32570, "text": "Python Dictionary" }, { "code": null, "e": 32604, "s": 32588, "text": "Arrays in C/C++" }, { "code": null, "e": 32623, "s": 32604, "text": "Inheritance in C++" }, { "code": null, "e": 32648, "s": 32623, "text": "Reverse a string in Java" } ]
How to backup and restore a Docker Container?
Docker allows us to automate the process of building and deploying an application. It also allows us to create a packaged environment to run the application which makes it easily portable and lightweight while also allowing us to keep track of the versions. All of these are possible through Docker Containers. It helps in making the applications platform independent. Let’s say we have a docker container running in our machine and we want to take a snapshot or keep a backup of that container so that in case of any emergency, if we want to roll back changes or execute a container with a previous timestamp, we can easily do it with the help of stored backups. Thus, backing up a docker container and restoring can become an essential component of the project. In this article, we will see how to backup and restore Docker containers with the help of certain commands. We also need to note that the processes used in this article to backup a docker container does not work if the containers use separate data volumes. To backup those docker containers that use separate data volumes, we need to create a separate backup for each of the data volumes. Backing up a Docker Container Backing up a Docker Container First of all, in order to backup the docker container, we need the container ID of that particular container. We will use the ps command to get the container IDs of all the running containers and copy the one which we need to backup. Check out the command below to do so. sudo docker ps −a After that, copy the container ID of the docker container that you want to create a backup for. To create a snapshot of the docker container, we use the docker commit command. The format of the Docker commit command is − sudo docker commit −p <CONTAINER_ID> <BACKUP_NAME> sudo docker commit −p 5c2f44fbb535 backup-ubuntu To save the image as a tar file in the local machine, you can use this command. sudo docker save −o ∽/backup−ubuntu.tar backup−ubuntu Use this command to check for the save tar file. sudo ls −l ∽/backup−ubuntu.tar You can also choose to push the image backup directly to the docker registry. Use this command to do so. Replace the username with your docker hub username. sudo docker login sudo docker push backup−ubuntu:tag Restoring a Docker Container Restoring a Docker Container After creating a backup of the docker container, if you want to restore the container for using it, here’s how you can do so. In case you have saved the tar file in your host machine, you can simply restore it back using the docker load command. Use the command below to do so. sudo docker load −i ∽/backup-ubuntu.tar To confirm if the image was successfully restored or not, you can list all the images using the following command. sudo docker images If you have pushed the backed up image to docker registry, you can pull it back using the following command sudo docker pull backup-ubuntu:tag After you have your restored image on your local machine, you can use the docker run command to run a new instance of the restored docker image. You can use the command below to do so. sudo docker run −ti backup−ubuntu:tag In the above article, we have seen how to backup and restore a docker container. If you want to migrate your docker container which is running in your host machine, to another machine, you can use the combination of both the processes (backup and restore) to do so. If you have created the backup of the image and pushed it in docker registry, you can simply login to the target machine and pull the backed up image. In case, you have created the tar files to backup your container, you can copy and paste the tar file on the target machine and use the docker load command to load the image and then run the docker run command to execute the container.
[ { "code": null, "e": 1431, "s": 1062, "text": "Docker allows us to automate the process of building and deploying an application. It also allows us to create a packaged environment to run the application which makes it easily portable and lightweight while also allowing us to keep track of the versions. All of these are possible through Docker Containers. It helps in making the applications platform independent." }, { "code": null, "e": 1826, "s": 1431, "text": "Let’s say we have a docker container running in our machine and we want to take a snapshot or keep a backup of that container so that in case of any emergency, if we want to roll back changes or execute a container with a previous timestamp, we can easily do it with the help of stored backups. Thus, backing up a docker container and restoring can become an essential component of the project." }, { "code": null, "e": 2215, "s": 1826, "text": "In this article, we will see how to backup and restore Docker containers with the help of certain commands. We also need to note that the processes used in this article to backup a docker container does not work if the containers use separate data volumes. To backup those docker containers that use separate data volumes, we need to create a separate backup for each of the data volumes." }, { "code": null, "e": 2245, "s": 2215, "text": "Backing up a Docker Container" }, { "code": null, "e": 2275, "s": 2245, "text": "Backing up a Docker Container" }, { "code": null, "e": 2509, "s": 2275, "text": "First of all, in order to backup the docker container, we need the container ID of that particular container. We will use the ps command to get the container IDs of all the running containers and copy the one which we need to backup." }, { "code": null, "e": 2547, "s": 2509, "text": "Check out the command below to do so." }, { "code": null, "e": 2565, "s": 2547, "text": "sudo docker ps −a" }, { "code": null, "e": 2786, "s": 2565, "text": "After that, copy the container ID of the docker container that you want to create a backup for. To create a snapshot of the docker container, we use the docker commit command. The format of the Docker commit command is −" }, { "code": null, "e": 2837, "s": 2786, "text": "sudo docker commit −p <CONTAINER_ID> <BACKUP_NAME>" }, { "code": null, "e": 2886, "s": 2837, "text": "sudo docker commit −p 5c2f44fbb535 backup-ubuntu" }, { "code": null, "e": 2966, "s": 2886, "text": "To save the image as a tar file in the local machine, you can use this command." }, { "code": null, "e": 3021, "s": 2966, "text": "sudo docker save −o ∽/backup−ubuntu.tar backup−ubuntu\n" }, { "code": null, "e": 3070, "s": 3021, "text": "Use this command to check for the save tar file." }, { "code": null, "e": 3101, "s": 3070, "text": "sudo ls −l ∽/backup−ubuntu.tar" }, { "code": null, "e": 3258, "s": 3101, "text": "You can also choose to push the image backup directly to the docker registry. Use this command to do so. Replace the username with your docker hub username." }, { "code": null, "e": 3311, "s": 3258, "text": "sudo docker login\nsudo docker push backup−ubuntu:tag" }, { "code": null, "e": 3340, "s": 3311, "text": "Restoring a Docker Container" }, { "code": null, "e": 3369, "s": 3340, "text": "Restoring a Docker Container" }, { "code": null, "e": 3495, "s": 3369, "text": "After creating a backup of the docker container, if you want to restore the container for using it, here’s how you can do so." }, { "code": null, "e": 3647, "s": 3495, "text": "In case you have saved the tar file in your host machine, you can simply restore it back using the docker load command. Use the command below to do so." }, { "code": null, "e": 3687, "s": 3647, "text": "sudo docker load −i ∽/backup-ubuntu.tar" }, { "code": null, "e": 3802, "s": 3687, "text": "To confirm if the image was successfully restored or not, you can list all the images using the following command." }, { "code": null, "e": 3821, "s": 3802, "text": "sudo docker images" }, { "code": null, "e": 3929, "s": 3821, "text": "If you have pushed the backed up image to docker registry, you can pull it back using the following command" }, { "code": null, "e": 3965, "s": 3929, "text": "sudo docker pull backup-ubuntu:tag\n" }, { "code": null, "e": 4150, "s": 3965, "text": "After you have your restored image on your local machine, you can use the docker run command to run a new instance of the restored docker image. You can use the command below to do so." }, { "code": null, "e": 4188, "s": 4150, "text": "sudo docker run −ti backup−ubuntu:tag" }, { "code": null, "e": 4841, "s": 4188, "text": "In the above article, we have seen how to backup and restore a docker container. If you want to migrate your docker container which is running in your host machine, to another machine, you can use the combination of both the processes (backup and restore) to do so. If you have created the backup of the image and pushed it in docker registry, you can simply login to the target machine and pull the backed up image. In case, you have created the tar files to backup your container, you can copy and paste the tar file on the target machine and use the docker load command to load the image and then run the docker run command to execute the container." } ]